Programs & Examples On #Access control

Access control is the process of limiting the access of ability of users or services to certain resources.

How do I use Access-Control-Allow-Origin? Does it just go in between the html head tags?

<?php header("Access-Control-Allow-Origin: http://example.com"); ?>

This command disables only first console warning info

console

Result: console result

Create new user in MySQL and give it full access to one database

To me this worked.

CREATE USER 'spowner'@'localhost' IDENTIFIED BY '1234'; 
GRANT ALL PRIVILEGES ON test.* To 'spowner'@'localhost'; 
FLUSH PRIVILEGES;

where

  • spowner : user name
  • 1234 : password of spowner
  • test : database 'spowner' has access right to

jQuery.getJSON - Access-Control-Allow-Origin Issue

You may well want to use JSON-P instead (see below). First a quick explanation.

The header you've mentioned is from the Cross Origin Resource Sharing standard. Beware that it is not supported by some browsers people actually use, and on other browsers (Microsoft's, sigh) it requires using a special object (XDomainRequest) rather than the standard XMLHttpRequest that jQuery uses. It also requires that you change server-side resources to explicitly allow the other origin (www.xxxx.com).

To get the JSON data you're requesting, you basically have three options:

  1. If possible, you can be maximally-compatible by correcting the location of the files you're loading so they have the same origin as the document you're loading them into. (I assume you must be loading them via Ajax, hence the Same Origin Policy issue showing up.)

  2. Use JSON-P, which isn't subject to the SOP. jQuery has built-in support for it in its ajax call (just set dataType to "jsonp" and jQuery will do all the client-side work). This requires server side changes, but not very big ones; basically whatever you have that's generating the JSON response just looks for a query string parameter called "callback" and wraps the JSON in JavaScript code that would call that function. E.g., if your current JSON response is:

    {"weather": "Dreary start but soon brightening into a fine summer day."}
    

    Your script would look for the "callback" query string parameter (let's say that the parameter's value is "jsop123") and wraps that JSON in the syntax for a JavaScript function call:

    jsonp123({"weather": "Dreary start but soon brightening into a fine summer day."});
    

    That's it. JSON-P is very broadly compatible (because it works via JavaScript script tags). JSON-P is only for GET, though, not POST (again because it works via script tags).

  3. Use CORS (the mechanism related to the header you quoted). Details in the specification linked above, but basically:

    A. The browser will send your server a "preflight" message using the OPTIONS HTTP verb (method). It will contain the various headers it would send with the GET or POST as well as the headers "Origin", "Access-Control-Request-Method" (e.g., GET or POST), and "Access-Control-Request-Headers" (the headers it wants to send).

    B. Your PHP decides, based on that information, whether the request is okay and if so responds with the "Access-Control-Allow-Origin", "Access-Control-Allow-Methods", and "Access-Control-Allow-Headers" headers with the values it will allow. You don't send any body (page) with that response.

    C. The browser will look at your response and see whether it's allowed to send you the actual GET or POST. If so, it will send that request, again with the "Origin" and various "Access-Control-Request-xyz" headers.

    D. Your PHP examines those headers again to make sure they're still okay, and if so responds to the request.

    In pseudo-code (I haven't done much PHP, so I'm not trying to do PHP syntax here):

    // Find out what the request is asking for
    corsOrigin = get_request_header("Origin")
    corsMethod = get_request_header("Access-Control-Request-Method")
    corsHeaders = get_request_header("Access-Control-Request-Headers")
    if corsOrigin is null or "null" {
        // Requests from a `file://` path seem to come through without an
        // origin or with "null" (literally) as the origin.
        // In my case, for testing, I wanted to allow those and so I output
        // "*", but you may want to go another way.
        corsOrigin = "*"
    }
    
    // Decide whether to accept that request with those headers
    // If so:
    
    // Respond with headers saying what's allowed (here we're just echoing what they
    // asked for, except we may be using "*" [all] instead of the actual origin for
    // the "Access-Control-Allow-Origin" one)
    set_response_header("Access-Control-Allow-Origin", corsOrigin)
    set_response_header("Access-Control-Allow-Methods", corsMethod)
    set_response_header("Access-Control-Allow-Headers", corsHeaders)
    if the HTTP request method is "OPTIONS" {
        // Done, no body in response to OPTIONS
        stop
    }
    // Process the GET or POST here; output the body of the response
    

    Again stressing that this is pseudo-code.

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at

The use-case for CORS is simple. Imagine the site alice.com has some data that the site bob.com wants to access. This type of request traditionally wouldn’t be allowed under the browser’s same origin policy. However, by supporting CORS requests, alice.com can add a few special response headers that allows bob.com to access the data. In order to understand it well, please visit this nice tutorial.. How to solve the issue of CORS

Pass a javascript variable value into input type hidden value

You could give your hidden field an id:

<input type="hidden" id="myField" value="" />

and then when you want to assign its value:

document.getElementById('myField').value = product(2, 3);

Make sure that you are performing this assignment after the DOM has been fully loaded, for example in the window.load event.

Is it ok to scrape data from Google results?

Google disallows automated access in their TOS, so if you accept their terms you would break them.

That said, I know of no lawsuit from Google against a scraper. Even Microsoft scraped Google, they powered their search engine Bing with it. They got caught in 2011 red handed :)

There are two options to scrape Google results:

1) Use their API

UPDATE 2020: Google has reprecated previous APIs (again) and has new prices and new limits. Now (https://developers.google.com/custom-search/v1/overview) you can query up to 10k results per day at 1,500 USD per month, more than that is not permitted and the results are not what they display in normal searches.

  • You can issue around 40 requests per hour You are limited to what they give you, it's not really useful if you want to track ranking positions or what a real user would see. That's something you are not allowed to gather.

  • If you want a higher amount of API requests you need to pay.

  • 60 requests per hour cost 2000 USD per year, more queries require a custom deal.

2) Scrape the normal result pages

  • Here comes the tricky part. It is possible to scrape the normal result pages. Google does not allow it.
  • If you scrape at a rate higher than 8 (updated from 15) keyword requests per hour you risk detection, higher than 10/h (updated from 20) will get you blocked from my experience.
  • By using multiple IPs you can up the rate, so with 100 IP addresses you can scrape up to 1000 requests per hour. (24k a day) (updated)
  • There is an open source search engine scraper written in PHP at http://scraping.compunect.com It allows to reliable scrape Google, parses the results properly and manages IP addresses, delays, etc. So if you can use PHP it's a nice kickstart, otherwise the code will still be useful to learn how it is done.

3) Alternatively use a scraping service (updated)

  • Recently a customer of mine had a huge search engine scraping requirement but it was not 'ongoing', it's more like one huge refresh per month.
    In this case I could not find a self-made solution that's 'economic'.
    I used the service at http://scraping.services instead. They also provide open source code and so far it's running well (several thousand resultpages per hour during the refreshes)
  • The downside is that such a service means that your solution is "bound" to one professional supplier, the upside is that it was a lot cheaper than the other options I evaluated (and faster in our case)
  • One option to reduce the dependency on one company is to make two approaches at the same time. Using the scraping service as primary source of data and falling back to a proxy based solution like described at 2) when required.

How to compile for Windows on Linux with gcc/g++?

Install a cross compiler, like mingw64 from your package manager. Then compile in the following way: instead of simply calling gcc call i686-w64-mingw32-gcc for 32-bit Windows or x86_64-w64-mingw32-gcc" for 64-bit Windows. I would also use the --static option, as the target system may not have all the libraries.

If you want to compile other language, like Fortran, replace -gcc with -gfortran in the previous commands.

Can regular JavaScript be mixed with jQuery?

Yes, they're both JavaScript, you can use whichever functions are appropriate for the situation.

In this case you can just put the code in a document.ready handler, like this:

$(function() {
  var canvas = document.getElementById("canvas");
  if (canvas.getContext) {
    var ctx = canvas.getContext("2d");

    ctx.fillStyle = "rgb(200,0,0)";
    ctx.fillRect (10, 10, 55, 50);

    ctx.fillStyle = "rgba(0, 0, 200, 0.5)";
    ctx.fillRect (30, 30, 55, 50);
  }
});

Pass by Reference / Value in C++

I think much confusion is generated by not communicating what is meant by passed by reference. When some people say pass by reference they usually mean not the argument itself, but rather the object being referenced. Some other say that pass by reference means that the object can't be changed in the callee. Example:

struct Object {
    int i;
};

void sample(Object* o) { // 1
    o->i++;
}

void sample(Object const& o) { // 2
    // nothing useful here :)
}

void sample(Object & o) { // 3
    o.i++;
}

void sample1(Object o) { // 4
    o.i++;
}

int main() {
    Object obj = { 10 };
    Object const obj_c = { 10 };

    sample(&obj); // calls 1
    sample(obj) // calls 3
    sample(obj_c); // calls 2
    sample1(obj); // calls 4
}

Some people would claim that 1 and 3 are pass by reference, while 2 would be pass by value. Another group of people say all but the last is pass by reference, because the object itself is not copied.

I would like to draw a definition of that here what i claim to be pass by reference. A general overview over it can be found here: Difference between pass by reference and pass by value. The first and last are pass by value, and the middle two are pass by reference:

    sample(&obj);
       // yields a `Object*`. Passes a *pointer* to the object by value. 
       // The caller can change the pointer (the parameter), but that 
       // won't change the temporary pointer created on the call side (the argument). 

    sample(obj)
       // passes the object by *reference*. It denotes the object itself. The callee
       // has got a reference parameter.

    sample(obj_c);
       // also passes *by reference*. the reference parameter references the
       // same object like the argument expression. 

    sample1(obj);
       // pass by value. The parameter object denotes a different object than the 
       // one passed in.

I vote for the following definition:

An argument (1.3.1) is passed by reference if and only if the corresponding parameter of the function that's called has reference type and the reference parameter binds directly to the argument expression (8.5.3/4). In all other cases, we have to do with pass by value.

That means that the following is pass by value:

void f1(Object const& o);
f1(Object()); // 1

void f2(int const& i);
f2(42); // 2

void f3(Object o);
f3(Object());     // 3
Object o1; f3(o1); // 4

void f4(Object *o);
Object o1; f4(&o1); // 5

1 is pass by value, because it's not directly bound. The implementation may copy the temporary and then bind that temporary to the reference. 2 is pass by value, because the implementation initializes a temporary of the literal and then binds to the reference. 3 is pass by value, because the parameter has not reference type. 4 is pass by value for the same reason. 5 is pass by value because the parameter has not got reference type. The following cases are pass by reference (by the rules of 8.5.3/4 and others):

void f1(Object *& op);
Object a; Object *op1 = &a; f1(op1); // 1

void f2(Object const& op);
Object b; f2(b); // 2

struct A { };
struct B { operator A&() { static A a; return a; } };
void f3(A &);
B b; f3(b); // passes the static a by reference

How to launch jQuery Fancybox on page load?

I actually managed to trigger a fancyBox link only from an external JS file using the "live" event:

First, add the live click event on your future dynamic anchor:

$('a.pub').live('click', function() {
  $(this).fancybox(... fancybox parameters ...);
})

Then, append the anchor to the body:

$('body').append('<a class="iframe pub" href="your-url.html"></a>');

Then trigger the fancyBox by "clicking" the anchor:

$('a.pub').click();

The fancyBox link is now "almost" ready. Why "almost" ? Because it looks like you need to add some delay before trigger the second click, otherwise the script is not ready.

It's a quick and dirty delay using some animation on our anchor but it works well:

$('a.pub').slideDown('fast', function() {
  $('a.pub').click();
});

Here you go, your fancyBox should appears onload!

HTH

Proper way to use AJAX Post in jquery to pass model from strongly typed MVC3 view

This is the way it worked for me:

$.post("/Controller/Action", $("#form").serialize(), function(json) {       
        // handle response
}, "json");

[HttpPost]
public ActionResult TV(MyModel id)
{
    return Json(new { success = true });
}

Sending email with gmail smtp with codeigniter email library

It can be this:

If you are using cpanel for your website smtp restrictions are problem and cause this error. SMTP Restrictions

Error while sending an email with CodeIgniter

How to iterate through a DataTable

There are already nice solution has been given. The below code can help others to query over datatable and get the value of each row of the datatable for the ImagePath column.

  for (int i = 0; i < dataTable.Rows.Count; i++)
  {
       var theUrl = dataTable.Rows[i]["ImagePath"].ToString();
  }

How to change facebook login button with my custom image

It is actually possible only using CSS, however, the image you use to replace must be the same size as the original facebook log in button. Fortunately Facebook delivers the button in different sizes.

From facebook:

size - Different sized buttons: small, medium, large, xlarge - the default is medium. https://developers.facebook.com/docs/reference/plugins/login/

Set the login iframe opacity to 0 and show a background image in the parent div

.fb_iframe_widget iframe {
    opacity: 0;
}

.fb_iframe_widget {
  background-image: url(another-button.png);
  background-repeat: no-repeat; 
}

If you use an image that is bigger than the original facebook button, the part of the image that is outside the width and height of the original button will not be clickable.

Programmatically trigger "select file" dialog box

Make sure you are using binding to get component props in REACT

class FileUploader extends Component {
  constructor (props) {
    super(props);
    this.handleClick = this.handleClick.bind(this);
  }
   onChange=(e,props)=>{
    const files = e.target.files;
    const selectedFile = files[0];
    ProcessFileUpload(selectedFile,props.ProgressCallBack,props.ErrorCallBack,props.CompleatedCallBack,props.BaseURL,props.Location,props.FilesAllowed);
  }
   handleClick = () => {
    this.refs.fileUploader.click();
  }
  render()
  {
  return(
      <div>
        <button type="button" onClick={this.handleClick}>Select File</button>  
        <input type='file' onChange={(e)=>this.onChange(e,this.props)} ref="fileUploader" style={{display:"none"}} />
      </div>)
  }
}

Palindrome check in Javascript

I'm wondering why nobody suggested this:

ES6:

// "aba" -> true
// "acb" -> false
// "aa" -> true
// "abba" -> true
// "s" -> true
isPalindrom = (str = "") => {
  if (str[0] === str[str.length - 1]) {
    return str.length <= 1 ? true : isPalindrom(str.slice(1, -1))
  }

  return false;
}

alert(["aba", "acb", "aa", "abba", "s"].map((e, i) => isPalindrom(e)).join())

ES5:

// "aba" -> true
// "acb" -> false
// "aa" -> true
// "abba" -> true
// "s" -> true
function isPalindrom(str) => {
  var str = typeof str !== "string" ? "" : str;

  if (str[0] === str[str.length - 1]) {
    return str.length <= 1 ? true : isPalindrom(str.slice(1, -1))
  }

  return false;
}

alert(["aba", "acb", "aa", "abba", "s"].map(function (e, i) {
    return isPalindrom(e);
}).join());

File content into unix variable with newlines

Your variable is set correctly by testvar=$(cat test.txt). To display this variable which consist new line characters, simply add double quotes, e.g.

echo "$testvar" 

Here is the full example:

$ printf "test1\ntest2" > test.txt
$ testvar=$(<test.txt)
$ grep testvar <(set)
testvar=$'test1\ntest2'
$ echo "$testvar"
text1
text2
$ printf "%b" "$testvar"
text1
text2

Python:Efficient way to check if dictionary is empty or not

I would say that way is more pythonic and fits on line:

If you need to check value only with the use of your function:

if filter( your_function, dictionary.values() ): ...

When you need to know if your dict contains any keys:

if dictionary: ...

Anyway, using loops here is not Python-way.

iOS Simulator to test website on Mac

You could also download Xcode to your mac and use iPhone simulator.

Installing Python library from WHL file

From How do I install a Python package with a .whl file? [sic], How do I install a Python package USING a .whl file ?

For all Windows platforms:

1) Download the .WHL package install file.

2) Make Sure path [C:\Progra~1\Python27\Scripts] is in the system PATH string. This is for using both [pip.exe] and [easy-install.exe].

3) Make sure the latest version of pip.EXE is now installed. At this time of posting:

pip.EXE --version

  pip 9.0.1 from C:\PROGRA~1\Python27\lib\site-packages (python 2.7)

4) Run pip.EXE in an Admin command shell.

 - Open an Admin privileged command shell.

 > easy_install.EXE --upgrade  pip

 - Check the pip.EXE version:
 > pip.EXE --version

 pip 9.0.1 from C:\PROGRA~1\Python27\lib\site-packages (python 2.7)

 > pip.EXE install --use-wheel --no-index 
     --find-links="X:\path to wheel file\DownloadedWheelFile.whl"

Be sure to double-quote paths or path\filenames with embedded spaces in them ! Alternatively, use the MSW 'short' paths and filenames.

Batch program to to check if process exists

TASKLIST does not set errorlevel.

echo off
tasklist /fi "imagename eq notepad.exe" |find ":" > nul
if errorlevel 1 taskkill /f /im "notepad.exe"
exit

should do the job, since ":" should appear in TASKLIST output only if the task is NOT found, hence FIND will set the errorlevel to 0 for not found and 1 for found

Nevertheless,

taskkill /f /im "notepad.exe"

will kill a notepad task if it exists - it can do nothing if no notepad task exists, so you don't really need to test - unless there's something else you want to do...like perhaps

echo off
tasklist /fi "imagename eq notepad.exe" |find ":" > nul
if errorlevel 1 taskkill /f /im "notepad.exe"&exit

which would appear to do as you ask - kill the notepad process if it exists, then exit - otherwise continue with the batch

How to bring back "Browser mode" in IE11?

In IE11 we can change user agent to IE10, IE9 and even as windows phone. It is really good

Fill remaining vertical space - only CSS

If you can add an extra couple of divs so your html looks like this:

<div id="wrapper">
    <div id="first" class="row">
        <div class="cell"></div>
    </div>
    <div id="second" class="row">
        <div class="cell"></div>
    </div>
</div>

You can make use of the display:table properties:

#wrapper
{
   width:300px;
   height:100%;
   display:table;
}

.row 
{
   display:table-row;
}

.cell 
{
   display:table-cell;
}

#first .cell
{
   height:200px;
   background-color:#F5DEB3;
}

#second .cell
{
   background-color:#9ACD32;
}

Example

PHP cURL HTTP CODE return 0

I had same problem and in my case this was because curl_exec function is disabled in php.ini. Check for logs:

PHP Warning:  curl_exec() has been disabled for security reasons in /var/www/***/html/test.php on line 18

Solution is remove curl_exec from disabled functions in php.ini on server configuration file.

Getting The ASCII Value of a character in a C# string

Here is another alternative. It will of course give you a bad result if the input char is not ascii. I've not perf tested it but I think it would be pretty fast:

[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static int GetAsciiVal(string s, int index) {
    return GetAsciiVal(s[index]);
}

[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static int GetAsciiVal(char c) {
    return unchecked(c & 0xFF);
}

How to find schema name in Oracle ? when you are connected in sql session using read only user

Call SYS_CONTEXT to get the current schema. From Ask Tom "How to get current schema:

select sys_context( 'userenv', 'current_schema' ) from dual;

Change the background color of CardView programmatically

Cardview is a bit coy. I had list of colors in my structure and Model is like

class ModelColor : Serializable {

var id: Int? = 0
var title: String? = ""
var color: Int? = 0// HERE IS THE COLOR FIELD WE WILL USE

constructor(id: Int?, title: String?, color: Int?) {
    this.id = id
    this.title = title
    this.color = color
}

}

load the model with color, last item on constructure taking from R.color

 list.add(ModelColor(2, getString(R.string.orange), R.color.orange_500))

and finaly you can setBackgriundResource

 cv_add_goal_choose_color.setBackgroundResource(color)

How can I use ":" as an AWK field separator?

"-F" is a command line argument, not AWK syntax. Try:

 echo "1: " | awk -F  ":" '/1/ {print $1}'

Spring @Transactional read-only propagation

By default transaction propagation is REQUIRED, meaning that the same transaction will propagate from a transactional caller to transactional callee. In this case also the read-only status will propagate. E.g. if a read-only transaction will call a read-write transaction, the whole transaction will be read-only.

Could you use the Open Session in View pattern to allow lazy loading? That way your handle method does not need to be transactional at all.

Passing data to a jQuery UI Dialog

I have now tried your suggestions and found that it kinda works,

  1. The dialog div is alsways written out in plaintext
  2. With the $.post version it actually works in terms that the controller gets called and actually cancels the booking, but the dialog stays open and page doesn't refresh. With the get version window.location = h.ref works great.

Se my "new" script below:

$('a.cancel').click(function() {
        var a = this;               
        $("#dialog").dialog({
            autoOpen: false,
            buttons: {
                "Ja": function() {
                    $.post(a.href);                     
                },
                "Nej": function() { $(this).dialog("close"); }
            },
            modal: true,
            overlay: {
                opacity: 0.5,

            background: "black"
        }
    });
    $("#dialog").dialog('open');
    return false;
});

});

Any clues?

oh and my Action link now looks like this:

<%= Html.ActionLink("Cancel", "Cancel", new { id = v.BookingId }, new  { @class = "cancel" })%>

Plugin org.apache.maven.plugins:maven-compiler-plugin or one of its dependencies could not be resolved

You only need to delete one folder it is throwing error for. Just go to your M2 repo and org/apache/maven/plugins/maven-compiler-plugins and delete the folder 2.3.2

Jquery validation plugin - TypeError: $(...).validate is not a function

It looks like the JavaScript error your getting is probably being caused by

password: {
    required:true,
    rangelenght:[4.20]
},

As the [4.20] should be [4,20], which i'd guess is throwing off the validation code in additional-methods hence giving the type error's you posted.

Edit: As others have noted in the below comments rangelenght is also misspelled & jquery.validate.js library appears to be missing (assuming its not compiled in to one of your other assets)

The transaction manager has disabled its support for remote/network transactions

I post the below solution here because after some searching this is where I landed, so other may too. I was trying to use EF 6 to call a stored procedure, but had a similar error because the stored procedure had a linked server being utilized.

The operation could not be performed because OLE DB provider _ for linked server _ was unable to begin a distributed transaction

The partner transaction manager has disabled its support for remote/network transactions*

Jumping over to SQL Client did fix my issue, which also confirmed for me that it was an EF thing.

EF model generated method based attempt:

db.SomeStoredProcedure();

ExecuteSqlCommand based attempt:

db.Database.ExecuteSqlCommand("exec [SomeDB].[dbo].[SomeStoredProcedure]");

With:

var connectionString = db.Database.Connection.ConnectionString;
var connection = new System.Data.SqlClient.SqlConnection(connectionString);    
var cmd = connection.CreateCommand();
cmd.CommandText = "exec [SomeDB].[dbo].[SomeStoredProcedure]";

connection.Open();
var result = cmd.ExecuteNonQuery();

That code can be shortened, but I think that version is slightly more convenient for debugging and stepping through.

I don't believe that Sql Client is necessarily a preferred choice, but I felt this was at least worth sharing if anyone else having similar problems gets landed here by google.

The above Code is C#, but the concept of trying to switch over to Sql Client still applies. At the very least it will be diagnostic to attempt to do so.

How to revert multiple git commits?

I'm so frustrated that this question can't just be answered. Every other question is in relation to how to revert correctly and preserve history. This question says "I want the head of the branch to point to A, i.e. I want B, C, D, and HEAD to disappear and I want head to be synonymous with A."

git checkout <branch_name>
git reset --hard <commit Hash for A>
git push -f

I learned a lot reading Jakub's post, but some guy in the company (with access to push to our "testing" branch without Pull-Request) pushed like 5 bad commits trying to fix and fix and fix a mistake he made 5 commits ago. Not only that, but one or two Pull Requests were accepted, which were now bad. So forget it, I found the last good commit (abc1234) and just ran the basic script:

git checkout testing
git reset --hard abc1234
git push -f

I told the other 5 guys working in this repo that they better make note of their changes for the last few hours and Wipe/Re-Branch from the latest testing. End of the story.

UIImage resize (Scale proportion)

This fixes the math to scale to the max size in both width and height rather than just one depending on the width and height of the original.

- (UIImage *) scaleProportionalToSize: (CGSize)size
{
    float widthRatio = size.width/self.size.width;
    float heightRatio = size.height/self.size.height;

    if(widthRatio > heightRatio)
    {
        size=CGSizeMake(self.size.width*heightRatio,self.size.height*heightRatio);
    } else {
        size=CGSizeMake(self.size.width*widthRatio,self.size.height*widthRatio);
    }

    return [self scaleToSize:size];
}

Custom format for time command

Not quite sure what you are asking, have you tried:

time yourscript | tail -n1 >log

Edit: ok, so you know how to get the times out and you just want to change the format. It would help if you described what format you want, but here are some things to try:

time -p script

This changes the output to one time per line in seconds with decimals. You only want the real time, not the other two so to get the number of seconds use:

time -p script | tail -n 3 | head -n 1

How to toggle font awesome icon on click?

Simply call jQuery's toggleClass() on the i element contained within your a element(s) to toggle either the plus and minus icons:

...click(function() {
    $(this).find('i').toggleClass('fa-minus-circle fa-plus-circle');
});

Note that this assumes that a class of fa-plus-circle is added to your i element by default.

JSFiddle demo.

Redirecting to a new page after successful login

First of all, move all your PHP code to the top. Without it, my code below wont work.

To do the redirect, use:

header('Location: http://www.example.com/');

Also, please consider my advice. Since it's not the first question today and all your questions are related to basics, you should consider reading some good PHP book to understand how things work.

Here you can find useful links to free books: https://stackoverflow.com/tags/php/info

What is uintptr_t data type

First thing, at the time the question was asked, uintptr_t was not in C++. It's in C99, in <stdint.h>, as an optional type. Many C++03 compilers do provide that file. It's also in C++11, in <cstdint>, where again it is optional, and which refers to C99 for the definition.

In C99, it is defined as "an unsigned integer type with the property that any valid pointer to void can be converted to this type, then converted back to pointer to void, and the result will compare equal to the original pointer".

Take this to mean what it says. It doesn't say anything about size.

uintptr_t might be the same size as a void*. It might be larger. It could conceivably be smaller, although such a C++ implementation approaches perverse. For example on some hypothetical platform where void* is 32 bits, but only 24 bits of virtual address space are used, you could have a 24-bit uintptr_t which satisfies the requirement. I don't know why an implementation would do that, but the standard permits it.

What are native methods in Java and where should they be used?

What are native methods in Java and where should they be used?

Once you see a small example, it becomes clear:

Main.java:

public class Main {
    public native int intMethod(int i);
    public static void main(String[] args) {
        System.loadLibrary("Main");
        System.out.println(new Main().intMethod(2));
    }
}

Main.c:

#include <jni.h>
#include "Main.h"

JNIEXPORT jint JNICALL Java_Main_intMethod(
    JNIEnv *env, jobject obj, jint i) {
  return i * i;
}

Compile and run:

javac Main.java
javah -jni Main
gcc -shared -fpic -o libMain.so -I${JAVA_HOME}/include \
  -I${JAVA_HOME}/include/linux Main.c
java -Djava.library.path=. Main

Output:

4

Tested on Ubuntu 14.04 with Oracle JDK 1.8.0_45.

So it is clear that it allows you to:

  • call a compiled dynamically loaded library (here written in C) with arbitrary assembly code from Java
  • and get results back into Java

This could be used to:

  • write faster code on a critical section with better CPU assembly instructions (not CPU portable)
  • make direct system calls (not OS portable)

with the tradeoff of lower portability.

It is also possible for you to call Java from C, but you must first create a JVM in C: How to call Java functions from C++?

Example on GitHub for you to play with.

AngularJs: How to set radio button checked based on model

One way that I see more powerful and avoid having a isDefault in all the models is by using the ng-attributes ng-model, ng-value and ng-checked.

ng-model: binds the value to your model.

ng-value: the value to pass to the ng-model binding.

ng-checked: value or expression that is evaluated. Useful for radio-button and check-boxes.

Example of use: In the following example, I have my model and a list of languages that my site supports. To display the different languages supported and updating the model with the selecting language we can do it in this way.

<!-- Radio -->
<div ng-repeat="language in languages">

  <div>
    <label>

      <input ng-model="site.lang"
             ng-value="language"
             ng-checked="(site.lang == language)"
             name="localizationOptions"
             type="radio">

      <span> {{language}} </span>

    </label>
  </div>

</div>
<!-- end of Radio -->

Our model site.lang will get a language value whenever the expression under evaluation (site.lang == language) is true. This will allow you to sync it with server easily since your model already has the change.

Entity framework left join

It might be a bit of an overkill, but I wrote an extension method, so you can do a LeftJoin using the Join syntax (at least in method call notation):

persons.LeftJoin(
    phoneNumbers,
    person => person.Id,
    phoneNumber => phoneNumber.PersonId,
    (person, phoneNumber) => new
        {
            Person = person,
            PhoneNumber = phoneNumber?.Number
        }
);

My code does nothing more than adding a GroupJoin and a SelectMany call to the current expression tree. Nevertheless, it looks pretty complicated because I have to build the expressions myself and modify the expression tree specified by the user in the resultSelector parameter to keep the whole tree translatable by LINQ-to-Entities.

public static class LeftJoinExtension
{
    public static IQueryable<TResult> LeftJoin<TOuter, TInner, TKey, TResult>(
        this IQueryable<TOuter> outer,
        IQueryable<TInner> inner,
        Expression<Func<TOuter, TKey>> outerKeySelector,
        Expression<Func<TInner, TKey>> innerKeySelector,
        Expression<Func<TOuter, TInner, TResult>> resultSelector)
    {
        MethodInfo groupJoin = typeof (Queryable).GetMethods()
                                                 .Single(m => m.ToString() == "System.Linq.IQueryable`1[TResult] GroupJoin[TOuter,TInner,TKey,TResult](System.Linq.IQueryable`1[TOuter], System.Collections.Generic.IEnumerable`1[TInner], System.Linq.Expressions.Expression`1[System.Func`2[TOuter,TKey]], System.Linq.Expressions.Expression`1[System.Func`2[TInner,TKey]], System.Linq.Expressions.Expression`1[System.Func`3[TOuter,System.Collections.Generic.IEnumerable`1[TInner],TResult]])")
                                                 .MakeGenericMethod(typeof (TOuter), typeof (TInner), typeof (TKey), typeof (LeftJoinIntermediate<TOuter, TInner>));
        MethodInfo selectMany = typeof (Queryable).GetMethods()
                                                  .Single(m => m.ToString() == "System.Linq.IQueryable`1[TResult] SelectMany[TSource,TCollection,TResult](System.Linq.IQueryable`1[TSource], System.Linq.Expressions.Expression`1[System.Func`2[TSource,System.Collections.Generic.IEnumerable`1[TCollection]]], System.Linq.Expressions.Expression`1[System.Func`3[TSource,TCollection,TResult]])")
                                                  .MakeGenericMethod(typeof (LeftJoinIntermediate<TOuter, TInner>), typeof (TInner), typeof (TResult));

        var groupJoinResultSelector = (Expression<Func<TOuter, IEnumerable<TInner>, LeftJoinIntermediate<TOuter, TInner>>>)
                                      ((oneOuter, manyInners) => new LeftJoinIntermediate<TOuter, TInner> {OneOuter = oneOuter, ManyInners = manyInners});

        MethodCallExpression exprGroupJoin = Expression.Call(groupJoin, outer.Expression, inner.Expression, outerKeySelector, innerKeySelector, groupJoinResultSelector);

        var selectManyCollectionSelector = (Expression<Func<LeftJoinIntermediate<TOuter, TInner>, IEnumerable<TInner>>>)
                                           (t => t.ManyInners.DefaultIfEmpty());

        ParameterExpression paramUser = resultSelector.Parameters.First();

        ParameterExpression paramNew = Expression.Parameter(typeof (LeftJoinIntermediate<TOuter, TInner>), "t");
        MemberExpression propExpr = Expression.Property(paramNew, "OneOuter");

        LambdaExpression selectManyResultSelector = Expression.Lambda(new Replacer(paramUser, propExpr).Visit(resultSelector.Body), paramNew, resultSelector.Parameters.Skip(1).First());

        MethodCallExpression exprSelectMany = Expression.Call(selectMany, exprGroupJoin, selectManyCollectionSelector, selectManyResultSelector);

        return outer.Provider.CreateQuery<TResult>(exprSelectMany);
    }

    private class LeftJoinIntermediate<TOuter, TInner>
    {
        public TOuter OneOuter { get; set; }
        public IEnumerable<TInner> ManyInners { get; set; }
    }

    private class Replacer : ExpressionVisitor
    {
        private readonly ParameterExpression _oldParam;
        private readonly Expression _replacement;

        public Replacer(ParameterExpression oldParam, Expression replacement)
        {
            _oldParam = oldParam;
            _replacement = replacement;
        }

        public override Expression Visit(Expression exp)
        {
            if (exp == _oldParam)
            {
                return _replacement;
            }

            return base.Visit(exp);
        }
    }
}

Git merge with force overwrite

When I tried using -X theirs and other related command switches I kept getting a merge commit. I probably wasn't understanding it correctly. One easy to understand alternative is just to delete the branch then track it again.

git branch -D <branch-name>
git branch --track <branch-name> origin/<branch-name>

This isn't exactly a "merge", but this is what I was looking for when I came across this question. In my case I wanted to pull changes from a remote branch that were force pushed.

vba pass a group of cells as range to function

As written, your function accepts only two ranges as arguments.

To allow for a variable number of ranges to be used in the function, you need to declare a ParamArray variant array in your argument list. Then, you can process each of the ranges in the array in turn.

For example,

Function myAdd(Arg1 As Range, ParamArray Args2() As Variant) As Double
    Dim elem As Variant
    Dim i As Long
    For Each elem In Arg1
        myAdd = myAdd + elem.Value
    Next elem
    For i = LBound(Args2) To UBound(Args2)
        For Each elem In Args2(i)
            myAdd = myAdd + elem.Value
        Next elem
    Next i
End Function

This function could then be used in the worksheet to add multiple ranges.

myAdd usage

For your function, there is the question of which of the ranges (or cells) that can passed to the function are 'Sessions' and which are 'Customers'.

The easiest case to deal with would be if you decided that the first range is Sessions and any subsequent ranges are Customers.

Function calculateIt(Sessions As Range, ParamArray Customers() As Variant) As Double
    'This function accepts a single Sessions range and one or more Customers
    'ranges
    Dim i As Long
    Dim sessElem As Variant
    Dim custElem As Variant
    For Each sessElem In Sessions
        'do something with sessElem.Value, the value of each
        'cell in the single range Sessions
        Debug.Print "sessElem: " & sessElem.Value
    Next sessElem
    'loop through each of the one or more ranges in Customers()
    For i = LBound(Customers) To UBound(Customers)
        'loop through the cells in the range Customers(i)
        For Each custElem In Customers(i)
            'do something with custElem.Value, the value of
            'each cell in the range Customers(i)
            Debug.Print "custElem: " & custElem.Value
         Next custElem
    Next i
End Function

If you want to include any number of Sessions ranges and any number of Customers range, then you will have to include an argument that will tell the function so that it can separate the Sessions ranges from the Customers range.

This argument could be set up as the first, numeric, argument to the function that would identify how many of the following arguments are Sessions ranges, with the remaining arguments implicitly being Customers ranges. The function's signature would then be:

Function calculateIt(numOfSessionRanges, ParamAray Args() As Variant)

Or it could be a "guard" argument that separates the Sessions ranges from the Customers ranges. Then, your code would have to test each argument to see if it was the guard. The function would look like:

Function calculateIt(ParamArray Args() As Variant)

Perhaps with a call something like:

calculateIt(sessRange1,sessRange2,...,"|",custRange1,custRange2,...)

The program logic might then be along the lines of:

Function calculateIt(ParamArray Args() As Variant) As Double
   ...
   'loop through Args
   IsSessionArg = True
   For i = lbound(Args) to UBound(Args)
       'only need to check for the type of the argument
       If TypeName(Args(i)) = "String" Then
          IsSessionArg = False
       ElseIf IsSessionArg Then
          'process Args(i) as Session range
       Else
          'process Args(i) as Customer range
       End if
   Next i
   calculateIt = <somevalue>
End Function

first-child and last-child with IE8

If your table is only 2 columns across, you can easily reach the second td with the adjacent sibling selector, which IE8 does support along with :first-child:

.editor td:first-child
{
    width: 150px; 
}

.editor td:first-child + td input,
.editor td:first-child + td textarea
{
    width: 500px;
    padding: 3px 5px 5px 5px;
    border: 1px solid #CCC; 
}

Otherwise, you'll have to use a JS selector library like jQuery, or manually add a class to the last td, as suggested by James Allardice.

org.hibernate.HibernateException: Access to DialectResolutionInfo cannot be null when 'hibernate.dialect' not set

Remove the redundant Hibernate Configuration

If you're using Spring Boot, you don't need to provide the JPA and Hibernate configuration explicitly, as Spring Boot can do that for you.

Add database configuration properties

In the application.properties Spring Boot configuration file, you have the add your database configuration properties:

spring.datasource.driverClassName = "org.postgresql.Driver
spring.datasource.url = jdbc:postgresql://localhost:5432/teste?charSet=LATIN1
spring.datasource.username = klebermo
spring.datasource.password = 123

Add Hibernate specific properties

And, in the same application.properties configuration file, you can also set custom Hibernate properties:

# Log SQL statements
spring.jpa.show-sql = false

# Hibernate ddl auto for generating the database schema
spring.jpa.hibernate.ddl-auto = create

# Hibernate database Dialect
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.PostgreSQLDialect

That's it!

OS X Bash, 'watch' command

Here's a slightly changed version of this answer that:

  • checks for valid args
  • shows a date and duration title at the top
  • moves the "duration" argument to be the 1st argument, so complex commands can be easily passed as the remaining arguments.

To use it:

  • Save this to ~/bin/watch
  • execute chmod 700 ~/bin/watch in a terminal to make it executable.
  • try it by running watch 1 echo "hi there"

~/bin/watch

#!/bin/bash

function show_help()
{
  echo ""
  echo "usage: watch [sleep duration in seconds] [command]"
  echo ""
  echo "e.g. To cat a file every second, run the following"
  echo ""
  echo "     watch 1 cat /tmp/it.txt" 
  exit;
}

function show_help_if_required()
{
  if [ "$1" == "help" ]
  then
      show_help
  fi
  if [ -z "$1" ]
    then
      show_help
  fi
}

function require_numeric_value()
{
  REG_EX='^[0-9]+$'
  if ! [[ $1 =~ $REG_EX ]] ; then
    show_help
  fi
}

show_help_if_required $1
require_numeric_value $1

DURATION=$1
shift

while :; do 
  clear
  echo "Updating every $DURATION seconds. Last updated $(date)"
  bash -c "$*"
  sleep $DURATION
done

Bootstrap Carousel Full Screen

You can do it without forcing html and body to me 100% height. Use view port height instead. And with mouse wheel control too.

_x000D_
_x000D_
function debounce(func, wait, immediate) {_x000D_
  var timeout;_x000D_
  return function() {_x000D_
    var context = this,_x000D_
      args = arguments;_x000D_
    var later = function() {_x000D_
      timeout = null;_x000D_
      if (!immediate) func.apply(context, args);_x000D_
    };_x000D_
    var callNow = immediate && !timeout;_x000D_
    clearTimeout(timeout);_x000D_
    timeout = setTimeout(later, wait);_x000D_
    if (callNow) func.apply(context, args);_x000D_
  };_x000D_
}_x000D_
_x000D_
var slider = document.getElementById("demo");_x000D_
var onScroll = debounce(function(direction) {_x000D_
  //console.log(direction);_x000D_
  if (direction == false) {_x000D_
   $('.carousel-control-next').click();_x000D_
  } else {_x000D_
   $('.carousel-control-prev').click();_x000D_
  }_x000D_
}, 100, true);_x000D_
_x000D_
slider.addEventListener("wheel", function(e) {_x000D_
  e.preventDefault();_x000D_
  var delta;_x000D_
  if (event.wheelDelta) {_x000D_
    delta = event.wheelDelta;_x000D_
  } else {_x000D_
    delta = -1 * event.deltaY;_x000D_
  }_x000D_
_x000D_
  onScroll(delta >= 0);_x000D_
});
_x000D_
.carousel-item {_x000D_
  height: 100vh;_x000D_
  background: #212121;_x000D_
}_x000D_
_x000D_
.carousel-control-next,_x000D_
.carousel-control-prev {_x000D_
  width: 8% !important;_x000D_
}_x000D_
_x000D_
.carousel-item.active,_x000D_
.carousel-item-left,_x000D_
.carousel-item-right {_x000D_
  display: flex !important;_x000D_
  justify-content: center;_x000D_
  align-items: center;_x000D_
}_x000D_
_x000D_
.carousel-item h1 {_x000D_
    color: #fff;_x000D_
    font-size: 72px;_x000D_
    padding: 0 10%;_x000D_
 }
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css" rel="stylesheet" />_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js"></script>_x000D_
_x000D_
_x000D_
<div id="demo" class="carousel slide" data-ride="carousel" data-interval="false">_x000D_
_x000D_
  <!-- The slideshow -->_x000D_
  <div class="carousel-inner">_x000D_
    <div class="carousel-item active">_x000D_
      <h1 class="display-1 text-center">Lorem ipsum dolor sit amet adipisicing</h1>_x000D_
    </div>_x000D_
    <div class="carousel-item">_x000D_
      <h1 class="display-1 text-center">Inventore omnis odio, dolore culpa atque?</h1>_x000D_
    </div>_x000D_
    <div class="carousel-item">_x000D_
     <h1 class="display-1 text-center">Lorem ipsum dolor sit</h1>_x000D_
    </div>_x000D_
  </div>_x000D_
_x000D_
  <!-- Left and right controls -->_x000D_
  <a class="carousel-control-prev" href="#demo" data-slide="prev">_x000D_
    <span class="carousel-control-prev-icon"></span>_x000D_
  </a>_x000D_
  <a class="carousel-control-next" href="#demo" data-slide="next">_x000D_
    <span class="carousel-control-next-icon"></span>_x000D_
  </a>_x000D_
_x000D_
</div>
_x000D_
_x000D_
_x000D_

convert string into array of integers

SO...older thread, I know, but...

EDIT

@RoccoMusolino had a nice catch; here's an alternative:

TL;DR:

 const intArray = [...("5 6 7 69 foo 0".split(' ').filter(i => /\d/g.test(i)))]

WRONG: "5 6 note this foo".split(" ").map(Number).filter(Boolean); // [5, 6]

There is a subtle flaw in the more elegant solutions listed here, specifically @amillara and @Marcus' otherwise beautiful answers.

The problem occurs when an element of the string array isn't integer-like, perhaps in a case without validation on an input. For a contrived example...

The problem:


var effedIntArray = "5 6 7 69 foo".split(' ').map(Number); // [5, 6, 7, 69, NaN]

Since you obviously want a PURE int array, that's a problem. Honestly, I didn't catch this until I copy-pasted SO code into my script... :/


The (slightly-less-baller) fix:


var intArray = "5 6 7 69 foo".split(" ").map(Number).filter(Boolean); // [5, 6, 7, 69]

So, now even when you have crap int string, your output is a pure integer array. The others are really sexy in most cases, but I did want to offer my mostly rambly w'actually. It is still a one-liner though, to my credit...

Hope it saves someone time!

Exit from app when click button in android phonegap?

@Pradip Kharbuja

In Cordova-2.6.0.js (l. 4032) :

exitApp:function() {
  console.log("Device.exitApp() is deprecated. Use App.exitApp().");
  app.exitApp();
}

how to hide a vertical scroll bar when not needed

overflow: auto (or overflow-y: auto) is the correct way to go.

The problem is that your text area is taller than your div. The div ends up cutting off the textbox, so even though it looks like it should start scrolling when the text is taller than 159px it won't start scrolling until the text is taller than 400px which is the height of the textbox.

Try this: http://jsfiddle.net/G9rfq/1/

I set overflow:auto on the text box, and made the textbox the same size as the div.

Also I don't believe it's valid to have a div inside a label, the browser will render it, but it might cause some funky stuff to happen. Also your div isn't closed.

How can I declare optional function parameters in JavaScript?

Update

With ES6, this is possible in exactly the manner you have described; a detailed description can be found in the documentation.

Old answer

Default parameters in JavaScript can be implemented in mainly two ways:

function myfunc(a, b)
{
    // use this if you specifically want to know if b was passed
    if (b === undefined) {
        // b was not passed
    }
    // use this if you know that a truthy value comparison will be enough
    if (b) {
        // b was passed and has truthy value
    } else {
        // b was not passed or has falsy value
    }
    // use this to set b to a default value (using truthy comparison)
    b = b || "default value";
}

The expression b || "default value" evaluates the value AND existence of b and returns the value of "default value" if b either doesn't exist or is falsy.

Alternative declaration:

function myfunc(a)
{
    var b;

    // use this to determine whether b was passed or not
    if (arguments.length == 1) {
        // b was not passed
    } else {
        b = arguments[1]; // take second argument
    }
}

The special "array" arguments is available inside the function; it contains all the arguments, starting from index 0 to N - 1 (where N is the number of arguments passed).

This is typically used to support an unknown number of optional parameters (of the same type); however, stating the expected arguments is preferred!

Further considerations

Although undefined is not writable since ES5, some browsers are known to not enforce this. There are two alternatives you could use if you're worried about this:

b === void 0;
typeof b === 'undefined'; // also works for undeclared variables

Spring MVC - HttpMediaTypeNotAcceptableException

response.setHeader("Accept",  "application/json");

Android - how do I investigate an ANR?

Consider using the ANR-Watchdog library to accurately track and capture ANR stack traces in a high level of detail. You can then send them to your crash reporting library. I recommend using setReportMainThreadOnly() in this scenario. You can either make the app throw a non-fatal exception of the freeze point, or make the app force quit when the ANR happens.

Note that the standard ANR reports sent to your Google Play Developer console are often not accurate enough to pinpoint the exact problem. That's why a third-party library is needed.

Removing duplicates from rows based on specific columns in an RDD/Spark DataFrame

The below programme will help you drop duplicates on whole , or if you want to drop duplicates based on certain columns , you can even do that:

import org.apache.spark.sql.SparkSession

object DropDuplicates {
def main(args: Array[String]) {
val spark =
  SparkSession.builder()
    .appName("DataFrame-DropDuplicates")
    .master("local[4]")
    .getOrCreate()

import spark.implicits._

// create an RDD of tuples with some data
val custs = Seq(
  (1, "Widget Co", 120000.00, 0.00, "AZ"),
  (2, "Acme Widgets", 410500.00, 500.00, "CA"),
  (3, "Widgetry", 410500.00, 200.00, "CA"),
  (4, "Widgets R Us", 410500.00, 0.0, "CA"),
  (3, "Widgetry", 410500.00, 200.00, "CA"),
  (5, "Ye Olde Widgete", 500.00, 0.0, "MA"),
  (6, "Widget Co", 12000.00, 10.00, "AZ")
)
val customerRows = spark.sparkContext.parallelize(custs, 4)

// convert RDD of tuples to DataFrame by supplying column names
val customerDF = customerRows.toDF("id", "name", "sales", "discount", "state")

println("*** Here's the whole DataFrame with duplicates")

customerDF.printSchema()

customerDF.show()

// drop fully identical rows
val withoutDuplicates = customerDF.dropDuplicates()

println("*** Now without duplicates")

withoutDuplicates.show()

// drop fully identical rows
val withoutPartials = customerDF.dropDuplicates(Seq("name", "state"))

println("*** Now without partial duplicates too")

withoutPartials.show()

 }
 }

How do you decompile a swf file

Usually 'lost' is a euphemism for "We stopped paying the developer and now he wont give us the source code."

That being said, I own a copy of Burak's ActionScript Viewer, and it works pretty well. A simple google search will find you many other SWF decompilers.

Removing numbers from string

If i understand your question right, one way to do is break down the string in chars and then check each char in that string using a loop whether it's a string or a number and then if string save it in a variable and then once the loop is finished, display that to the user

How do I update Homebrew?

Alternatively you could update brew by installing it again. (Think I did this as El Capitan changed something)

Note: this is a heavy handed approach that will remove all applications installed via brew!

Try to install brew a fresh and it will tell how to uninstall.

At original time of writing to uninstall:

ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/uninstall)"

Edit: As of 2020 to uninstall:

/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/uninstall.sh)"

Color text in discord

Discord doesn't allow colored text. Though, currently, you have two options to "mimic" colored text.

Option #1 (Markdown code-blocks)

Discord supports Markdown and uses highlight.js to highlight code-blocks. Some programming languages have specific color outputs from highlight.js and can be used to mimic colored output.

To use code-blocks, send a normal message in this format (Which follows Markdown's standard format).

```language
message
```

Languages that currently reproduce nice colors: prolog (red/orange), css (yellow).

Option #2 (Embeds)

Discord now supports Embeds and Webhooks, which can be used to display colored blocks, they also support markdown. For documentation on how to use Embeds, please read your lib's documentation.

(Embed Cheat-sheet)
Embed Cheat-sheet

How to close a GUI when I push a JButton?

See JFrame.setDefaultCloseOperation(DISPOSE_ON_CLOSE)1. You might also use EXIT_ON_CLOSE, but it is better to explicitly clean up any running threads, then when the last GUI element becomes invisible, the EDT & JRE will end.

The 'button' to invoke this operation is already on a frame.

  1. See this answer to How to best position Swing GUIs? for a demo. of the DISPOSE_ON_CLOSE functionality.

    The JRE will end after all 3 frames are closed by clicking the X button.

Loading a .json file into c# program

I have done it like:

            using (StreamReader sr = File.OpenText(jsonFilePath))
            {
                var myObject = JsonConvert.DeserializeObject<List<YourObject>>(sr.ReadToEnd());
            }

also, you can do this with async call like: sr.ReadToEndAsync(). using Newtonsoft.Json as reference.

Hope, this helps.

Non-Static method cannot be referenced from a static context with methods and variables

You can either

1) Declare printMenu(), getUserchoice() and input as static

OR

2) If you want to design it better, move the logic from your main into a separate instance method. And then from the main create a new instance of your class and call your instance method(s)

Add days Oracle SQL

In a more general way you can use "INTERVAL". Here some examples:

1) add a day

select sysdate + INTERVAL '1' DAY from dual;

2) add 20 days

select sysdate + INTERVAL '20' DAY from dual;

2) add some minutes

select sysdate + INTERVAL '15' MINUTE from dual;

Most efficient way to append arrays in C#?

The solution looks like great fun, but it is possible to concatenate arrays in just two statements. When you're handling large byte arrays, I suppose it is inefficient to use a Linked List to contain each byte.

Here is a code sample for reading bytes from a stream and extending a byte array on the fly:

    byte[] buf = new byte[8192];
    byte[] result = new byte[0];
    int count = 0;
    do
    {
        count = resStream.Read(buf, 0, buf.Length);
        if (count != 0)
        {
            Array.Resize(ref result, result.Length + count);
            Array.Copy(buf, 0, result, result.Length - count, count);
        }
    }
    while (count > 0); // any more data to read?
    resStream.Close();

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

Aligning Three Divs Horizontally Using Flexbox

Here is a CSS3 method for aligning divs horizontally inside another div.

_x000D_
_x000D_
#container {_x000D_
  display: flex;                  /* establish flex container */_x000D_
  flex-direction: row;            /* default value; can be omitted */_x000D_
  flex-wrap: nowrap;              /* default value; can be omitted */_x000D_
  justify-content: space-between; /* switched from default (flex-start, see below) */_x000D_
  background-color: lightyellow;_x000D_
}_x000D_
#container > div {_x000D_
  width: 100px;_x000D_
  height: 100px;_x000D_
  border: 2px dashed red;_x000D_
}
_x000D_
<div id="container">_x000D_
  <div></div>_x000D_
  <div></div>_x000D_
  <div></div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

jsFiddle

The justify-content property takes five values:

  • flex-start (default)
  • flex-end
  • center
  • space-between
  • space-around

In all cases, the three divs are on the same line. For a description of each value see: https://stackoverflow.com/a/33856609/3597276


Benefits of flexbox:

  1. minimal code; very efficient
  2. centering, both vertically and horizontally, is simple and easy
  3. equal height columns are simple and easy
  4. multiple options for aligning flex elements
  5. it's responsive
  6. unlike floats and tables, which offer limited layout capacity because they were never intended for building layouts, flexbox is a modern (CSS3) technique with a broad range of options.

To learn more about flexbox visit:


Browser support: Flexbox is supported by all major browsers, except IE < 10. Some recent browser versions, such as Safari 8 and IE10, require vendor prefixes. For a quick way to add prefixes use Autoprefixer. More details in this answer.

Differences between JDK and Java SDK

I think jdk has certain features which can be used along with particular framework. Well call it SDK as a whole.

Like Android or Blackberry both use java along with their framework.

Detect and exclude outliers in Pandas data frame

For each of your dataframe column, you could get quantile with:

q = df["col"].quantile(0.99)

and then filter with:

df[df["col"] < q]

If one need to remove lower and upper outliers, combine condition with an AND statement:

q_low = df["col"].quantile(0.01)
q_hi  = df["col"].quantile(0.99)

df_filtered = df[(df["col"] < q_hi) & (df["col"] > q_low)]

Execute a large SQL script (with GO commands)

If you don't want to install SMO objects you can use gplex tool (see this answer)

Create a date from day month and year with T-SQL

Assuming y, m, d are all int, how about:

CAST(CAST(y AS varchar) + '-' + CAST(m AS varchar) + '-' + CAST(d AS varchar) AS DATETIME)

Please see my other answer for SQL Server 2012 and above

MVC 4 Razor File Upload

The Upload method's HttpPostedFileBase parameter must have the same name as the the file input.

So just change the input to this:

<input type="file" name="file" />

Also, you could find the files in Request.Files:

[HttpPost]
public ActionResult Upload()
{
     if (Request.Files.Count > 0)
     {
         var file = Request.Files[0];

         if (file != null && file.ContentLength > 0)
         {
            var fileName = Path.GetFileName(file.FileName);
            var path = Path.Combine(Server.MapPath("~/Images/"), fileName);
            file.SaveAs(path);
         }
     }

     return RedirectToAction("UploadDocument");
 }

Reading json files in C++

Here is another easier possibility to read in a json file:

#include "json/json.h"

std::ifstream file_input("input.json");
Json::Reader reader;
Json::Value root;
reader.parse(file_input, root);
cout << root;

You can then get the values like this:

cout << root["key"]

Items in JSON object are out of order using "json.dumps"?

in JSON, as in Javascript, order of object keys is meaningless, so it really doesn't matter what order they're displayed in, it is the same object.

Split string with JavaScript

var wrapper = $(document.body);

strings = [
    "19 51 2.108997",
    "20 47 2.1089"
];

$.each(strings, function(key, value) {
    var tmp = value.split(" ");
    $.each([
        tmp[0] + " " + tmp[1],
        tmp[2]
    ], function(key, value) {
        $("<span>" + value + "</span>").appendTo(wrapper);
    }); 
});

OnItemClickListener using ArrayAdapter for ListView

Use OnItemClickListener

   ListView lv = getListView();
   lv.setOnItemClickListener(new OnItemClickListener()
   {
      @Override
      public void onItemClick(AdapterView<?> adapter, View v, int position,
            long arg3) 
      {
            String value = (String)adapter.getItemAtPosition(position); 
            // assuming string and if you want to get the value on click of list item
            // do what you intend to do on click of listview row
      }
   });

When you click on a row a listener is fired. So you setOnClickListener on the listview and use the annonymous inner class OnItemClickListener.

You also override onItemClick. The first param is a adapter. Second param is the view. third param is the position ( index of listview items).

Using the position you get the item .

Edit : From your comments i assume you need to set the adapter o listview

So assuming your activity extends ListActivtiy

     setListAdapter(adapter); 

Or if your activity class extends Activity

     ListView lv = (ListView) findViewById(R.id.listview1);
     //initialize adapter 
     lv.setAdapter(adapter); 

How to find and restore a deleted file in a Git repository

To restore all those deleted files in a folder, enter the following command.

git ls-files -d | xargs git checkout --

How to run an external program, e.g. notepad, using hyperlink?

Try this

<html>
    <head>
        <script type="text/javascript">
        function runProgram()
        {
            var shell = new ActiveXObject("WScript.Shell");                 
            var appWinMerge = "\"C:\\Program Files\\WinMerge\\WinMergeU.exe\" /e /s /u /wl /wr /maximize";
            var fileLeft = "\"D:\\Path\\to\\your\\file\"";
            var fileRight= "\"D:\\Path\\to\\your\\file2\"";
            shell.Run(appWinMerge + " " + fileLeft + " " + fileRight);
        }
        </script>
    </head>

    <body>
        <a href="javascript:runProgram()">Run program</a>
    </body>
</html>

How to clear the cache of nginx?

In my case, touch that Css file, make it looks like resources changed (actually touch does nothing to the file, except change last modify time), so browser and nginx will apply latest resources

Vim clear last search highlighting

To turn off highlighting until the next search

:noh

Visual Illustration

Repeat string to certain length

How about string * (length / len(string)) + string[0:(length % len(string))]

How to stop BackgroundWorker correctly

The problem is caused by the fact that cmbDataSourceExtractor.CancelAsync() is an asynchronous method, the Cancel operation has not yet completed when cmdDataSourceExtractor.RunWorkerAsync(...) exitst. You should wait for cmdDataSourceExtractor to complete before calling RunWorkerAsync again. How to do this is explained in this SO question.

Find the files that have been changed in last 24 hours

For others who land here in the future (including myself), add a -name option to find specific file types, for instance: find /var -name "*.php" -mtime -1 -ls

Self-references in object literals / initializers

Well, the only thing that I can tell you about are getter:

_x000D_
_x000D_
var foo = {_x000D_
  a: 5,_x000D_
  b: 6,_x000D_
  get c() {_x000D_
    return this.a + this.b;_x000D_
  }_x000D_
}_x000D_
_x000D_
console.log(foo.c) // 11
_x000D_
_x000D_
_x000D_

This is a syntactic extension introduced by the ECMAScript 5th Edition Specification, the syntax is supported by most modern browsers (including IE9).

jQuery CSS Opacity

jQuery('#main').css('opacity') = '0.6';

should be

jQuery('#main').css('opacity', '0.6');

Update:

http://jsfiddle.net/GegMk/ if you type in the text box. Click away, the opacity changes.

How to loop through array in jQuery?

You can use a for() loop:

var things = currnt_image_list.split(','); 
for(var i = 0; i < things.length; i++) {
    //Do things with things[i]
}

With android studio no jvm found, JAVA_HOME has been set

Though, the question is asked long back, I see this same issue recently after installing Android Studio 2.1.0v, and JDK 7.80 on my PC Windows 10, 32 bit OS. I got this error.

No JVM installation found. Please install a 32 bit JDK. If you already have a JDK installed define a JAVA_HOME variable in Computer > System Properties > System Settings > Environment Variables.

I tried different ways to fix this nothing worked. But As per System Requirements in this Android developer website link.

Its solved after installing JDK 8(jdk-8u101-windows-i586.exe) JDK download site link.

Hope it helps somebody.

Android 8.0: java.lang.IllegalStateException: Not allowed to start service Intent

Alternate solution by using JobScheduler, it can start service in background in regular interval of time.

Firstly make class named as Util.java

import android.app.job.JobInfo;
import android.app.job.JobScheduler;
import android.content.ComponentName;
import android.content.Context;

public class Util {
// schedule the start of the service every 10 - 30 seconds
public static void schedulerJob(Context context) {
    ComponentName serviceComponent = new ComponentName(context,TestJobService.class);
    JobInfo.Builder builder = new JobInfo.Builder(0,serviceComponent);
    builder.setMinimumLatency(1*1000);    // wait at least
    builder.setOverrideDeadline(3*1000);  //delay time
    builder.setRequiredNetworkType(JobInfo.NETWORK_TYPE_UNMETERED);  // require unmetered network
    builder.setRequiresCharging(false);  // we don't care if the device is charging or not
    builder.setRequiresDeviceIdle(true); // device should be idle
    System.out.println("(scheduler Job");

    JobScheduler jobScheduler = null;
    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
        jobScheduler = context.getSystemService(JobScheduler.class);
    }
    jobScheduler.schedule(builder.build());
   }
  }

Then, make JobService class named as TestJobService.java

import android.app.job.JobParameters;
import android.app.job.JobService;
import android.widget.Toast;
 
  /**
   * JobService to be scheduled by the JobScheduler.
   * start another service
   */ 
public class TestJobService extends JobService {
@Override
public boolean onStartJob(JobParameters params) {
    Util.schedulerJob(getApplicationContext()); // reschedule the job
    Toast.makeText(this, "Bg Service", Toast.LENGTH_SHORT).show();
    return true;
}

@Override
public boolean onStopJob(JobParameters params) {
    return true;
  }
 }

After that BroadCast Receiver class named ServiceReceiver.java

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;

 public class ServiceReceiver extends BroadcastReceiver {
 @Override
public void onReceive(Context context, Intent intent) {
    Util.schedulerJob(context);
 }
}

Update Manifest file with service and receiver class code

<receiver android:name=".ServiceReceiver" >
        <intent-filter>
            <action android:name="android.intent.action.BOOT_COMPLETED" />
        </intent-filter>
    </receiver>
    <service
        android:name=".TestJobService"
        android:label="Word service"
        android:permission="android.permission.BIND_JOB_SERVICE" >

    </service>

Left main_intent launcher to mainActivity.java file which is created by default, and changes in MainActivity.java file are

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Util.schedulerJob(getApplicationContext());
  }
 }

WOOAAH!! Background Service starts without Foreground service

[Edit]: You can use Work Manager for any type of background tasks in Android.

Detect Safari browser

This unique "issue" is 100% sign that browser is Safari (believe it or not).

if (Object.getOwnPropertyDescriptor(Document.prototype, 'cookie').descriptor === false) {
   console.log('Hello Safari!');
}

This means that cookie object descriptor is set to false on Safari while on the all other is true, which is actually giving me a headache on the other project. Happy coding!

How to escape a JSON string containing newline characters using JavaScript?

Use encodeURIComponent() to encode the string.

Eg. var myEscapedJSONString = encodeURIComponent(JSON.stringify(myJSON));

You don't need to decode it since the web server automatically do the same.

How to get HttpClient to pass credentials along with the request?

Ok so I took Joshoun code and made it generic. I am not sure if I should implement singleton pattern on SynchronousPost class. Maybe someone more knowledgeble can help.

Implementation

//I assume you have your own concrete type. In my case I have am using code first with a class called FileCategory

FileCategory x = new FileCategory { CategoryName = "Some Bs"};
SynchronousPost<FileCategory>test= new SynchronousPost<FileCategory>();
test.PostEntity(x, "/api/ApiFileCategories"); 

Generic Class here. You can pass any type

 public class SynchronousPost<T>where T :class
    {
        public SynchronousPost()
        {
            Client = new WebClient { UseDefaultCredentials = true };
        }

        public void PostEntity(T PostThis,string ApiControllerName)//The ApiController name should be "/api/MyName/"
        {
            //this just determines the root url. 
            Client.BaseAddress = string.Format(
         (
            System.Web.HttpContext.Current.Request.Url.Port != 80) ? "{0}://{1}:{2}" : "{0}://{1}",
            System.Web.HttpContext.Current.Request.Url.Scheme,
            System.Web.HttpContext.Current.Request.Url.Host,
            System.Web.HttpContext.Current.Request.Url.Port
           );
            Client.Headers.Add(HttpRequestHeader.ContentType, "application/json;charset=utf-8");
            Client.UploadData(
                                 ApiControllerName, "Post", 
                                 Encoding.UTF8.GetBytes
                                 (
                                    JsonConvert.SerializeObject(PostThis)
                                 )
                             );  
        }
        private WebClient Client  { get; set; }
    }

My Api classs looks like this, if you are curious

public class ApiFileCategoriesController : ApiBaseController
{
    public ApiFileCategoriesController(IMshIntranetUnitOfWork unitOfWork)
    {
        UnitOfWork = unitOfWork;
    }

    public IEnumerable<FileCategory> GetFiles()
    {
        return UnitOfWork.FileCategories.GetAll().OrderBy(x=>x.CategoryName);
    }
    public FileCategory GetFile(int id)
    {
        return UnitOfWork.FileCategories.GetById(id);
    }
    //Post api/ApileFileCategories

    public HttpResponseMessage Post(FileCategory fileCategory)
    {
        UnitOfWork.FileCategories.Add(fileCategory);
        UnitOfWork.Commit(); 
        return new HttpResponseMessage();
    }
}

I am using ninject, and repo pattern with unit of work. Anyways, the generic class above really helps.

Decimal or numeric values in regular expression validation

Here is my regex for validating numbers:

^(-?[1-9]+\\d*([.]\\d+)?)$|^(-?0[.]\\d*[1-9]+)$|^0$

Valid numbers:

String []validNumbers={"3","-3","0","0.0","1.0","0.1","0.0001","-555","94549870965"};

Invalid numbers:

String []invalidNumbers={"a",""," ","-","001","-00.2","000.5",".3","3."," -1","--1","-.1","-0"};

Python: Checking if a 'Dictionary' is empty doesn't seem to work

Empty dictionaries evaluate to False in Python:

>>> dct = {}
>>> bool(dct)
False
>>> not dct
True
>>>

Thus, your isEmpty function is unnecessary. All you need to do is:

def onMessage(self, socket, message):
    if not self.users:
        socket.send("Nobody is online, please use REGISTER command" \
                    " in order to register into the server")
    else:
        socket.send("ONLINE " + ' ' .join(self.users.keys()))

Angular 2: How to style host element of the component?

There was a bug, but it was fixed in the meantime. :host { } works fine now.

Also supported are

  • :host(selector) { ... } for selector to match attributes, classes, ... on the host element
  • :host-context(selector) { ... } for selector to match elements, classes, ...on parent components

  • selector /deep/ selector (alias selector >>> selector doesn't work with SASS) for styles to match across element boundaries

    • UPDATE: SASS is deprecating /deep/.
      Angular (TS and Dart) added ::ng-deep as a replacement that's also compatible with SASS.

    • UPDATE2: ::slotted ::slotted is now supported by all new browsers and can be used with `ViewEncapsulation.ShadowDom
      https://developer.mozilla.org/en-US/docs/Web/CSS/::slotted

See also Load external css style into Angular 2 Component

/deep/ and >>> are not affected by the same selector combinators that in Chrome which are deprecated.
Angular emulates (rewrites) them, and therefore doesn't depend on browsers supporting them.

This is also why /deep/ and >>> don't work with ViewEncapsulation.Native which enables native shadow DOM and depends on browser support.

Get value when selected ng-option changes

You will get selected option's value and text from list/array by using filter.
editobj.FlagName=(EmployeeStatus|filter:{Value:editobj.Flag})[0].KeyName

<select name="statusSelect"
      id="statusSelect"
      class="form-control"
      ng-model="editobj.Flag"
      ng-options="option.Value as option.KeyName for option in EmployeeStatus"
      ng-change="editobj.FlagName=(EmployeeStatus|filter:{Value:editobj.Flag})[0].KeyName">
</select>

Is Java "pass-by-reference" or "pass-by-value"?

I see that all answers contain the same: pass by value. However, a recent Brian Goetz update on project Valhalla actually answers it differently:

Indeed, it is a common “gotcha” question about whether Java objects are passed by value or by reference, and the answer is “neither”: object references are passed by value.

You can read more here: State of Valhalla. Section 2: Language Model

Edit: Brian Goetz is Java Language Architect, leading such projects as Project Valhalla and Project Amber.

Edit-2020-12-08: Updated State of Valhalla

How to get these two divs side-by-side?

Using the style

.child_div_1 {
    float:left
}

Converting a String to a List of Words?

A regular expression for words would give you the most control. You would want to carefully consider how to deal with words with dashes or apostrophes, like "I'm".

Error : Program type already present: android.support.design.widget.CoordinatorLayout$Behavior

Important Update

Android support libraries will not be updated after 28.0.0. According to Support Library Release Notes -

This will be the last feature release under the android.support packaging, and developers are encouraged to migrate to AndroidX 1.0.0.

So use AndroidX support libraries instead. In your case design library is now available in material package.

dependencies {
    implementation 'com.google.android.material:material:1.0.0' // instead of design
    implementation 'androidx.appcompat:appcompat:1.0.2' // instead of support-v7
}

I have put latest versions in dependency, you can check latest version here at read time.

Useful Posts :

  1. AndroidX introduction & integration
  2. Learn about Jetifier (engine behind AndroidX migration)
  3. Some Do's and Dont's

Remove duplicate values from JS array

I know Im a little late, but here is another option using jinqJs

See Fiddle

var result = jinqJs().from(["Mike","Matt","Nancy","Adam","Jenny","Nancy","Carl"]).distinct().select();

cartesian product in pandas

Presenting to you

pandas >= 1.2

left.merge(right, how='cross')

import pandas as pd 

pd.__version__
# '1.2.0'

left = pd.DataFrame({'col1': [1, 2], 'col2': [3, 4]})
right = pd.DataFrame({'col3': [5, 6]}) 

left.merge(right, how='cross')

   col1  col2  col3
0     1     3     5
1     1     3     6
2     2     4     5
3     2     4     6

Indexes are ignored in the result.

Implementation wise, this uses the join on common key column method as described in the accepted answer. The upsides of using the API is that it saves you a lot of typing and handles some corner cases pretty well. I'd almost always recommend this syntax as my first preference for cartesian product in pandas unless you're looking for something more performant.

Detect whether there is an Internet connection available on Android

The getActiveNetworkInfo() method of ConnectivityManager returns a NetworkInfo instance representing the first connected network interface it can find or null if none if the interfaces are connected. Checking if this method returns null should be enough to tell if an internet connection is available.

private boolean isNetworkAvailable() {
     ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
     NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
     return activeNetworkInfo != null; 
}

You will also need:

in your android manifest.

Edit:

Note that having an active network interface doesn't guarantee that a particular networked service is available. Networks issues, server downtime, low signal, captive portals, content filters and the like can all prevent your app from reaching a server. For instance you can't tell for sure if your app can reach Twitter until you receive a valid response from the Twitter service.

getActiveNetworkInfo() shouldn't never give null. I don't know what they were thinking when they came up with that. It should give you an object always.

How to export a Vagrant virtual machine to transfer it

As of 2019 there is a subcommand: vagrant box repackage

vagrant box repackage --help 
Usage: vagrant box repackage <name> <provider> <version>
    -h, --help                       Print this help

You can find name provider and version by running vagrant box list

vagrant box list
macinbox (virtualbox, 10.14.5)

The ouput of vagrant box repackage is a file called package.box which is basically a tgz file which the content can be listed as below:

tar tzf package.box
./metadata.json
./box.ovf
./Vagrantfile
./box-disk001.vmdk

Entity Framework VS LINQ to SQL VS ADO.NET with stored procedures?

your question is basically O/RM's vs hand writing SQL

Using an ORM or plain SQL?

Take a look at some of the other O/RM solutions out there, L2S isn't the only one (NHibernate, ActiveRecord)

http://en.wikipedia.org/wiki/List_of_object-relational_mapping_software

to address the specific questions:

  1. Depends on the quality of the O/RM solution, L2S is pretty good at generating SQL
  2. This is normally much faster using an O/RM once you grok the process
  3. Code is also usually much neater and more maintainable
  4. Straight SQL will of course get you more flexibility, but most O/RM's can do all but the most complicated queries
  5. Overall I would suggest going with an O/RM, the flexibility loss is negligable

nginx upload client_max_body_size issue

From the documentation:

It is necessary to keep in mind that the browsers do not know how to correctly show this error.

I suspect this is what's happening, if you inspect the HTTP to-and-fro using tools such as Firebug or Live HTTP Headers (both Firefox extensions) you'll be able to see what's really going on.

List directory in Go

You can try using the ReadDir function in the io/ioutil package. Per the docs:

ReadDir reads the directory named by dirname and returns a list of sorted directory entries.

The resulting slice contains os.FileInfo types, which provide the methods listed here. Here is a basic example that lists the name of everything in the current directory (folders are included but not specially marked - you can check if an item is a folder by using the IsDir() method):

package main

import (
    "fmt"
    "io/ioutil"
     "log"
)

func main() {
    files, err := ioutil.ReadDir("./")
    if err != nil {
        log.Fatal(err)
    }
 
    for _, f := range files {
            fmt.Println(f.Name())
    }
}

Undefined index error PHP

To remove this error, in your html form you should do the following in enctype:

<form  enctype="multipart/form-data">

The following down is the cause of that error i.e if you start with form-data in enctype, so you should start with multipart:

<form enctype="form-data/multipart">

Converting bool to text in C++

With C++11 you might use a lambda to get a slightly more compact code and in place usage:

bool to_convert{true};
auto bool_to_string = [](bool b) -> std::string {
    return b ? "true" : "false";
};
std::string str{"string to print -> "};
std::cout<<str+bool_to_string(to_convert);

Prints:

string to print -> true

How to strip a specific word from a string?

A bit 'lazy' way to do this is to use startswith- it is easier to understand this rather regexps. However regexps might work faster, I haven't measured.

>>> papa = "papa is a good man"
>>> app = "app is important"
>>> strip_word = 'papa'
>>> papa[len(strip_word):] if papa.startswith(strip_word) else papa
' is a good man'
>>> app[len(strip_word):] if app.startswith(strip_word) else app
'app is important'

MySql export schema without data

You can do with the --no-data option with mysqldump command

mysqldump -h yourhostnameorIP -u root -p --no-data dbname > schema.sql

How do I sum values in a column that match a given condition using pandas?

The essential idea here is to select the data you want to sum, and then sum them. This selection of data can be done in several different ways, a few of which are shown below.

Boolean indexing

Arguably the most common way to select the values is to use Boolean indexing.

With this method, you find out where column 'a' is equal to 1 and then sum the corresponding rows of column 'b'. You can use loc to handle the indexing of rows and columns:

>>> df.loc[df['a'] == 1, 'b'].sum()
15

The Boolean indexing can be extended to other columns. For example if df also contained a column 'c' and we wanted to sum the rows in 'b' where 'a' was 1 and 'c' was 2, we'd write:

df.loc[(df['a'] == 1) & (df['c'] == 2), 'b'].sum()

Query

Another way to select the data is to use query to filter the rows you're interested in, select column 'b' and then sum:

>>> df.query("a == 1")['b'].sum()
15

Again, the method can be extended to make more complicated selections of the data:

df.query("a == 1 and c == 2")['b'].sum()

Note this is a little more concise than the Boolean indexing approach.

Groupby

The alternative approach is to use groupby to split the DataFrame into parts according to the value in column 'a'. You can then sum each part and pull out the value that the 1s added up to:

>>> df.groupby('a')['b'].sum()[1]
15

This approach is likely to be slower than using Boolean indexing, but it is useful if you want check the sums for other values in column a:

>>> df.groupby('a')['b'].sum()
a
1    15
2     8

Sorting a list using Lambda/Linq to objects

This can be done as

list.Sort( (emp1,emp2)=>emp1.FirstName.CompareTo(emp2.FirstName) );

The .NET framework is casting the lambda (emp1,emp2)=>int as a Comparer<Employee>.

This has the advantage of being strongly typed.

Nginx not picking up site in sites-enabled?

Changing from:

include /etc/nginx/sites-enabled/*; 

to

include /etc/nginx/sites-enabled/*.*; 

fixed my issue

When should null values of Boolean be used?

The best way would be to avoid booleans completely, since every boolean implies that you have a conditional statement anywhere else in your code (see http://www.antiifcampaign.com/ and this question: Can you write any algorithm without an if statement?).

However, pragmatically you have to use booleans from time to time, but, as you have already found out by yourself, dealing with Booleans is more error prone and more cumbersome. So I would suggest using booleans wherever possible. Exceptions from this might be a legacy database with nullable boolean-columns, although I would try to hide that in my mapping as well.

DLL Load Library - Error Code 126

Windows dll error 126 can have many root causes. The most useful methods I have found to debug this are:

  1. Use dependency walker to look for any obvious problems (which you have already done)
  2. Use the sysinternals utility Process Monitor http://technet.microsoft.com/en-us/sysinternals/bb896645 from Microsoft to trace all file access while your dll is trying to load. With this utility, you will see everything that that dll is trying to pull in and usually the problem can be determined from there.

Python list sort in descending order

you simple type:

timestamps.sort()
timestamps=timestamps[::-1]

C# Creating and using Functions

Because your function is an instance or non-static function you should create an object first.

Program p=new Program();
p.Add(1,1)

PHP Redirect with POST data

I know this is an old question, but I have yet another alternative solution with jQuery:

var actionForm = $('<form>', {'action': 'nextpage.php', 'method': 'post'}).append($('<input>', {'name': 'action', 'value': 'delete', 'type': 'hidden'}), $('<input>', {'name': 'id', 'value': 'some_id', 'type': 'hidden'}));
actionForm.submit();

The above code uses jQuery to create a form tag, appending hidden fields as post fields, and submit it at last. The page will forward to the form target page with the POST data attached.

p.s. JavaScript & jQuery are required for this case. As suggested by the comments of the other answers, you can make use of <noscript> tag to create a standard HTML form in case JS is disabled.

How can I center <ul> <li> into div

Just add text-align: center; to your <ul>. Problem solved.

How can I change a button's color on hover?

Seems your selector is wrong, try using:

a.button:hover{
     background: #383;
}

Your code

a.button a:hover

Means it is going to search for an a element inside a with class button.

Why does visual studio 2012 not find my tests?

I was experiencing this issue many times when I try to build the solution in a different PC.

I am using NUnit and Specflow as well. By default My test project targets X86 But I have to change this to X64. Steps are 1. Test Menu -> Test Setting -Default Processor Architecture -> x64. 2. Clean Build 3. Build 4. If still tests didn't show up. 5. Go to Tools ? Extensions and Updates Then Install NUnit and Specflow libraries 6. Clean Build 7. Build

Then usually test will showed up in Test Editor.

height style property doesn't work in div elements

Set positioning to absolute. That will solve the problem immediately, but might cause some problems in layout later. You can always figure out a way around them ;)

Example:

position:absolute;

Given an RGB value, how do I create a tint (or shade)?

Some definitions

  • A shade is produced by "darkening" a hue or "adding black"
  • A tint is produced by "ligthening" a hue or "adding white"

Creating a tint or a shade

Depending on your Color Model, there are different methods to create a darker (shaded) or lighter (tinted) color:

  • RGB:

    • To shade:

      newR = currentR * (1 - shade_factor)
      newG = currentG * (1 - shade_factor)
      newB = currentB * (1 - shade_factor)
      
    • To tint:

      newR = currentR + (255 - currentR) * tint_factor
      newG = currentG + (255 - currentG) * tint_factor
      newB = currentB + (255 - currentB) * tint_factor
      
    • More generally, the color resulting in layering a color RGB(currentR,currentG,currentB) with a color RGBA(aR,aG,aB,alpha) is:

      newR = currentR + (aR - currentR) * alpha
      newG = currentG + (aG - currentG) * alpha
      newB = currentB + (aB - currentB) * alpha
      

    where (aR,aG,aB) = black = (0,0,0) for shading, and (aR,aG,aB) = white = (255,255,255) for tinting

  • HSV or HSB:

    • To shade: lower the Value / Brightness or increase the Saturation
    • To tint: lower the Saturation or increase the Value / Brightness
  • HSL:
    • To shade: lower the Lightness
    • To tint: increase the Lightness

There exists formulas to convert from one color model to another. As per your initial question, if you are in RGB and want to use the HSV model to shade for example, you can just convert to HSV, do the shading and convert back to RGB. Formula to convert are not trivial but can be found on the internet. Depending on your language, it might also be available as a core function :

Comparing the models

  • RGB has the advantage of being really simple to implement, but:
    • you can only shade or tint your color relatively
    • you have no idea if your color is already tinted or shaded
  • HSV or HSB is kind of complex because you need to play with two parameters to get what you want (Saturation & Value / Brightness)
  • HSL is the best from my point of view:
    • supported by CSS3 (for webapp)
    • simple and accurate:
      • 50% means an unaltered Hue
      • >50% means the Hue is lighter (tint)
      • <50% means the Hue is darker (shade)
    • given a color you can determine if it is already tinted or shaded
    • you can tint or shade a color relatively or absolutely (by just replacing the Lightness part)

Get environment variable value in Dockerfile

You should use the ARG directive in your Dockerfile which is meant for this purpose.

The ARG instruction defines a variable that users can pass at build-time to the builder with the docker build command using the --build-arg <varname>=<value> flag.

So your Dockerfile will have this line:

ARG request_domain

or if you'd prefer a default value:

ARG request_domain=127.0.0.1

Now you can reference this variable inside your Dockerfile:

ENV request_domain=$request_domain

then you will build your container like so:

$ docker build --build-arg request_domain=mydomain Dockerfile


Note 1: Your image will not build if you have referenced an ARG in your Dockerfile but excluded it in --build-arg.

Note 2: If a user specifies a build argument that was not defined in the Dockerfile, the build outputs a warning:

[Warning] One or more build-args [foo] were not consumed.

Node JS Error: ENOENT

use "temp" in lieu of "tmp"

"/temp/test.png"

it worked for me after i realized the tmp is a temporary folder that didn't exist on my computer, but my temp was my temporary folder

///

EDIT:

I also created a new folder "tmp" in my C: drive and everything worked perfectly. The book may have missed mentioning that small step

check out http://webchat.freenode.net/?channels=node.js to chat with some of the node.js community

Validate that end date is greater than start date with jQuery

First you split the values of two input box by using split function. then concat the same in reverse order. after concat nation parse it to integer. then compare two values in in if statement. eg.1>20-11-2018 2>21-11-2018

after split and concat new values for comparison 20181120 and 20181121 the after that compare the same.

var date1 = $('#datevalue1').val();
var date2 = $('#datevalue2').val();
var d1 = date1.split("-");
var d2 = date2.split("-");

d1 = d1[2].concat(d1[1], d1[0]);
d2 = d2[2].concat(d2[1], d2[0]);

if (parseInt(d1) > parseInt(d2)) {

    $('#fromdatepicker').val('');
} else {

}

Spring: return @ResponseBody "ResponseEntity<List<JSONObject>>"

Instead of

return new ResponseEntity<JSONObject>(entities, HttpStatus.OK);

try

return new ResponseEntity<List<JSONObject>>(entities, HttpStatus.OK);

How do I center an SVG in a div?

Flexbox is another approach: add

_x000D_
_x000D_
.container {
  display: flex;
  justify-content: center;
}
_x000D_
_x000D_
_x000D_

And add the .container class to the div which contains your svg.

How to Correctly Use Lists in R?

This is a very old question, but I think that a new answer might add some value since, in my opinion, no one directly addressed some of the concerns in the OP.

Despite what the accepted answer suggests, list objects in R are not hash maps. If you want to make a parallel with python, list are more like, you guess, python lists (or tuples actually).

It's better to describe how most R objects are stored internally (the C type of an R object is SEXP). They are made basically of three parts:

  • an header, which declares the R type of the object, the length and some other meta data;
  • the data part, which is a standard C heap-allocated array (contiguous block of memory);
  • the attributes, which are a named linked list of pointers to other R objects (or NULL if the object doesn't have attributes).

From an internal point of view, there is little difference between a list and a numeric vector for instance. The values they store are just different. Let's break two objects into the paradigm we described before:

x <- runif(10)
y <- list(runif(10), runif(3))

For x:

  • The header will say that the type is numeric (REALSXP in the C-side), the length is 10 and other stuff.
  • The data part will be an array containing 10 double values.
  • The attributes are NULL, since the object doesn't have any.

For y:

  • The header will say that the type is list (VECSXP in the C-side), the length is 2 and other stuff.
  • The data part will be an array containing 2 pointers to two SEXP types, pointing to the value obtained by runif(10) and runif(3) respectively.
  • The attributes are NULL, as for x.

So the only difference between a numeric vector and a list is that the numeric data part is made of double values, while for the list the data part is an array of pointers to other R objects.

What happens with names? Well, names are just some of the attributes you can assign to an object. Let's see the object below:

z <- list(a=1:3, b=LETTERS)
  • The header will say that the type is list (VECSXP in the C-side), the length is 2 and other stuff.
  • The data part will be an array containing 2 pointers to two SEXP types, pointing to the value obtained by 1:3 and LETTERS respectively.
  • The attributes are now present and are a names component which is a character R object with value c("a","b").

From the R level, you can retrieve the attributes of an object with the attributes function.

The key-value typical of an hash map in R is just an illusion. When you say:

z[["a"]]

this is what happens:

  • the [[ subset function is called;
  • the argument of the function ("a") is of type character, so the method is instructed to search such value from the names attribute (if present) of the object z;
  • if the names attribute isn't there, NULL is returned;
  • if present, the "a" value is searched in it. If "a" is not a name of the object, NULL is returned;
  • if present, the position of the first occurence is determined (1 in the example). So the first element of the list is returned, i.e. the equivalent of z[[1]].

The key-value search is rather indirect and is always positional. Also, useful to keep in mind:

  • in hash maps the only limit a key must have is that it must be hashable. names in R must be strings (character vectors);

  • in hash maps you cannot have two identical keys. In R, you can assign names to an object with repeated values. For instance:

      names(y) <- c("same", "same")
    

is perfectly valid in R. When you try y[["same"]] the first value is retrieved. You should know why at this point.

In conclusion, the ability to give arbitrary attributes to an object gives you the appearance of something different from an external point of view. But R lists are not hash maps in any way.

How to use range-based for() loop with std::map?

If you only want to see the keys/values from your map and like using boost, you can use the boost adaptors with the range based loops:

for (const auto& value : myMap | boost::adaptors::map_values)
{
    std::cout << value << std::endl;
}

there is an equivalent boost::adaptors::key_values

http://www.boost.org/doc/libs/1_51_0/libs/range/doc/html/range/reference/adaptors/reference/map_values.html

Integrate ZXing in Android Studio

this tutorial help me to integrate to android studio: http://wahidgazzah.olympe.in/integrating-zxing-in-your-android-app-as-standalone-scanner/ if down try THIS

just add to AndroidManifest.xml

<activity
         android:name="com.google.zxing.client.android.CaptureActivity"
         android:configChanges="orientation|keyboardHidden"
         android:screenOrientation="landscape"
         android:theme="@android:style/Theme.NoTitleBar.Fullscreen"
         android:windowSoftInputMode="stateAlwaysHidden" >
         <intent-filter>
             <action android:name="com.google.zxing.client.android.SCAN" />
             <category android:name="android.intent.category.DEFAULT" />
         </intent-filter>
     </activity>

Hope this help!.

How can I send a file document to the printer and have it print?

System.Diagnostics.Process.Start can be used to print a document. Set UseShellExecute to True and set the Verb to "print".

CSS3 Fade Effect

It's possible, use the structure below:

<li><a><span></span></a></li>
<li><a><span></span></a></li>

etc...

Where the <li> contains an <a> anchor tag that contains a span as shown above. Then insert the following css:

  • LI get position: relative;
  • Give <a> tag a height, width
  • Set <span> width & height to 100%, so that both <a> and <span> have same dimensions
  • Both <a> and <span> get position: relative;.
  • Assign the same background image to each element
  • <a> tag will have the 'OFF' background-position, and the <span> will have the 'ON' background-poisiton.
  • For 'OFF' state use opacity 0 for <span>
  • For 'ON' :hover state use opacity 1 for <span>
  • Set the -webkit or -moz transition on the <span> element

You'll have the ability to use the transition effect while still defaulting to the old background-position swap. Don't forget to insert IE alpha filter.

Regex: match everything but specific pattern

Regex: match everything but:

Demo note: the newline \n is used inside negated character classes in demos to avoid match overflow to the neighboring line(s). They are not necessary when testing individual strings.

Anchor note: In many languages, use \A to define the unambiguous start of string, and \z (in Python, it is \Z, in JavaScript, $ is OK) to define the very end of the string.

Dot note: In many flavors (but not POSIX, TRE, TCL), . matches any char but a newline char. Make sure you use a corresponding DOTALL modifier (/s in PCRE/Boost/.NET/Python/Java and /m in Ruby) for the . to match any char including a newline.

Backslash note: In languages where you have to declare patterns with C strings allowing escape sequences (like \n for a newline), you need to double the backslashes escaping special characters so that the engine could treat them as literal characters (e.g. in Java, world\. will be declared as "world\\.", or use a character class: "world[.]"). Use raw string literals (Python r'\bworld\b'), C# verbatim string literals @"world\.", or slashy strings/regex literal notations like /world\./.

How to scroll to specific item using jQuery?

I managed to do it myself. No need for any plugins. Check out my gist:

// Replace #fromA with your button/control and #toB with the target to which     
// You wanna scroll to. 
//
$("#fromA").click(function() {
    $("html, body").animate({ scrollTop: $("#toB").offset().top }, 1500);
});

TypeError: a bytes-like object is required, not 'str' in python and CSV

You are using Python 2 methodology instead of Python 3.

Change:

outfile=open('./immates.csv','wb')

To:

outfile=open('./immates.csv','w')

and you will get a file with the following output:

SNo,States,Dist,Population
1,Andhra Pradesh,13,49378776
2,Arunachal Pradesh,16,1382611
3,Assam,27,31169272
4,Bihar,38,103804637
5,Chhattisgarh,19,25540196
6,Goa,2,1457723
7,Gujarat,26,60383628
.....

In Python 3 csv takes the input in text mode, whereas in Python 2 it took it in binary mode.

Edited to Add

Here is the code I ran:

url='http://www.mapsofindia.com/districts-india/'
html = urllib.request.urlopen(url).read()
soup = BeautifulSoup(html)
table=soup.find('table', attrs={'class':'tableizer-table'})
list_of_rows=[]
for row in table.findAll('tr')[1:]:
    list_of_cells=[]
    for cell in row.findAll('td'):
        list_of_cells.append(cell.text)
    list_of_rows.append(list_of_cells)
outfile = open('./immates.csv','w')
writer=csv.writer(outfile)
writer.writerow(['SNo', 'States', 'Dist', 'Population'])
writer.writerows(list_of_rows)

Dynamically add properties to a existing object

Consider using the decorator pattern http://en.wikipedia.org/wiki/Decorator_pattern

You can change the decorator at runtime with one that has different properties when an event occurs.

In bootstrap how to add borders to rows without adding up?

Here is one solution:

div.row { 
  border: 1px solid;
  border-bottom: 0px;
}
.container div.row:last-child {
  border-bottom: 1px solid;
}

I'm not 100% its the most effiecent, but it works :D

http://jsfiddle.net/aaronmallen/7cb3Y/2/

python time + timedelta equivalent

If it's worth adding another file / dependency to your project, I've just written a tiny little class that extends datetime.time with the ability to do arithmetic. If you go past midnight, it just wraps around:

>>> from nptime import nptime
>>> from datetime import timedelta
>>> afternoon = nptime(12, 24) + timedelta(days=1, minutes=36)
>>> afternoon
nptime(13, 0)
>>> str(afternoon)
'13:00:00'

It's available from PyPi as nptime ("non-pedantic time"), or on GitHub: https://github.com/tgs/nptime

The documentation is at http://tgs.github.io/nptime/

Is it possible to get only the first character of a String?

Here I am taking Mobile No From EditText It may start from +91 or 0 but i am getting actual 10 digits. Hope this will help you.

              String mob=edit_mobile.getText().toString();
                    if (mob.length() >= 10) {
                        if (mob.contains("+91")) {
                            mob= mob.substring(3, 13);
                        }
                        if (mob.substring(0, 1).contains("0")) {
                            mob= mob.substring(1, 11);
                        }
                        if (mob.contains("+")) {
                            mob= mob.replace("+", "");
                        }
                        mob= mob.substring(0, 10);
                        Log.i("mob", mob);

                    }

python modify item in list, save back in list

A common idiom to change every element of a list looks like this:

for i in range(len(L)):
    item = L[i]
    # ... compute some result based on item ...
    L[i] = result

This can be rewritten using enumerate() as:

for i, item in enumerate(L):
    # ... compute some result based on item ...
    L[i] = result

See enumerate.

Creating instance list of different objects

List anyObject = new ArrayList();

or

List<Object> anyObject = new ArrayList<Object>();

now anyObject can hold objects of any type.

use instanceof to know what kind of object it is.

Appending items to a list of lists in python

Python lists are mutable objects and here:

plot_data = [[]] * len(positions) 

you are repeating the same list len(positions) times.

>>> plot_data = [[]] * 3
>>> plot_data
[[], [], []]
>>> plot_data[0].append(1)
>>> plot_data
[[1], [1], [1]]
>>> 

Each list in your list is a reference to the same object. You modify one, you see the modification in all of them.

If you want different lists, you can do this way:

plot_data = [[] for _ in positions]

for example:

>>> pd = [[] for _ in range(3)]
>>> pd
[[], [], []]
>>> pd[0].append(1)
>>> pd
[[1], [], []]

Padding characters in printf

Pure Bash, no external utilities

This demonstration does full justification, but you can just omit subtracting the length of the second string if you want ragged-right lines.

pad=$(printf '%0.1s' "-"{1..60})
padlength=40
string2='bbbbbbb'
for string1 in a aa aaaa aaaaaaaa
do
     printf '%s' "$string1"
     printf '%*.*s' 0 $((padlength - ${#string1} - ${#string2} )) "$pad"
     printf '%s\n' "$string2"
     string2=${string2:1}
done

Unfortunately, in that technique, the length of the pad string has to be hardcoded to be longer than the longest one you think you'll need, but the padlength can be a variable as shown. However, you can replace the first line with these three to be able to use a variable for the length of the pad:

padlimit=60
pad=$(printf '%*s' "$padlimit")
pad=${pad// /-}

So the pad (padlimit and padlength) could be based on terminal width ($COLUMNS) or computed from the length of the longest data string.

Output:

a--------------------------------bbbbbbb
aa--------------------------------bbbbbb
aaaa-------------------------------bbbbb
aaaaaaaa----------------------------bbbb

Without subtracting the length of the second string:

a---------------------------------------bbbbbbb
aa--------------------------------------bbbbbb
aaaa------------------------------------bbbbb
aaaaaaaa--------------------------------bbbb

The first line could instead be the equivalent (similar to sprintf):

printf -v pad '%0.1s' "-"{1..60}

or similarly for the more dynamic technique:

printf -v pad '%*s' "$padlimit"

You can do the printing all on one line if you prefer:

printf '%s%*.*s%s\n' "$string1" 0 $((padlength - ${#string1} - ${#string2} )) "$pad" "$string2"

Find Facebook user (url to profile page) by known email address

In response to the bug filed here: http://developers.facebook.com/bugs/167188686695750 a Facebook engineer replied:

This is by design, searching for users is intended to be a user to user function only, for use in finding new friends or searching by email to find existing contacts on Facebook. The "scraping" mentioned on StackOverflow is specifically against our Terms of Service https://www.facebook.com/terms.php and in fact the only legitimate way to search for users on Facebook is when you are a user.

Best JavaScript compressor

Revisiting this question a few years later, UglifyJS, seems to be the best option as of now.

As stated below, it runs on the NodeJS platform, but can be easily modified to run on any JavaScript engine.

--- Old answer below---

Google released Closure Compiler which seems to be generating the smallest files so far as seen here and here

Previous to that the various options were as follow

Basically Packer does a better job at initial compression , but if you are going to gzip the files before sending on the wire (which you should be doing) YUI Compressor gets the smallest final size.

The tests were done on jQuery code btw.

  • Original jQuery library 62,885 bytes , 19,758 bytes after gzip
  • jQuery minified with JSMin 36,391 bytes , 11,541 bytes after gzip
  • jQuery minified with Packer 21,557 bytes , 11,119 bytes after gzip
  • jQuery minified with the YUI Compressor 31,822 bytes , 10,818 bytes after gzip

@daniel james mentions in the comment compressorrater which shows Packer leading the chart in best compression, so I guess ymmv

What is the meaning of git reset --hard origin/master?

git reset --hard origin/master

says: throw away all my staged and unstaged changes, forget everything on my current local branch and make it exactly the same as origin/master.

You probably wanted to ask this before you ran the command. The destructive nature is hinted at by using the same words as in "hard reset".

How to uninstall Ruby from /usr/local?

It's not a good idea to uninstall 1.8.6 if it's in /usr/bin. That is owned by the OS and is expected to be there.

If you put /usr/local/bin in your PATH before /usr/bin then things you have installed in /usr/local/bin will be found before any with the same name in /usr/bin, effectively overwriting or updating them, without actually doing so. You can still reach them by explicitly using /usr/bin in your #! interpreter invocation line at the top of your code.

@Anurag recommended using RVM, which I'll second. I use it to manage 1.8.7 and 1.9.1 in addition to the OS's 1.8.6.

Move seaborn plot legend to a different position?

This is how I was able to move the legend to a particular place inside the plot and change the aspect and size of the plot:

import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
matplotlib.style.use('ggplot')
import seaborn as sns
sns.set(style="ticks")

figure_name = 'rater_violinplot.png'
figure_output_path = output_path + figure_name

viol_plot = sns.factorplot(x="Rater", 
                       y="Confidence", 
                       hue="Event Type", 
                       data=combo_df, 
                       palette="colorblind",
                       kind='violin',
                       size = 10,
                       aspect = 1.5,
                       legend=False)

viol_plot.ax.legend(loc=2)
viol_plot.fig.savefig(figure_output_path)  

Legend location changed

This worked for me to change the size and aspect of the plot as well as move the legend outside the plot area.

import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
matplotlib.style.use('ggplot')
import seaborn as sns
sns.set(style="ticks")


figure_name = 'rater_violinplot.png'
figure_output_path = output_path + figure_name

viol_plot = sns.factorplot(x="Rater", 
                       y="Confidence", 
                       hue="Event Type", 
                       data=combo_df, 
                       palette="colorblind",
                       kind='violin',
                       size = 10,
                       aspect = 1.5,
                       legend_out=True)

viol_plot.fig.savefig(figure_output_path)  

violin plot with changed size, aspect and legend located outside

I figured this out from mwaskom's answer here and Fernando Hernandez's answer here.

Use LINQ to get items in one List<>, that are not in another List<>

first, extract ids from the collection where condition

List<int> indexes_Yes = this.Contenido.Where(x => x.key == 'TEST').Select(x => x.Id).ToList();

second, use "compare" estament to select ids diffent to the selection

List<int> indexes_No = this.Contenido.Where(x => !indexes_Yes.Contains(x.Id)).Select(x => x.Id).ToList();

Obviously you can use x.key != "TEST", but is only a example

How to add white spaces in HTML paragraph

You can try it by adding &nbsp;

regex for zip-code

^\d{5}(?:[-\s]\d{4})?$
  • ^ = Start of the string.
  • \d{5} = Match 5 digits (for condition 1, 2, 3)
  • (?:…) = Grouping
  • [-\s] = Match a space (for condition 3) or a hyphen (for condition 2)
  • \d{4} = Match 4 digits (for condition 2, 3)
  • …? = The pattern before it is optional (for condition 1)
  • $ = End of the string.

How do I show a message in the foreach loop?

You are looking to see if a single value is in an array. Use in_array.

However note that case is important, as are any leading or trailing spaces. Use var_dump to find out the length of the strings too, and see if they fit.

MySQL Query - Records between Today and Last 30 Days

You can also write this in mysql -

SELECT  DATE_FORMAT(create_date, '%m/%d/%Y')
FROM    mytable
WHERE   create_date < DATE_ADD(NOW(), INTERVAL -1 MONTH);

FIXED

Writing Python lists to columns in csv

I just wanted to add to this one- because quite frankly, I banged my head against it for a while - and while very new to python - perhaps it will help someone else out.

 writer.writerow(("ColName1", "ColName2", "ColName"))
                 for i in range(len(first_col_list)):
                     writer.writerow((first_col_list[i], second_col_list[i], third_col_list[i]))

How to show/hide JPanels in a JFrame?

Call parent.remove(panel), where parent is the container that you want the frame in and panel is the panel you want to add.

How to negate 'isblank' function

If you're trying to just count how many of your cells in a range are not blank try this:

=COUNTA(range)

Example: (assume that it starts from A1 downwards):

---------    
Something 
---------
Something
---------

---------
Something
---------

---------
Something
---------

=COUNTA(A1:A6) returns 4 since there are two blank cells in there.

Setting a max character length in CSS

HTML

<div id="dash">
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin nisi ligula, dapibus a volutpat sit amet, mattis et dui. Nunc porttitor accumsan orci id luctus. Phasellus ipsum metus, tincidunt non rhoncus id, dictum a lectus. Nam sed ipsum a urna ac
quam.</p>
</div>

jQuery

var p = $('#dash p');
var ks = $('#dash').height();
while ($(p).outerHeight() > ks) {
  $(p).text(function(index, text) {
    return text.replace(/\W*\s(\S)*$/, '...');
  });
}

CSS

#dash {
  width: 400px;
  height: 60px;
  overflow: hidden;
}

#dash p {
  padding: 10px;
  margin: 0;
}

RESULT

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin nisi ligula, dapibus a volutpat sit amet, mattis et...

Jsfiddle

How do you create a static class in C++?

Consider Matt Price's solution.

  1. In C++, a "static class" has no meaning. The nearest thing is a class with only static methods and members.
  2. Using static methods will only limit you.

What you want is, expressed in C++ semantics, to put your function (for it is a function) in a namespace.

Edit 2011-11-11

There is no "static class" in C++. The nearest concept would be a class with only static methods. For example:

// header
class MyClass
{
   public :
      static void myMethod() ;
} ;

// source
void MyClass::myMethod()
{
   // etc.
}

But you must remember that "static classes" are hacks in the Java-like kind of languages (e.g. C#) that are unable to have non-member functions, so they have instead to move them inside classes as static methods.

In C++, what you really want is a non-member function that you'll declare in a namespace:

// header
namespace MyNamespace
{
   void myMethod() ;
}

// source
namespace MyNamespace
{
   void myMethod()
   {
      // etc.
   }
}

Why is that?

In C++, the namespace is more powerful than classes for the "Java static method" pattern, because:

  • static methods have access to the classes private symbols
  • private static methods are still visible (if inaccessible) to everyone, which breaches somewhat the encapsulation
  • static methods cannot be forward-declared
  • static methods cannot be overloaded by the class user without modifying the library header
  • there is nothing that can be done by a static method that can't be done better than a (possibly friend) non-member function in the same namespace
  • namespaces have their own semantics (they can be combined, they can be anonymous, etc.)
  • etc.

Conclusion: Do not copy/paste that Java/C#'s pattern in C++. In Java/C#, the pattern is mandatory. But in C++, it is bad style.

Edit 2010-06-10

There was an argument in favor to the static method because sometimes, one needs to use a static private member variable.

I disagree somewhat, as show below:

The "Static private member" solution

// HPP

class Foo
{
   public :
      void barA() ;
   private :
      void barB() ;
      static std::string myGlobal ;
} ;

First, myGlobal is called myGlobal because it is still a global private variable. A look at the CPP source will clarify that:

// CPP
std::string Foo::myGlobal ; // You MUST declare it in a CPP

void Foo::barA()
{
   // I can access Foo::myGlobal
}

void Foo::barB()
{
   // I can access Foo::myGlobal, too
}

void barC()
{
   // I CAN'T access Foo::myGlobal !!!
}

At first sight, the fact the free function barC can't access Foo::myGlobal seems a good thing from an encapsulation viewpoint... It's cool because someone looking at the HPP won't be able (unless resorting to sabotage) to access Foo::myGlobal.

But if you look at it closely, you'll find that it is a colossal mistake: Not only your private variable must still be declared in the HPP (and so, visible to all the world, despite being private), but you must declare in the same HPP all (as in ALL) functions that will be authorized to access it !!!

So using a private static member is like walking outside in the nude with the list of your lovers tattooed on your skin : No one is authorized to touch, but everyone is able to peek at. And the bonus: Everyone can have the names of those authorized to play with your privies.

private indeed... :-D

The "Anonymous namespaces" solution

Anonymous namespaces will have the advantage of making things private really private.

First, the HPP header

// HPP

namespace Foo
{
   void barA() ;
}

Just to be sure you remarked: There is no useless declaration of barB nor myGlobal. Which means that no one reading the header knows what's hidden behind barA.

Then, the CPP:

// CPP
namespace Foo
{
   namespace
   {
      std::string myGlobal ;

      void Foo::barB()
      {
         // I can access Foo::myGlobal
      }
   }

   void barA()
   {
      // I can access myGlobal, too
   }
}

void barC()
{
   // I STILL CAN'T access myGlobal !!!
}

As you can see, like the so-called "static class" declaration, fooA and fooB are still able to access myGlobal. But no one else can. And no one else outside this CPP knows fooB and myGlobal even exist!

Unlike the "static class" walking on the nude with her address book tattooed on her skin the "anonymous" namespace is fully clothed, which seems quite better encapsulated AFAIK.

Does it really matter?

Unless the users of your code are saboteurs (I'll let you, as an exercise, find how one can access to the private part of a public class using a dirty behaviour-undefined hack...), what's private is private, even if it is visible in the private section of a class declared in a header.

Still, if you need to add another "private function" with access to the private member, you still must declare it to all the world by modifying the header, which is a paradox as far as I am concerned: If I change the implementation of my code (the CPP part), then the interface (the HPP part) should NOT change. Quoting Leonidas : "This is ENCAPSULATION!"

Edit 2014-09-20

When are classes static methods are actually better than namespaces with non-member functions?

When you need to group together functions and feed that group to a template:

namespace alpha
{
   void foo() ;
   void bar() ;
}

struct Beta
{
   static void foo() ;
   static void bar() ;
};

template <typename T>
struct Gamma
{
   void foobar()
   {
      T::foo() ;
      T::bar() ;
   }
};

Gamma<alpha> ga ; // compilation error
Gamma<Beta> gb ;  // ok
gb.foobar() ;     // ok !!!

Because, if a class can be a template parameter, a namespaces cannot.

Why should text files end with a newline?

This answer is an attempt at a technical answer rather than opinion.

If we want to be POSIX purists, we define a line as:

A sequence of zero or more non- <newline> characters plus a terminating <newline> character.

Source: https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap03.html#tag_03_206

An incomplete line as:

A sequence of one or more non- <newline> characters at the end of the file.

Source: https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap03.html#tag_03_195

A text file as:

A file that contains characters organized into zero or more lines. The lines do not contain NUL characters and none can exceed {LINE_MAX} bytes in length, including the <newline> character. Although POSIX.1-2008 does not distinguish between text files and binary files (see the ISO C standard), many utilities only produce predictable or meaningful output when operating on text files. The standard utilities that have such restrictions always specify "text files" in their STDIN or INPUT FILES sections.

Source: https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap03.html#tag_03_397

A string as:

A contiguous sequence of bytes terminated by and including the first null byte.

Source: https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap03.html#tag_03_396

From this then, we can derive that the only time we will potentially encounter any type of issues are if we deal with the concept of a line of a file or a file as a text file (being that a text file is an organization of zero or more lines, and a line we know must terminate with a <newline>).

Case in point: wc -l filename.

From the wc's manual we read:

A line is defined as a string of characters delimited by a <newline> character.

What are the implications to JavaScript, HTML, and CSS files then being that they are text files?

In browsers, modern IDEs, and other front-end applications there are no issues with skipping EOL at EOF. The applications will parse the files properly. It has to since not all Operating Systems conform to the POSIX standard, so it would be impractical for non-OS tools (e.g. browsers) to handle files according to the POSIX standard (or any OS-level standard).

As a result, we can be relatively confident that EOL at EOF will have virtually no negative impact at the application level - regardless if it is running on a UNIX OS.

At this point we can confidently say that skipping EOL at EOF is safe when dealing with JS, HTML, CSS on the client-side. Actually, we can state that minifying any one of these files, containing no <newline> is safe.

We can take this one step further and say that as far as NodeJS is concerned it too cannot adhere to the POSIX standard being that it can run in non-POSIX compliant environments.

What are we left with then? System level tooling.

This means the only issues that may arise are with tools that make an effort to adhere their functionality to the semantics of POSIX (e.g. definition of a line as shown in wc).

Even so, not all shells will automatically adhere to POSIX. Bash for example does not default to POSIX behavior. There is a switch to enable it: POSIXLY_CORRECT.

Food for thought on the value of EOL being <newline>: https://www.rfc-editor.org/old/EOLstory.txt

Staying on the tooling track, for all practical intents and purposes, let's consider this:

Let's work with a file that has no EOL. As of this writing the file in this example is a minified JavaScript with no EOL.

curl http://cdnjs.cloudflare.com/ajax/libs/AniJS/0.5.0/anijs-min.js -o x.js
curl http://cdnjs.cloudflare.com/ajax/libs/AniJS/0.5.0/anijs-min.js -o y.js

$ cat x.js y.js > z.js

-rw-r--r--  1 milanadamovsky   7905 Aug 14 23:17 x.js
-rw-r--r--  1 milanadamovsky   7905 Aug 14 23:17 y.js
-rw-r--r--  1 milanadamovsky  15810 Aug 14 23:18 z.js

Notice the cat file size is exactly the sum of its individual parts. If the concatenation of JavaScript files is a concern for JS files, the more appropriate concern would be to start each JavaScript file with a semi-colon.

As someone else mentioned in this thread: what if you want to cat two files whose output becomes just one line instead of two? In other words, cat does what it's supposed to do.

The man of cat only mentions reading input up to EOF, not <newline>. Note that the -n switch of cat will also print out a non- <newline> terminated line (or incomplete line) as a line - being that the count starts at 1 (according to the man.)

-n Number the output lines, starting at 1.

Now that we understand how POSIX defines a line , this behavior becomes ambiguous, or really, non-compliant.

Understanding a given tool's purpose and compliance will help in determining how critical it is to end files with an EOL. In C, C++, Java (JARs), etc... some standards will dictate a newline for validity - no such standard exists for JS, HTML, CSS.

For example, instead of using wc -l filename one could do awk '{x++}END{ print x}' filename , and rest assured that the task's success is not jeopardized by a file we may want to process that we did not write (e.g. a third party library such as the minified JS we curld) - unless our intent was truly to count lines in the POSIX compliant sense.

Conclusion

There will be very few real life use cases where skipping EOL at EOF for certain text files such as JS, HTML, and CSS will have a negative impact - if at all. If we rely on <newline> being present, we are restricting the reliability of our tooling only to the files that we author and open ourselves up to potential errors introduced by third party files.

Moral of the story: Engineer tooling that does not have the weakness of relying on EOL at EOF.

Feel free to post use cases as they apply to JS, HTML and CSS where we can examine how skipping EOL has an adverse effect.

Count unique values with pandas per groups

You need nunique:

df = df.groupby('domain')['ID'].nunique()

print (df)
domain
'facebook.com'    1
'google.com'      1
'twitter.com'     2
'vk.com'          3
Name: ID, dtype: int64

If you need to strip ' characters:

df = df.ID.groupby([df.domain.str.strip("'")]).nunique()
print (df)
domain
facebook.com    1
google.com      1
twitter.com     2
vk.com          3
Name: ID, dtype: int64

Or as Jon Clements commented:

df.groupby(df.domain.str.strip("'"))['ID'].nunique()

You can retain the column name like this:

df = df.groupby(by='domain', as_index=False).agg({'ID': pd.Series.nunique})
print(df)
    domain  ID
0       fb   1
1      ggl   1
2  twitter   2
3       vk   3

The difference is that nunique() returns a Series and agg() returns a DataFrame.

Python Error: "ValueError: need more than 1 value to unpack"

You have to pass the arguments in the terminal in order to store them in 'argv'. This variable holds the arguments you pass to your Python script when you run it. It later unpacks the arguments and store them in different variables you specify in the program e.g.

script, first, second = argv
print "Your file is:", script
print "Your first entry is:", first
print "Your second entry is:" second

Then in your command line you have to run your code like this,

$python ex14.py Hamburger Pizza

Your output will look like this:

Your file is: ex14.py
Your first entry is: Hamburger
Your second entry is: Pizza

How can I turn a List of Lists into a List in Java 8?

You can use flatMap to flatten the internal lists (after converting them to Streams) into a single Stream, and then collect the result into a list:

List<List<Object>> list = ...
List<Object> flat = 
    list.stream()
        .flatMap(List::stream)
        .collect(Collectors.toList());

Driver executable must be set by the webdriver.ie.driver system property

The error message says

"The path to the driver executable must be set by the webdriver.ie.driver system property;"

You are setting the path for the Chrome Driver with "webdriver.chrome.driver" property. You are not setting the file location when for InternetExplorerDriver, to do that you must set "webdriver.ie.driver" property.

You can set these properties in your shell, via maven, or your IDE with the -DpropertyName=Value

-Dwebdriver.ie.driver="C:/.../IEDriverServer.exe" 

You need to use quotes because of spaces or slashes in your path on windows machines, or alternatively reverse the slashes other wise they are the string string escape prefix.

You could also use

System.setProperty("webdriver.ie.driver","C:/.../IEDriverServer.exe"); 

inside your code.

Adding a guideline to the editor in Visual Studio

With VS 2013 Express this key does not exist. What I see is HKEY_CURRENT_USER\Software\Microsoft\VisualStudio\12.0 and there is no mention of Text Editor under that.

How to move all HTML element children to another parent using JavaScript?

If you not use - in id's names then you can do this

_x000D_
_x000D_
oldParent.id='xxx';_x000D_
newParent.id='oldParent';_x000D_
xxx.id='newParent';_x000D_
oldParent.parentNode.insertBefore(oldParent,newParent);
_x000D_
#newParent { color: red }
_x000D_
<div id="oldParent">_x000D_
    <span>Foo</span>_x000D_
    <b>Bar</b>_x000D_
    Hello World_x000D_
</div>_x000D_
<div id="newParent"></div>
_x000D_
_x000D_
_x000D_

C# HttpClient 4.5 multipart/form-data upload

Try this its working for me.

private static async Task<object> Upload(string actionUrl)
{
    Image newImage = Image.FromFile(@"Absolute Path of image");
    ImageConverter _imageConverter = new ImageConverter();
    byte[] paramFileStream= (byte[])_imageConverter.ConvertTo(newImage, typeof(byte[]));

    var formContent = new MultipartFormDataContent
    {
        // Send form text values here
        {new StringContent("value1"),"key1"},
        {new StringContent("value2"),"key2" },
        // Send Image Here
        {new StreamContent(new MemoryStream(paramFileStream)),"imagekey","filename.jpg"}
    };

    var myHttpClient = new HttpClient();
    var response = await myHttpClient.PostAsync(actionUrl.ToString(), formContent);
    string stringContent = await response.Content.ReadAsStringAsync();

    return response;
}

Usages of doThrow() doAnswer() doNothing() and doReturn() in mockito

doThrow : Basically used when you want to throw an exception when a method is being called within a mock object.

public void validateEntity(final Object object){}
Mockito.doThrow(IllegalArgumentException.class)
.when(validationService).validateEntity(Matchers.any(AnyObjectClass.class));

doReturn : Used when you want to send back a return value when a method is executed.

public Socket getCosmosSocket() throws IOException {}
Mockito.doReturn(cosmosSocket).when(cosmosServiceImpl).getCosmosSocket();

doAnswer: Sometimes you need to do some actions with the arguments that are passed to the method, for example, add some values, make some calculations or even modify them doAnswer gives you the Answer interface that being executed in the moment that method is called, this interface allows you to interact with the parameters via the InvocationOnMock argument. Also, the return value of answer method will be the return value of the mocked method.

public ReturnValueObject quickChange(Object1 object);
Mockito.doAnswer(new Answer<ReturnValueObject>() {

        @Override
        public ReturnValueObject answer(final InvocationOnMock invocation) throws Throwable {

            final Object1 originalArgument = (invocation.getArguments())[0];
            final ReturnValueObject returnedValue = new ReturnValueObject();
            returnedValue.setCost(new Cost());

            return returnedValue ;
        }
}).when(priceChangeRequestService).quickCharge(Matchers.any(Object1.class));

doNothing: Is the easiest of the list, basically it tells Mockito to do nothing when a method in a mock object is called. Sometimes used in void return methods or method that does not have side effects, or are not related to the unit testing you are doing.

public void updateRequestActionAndApproval(final List<Object1> cmItems);

Mockito.doNothing().when(pagLogService).updateRequestActionAndApproval(
                Matchers.any(Object1.class));

Angularjs: Error: [ng:areq] Argument 'HomeController' is not a function, got undefined

In my case, I was missing the name of the Angular application in the html file. For example, I had included this file to be start of my application code. I had assumed it was being ran, but it wasn't.

app.module.js

(function () {
    'use strict';

    angular
        .module('app', [
        // Other dependencies here...
        ])
    ;

})();

However, when I declared the app in the html I had this:

index.html

<html lang="en" ng-app>

But to reference the Angular application by the name I used, I had to use:

index.html (Fixed)

<html lang="en" ng-app="app">

Best way to add Activity to an Android project in Eclipse?

It is now much easier to do this in Eclipse now. Just right click on the package that will contain your new activity. New -> Other -> (Under Android tab) Android Activity.

And that's all. Your new activity is automatically added to the manifest file as well.

Setting the character encoding in form submit for Internet Explorer

I seem to remember that Internet Explorer gets confused if the accept-charset encoding doesn't match the encoding specified in the content-type header. In your example, you claim the document is sent as UTF-8, but want form submits in ISO-8859-1. Try matching those and see if that solves your problem.

C# Generics and Type Checking

You can use typeof(T).

private static string BuildClause<T>(IList<T> clause)
{
     Type itemType = typeof(T);
     if(itemType == typeof(int) || itemType == typeof(decimal))
    ...
}

C# LINQ select from list

In likeness of how I found this question using Google, I wanted to take it one step further. Lets say I have a string[] states and a db Entity of StateCounties and I just want the states from the list returned and not all of the StateCounties.

I would write:

db.StateCounties.Where(x => states.Any(s => x.State.Equals(s))).ToList();

I found this within the sample of CheckBoxList for nu-get.

Navigate to another page with a button in angular 2

you can change

    this.router.routeReuseStrategy.shouldReuseRoute = () => false;

at the component level in constructor like bellow

    constructor(private router: Router) {
            this.router.routeReuseStrategy.shouldReuseRoute = () => false; 
}

What is correct media query for IPad Pro?

Too late but may this save you from headache! All of these is because we have to detect the target browser is a mobile!

Is this a mobile then combine it with min/max-(width/height)'s

So Just this seems works:

@media (hover: none) {
    /* ... */
}

If the primary input mechanism system of the device cannot hover over elements with ease or they can but not easily (for example a long touch is performed to emulate the hover) or there is no primary input mechanism at all, we use none! There are many cases that you can read from bellow links.

Described as well Also for browser Support See this from MDN

How to subtract 2 hours from user's local time?

According to Javascript Date Documentation, you can easily do this way:

var twoHoursBefore = new Date();
twoHoursBefore.setHours(twoHoursBefore.getHours() - 2);

And don't worry about if hours you set will be out of 0..23 range. Date() object will update the date accordingly.

Using PowerShell to write a file in UTF-8 without the BOM

This script will convert, to UTF-8 without BOM, all .txt files in DIRECTORY1 and output them to DIRECTORY2

foreach ($i in ls -name DIRECTORY1\*.txt)
{
    $file_content = Get-Content "DIRECTORY1\$i";
    [System.IO.File]::WriteAllLines("DIRECTORY2\$i", $file_content);
}

Console.WriteLine does not show up in Output window

Try to uncheck the CheckBox “Use Managed Compatibility Mode” in

Tools => Options => Debugging => General

It worked for me.

Getting the inputstream from a classpath resource (XML file)

ClassLoader.class.getResourceAsStream("/path/file.ext");

how to call service method from ng-change of select in angularjs?

You have at least two issues in your code:

  • ng-change="getScoreData(Score)

    Angular doesn't see getScoreData method that refers to defined service

  • getScoreData: function (Score, callback)

    We don't need to use callback since GET returns promise. Use then instead.

Here is a working example (I used random address only for simulation):

HTML

<select ng-model="score"
        ng-change="getScoreData(score)" 
        ng-options="score as score.name for score in  scores"></select>
    <pre>{{ScoreData|json}}</pre> 

JS

var fessmodule = angular.module('myModule', ['ngResource']);

fessmodule.controller('fessCntrl', function($scope, ScoreDataService) {

    $scope.scores = [{
        name: 'Bukit Batok Street 1',
        URL: 'http://maps.googleapis.com/maps/api/geocode/json?address=Singapore, SG, Singapore, 153 Bukit Batok Street 1&sensor=true'
    }, {
        name: 'London 8',
        URL: 'http://maps.googleapis.com/maps/api/geocode/json?address=Singapore, SG, Singapore, London 8&sensor=true'
    }];

    $scope.getScoreData = function(score) {
        ScoreDataService.getScoreData(score).then(function(result) {
            $scope.ScoreData = result;
        }, function(result) {
            alert("Error: No data returned");
        });
    };

});

fessmodule.$inject = ['$scope', 'ScoreDataService'];

fessmodule.factory('ScoreDataService', ['$http', '$q', function($http) {

    var factory = {
        getScoreData: function(score) {
            console.log(score);
            var data = $http({
                method: 'GET',
                url: score.URL
            });


            return data;
        }
    }
    return factory;
}]);

Demo Fiddle

How can I make all images of different height and width the same via CSS?

Simplest way - This will keep the image size as it is and fill the other area with space, this way all the images will take same specified space regardless of the image size without stretching

.img{
   width:100px;
   height:100px;

/*Scale down will take the necessary specified space that is 100px x 100px without stretching the image*/
    object-fit:scale-down;

}

Remove a string from the beginning of a string

Here's an even faster approach:

// strpos is faster than an unnecessary substr() and is built just for that 
if (strpos($str, $prefix) === 0) $str = substr($str, strlen($prefix));

Numpy: Get random set of rows from 2D array

If you want to generate multiple random subsets of rows, for example if your doing RANSAC.

num_pop = 10
num_samples = 2
pop_in_sample = 3
rows_to_sample = np.random.random([num_pop, 5])
random_numbers = np.random.random([num_samples, num_pop])
samples = np.argsort(random_numbers, axis=1)[:, :pop_in_sample]
# will be shape [num_samples, pop_in_sample, 5]
row_subsets = rows_to_sample[samples, :]

stale element reference: element is not attached to the page document

This could be done in newer versions of selenium in JS( but all supporting stalenessOf will work):

 const { until } = require('selenium-webdriver');
 driver.wait(
        until.stalenessOf(
          driver.findElement(
            By.css(SQLQueriesByPhpMyAdminSelectors.sqlQueryArea)
          )
        ),
        5 * 1000
      )
      .then( driver.findElement(By.css(SQLQueriesByPhpMyAdminSelectors.sqlQueryArea))
      .sendKeys(sqlString)
  );

Show a PDF files in users browser via PHP/Perl

You could modify a PDF renderer such as xpdf or evince to render into a graphics image on your server, and then deliver the image to the user. This is how Google's quick view of PDF files works, they render it locally, then deliver images to the user. No downloaded PDF file, and the source is pretty well obscured. :)

How to pass credentials to the Send-MailMessage command for sending emails

It took me a while to combine everything, make it a bit secure, and have it work with Gmail. I hope this answer saves someone some time.

Create a file with the encrypted server password:

In Powershell, enter the following command (replace myPassword with your actual password):

"myPassword" | ConvertTo-SecureString -AsPlainText -Force | ConvertFrom-SecureString | Out-File "C:\EmailPassword.txt"

Create a powershell script (Ex. sendEmail.ps1):

$User = "[email protected]"
$File = "C:\EmailPassword.txt"
$cred=New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $User, (Get-Content $File | ConvertTo-SecureString)
$EmailTo = "[email protected]"
$EmailFrom = "[email protected]"
$Subject = "Email Subject" 
$Body = "Email body text" 
$SMTPServer = "smtp.gmail.com" 
$filenameAndPath = "C:\fileIwantToSend.csv"
$SMTPMessage = New-Object System.Net.Mail.MailMessage($EmailFrom,$EmailTo,$Subject,$Body)
$attachment = New-Object System.Net.Mail.Attachment($filenameAndPath)
$SMTPMessage.Attachments.Add($attachment)
$SMTPClient = New-Object Net.Mail.SmtpClient($SmtpServer, 587) 
$SMTPClient.EnableSsl = $true 
$SMTPClient.Credentials = New-Object System.Net.NetworkCredential($cred.UserName, $cred.Password); 
$SMTPClient.Send($SMTPMessage)

Automate with Task Scheduler:

Create a batch file (Ex. emailFile.bat) with the following:

powershell -ExecutionPolicy ByPass -File C:\sendEmail.ps1

Create a task to run the batch file. Note: you must have the task run with the same user account that you used to encrypted the password! (Aka, probably the logged in user)

That's all; you now have a way to automate and schedule sending an email and an attachment with Windows Task Scheduler and Powershell. No 3rd party software and the password is not stored as plain text (though granted, not terribly secure either).

You can also read this article on the level of security this provides for your email password.

File path to resource in our war/WEB-INF folder?

There's a couple ways of doing this. As long as the WAR file is expanded (a set of files instead of one .war file), you can use this API:

ServletContext context = getContext();
String fullPath = context.getRealPath("/WEB-INF/test/foo.txt");

http://tomcat.apache.org/tomcat-5.5-doc/servletapi/javax/servlet/ServletContext.html#getRealPath(java.lang.String)

That will get you the full system path to the resource you are looking for. However, that won't work if the Servlet Container never expands the WAR file (like Tomcat). What will work is using the ServletContext's getResource methods.

ServletContext context = getContext();
URL resourceUrl = context.getResource("/WEB-INF/test/foo.txt");

or alternatively if you just want the input stream:

InputStream resourceContent = context.getResourceAsStream("/WEB-INF/test/foo.txt");

http://tomcat.apache.org/tomcat-5.5-doc/servletapi/javax/servlet/ServletContext.html#getResource(java.lang.String)

The latter approach will work no matter what Servlet Container you use and where the application is installed. The former approach will only work if the WAR file is unzipped before deployment.

EDIT: The getContext() method is obviously something you would have to implement. JSP pages make it available as the context field. In a servlet you get it from your ServletConfig which is passed into the servlet's init() method. If you store it at that time, you can get your ServletContext any time you want after that.

Can pm2 run an 'npm start' script

See to enable clustering:

pm2 start npm --name "AppName" -i 0 -- run start

What do you think?

How to use an array list in Java?

You could either get your strings by index (System.out.println(S.get(0));) or iterate through it:

for (String s : S) {
  System.out.println(s);
}

For other ways to iterate through a list (and their implications) see traditional for loop vs Iterator in Java.

Additionally:

  • you shouldn't use variable names starting with upper-case letters
  • you should parametrize your array list: ArrayList<String> list = new ArrayList<String>();
  • you should get familiar with Java's extensive API documentation (aka Javadoc), e.g. Java 5, Java 6

Dynamic SQL results into temp table in SQL Stored procedure

Not sure if I understand well, but maybe you could form the CREATE statement inside a string, then execute that String? That way you could add as many columns as you want.

How to change Toolbar Navigation and Overflow Menu icons (appcompat v7)?

For right menu you can do it:

public static Drawable setTintDrawable(Drawable drawable, @ColorInt int color) {
            drawable.clearColorFilter();
            drawable.setColorFilter(color, PorterDuff.Mode.SRC_IN);
            drawable.invalidateSelf();
            Drawable wrapDrawable = DrawableCompat.wrap(drawable).mutate();
            DrawableCompat.setTint(wrapDrawable, color);
            return wrapDrawable;
        }

And in your activity

@Override
 public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_profile, menu);
        Drawable send = menu.findItem(R.id.send);
        Drawable msg = menu.findItem(R.id.message);
        DrawableUtils.setTintDrawable(send.getIcon(), Color.WHITE);
        DrawableUtils.setTintDrawable(msg.getIcon(), Color.WHITE);
        return true;
    }

This is the result:

enter image description here

Do while loop in SQL Server 2008

Only While Loop is officially supported by SQL server. Already there is answer for DO while loop. I am detailing answer on ways to achieve different types of loops in SQL server.

If you know, you need to complete first iteration of loop anyway, then you can try DO..WHILE or REPEAT..UNTIL version of SQL server.

DO..WHILE Loop

DECLARE @X INT=1;

WAY:  --> Here the  DO statement

  PRINT @X;

  SET @X += 1;

IF @X<=10 GOTO WAY;

REPEAT..UNTIL Loop

DECLARE @X INT = 1;

WAY:  -- Here the REPEAT statement

  PRINT @X;

  SET @X += 1;

IFNOT(@X > 10) GOTO WAY;

FOR Loop

DECLARE @cnt INT = 0;

WHILE @cnt < 10
BEGIN
   PRINT 'Inside FOR LOOP';
   SET @cnt = @cnt + 1;
END;

PRINT 'Done FOR LOOP';

Reference

Batch - Echo or Variable Not Working

Try the following (note that there should not be a space between the VAR, =, and GREG).

SET VAR=GREG
ECHO %VAR%
PAUSE

How to get all elements which name starts with some string?

Using pure java-script, here is a working code example

<input type="checkbox" name="fruit1" checked/>
<input type="checkbox" name="fruit2" checked />
<input type="checkbox" name="fruit3" checked />
<input type="checkbox" name="other1" checked />
<input type="checkbox" name="other2" checked />
<br>
<input type="button" name="check" value="count checked checkboxes name starts with fruit*" onClick="checkboxes();" />


<script>
function checkboxes()
{
var inputElems = document.getElementsByTagName("input"),
count = 0;
for (var i=0; i<inputElems.length; i++) {       
if (inputElems[i].type == "checkbox" && inputElems[i].checked == true && 
inputElems[i].name.indexOf('fruit') == 0) 
{
count++;

}

}
alert(count);
}
</script>

How to convert a time string to seconds?

without imports

time = "01:34:11"
sum(x * int(t) for x, t in zip([3600, 60, 1], time.split(":"))) 

Error inflating class android.support.v7.widget.Toolbar?

Sorry Guys. I have solved this Issue long ago. I did a lot of changes. So I can't figure out which one does the trick.

  1. I have changed the id as suggested by Jared Burrows.

  2. Removed my support library and cleaned my project and Re added it.

  3. Go to File -> Invalidate Caches/Restart.

Hope it works.

This is how my code looks now

activity.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <include
        android:id="@+id/toolbar_actionbar"
        layout="@layout/toolbar_default"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>

    <android.support.v4.widget.DrawerLayout
        android:id="@+id/drawer"
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@+id/toolbar_actionbar">

        <FrameLayout
            android:id="@+id/container"
            android:layout_width="match_parent"
            android:layout_height="match_parent"/>

        <fragment
            android:id="@+id/fragment_drawer"
            android:name="com.arul.anahy.drawer.NavigationDrawerFragment"
            android:layout_width="@dimen/navigation_drawer_width"
            android:layout_height="match_parent"
            android:layout_gravity="start"
            app:layout="@layout/fragment_navigation_drawer"/>
    </android.support.v4.widget.DrawerLayout>
</RelativeLayout>

toolbar_default.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.Toolbar
    style="@style/ToolBarStyle"
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="?attr/colorPrimary"
    android:minHeight="@dimen/abc_action_bar_default_height_material"/>

ToolBarStyle

<style name="ToolBarStyle" parent="">
        <item name="popupTheme">@style/ThemeOverlay.AppCompat.Light</item>
        <item name="theme">@style/ThemeOverlay.AppCompat.Dark.ActionBar</item>
 </style>

The program can't start because MSVCR110.dll is missing from your computer

I was getting a similar issue from the Apache Lounge 32 bit version. After downloading the 64 bit version, the issue was resolved.

Here is an excellent video explain the steps involved: https://www.youtube.com/watch?v=17qhikHv5hY

How to convert comma-separated String to List?

There are many ways to solve this using streams in Java 8 but IMO the following one liners are straight forward:

String  commaSeparated = "item1 , item2 , item3";
List<String> result1 = Arrays.stream(commaSeparated.split(" , "))
                                             .collect(Collectors.toList());
List<String> result2 = Stream.of(commaSeparated.split(" , "))
                                             .collect(Collectors.toList());

PHP - syntax error, unexpected T_CONSTANT_ENCAPSED_STRING

You have a sintax error in your code:

try changing this line

$out.='<option value=''.$key.'">'.$value["name"].';

with

$out.='<option value="'.$key.'">'.$value["name"].'</option>';

How can I detect Internet Explorer (IE) and Microsoft Edge using JavaScript?

Topic is a bit old, but since the scripts here detect Firefox as a False Positive (EDGE v12), here is the version I use:

function isIEorEDGE(){
  if (navigator.appName == 'Microsoft Internet Explorer'){
    return true; // IE
  }
  else if(navigator.appName == "Netscape"){                       
     return navigator.userAgent.indexOf('.NET') > -1; // Only Edge uses .NET libraries
  }       

  return false;
}

which of course can be written in a more concise way:

function isIEorEDGE(){
  return navigator.appName == 'Microsoft Internet Explorer' || (navigator.appName == "Netscape" && navigator.userAgent.indexOf('.NET') > -1);
}

How to copy std::string into std::vector<char>?

You need a back inserter to copy into vectors:

std::copy(str.c_str(), str.c_str()+str.length(), back_inserter(data));

Java Constructor Inheritance

Constructors are not polymorphic.
When dealing with already constructed classes, you could be dealing with the declared type of the object, or any of its subclasses. That's what inheritance is useful for.
Constructor are always called on the specific type,eg new String(). Hypothetical subclasses have no role in this.

How to add external library in IntelliJ IDEA?

A better way in long run is to integrate Gradle in your project environment. Its a build tool for Java, and now being used a lot in the android development space.

You will need to make a .gradle file and list your library dependencies. Then, all you would need to do is import the project in IntelliJ using Gradle.

Cheers

How can I insert into a BLOB column from an insert statement in sqldeveloper?

To insert a VARCHAR2 into a BLOB column you can rely on the function utl_raw.cast_to_raw as next:

insert into mytable(id, myblob) values (1, utl_raw.cast_to_raw('some magic here'));

It will cast your input VARCHAR2 into RAW datatype without modifying its content, then it will insert the result into your BLOB column.

More details about the function utl_raw.cast_to_raw