Programs & Examples On #Editmode

How to get `DOM Element` in Angular 2?

Angular 2.0.0 Final:

I have found that using a ViewChild setter is most reliable way to set the initial form control focus:

@ViewChild("myInput")
set myInput(_input: ElementRef | undefined) {
    if (_input !== undefined) {
        setTimeout(() => {
            this._renderer.invokeElementMethod(_input.nativeElement, "focus");
        }, 0);
    }
}

The setter is first called with an undefined value followed by a call with an initialized ElementRef.

Working example and full source here: http://plnkr.co/edit/u0sLLi?p=preview

Using TypeScript 2.0.3 Final/RTM, Angular 2.0.0 Final/RTM, and Chrome 53.0.2785.116 m (64-bit).

UPDATE for Angular 4+

Renderer has been deprecated in favor of Renderer2, but Renderer2 does not have the invokeElementMethod. You will need to access the DOM directly to set the focus as in input.nativeElement.focus().

I'm still finding that the ViewChild setter approach works best. When using AfterViewInit I sometimes get read property 'nativeElement' of undefined error.

@ViewChild("myInput")
set myInput(_input: ElementRef | undefined) {
    if (_input !== undefined) {
        setTimeout(() => { //This setTimeout call may not be necessary anymore.
            _input.nativeElement.focus();
        }, 0);
    }
}

Angular2 - Focusing a textbox on component load

I had a slightly different problem. I worked with inputs in a modal and it drove me mad. No of the proposed solutions worked for me.

Until i found this issue: https://github.com/valor-software/ngx-bootstrap/issues/1597

This good guy gave me the hint that ngx-bootstrap modal has a focus configuration. If this configuration is not set to false, the modal will be focused after the animation and there is NO WAY to focus anything else.

Update:

To set this configuration, add the following attribute to the modal div:

[config]="{focus: false}"

Update 2:

To force the focus on the input field i wrote a directive and set the focus in every AfterViewChecked cycle as long as the input field has the class ng-untouched.

 ngAfterViewChecked() {
    // This dirty hack is needed to force focus on an input element of a modal.
    if (this.el.nativeElement.classList.contains('ng-untouched')) {
        this.renderer.invokeElementMethod(this.el.nativeElement, 'focus', []);
    }
}

How to Create simple drag and Drop in angularjs

I'm a bit late to the party, but I have my own directive that looks like it'll fit your case (You can adapt it yourself). It's a modification of the ng-repeat directive that's specifically built for list re-ordering via DnD. I built it as I don't like JQuery UI (preference for less libraries than anything else) also I wanted mine to work on touch screens too ;).

Code is here: http://codepen.io/SimeonC/pen/AJIyC

Blog post is here: http://sdevgame.wordpress.com/2013/08/27/angularjs-drag-n-drop-re-order-in-ngrepeat/

Display DateTime value in dd/mm/yyyy format in Asp.NET MVC

Or just use this in your View(Razor page)

@item.ResgistrationhaseDate.ToString(string.Format("dd/MM/yyyy"))

I recommend that don't add date format in your model class

What is the best way to conditionally apply attributes in AngularJS?

In the latest version of Angular (1.1.5), they have included a conditional directive called ngIf. It is different from ngShow and ngHide in that the elements aren't hidden, but not included in the DOM at all. They are very useful for components which are costly to create but aren't used:

<h1 ng-if="editMode" contenteditable=true>{{content.title}}</h1>

Format datetime in asp.net mvc 4

Thanks Darin, For me, to be able to post to the create method, It only worked after I modified the BindModel code to :

public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
    var displayFormat = bindingContext.ModelMetadata.DisplayFormatString;
    var value = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);

    if (!string.IsNullOrEmpty(displayFormat) && value != null)
    {
        DateTime date;
        displayFormat = displayFormat.Replace("{0:", string.Empty).Replace("}", string.Empty);
        // use the format specified in the DisplayFormat attribute to parse the date
         if (DateTime.TryParse(value.AttemptedValue, CultureInfo.GetCultureInfo("en-GB"), DateTimeStyles.None, out date))
        {
            return date;
        }
        else
        {
            bindingContext.ModelState.AddModelError(
                bindingContext.ModelName,
                string.Format("{0} is an invalid date format", value.AttemptedValue)
            );
        }
    }

    return base.BindModel(controllerContext, bindingContext);
}

Hope this could help someone else...

Validation failed for one or more entities. See 'EntityValidationErrors' property for more details

Note that Entity.GetType().BaseType.Name gives the type name you specified, not the one with all the hex digits in its name.

What does the question mark and the colon (?: ternary operator) mean in objective-c?

int padding = ([[UIScreen mainScreen] bounds].size.height <= 480) ? 15 : 55;

means

int padding; 
if ([[UIScreen mainScreen] bounds].size.height <= 480)
  padding = 15;
else
  padding = 55; 

HTML: Is it possible to have a FORM tag in each TABLE ROW in a XHTML valid way?

In fact I have the problem with a form on each row of a table, with javascript (actually jquery) :

like Lothre1 said, "some browsers in the process of rendering will close form tag right after the declaration leaving inputs outside of the element"

which makes my input fields OUTSIDE the form, therefore I can't access the children of my form through the DOM with JAVASCRIPT..

typically, the following JQUERY code won't work :

$('#id_form :input').each(function(){/*action*/});
// this is supposed to select all inputS 
// within the form that has an id ='id_form'

BUT the above exemple doesn't work with the rendered HTML :

<table>
    <form id="id_form"></form>
    <tr id="tr_id">
    <td><input type="text"/></td>
    <td><input type="submit"/></td>
    </tr>
    </table>

I'm still looking for a clean solution (though using the TR 'id' parameter to walk the DOM would fix this specific problem)

dirty solution would be (for jquery):

$('#tr_id :input').each(function(){/*action*/});
// this will select all the inputS
// fields within the TR with the id='tr_id'

the above exemple will work, but it's not really "clean", because it refers to the TR instead of the FORM, AND it requires AJAX ...

EDIT : complete process with jquery/ajax would be :

//init data string
// the dummy init value (1=1)is just here 
// to avoid dealing with trailing &
// and should not be implemented
// (though it works)
var data_str = '1=1'; 
// for each input in the TR
$('#tr_id :input').each(function(){

 //retrieve field name and value from the DOM
 var field = $(this).attr('name');
 var value = $(this).val();

 //iterate the string to pass the datas
 // so in the end it will render s/g like
 // "1=1&field1_name=value1&field2_name=value2"...
 data_str += '&' + field + '=' + value; 


});

//Sendind fields datawith ajax 
// to be treated 
$.ajax({
 type:"POST",
 url: "target_for_the_form_treatment",
 data:data_string,
 success:function(msg){
    /*actions on success of the request*/
 });
});

this way, the "target_for_the_form_treatment" should receive POST data as if a form was sent to him (appart from the post[1] = 1, but to implement this solution i would recommand dealing with the trailing '&' of the data_str instead).

still I don't like this solution, but I'm forced to use TABLE structure because of the dataTables jquery plugin...

Difference between int32, int, int32_t, int8 and int8_t

Between int32 and int32_t, (and likewise between int8 and int8_t) the difference is pretty simple: the C standard defines int8_t and int32_t, but does not define anything named int8 or int32 -- the latter (if they exist at all) is probably from some other header or library (most likely predates the addition of int8_t and int32_t in C99).

Plain int is quite a bit different from the others. Where int8_t and int32_t each have a specified size, int can be any size >= 16 bits. At different times, both 16 bits and 32 bits have been reasonably common (and for a 64-bit implementation, it should probably be 64 bits).

On the other hand, int is guaranteed to be present in every implementation of C, where int8_t and int32_t are not. It's probably open to question whether this matters to you though. If you use C on small embedded systems and/or older compilers, it may be a problem. If you use it primarily with a modern compiler on desktop/server machines, it probably won't be.

Oops -- missed the part about char. You'd use int8_t instead of char if (and only if) you want an integer type guaranteed to be exactly 8 bits in size. If you want to store characters, you probably want to use char instead. Its size can vary (in terms of number of bits) but it's guaranteed to be exactly one byte. One slight oddity though: there's no guarantee about whether a plain char is signed or unsigned (and many compilers can make it either one, depending on a compile-time flag). If you need to ensure its being either signed or unsigned, you need to specify that explicitly.

How to force open links in Chrome not download them?

I think the question was about to open a local file directly instead of downloading a local file to the download folder and open the file in the download folder, which seems not possible in Chrome, except some add-on mentioned above.

My workaround would be to right click -> Copy the link location Windows + R and paste the link there and Enter It will go to the file directly.

MySQL/Writing file error (Errcode 28)

This error occurs when you don't have enough space in the partition. Usually MYSQL uses /tmp on linux servers. This may happen with some queries because the lookup was either returning a lot of data, or possibly even just sifting through a lot of data creating big temp files.

Edit your /etc/mysql/my.cnf

tmpdir = /your/new/dir

e.g

tmpdir = /var/tmp

Should be allocated with more space than /tmp that is usually in it's own partition.

Maven: The packaging for this project did not assign a file to the build artifact

This worked for me when I got the same error message...

mvn install deploy

seek() function?

The seek function expect's an offset in bytes.

Ascii File Example:

So if you have a text file with the following content:

simple.txt

abc

You can jump 1 byte to skip over the first character as following:

fp = open('simple.txt', 'r')
fp.seek(1)
print fp.readline()
>>> bc

Binary file example gathering width :

fp = open('afile.png', 'rb')
fp.seek(16)
print 'width: {0}'.format(struct.unpack('>i', fp.read(4))[0])
print 'height: ', struct.unpack('>i', fp.read(4))[0]

Note: Once you call read you are changing the position of the read-head, which act's like seek.

jQuery adding 2 numbers from input fields

There are two way that you can add two number in jQuery

First way:

var x = parseInt(a) + parseInt(b);
alert(x);

Second Way:

var x = parseInt(a+2);
alert(x);

Now come your question

var a = parseInt($("#a").val()); 
var b = parseInt($("#b").val());
alert(a+b);

setValue:forUndefinedKey: this class is not key value coding-compliant for the key

If you have different storybord files and if you have outlet references with out outlets creation in your header files then you just remove the connections by right clicking on files owner.

Files owner->Right click->remove unwanted connection over there.

Go through this for clear explanation. What does this mean? "'NSUnknownKeyException', reason: … this class is not key value coding-compliant for the key X"

How to skip over an element in .map()?

Here's a utility method (ES5 compatible) which only maps non null values (hides the call to reduce):

_x000D_
_x000D_
function mapNonNull(arr, cb) {_x000D_
    return arr.reduce(function (accumulator, value, index, arr) {_x000D_
        var result = cb.call(null, value, index, arr);_x000D_
        if (result != null) {_x000D_
            accumulator.push(result);_x000D_
        }_x000D_
_x000D_
        return accumulator;_x000D_
    }, []);_x000D_
}_x000D_
_x000D_
var result = mapNonNull(["a", "b", "c"], function (value) {_x000D_
    return value === "b" ? null : value; // exclude "b"_x000D_
});_x000D_
_x000D_
console.log(result); // ["a", "c"]
_x000D_
_x000D_
_x000D_

How to get height and width of device display in angular2 using typescript?

export class Dashboard {
    innerHeight: any;
    innerWidth: any;
    constructor() {
        this.innerHeight = (window.screen.height) + "px";
        this.innerWidth = (window.screen.width) + "px";
    }
}

Set Windows process (or user) memory limit

Use Windows Job Objects. Jobs are like process groups and can limit memory usage and process priority.

How to use continue in jQuery each() loop?

We can break both a $(selector).each() loop and a $.each() loop at a particular iteration by making the callback function return false. Returning non-false is the same as a continue statement in a for loop; it will skip immediately to the next iteration.

return false; // this is equivalent of 'break' for jQuery loop

return;       // this is equivalent of 'continue' for jQuery loop

Note that $(selector).each() and $.each() are different functions.

References:

Fail during installation of Pillow (Python module) in Linux

brew install zlib

on OS X doesn't work anymore and instead prompts to install lzlib. Installing that doesn't help.

Instead you install XCode Command line tools and that should install zlib

xcode-select --install

Nodejs send file in response

Here's an example program that will send myfile.mp3 by streaming it from disk (that is, it doesn't read the whole file into memory before sending the file). The server listens on port 2000.

[Update] As mentioned by @Aftershock in the comments, util.pump is gone and was replaced with a method on the Stream prototype called pipe; the code below reflects this.

var http = require('http'),
    fileSystem = require('fs'),
    path = require('path');

http.createServer(function(request, response) {
    var filePath = path.join(__dirname, 'myfile.mp3');
    var stat = fileSystem.statSync(filePath);

    response.writeHead(200, {
        'Content-Type': 'audio/mpeg',
        'Content-Length': stat.size
    });

    var readStream = fileSystem.createReadStream(filePath);
    // We replaced all the event handlers with a simple call to readStream.pipe()
    readStream.pipe(response);
})
.listen(2000);

Taken from http://elegantcode.com/2011/04/06/taking-baby-steps-with-node-js-pumping-data-between-streams/

how to re-format datetime string in php?

why not use date() just like below,try this

$t = strtotime('20130409163705');
echo date('d/m/y H:i:s',$t);

and will be output

09/04/13 16:37:05

Difference between applicationContext.xml and spring-servlet.xml in Spring Framework

In simple words,

applicationContext.xml defines the beans that are shared among all the servlets. If your application have more than one servlet, then defining the common resources in the applicationContext.xml would make more sense.

spring-servlet.xml defines the beans that are related only to that servlet. Here it is the dispatcher servlet. So, your Spring MVC controllers must be defined in this file.

There is nothing wrong in defining all the beans in the spring-servlet.xml if you are running only one servlet in your web application.

Select row and element in awk

Since awk and perl are closely related...


Perl equivalents of @Dennis's awk solutions:

To print the second line:
perl -ne 'print if $. == 2' file

To print the second field:
perl -lane 'print $F[1]' file

To print the third field of the fifth line:
perl -lane 'print $F[2] if $. == 5' file


Perl equivalent of @Glenn's solution:

Print the j'th field of the i'th line

perl -lanse 'print $F[$j-1] if $. == $i' -- -i=5 -j=3 file


Perl equivalents of @Hai's solutions:

if you are looking for second columns that contains abc:

perl -lane 'print if $F[1] =~ /abc/' foo

... and if you want to print only a particular column:

perl -lane 'print $F[2] if $F[1] =~ /abc/' foo

... and for a particular line number:

perl -lane 'print $F[2] if $F[1] =~ /abc/ && $. == 5' foo


-l removes newlines, and adds them back in when printing
-a autosplits the input line into array @F, using whitespace as the delimiter
-n loop over each line of the input file
-e execute the code within quotes
$F[1] is the second element of the array, since Perl starts at 0
$. is the line number

How do you enable auto-complete functionality in Visual Studio C++ express edition?

Have you tried Visual Assist X ? Sort of lights up the VS editor.

JSON Post with Customized HTTPHeader Field

Just wanted to update this thread for future developers.

JQuery >1.12 Now supports being able to change every little piece of the request through JQuery.post ($.post({...}). see second function signature in https://api.jquery.com/jquery.post/

INSERT INTO @TABLE EXEC @query with SQL Server 2000

N.B. - this question and answer relate to the 2000 version of SQL Server. In later versions, the restriction on INSERT INTO @table_variable ... EXEC ... were lifted and so it doesn't apply for those later versions.


You'll have to switch to a temp table:

CREATE TABLE #tmp (code varchar(50), mount money)
DECLARE @q nvarchar(4000)
SET @q = 'SELECT coa_code, amount FROM T_Ledger_detail'

INSERT INTO  #tmp (code, mount)
EXEC sp_executesql (@q)

SELECT * from #tmp

From the documentation:

A table variable behaves like a local variable. It has a well-defined scope, which is the function, stored procedure, or batch in which it is declared.

Within its scope, a table variable may be used like a regular table. It may be applied anywhere a table or table expression is used in SELECT, INSERT, UPDATE, and DELETE statements. However, table may not be used in the following statements:

INSERT INTO table_variable EXEC stored_procedure

SELECT select_list INTO table_variable statements.

What does the error "JSX element type '...' does not have any construct or call signatures" mean?

This is a confusion between constructors and instances.

Remember that when you write a component in React:

class Greeter extends React.Component<any, any> {
    render() {
        return <div>Hello, {this.props.whoToGreet}</div>;
    }
}

You use it this way:

return <Greeter whoToGreet='world' />;

You don't use it this way:

let Greet = new Greeter();
return <Greet whoToGreet='world' />;

In the first example, we're passing around Greeter, the constructor function for our component. That's the correct usage. In the second example, we're passing around an instance of Greeter. That's incorrect, and will fail at runtime with an error like "Object is not a function".


The problem with this code

function renderGreeting(Elem: React.Component<any, any>) {
    return <span>Hello, <Elem />!</span>;
}

is that it's expecting an instance of React.Component. What you want is a function that takes a constructor for React.Component:

function renderGreeting(Elem: new() => React.Component<any, any>) {
    return <span>Hello, <Elem />!</span>;
}

or similarly:

function renderGreeting(Elem: typeof React.Component) {
    return <span>Hello, <Elem />!</span>;
}

C# Double - ToString() formatting with two decimal places but no rounding

The following rounds the numbers, but only shows up to 2 decimal places (removing any trailing zeros), thanks to .##.

decimal d0 = 24.154m;
decimal d1 = 24.155m;
decimal d2 = 24.1m;
decimal d3 = 24.0m;

d0.ToString("0.##");   //24.15
d1.ToString("0.##");   //24.16 (rounded up)
d2.ToString("0.##");   //24.1  
d3.ToString("0.##");   //24

http://dobrzanski.net/2009/05/14/c-decimaltostring-and-how-to-get-rid-of-trailing-zeros/

Convert RGB values to Integer

int rgb = ((r&0x0ff)<<16)|((g&0x0ff)<<8)|(b&0x0ff);

If you know that your r, g, and b values are never > 255 or < 0 you don't need the &0x0ff

Additionaly

int red = (rgb>>16)&0x0ff;
int green=(rgb>>8) &0x0ff;
int blue= (rgb)    &0x0ff;

No need for multipling.

How to get the function name from within that function?

This might work for you:

function foo() { bar(); }

function bar() { console.log(bar.caller.name); }

running foo() will output "foo" or undefined if you call from an anonymous function.

It works with constructors too, in which case it would output the name of the calling constructor (eg "Foo").

More info here: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function/Caller

They claim it's non-standard, but also that it's supported by all major browsers: Firefox, Safari, Chrome, Opera and IE.

Eclipse JPA Project Change Event Handler (waiting)

I still have the same issue in Neon.2 My solution is to disable the JPA Configurator.

Open the Eclipse Preferences (not the project prefs!). Go to Maven --> Java EE Integration and disable the JPA Configurator. I also disabled the JAX-RS Configurator and the JSF Configurator.

From that point on the JPA Project Change Event Handler doesn't show up anymore.

Restart Eclipse if the change does not take effect immediately.

CSS align one item right with flexbox

For a terse, pure flexbox option, group the left-aligned items and the right-aligned items:

<div class="wrap">
  <div>
    <span>One</span>
    <span>Two</span>
  </div>
  <div>Three</div>
</div>

and use space-between:

.wrap {
  display: flex;
  background: #ccc;
  justify-content: space-between;
}

This way you can group multiple items to the right(or just one).

https://jsfiddle.net/c9mkewwv/3/

Playing HTML5 video on fullscreen in android webview

This is great. But if you want your website links to open in the app itself, add this code in your ExampleActivity.java:

webView.setWebViewClient(new WebViewClient() {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            if (Uri.parse(url).getHost().endsWith("yourwebsite.com")) {
                return false;
            }

            Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
            view.getContext().startActivity(intent);
            return true;
        }
    });

How to get Spinner value?

The Spinner should fire an "OnItemSelected" event when something is selected:

spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
    public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
        Object item = parent.getItemAtPosition(pos);
    }
    public void onNothingSelected(AdapterView<?> parent) {
    }
});

How do you do exponentiation in C?

To add to what Evan said: C does not have a built-in operator for exponentiation, because it is not a primitive operation for most CPUs. Thus, it's implemented as a library function.

Also, for computing the function e^x, you can use the exp(double), expf(float), and expl(long double) functions.

Note that you do not want to use the ^ operator, which is the bitwise exclusive OR operator.

Get java.nio.file.Path object from java.io.File

As many have suggested, JRE v1.7 and above has File.toPath();

File yourFile = ...;
Path yourPath = yourFile.toPath();

On Oracle's jdk 1.7 documentation which is also mentioned in other posts above, the following equivalent code is described in the description for toPath() method, which may work for JRE v1.6;

File yourFile = ...;
Path yourPath = FileSystems.getDefault().getPath(yourFile.getPath());

What is the difference between exit and return?

  • return returns from the current function; it's a language keyword like for or break.
  • exit() terminates the whole program, wherever you call it from. (After flushing stdio buffers and so on).

The only case when both do (nearly) the same thing is in the main() function, as a return from main performs an exit().

In most C implementations, main is a real function called by some startup code that does something like int ret = main(argc, argv); exit(ret);. The C standard guarantees that something equivalent to this happens if main returns, however the implementation handles it.

Example with return:

#include <stdio.h>

void f(){
    printf("Executing f\n");
    return;
}

int main(){
    f();
    printf("Back from f\n");
}

If you execute this program it prints:

Executing f
Back from f

Another example for exit():

#include <stdio.h>
#include <stdlib.h>

void f(){
    printf("Executing f\n");
    exit(0);
}

int main(){
    f();
    printf("Back from f\n");
}

If you execute this program it prints:

Executing f

You never get "Back from f". Also notice the #include <stdlib.h> necessary to call the library function exit().

Also notice that the parameter of exit() is an integer (it's the return status of the process that the launcher process can get; the conventional usage is 0 for success or any other value for an error).

The parameter of the return statement is whatever the return type of the function is. If the function returns void, you can omit the return at the end of the function.

Last point, exit() come in two flavors _exit() and exit(). The difference between the forms is that exit() (and return from main) calls functions registered using atexit() or on_exit() before really terminating the process while _exit() (from #include <unistd.h>, or its synonymous _Exit from #include <stdlib.h>) terminates the process immediately.

Now there are also issues that are specific to C++.

C++ performs much more work than C when it is exiting from functions (return-ing). Specifically it calls destructors of local objects going out of scope. In most cases programmers won't care much of the state of a program after the processus stopped, hence it wouldn't make much difference: allocated memory will be freed, file ressource closed and so on. But it may matter if your destructor performs IOs. For instance automatic C++ OStream locally created won't be flushed on a call to exit and you may lose some unflushed data (on the other hand static OStream will be flushed).

This won't happen if you are using the good old C FILE* streams. These will be flushed on exit(). Actually, the rule is the same that for registered exit functions, FILE* will be flushed on all normal terminations, which includes exit(), but not calls to _exit() or abort().

You should also keep in mind that C++ provide a third way to get out of a function: throwing an exception. This way of going out of a function will call destructor. If it is not catched anywhere in the chain of callers, the exception can go up to the main() function and terminate the process.

Destructors of static C++ objects (globals) will be called if you call either return from main() or exit() anywhere in your program. They wont be called if the program is terminated using _exit() or abort(). abort() is mostly useful in debug mode with the purpose to immediately stop the program and get a stack trace (for post mortem analysis). It is usually hidden behind the assert() macro only active in debug mode.

When is exit() useful ?

exit() means you want to immediately stops the current process. It can be of some use for error management when we encounter some kind of irrecoverable issue that won't allow for your code to do anything useful anymore. It is often handy when the control flow is complicated and error codes has to be propagated all way up. But be aware that this is bad coding practice. Silently ending the process is in most case the worse behavior and actual error management should be preferred (or in C++ using exceptions).

Direct calls to exit() are especially bad if done in libraries as it will doom the library user and it should be a library user's choice to implement some kind of error recovery or not. If you want an example of why calling exit() from a library is bad, it leads for instance people to ask this question.

There is an undisputed legitimate use of exit() as the way to end a child process started by fork() on Operating Systems supporting it. Going back to the code before fork() is usually a bad idea. This is the rationale explaining why functions of the exec() family will never return to the caller.

c++ "Incomplete type not allowed" error accessing class reference information (Circular dependency with forward declaration)

Here is what I had and what caused my "incomplete type error":

#include "X.h" // another already declared class
class Big {...} // full declaration of class A

class Small : Big {
    Small() {}
    Small(X); // line 6
}
//.... all other stuff

What I did in the file "Big.cpp", where I declared the A2's constructor with X as a parameter is..

Big.cpp

Small::Big(X my_x) { // line 9 <--- LOOK at this !
}

I wrote "Small::Big" instead of "Small::Small", what a dumb mistake.. I received the error "incomplete type is now allowed" for the class X all the time (in lines 6 and 9), which made a total confusion..

Anyways, that is where a mistake can happen, and the main reason is that I was tired when I wrote it and I needed 2 hours of exploring and rewriting the code to reveal it.

How to force IE10 to render page in IE9 document mode

there are many ways can do this:

add X-UA-Compatible tag to head http response header

using IE tools F12

change windows Registry

Multiple axis line chart in excel

The picture you showd in the question is actually a chart made using JavaScript. It is actually very easy to plot multi-axis chart using JavaScript with the help of 3rd party libraries like HighChart.js or D3.js. Here I propose to use the Funfun Excel add-in which allows you to use JavaScript directly in Excel so you could plot chart like you've showed easily in Excel. Here I made an example using Funfun in Excel.

enter image description here

You could see in this chart you have one axis of Rainfall at the left side while two axis of Temperature and Sea-pressure level at the right side. This is also a combination of line chart and bar chart for different datasets. In this example, with the help of the Funfun add-in, I used HighChart.js to plot this chart.

Funfun also has an online editor in which you could test your JavaScript code with you data. You could check the detailed code of this example on the link below.

https://www.funfun.io/1/#/edit/5a43b416b848f771fbcdee2c

Edit: The content on the previous link has been changed so I posted a new link here. The link below is the original link https://www.funfun.io/1/#/edit/5a55dc978dfd67466879eb24

If you are satisfied with the result you achieved in the online editor, you could easily load the result into you Excel using the URL above. Of couse first you need to insert the Funfun add-in from Insert - My add-ins. Here are some screenshots showing how you could do this.

enter image description here

enter image description here

enter image description here

Disclosure: I'm a developer of Funfun

What's "P=NP?", and why is it such a famous question?

P stands for polynomial time. NP stands for non-deterministic polynomial time.

Definitions:

  • Polynomial time means that the complexity of the algorithm is O(n^k), where n is the size of your data (e. g. number of elements in a list to be sorted), and k is a constant.

  • Complexity is time measured in the number of operations it would take, as a function of the number of data items.

  • Operation is whatever makes sense as a basic operation for a particular task. For sorting, the basic operation is a comparison. For matrix multiplication, the basic operation is multiplication of two numbers.

Now the question is, what does deterministic vs. non-deterministic mean? There is an abstract computational model, an imaginary computer called a Turing machine (TM). This machine has a finite number of states, and an infinite tape, which has discrete cells into which a finite set of symbols can be written and read. At any given time, the TM is in one of its states, and it is looking at a particular cell on the tape. Depending on what it reads from that cell, it can write a new symbol into that cell, move the tape one cell forward or backward, and go into a different state. This is called a state transition. Amazingly enough, by carefully constructing states and transitions, you can design a TM, which is equivalent to any computer program that can be written. This is why it is used as a theoretical model for proving things about what computers can and cannot do.

There are two kinds of TM's that concern us here: deterministic and non-deterministic. A deterministic TM only has one transition from each state for each symbol that it is reading off the tape. A non-deterministic TM may have several such transition, i. e. it is able to check several possibilities simultaneously. This is sort of like spawning multiple threads. The difference is that a non-deterministic TM can spawn as many such "threads" as it wants, while on a real computer only a specific number of threads can be executed at a time (equal to the number of CPUs). In reality, computers are basically deterministic TMs with finite tapes. On the other hand, a non-deterministic TM cannot be physically realized, except maybe with a quantum computer.

It has been proven that any problem that can be solved by a non-deterministic TM can be solved by a deterministic TM. However, it is not clear how much time it will take. The statement P=NP means that if a problem takes polynomial time on a non-deterministic TM, then one can build a deterministic TM which would solve the same problem also in polynomial time. So far nobody has been able to show that it can be done, but nobody has been able to prove that it cannot be done, either.

NP-complete problem means an NP problem X, such that any NP problem Y can be reduced to X by a polynomial reduction. That implies that if anyone ever comes up with a polynomial-time solution to an NP-complete problem, that will also give a polynomial-time solution to any NP problem. Thus that would prove that P=NP. Conversely, if anyone were to prove that P!=NP, then we would be certain that there is no way to solve an NP problem in polynomial time on a conventional computer.

An example of an NP-complete problem is the problem of finding a truth assignment that would make a boolean expression containing n variables true.
For the moment in practice any problem that takes polynomial time on the non-deterministic TM can only be done in exponential time on a deterministic TM or on a conventional computer.
For example, the only way to solve the truth assignment problem is to try 2^n possibilities.

How to replace existing value of ArrayList element in Java

Use the set method to replace the old value with a new one.

list.set( 2, "New" );

Using AJAX to pass variable to PHP and retrieve those using AJAX again

In your PhP file there's going to be a variable called $_REQUEST and it contains an array with all the data send from Javascript to PhP using AJAX.

Try this: var_dump($_REQUEST); and check if you're receiving the values.

Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding. The statement has been terminated

If you are using ASP.NET Core with the Startup.cs convention, you can access and set the query command timeout option like this:

public void ConfigureServices(IServiceCollection services)
{
    services.AddDbContextPool<MyDbContext>(_ =>
    {
        _.UseSqlServer(Configuration.GetConnectionString("MyConnectionString"), options => 
        {
            options.CommandTimeout(180); // 3 minutes
        });
    });
}

How to add action listener that listens to multiple buttons

There are good answers here but let me address the more global point of adding action listener that listens to multiple buttons.

There are two popular approaches.

Using a Common Action Listener

You can get the source of the action in your actionPerformed(ActionEvent e) implementation:

JButton button1, button2; //your button

@Override
public void actionPerformed(ActionEvent e) {

    JButton actionSource = (JButton) e.getSource();

    if(actionSource.equals(button1)){
        // YOU BUTTON 1 CODE HERE
    } else if (actionSource.equals(button2)) {
        // YOU BUTTON 2 CODE HERE
    }
}

Using ActionCommand

With this approach you setting the actionCommand field of your button which later will allow you to use switch:

button1.setActionCommand("actionName1");
button2.setActionCommand("actionName2");

And later:

@Override
public void actionPerformed(ActionEvent e) {
    String actionCommand = ((JButton) e.getSource()).getActionCommand();

    switch (actionCommand) {
        case "actionName1": 
            // YOU BUTTON 1 CODE HERE
        break;
        case "actionName2": 
            // YOU BUTTON 2 CODE HERE
        break;
    }
}

Check out to learn more about JFrame Buttons, Listeners and Fields.

Jenkins: Failed to connect to repository

I faced a similar issue when I tried to connect jenkins in my Windows server with my private GIT repo. Following is the error returned in the source code management section of Jenkins job

Failed to connect to repository : Command "git.exe ls-remote -h ssh://git@my_server/repo.git HEAD" returned status code 128: stdout: stderr: Load key "C:\Windows\TEMP\ssh4813927591749610777.key": invalid format git@my_server: Permission denied (publickey). fatal: Could not read from remote repository.

Please make sure you have the correct access rights and the repository exists.

This error is thrown because jenkins is not able to pick the private ssh key from its user directory. I solved this in the following manner

Step 1

In the jenkins job, fill up the following info under Source Code Management

Repositories

Repository URL: ssh://git@my_server/repo.git
Credentials: -none-

Step 2

In my setup jenkins is running under local system account, so the user directory is C:\Windows\System32\config\systemprofile (This is the important thing in this setup that is not very obvious).

Now create ssh private and public keys using ssh-keygen -t rsa -C "key label" via git bash shell. The ssh private and public keys go under .ssh directory of your logged in user directory. Just copy the .ssh folder and paste it under C:\Windows\System32\config\systemprofile

Step 3

Add your public key to your GIT server account. Run the jenkins job and now you should be able to connect to the GIT account via ssh from jenkins.

SQL query to check if a name begins and ends with a vowel

select distinct(city) from STATION 
where lower(substr(city, -1)) in ('a','e','i','o','u') 
      and lower(substr(city, 1,1)) in ('a','e','i','o','u');

Incorrect integer value: '' for column 'id' at row 1

Try to edit your my.cf and comment the original sql_mode and add sql_mode = "".

vi /etc/mysql/my.cnf

sql_mode = ""

save and quit...

service mysql restart

Sending files using POST with HttpURLConnection

To upload file on server with some parameter using MultipartUtility in simple way.

MultipartUtility.java

public class MultipartUtility {

    private final String boundary;
    private static final String LINE_FEED = "\r\n";
    private HttpURLConnection httpConn;
    private String charset;
    private OutputStream outputStream;
    private PrintWriter writer;

    /**
     * This constructor initializes a new HTTP POST request with content type
     * is set to multipart/form-data
     *
     * @param requestURL
     * @param charset
     * @throws IOException
     */
    public MultipartUtility(String requestURL, String charset)
            throws IOException {
        this.charset = charset;

        // creates a unique boundary based on time stamp
        boundary = "===" + System.currentTimeMillis() + "===";

        URL url = new URL(requestURL);
        Log.e("URL", "URL : " + requestURL.toString());
        httpConn = (HttpURLConnection) url.openConnection();
        httpConn.setUseCaches(false);
        httpConn.setDoOutput(true); // indicates POST method
        httpConn.setDoInput(true);
        httpConn.setRequestProperty("Content-Type",
                "multipart/form-data; boundary=" + boundary);
        httpConn.setRequestProperty("User-Agent", "CodeJava Agent");
        httpConn.setRequestProperty("Test", "Bonjour");
        outputStream = httpConn.getOutputStream();
        writer = new PrintWriter(new OutputStreamWriter(outputStream, charset),
                true);
    }

    /**
     * Adds a form field to the request
     *
     * @param name  field name
     * @param value field value
     */
    public void addFormField(String name, String value) {
        writer.append("--" + boundary).append(LINE_FEED);
        writer.append("Content-Disposition: form-data; name=\"" + name + "\"")
                .append(LINE_FEED);
        writer.append("Content-Type: text/plain; charset=" + charset).append(
                LINE_FEED);
        writer.append(LINE_FEED);
        writer.append(value).append(LINE_FEED);
        writer.flush();
    }

    /**
     * Adds a upload file section to the request
     *
     * @param fieldName  name attribute in <input type="file" name="..." />
     * @param uploadFile a File to be uploaded
     * @throws IOException
     */
    public void addFilePart(String fieldName, File uploadFile)
            throws IOException {
        String fileName = uploadFile.getName();
        writer.append("--" + boundary).append(LINE_FEED);
        writer.append(
                "Content-Disposition: form-data; name=\"" + fieldName
                        + "\"; filename=\"" + fileName + "\"")
                .append(LINE_FEED);
        writer.append(
                "Content-Type: "
                        + URLConnection.guessContentTypeFromName(fileName))
                .append(LINE_FEED);
        writer.append("Content-Transfer-Encoding: binary").append(LINE_FEED);
        writer.append(LINE_FEED);
        writer.flush();

        FileInputStream inputStream = new FileInputStream(uploadFile);
        byte[] buffer = new byte[4096];
        int bytesRead = -1;
        while ((bytesRead = inputStream.read(buffer)) != -1) {
            outputStream.write(buffer, 0, bytesRead);
        }
        outputStream.flush();
        inputStream.close();

        writer.append(LINE_FEED);
        writer.flush();
    }

    /**
     * Adds a header field to the request.
     *
     * @param name  - name of the header field
     * @param value - value of the header field
     */
    public void addHeaderField(String name, String value) {
        writer.append(name + ": " + value).append(LINE_FEED);
        writer.flush();
    }

    /**
     * Completes the request and receives response from the server.
     *
     * @return a list of Strings as response in case the server returned
     * status OK, otherwise an exception is thrown.
     * @throws IOException
     */
    public String finish() throws IOException {
        StringBuffer response = new StringBuffer();

        writer.append(LINE_FEED).flush();
        writer.append("--" + boundary + "--").append(LINE_FEED);
        writer.close();

        // checks server's status code first
        int status = httpConn.getResponseCode();
        if (status == HttpURLConnection.HTTP_OK) {
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    httpConn.getInputStream()));
            String line = null;
            while ((line = reader.readLine()) != null) {
                response.append(line);
            }
            reader.close();
            httpConn.disconnect();
        } else {
            throw new IOException("Server returned non-OK status: " + status);
        }

        return response.toString();
    }
}

To upload you file along with parameters.

NOTE : put this code below in non-ui-thread to get response.

String charset = "UTF-8";
String requestURL = "YOUR_URL";

MultipartUtility multipart = new MultipartUtility(requestURL, charset);
multipart.addFormField("param_name_1", "param_value");
multipart.addFormField("param_name_2", "param_value");
multipart.addFormField("param_name_3", "param_value");
multipart.addFilePart("file_param_1", new File(file_path));
String response = multipart.finish(); // response from server.

Understanding the map function

Simplifying a bit, you can imagine map() doing something like this:

def mymap(func, lst):
    result = []
    for e in lst:
        result.append(func(e))
    return result

As you can see, it takes a function and a list, and returns a new list with the result of applying the function to each of the elements in the input list. I said "simplifying a bit" because in reality map() can process more than one iterable:

If additional iterable arguments are passed, function must take that many arguments and is applied to the items from all iterables in parallel. If one iterable is shorter than another it is assumed to be extended with None items.

For the second part in the question: What role does this play in making a Cartesian product? well, map() could be used for generating the cartesian product of a list like this:

lst = [1, 2, 3, 4, 5]

from operator import add
reduce(add, map(lambda i: map(lambda j: (i, j), lst), lst))

... But to tell the truth, using product() is a much simpler and natural way to solve the problem:

from itertools import product
list(product(lst, lst))

Either way, the result is the cartesian product of lst as defined above:

[(1, 1), (1, 2), (1, 3), (1, 4), (1, 5),
 (2, 1), (2, 2), (2, 3), (2, 4), (2, 5),
 (3, 1), (3, 2), (3, 3), (3, 4), (3, 5),
 (4, 1), (4, 2), (4, 3), (4, 4), (4, 5),
 (5, 1), (5, 2), (5, 3), (5, 4), (5, 5)]

Location of WSDL.exe

If you have Windows 10 and VS2019, and the .NET Framework 4.8, below you can see the Location of WSDL.exe

Path in your pc C:\Program Files (x86)\Microsoft SDKs\Windows\v10.0A\bin\NETFX 4.8 Tools

jQuery autohide element after 5 seconds

I think, you could also do something like...

setTimeout(function(){
    $(".message-class").trigger("click");
}, 5000);

and do your animated effects on the event-click...

$(".message-class").click(function() {
    //your event-code
});

Greetings,

How to call same method for a list of objects?

The *_all() functions are so simple that for a few methods I'd just write the functions. If you have lots of identical functions, you can write a generic function:

def apply_on_all(seq, method, *args, **kwargs):
    for obj in seq:
         getattr(obj, method)(*args, **kwargs)

Or create a function factory:

def create_all_applier(method, doc=None):
    def on_all(seq, *args, **kwargs):
        for obj in seq:
            getattr(obj, method)(*args, **kwargs)
    on_all.__doc__ = doc
    return on_all

start_all = create_all_applier('start', "Start all instances")
stop_all = create_all_applier('stop', "Stop all instances")
...

When to use MyISAM and InnoDB?

Use MyISAM for very unimportant data or if you really need those minimal performance advantages. The read performance is not better in every case for MyISAM.

I would personally never use MyISAM at all anymore. Choose InnoDB and throw a bit more hardware if you need more performance. Another idea is to look at database systems with more features like PostgreSQL if applicable.

EDIT: For the read-performance, this link shows that innoDB often is actually not slower than MyISAM: https://www.percona.com/blog/2007/01/08/innodb-vs-myisam-vs-falcon-benchmarks-part-1/

Find if a textbox is disabled or not using jquery

.prop('disabled') will return a Boolean:

var isDisabled = $('textbox').prop('disabled');

Here's the fiddle: http://jsfiddle.net/unhjM/

How to alter a column's data type in a PostgreSQL table?

See documentation here: http://www.postgresql.org/docs/current/interactive/sql-altertable.html

ALTER TABLE tbl_name ALTER COLUMN col_name TYPE varchar (11);

How to remove trailing whitespaces with sed?

Just for fun:

#!/bin/bash

FILE=$1

if [[ -z $FILE ]]; then
   echo "You must pass a filename -- exiting" >&2
   exit 1
fi

if [[ ! -f $FILE ]]; then
   echo "There is not file '$FILE' here -- exiting" >&2
   exit 1
fi

BEFORE=`wc -c "$FILE" | cut --delimiter=' ' --fields=1`

# >>>>>>>>>>
sed -i.bak -e's/[ \t]*$//' "$FILE"
# <<<<<<<<<<

AFTER=`wc -c "$FILE" | cut --delimiter=' ' --fields=1`

if [[ $? != 0 ]]; then
   echo "Some error occurred" >&2
else
   echo "Filtered '$FILE' from $BEFORE characters to $AFTER characters"
fi

PHP - remove <img> tag from string

I wanted to display the first 300 words of a news story as a preview which unfortunately meant that if a story had an image within the first 300 words then it was displayed in the list of previews which really messed with my layout. I used the above code to hide all of the images from the string taken from my database and it works wonderfully!

$news = $row_latest_news ['content'];
$news = preg_replace("/<img[^>]+\>/i", "", $news); 
if (strlen($news) > 300){
echo substr($news, 0, strpos($news,' ',300)).'...';
} 
else { 
echo $news; 
}

How can I get the size of an std::vector as an int?

In the first two cases, you simply forgot to actually call the member function (!, it's not a value) std::vector<int>::size like this:

#include <vector>

int main () {
    std::vector<int> v;
    auto size = v.size();
}

Your third call

int size = v.size();

triggers a warning, as not every return value of that function (usually a 64 bit unsigned int) can be represented as a 32 bit signed int.

int size = static_cast<int>(v.size());

would always compile cleanly and also explicitly states that your conversion from std::vector::size_type to int was intended.

Note that if the size of the vector is greater than the biggest number an int can represent, size will contain an implementation defined (de facto garbage) value.

How to import a CSS file in a React Component

Using extract-css-chunks-webpack-plugin and css-loader loader work for me, see below:

webpack.config.js Import extract-css-chunks-webpack-plugin

const ExtractCssChunks = require('extract-css-chunks-webpack-plugin');

webpack.config.js Add the css rule, Extract css Chunks first then the css loader css-loader will embed them into the html document, ensure css-loader and extract-css-chunks-webpack-plugin are in the package.json dev dependencies

rules: [
      {
        test: /\.css$/,
        use: [
          {
            loader: ExtractCssChunks.loader,
          },
          'css-loader',
        ],
      }
]

webpack.config.js Make instance of the plugin

plugins: [
    new ExtractCssChunks({
      // Options similar to the same options in webpackOptions.output
      // both options are optional
      filename: '[name].css',
      chunkFilename: '[id].css'
    })
  ]

And now importing css is possible And now in a tsx file like index.tsx i can use import like this import './Tree.css' where Tree.css contains css rules like

body {
    background: red;
}

My app is using typescript and this works for me, check my repo for the source : https://github.com/nickjohngray/staticbackeditor

For homebrew mysql installs, where's my.cnf?

The homebrew mysql contains sample configuration files in the installation's support-files folder.

ls $(brew --prefix mysql)/support-files/my-*

If you need to change the default settings you can use one of these as a starting point.

cp $(brew --prefix mysql)/support-files/my-default.cnf /usr/local/etc/my.cnf

As @rednaw points out, a homebrew install of MySQL will most likely be in /usr/local so the my.cnf file should not be added to the system /etc folder, so I’ve changed the command to copy the file into /usr/local/etc.

If you are using MariaDB rather than MySQL use the following:

cp $(brew --prefix mariadb)/support-files/my-small.cnf /usr/local/etc/my.cnf

How to iterate a table rows with JQuery and access some cell values?

do this:

$("tr.item").each(function(i, tr) {
    var value = $("span.value", tr).text();
    var quantity = $("input.quantity", tr).val();
});

Configure active profile in SpringBoot via Maven

In development, activating a Spring Boot profile when a specific Maven profile is activate is straight. You should use the profiles property of the spring-boot-maven-plugin in the Maven profile such as :

<project>
    <...>
    <profiles>
        <profile>
            <id>development</id>
            <activation>
                <activeByDefault>true</activeByDefault>
            </activation>
            <build>
                <plugins>
                    <plugin>
                        <groupId>org.springframework.boot</groupId>
                        <artifactId>spring-boot-maven-plugin</artifactId>
                        <configuration>
                            <profiles>
                                <profile>development</profile>
                            </profiles>
                        </configuration>
                    </plugin>
                </plugins>
            </build>
        </profile>
    <profiles>
    </...>
</project>

You can run the following command to use both the Spring Boot and the Maven development profile :

mvn spring-boot:run -Pdevelopment

If you want to be able to map any Spring Boot profiles to a Maven profile with the same profile name, you could define a single Maven profile and enabling that as the presence of a Maven property is detected. This property would be the single thing that you need to specify as you run the mvn command.
The profile would look like :

    <profile>
        <id>spring-profile-active</id>
        <activation>
            <property>
                <name>my.active.spring.profiles</name>
            </property>
        </activation>
        <build>
            <plugins>
                <plugin>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-maven-plugin</artifactId>
                    <configuration>
                        <profiles>
                            <profile>${my.active.spring.profiles}</profile>
                        </profiles>
                    </configuration>
                </plugin>
            </plugins>
        </build>
    </profile>

And you can run the following command to use both the Spring Boot and the Maven development profile :

mvn spring-boot:run -Dmy.active.spring.profiles=development

or :

mvn spring-boot:run -Dmy.active.spring.profiles=integration

or :

 mvn spring-boot:run -Dmy.active.spring.profiles=production

And so for...

This kind of configuration makes sense as in the generic Maven profile you rely on the my.active.spring.profiles property that is passed to perform some tasks or value some things.
For example I use this way to configure a generic Maven profile that packages the application and build a docker image specific to the environment selected.

How do I add my new User Control to the Toolbox or a new Winform?

One user control can't be applied to it ownself. So open another winform and the one will appear in the toolbox.

Android getResources().getDrawable() deprecated API 22

Just an example of how I fixed the problem in an array to load a listView, hope it helps.

 mItems = new ArrayList<ListViewItem>();
//    Resources resources = getResources();

//    mItems.add(new ListViewItem(resources.getDrawable(R.drawable.az_lgo), getString(R.string.st_az), getString(R.string.all_nums)));
//    mItems.add(new ListViewItem(resources.getDrawable(R.drawable.ca_lgo), getString(R.string.st_ca), getString(R.string.all_nums)));
//    mItems.add(new ListViewItem(resources.getDrawable(R.drawable.co_lgo), getString(R.string.st_co), getString(R.string.all_nums)));
    mItems.add(new ListViewItem(ResourcesCompat.getDrawable(getResources(), R.drawable.az_lgo, null), getString(R.string.st_az), getString(R.string.all_nums)));
    mItems.add(new ListViewItem(ResourcesCompat.getDrawable(getResources(), R.drawable.ca_lgo, null), getString(R.string.st_ca), getString(R.string.all_nums)));
    mItems.add(new ListViewItem(ResourcesCompat.getDrawable(getResources(), R.drawable.co_lgo, null), getString(R.string.st_co), getString(R.string.all_nums)));

Use images instead of radio buttons

You can use CSS for that.

HTML (only for demo, it is customizable)

<div class="button">
    <input type="radio" name="a" value="a" id="a" />
    <label for="a">a</label>
</div>
<div class="button">
    <input type="radio" name="a" value="b" id="b" />
    <label for="b">b</label>
</div>
<div class="button">
    <input type="radio" name="a" value="c" id="c" />
    <label for="c">c</label>
</div>
...

CSS

input[type="radio"] {
    display: none;
}
input[type="radio"]:checked + label {
    border: 1px solid red;
}

jsFiddle

How is Perl's @INC constructed? (aka What are all the ways of affecting where Perl modules are searched for?)

We will look at how the contents of this array are constructed and can be manipulated to affect where the Perl interpreter will find the module files.

  1. Default @INC

    Perl interpreter is compiled with a specific @INC default value. To find out this value, run env -i perl -V command (env -i ignores the PERL5LIB environmental variable - see #2) and in the output you will see something like this:

    $ env -i perl -V
    ...
    @INC:
     /usr/lib/perl5/site_perl/5.18.0/x86_64-linux-thread-multi-ld
     /usr/lib/perl5/site_perl/5.18.0
     /usr/lib/perl5/5.18.0/x86_64-linux-thread-multi-ld
     /usr/lib/perl5/5.18.0
     .
    

Note . at the end; this is the current directory (which is not necessarily the same as the script's directory). It is missing in Perl 5.26+, and when Perl runs with -T (taint checks enabled).

To change the default path when configuring Perl binary compilation, set the configuration option otherlibdirs:

Configure -Dotherlibdirs=/usr/lib/perl5/site_perl/5.16.3

  1. Environmental variable PERL5LIB (or PERLLIB)

    Perl pre-pends @INC with a list of directories (colon-separated) contained in PERL5LIB (if it is not defined, PERLLIB is used) environment variable of your shell. To see the contents of @INC after PERL5LIB and PERLLIB environment variables have taken effect, run perl -V.

    $ perl -V
    ...
    %ENV:
      PERL5LIB="/home/myuser/test"
    @INC:
     /home/myuser/test
     /usr/lib/perl5/site_perl/5.18.0/x86_64-linux-thread-multi-ld
     /usr/lib/perl5/site_perl/5.18.0
     /usr/lib/perl5/5.18.0/x86_64-linux-thread-multi-ld
     /usr/lib/perl5/5.18.0
     .
    
  2. -I command-line option

    Perl pre-pends @INC with a list of directories (colon-separated) passed as value of the -I command-line option. This can be done in three ways, as usual with Perl options:

    • Pass it on command line:

      perl -I /my/moduledir your_script.pl
      
    • Pass it via the first line (shebang) of your Perl script:

      #!/usr/local/bin/perl -w -I /my/moduledir
      
    • Pass it as part of PERL5OPT (or PERLOPT) environment variable (see chapter 19.02 in Programming Perl)

  3. Pass it via the lib pragma

    Perl pre-pends @INC with a list of directories passed in to it via use lib.

    In a program:

    use lib ("/dir1", "/dir2");
    

    On the command line:

    perl -Mlib=/dir1,/dir2
    

    You can also remove the directories from @INC via no lib.

  4. You can directly manipulate @INC as a regular Perl array.

    Note: Since @INC is used during the compilation phase, this must be done inside of a BEGIN {} block, which precedes the use MyModule statement.

    • Add directories to the beginning via unshift @INC, $dir.

    • Add directories to the end via push @INC, $dir.

    • Do anything else you can do with a Perl array.

Note: The directories are unshifted onto @INC in the order listed in this answer, e.g. default @INC is last in the list, preceded by PERL5LIB, preceded by -I, preceded by use lib and direct @INC manipulation, the latter two mixed in whichever order they are in Perl code.

References:

There does not seem to be a comprehensive @INC FAQ-type post on Stack Overflow, so this question is intended as one.

When to use each approach?

  • If the modules in a directory need to be used by many/all scripts on your site, especially run by multiple users, that directory should be included in the default @INC compiled into the Perl binary.

  • If the modules in the directory will be used exclusively by a specific user for all the scripts that user runs (or if recompiling Perl is not an option to change default @INC in previous use case), set the users' PERL5LIB, usually during user login.

    Note: Please be aware of the usual Unix environment variable pitfalls - e.g. in certain cases running the scripts as a particular user does not guarantee running them with that user's environment set up, e.g. via su.

  • If the modules in the directory need to be used only in specific circumstances (e.g. when the script(s) is executed in development/debug mode, you can either set PERL5LIB manually, or pass the -I option to perl.

  • If the modules need to be used only for specific scripts, by all users using them, use use lib/no lib pragmas in the program itself. It also should be used when the directory to be searched needs to be dynamically determined during runtime - e.g. from the script's command line parameters or script's path (see the FindBin module for very nice use case).

  • If the directories in @INC need to be manipulated according to some complicated logic, either impossible to too unwieldy to implement by combination of use lib/no lib pragmas, then use direct @INC manipulation inside BEGIN {} block or inside a special purpose library designated for @INC manipulation, which must be used by your script(s) before any other modules are used.

    An example of this is automatically switching between libraries in prod/uat/dev directories, with waterfall library pickup in prod if it's missing from dev and/or UAT (the last condition makes the standard "use lib + FindBin" solution fairly complicated. A detailed illustration of this scenario is in How do I use beta Perl modules from beta Perl scripts?.

  • An additional use case for directly manipulating @INC is to be able to add subroutine references or object references (yes, Virginia, @INC can contain custom Perl code and not just directory names, as explained in When is a subroutine reference in @INC called?).

Running windows shell commands with python

You would use the os module system method.

You just put in the string form of the command, the return value is the windows enrivonment variable COMSPEC

For example:

os.system('python') opens up the windows command prompt and runs the python interpreter

os.system('python') example

Need to get a string after a "word" in a string in c#

use indexOf() function

string s = "Error description, code : -1";
int index = s.indexOf("code");
if(index != -1)
{
  //DO YOUR LOGIC
  string errorCode = s.Substring(index+4);
}

Best way to convert strings to symbols in hash

symbolize_keys recursively for any hash:

class Hash
  def symbolize_keys
    self.is_a?(Hash) ? Hash[ self.map { |k,v| [k.respond_to?(:to_sym) ? k.to_sym : k, v.is_a?(Hash) ? v.symbolize_keys : v] } ] : self
  end
end

How to grep and replace

Another option would be to just use perl with globstar.

Enabling shopt -s globstar in your .bashrc (or wherever) allows the ** glob pattern to match all sub-directories and files recursively.

Thus using perl -pXe 's/SEARCH/REPLACE/g' -i ** will recursively replace SEARCH with REPLACE.

The -X flag tells perl to "disable all warnings" - which means that it won't complain about directories.

The globstar also allows you to do things like sed -i 's/SEARCH/REPLACE/g' **/*.ext if you wanted to replace SEARCH with REPLACE in all child files with the extension .ext.

Why is setState in reactjs Async instead of Sync?

Imagine incrementing a counter in some component:

  class SomeComponent extends Component{

    state = {
      updatedByDiv: '',
      updatedByBtn: '',
      counter: 0
    }

    divCountHandler = () => {
      this.setState({
        updatedByDiv: 'Div',
        counter: this.state.counter + 1
      });
      console.log('divCountHandler executed');
    }

    btnCountHandler = () => {
      this.setState({
        updatedByBtn: 'Button',
        counter: this.state.counter + 1
      });
      console.log('btnCountHandler executed');
    }
    ...
    ...
    render(){
      return (
        ...
        // a parent div
        <div onClick={this.divCountHandler}>
          // a child button
          <button onClick={this.btnCountHandler}>Increment Count</button>
        </div>
        ...
      )
    }
  }

There is a count handler attached to both the parent and the child components. This is done purposely so we can execute the setState() twice within the same click event bubbling context, but from within 2 different handlers.

As we would imagine, a single click event on the button would now trigger both these handlers since the event bubbles from target to the outermost container during the bubbling phase.

Therefore the btnCountHandler() executes first, expected to increment the count to 1 and then the divCountHandler() executes, expected to increment the count to 2.

However the count only increments to 1 as you can inspect in React Developer tools.

This proves that react

  • queues all the setState calls

  • comes back to this queue after executing the last method in the context(the divCountHandler in this case)

  • merges all the object mutations happening within multiple setState calls in the same context(all method calls within a single event phase is same context for e.g.) into one single object mutation syntax (merging makes sense because this is why we can update the state properties independently in setState() in the first place)

  • and passes it into one single setState() to prevent re-rendering due to multiple setState() calls (this is a very primitive description of batching).

Resultant code run by react:

this.setState({
  updatedByDiv: 'Div',
  updatedByBtn: 'Button',
  counter: this.state.counter + 1
})

To stop this behaviour, instead of passing objects as arguments to the setState method, callbacks are passed.

    divCountHandler = () => {
          this.setState((prevState, props) => {
            return {
              updatedByDiv: 'Div',
              counter: prevState.counter + 1
            };
          });
          console.log('divCountHandler executed');
        }

    btnCountHandler = () => {
          this.setState((prevState, props) => {
            return {
              updatedByBtn: 'Button',
              counter: prevState.counter + 1
            };
          });
      console.log('btnCountHandler executed');
    }

After the last method finishes execution and when react returns to process the setState queue, it simply calls the callback for each setState queued, passing in the previous component state.

This way react ensures that the last callback in the queue gets to update the state that all of its previous counterparts have laid hands on.

How do I output coloured text to a Linux terminal?

This is an old topic, but I wrote a class with nested subclasses and static members for colors defined by simple C macros.

I got the color function from this post Color Text In C Programming in dreamincode.net by user no2pencil.

I made it this way so to be able to use the static constants in std::cout stream like this:

cout << zkr::cc::fore::red << "This is red text. " 
     << zkr::cc::console << "And changing to console default colors, fg, bg."
     << endl;

The class and a test program source code can be downloaded here.

cc::console will reset to console default colors and attributes, cc::underline will underline the text, which works on putty which I've tested the test program.

Colors:

black
blue
red
magenta
green
cyan
yellow
white

lightblack
lightblue
lightred
lightmagenta
lightgreen
lightcyan
lightyellow
lightwhite

Which can be used with both fore and back static subclasses of the cc static class.

EDIT 2017

I'm just adding the class code here to be more practical.

The color code macros:

#define CC_CONSOLE_COLOR_DEFAULT "\033[0m"
#define CC_FORECOLOR(C) "\033[" #C "m"
#define CC_BACKCOLOR(C) "\033[" #C "m"
#define CC_ATTR(A) "\033[" #A "m"

and the main color function that defines a color or an attribute to the screen:

char *cc::color(int attr, int fg, int bg)
{
    static char command[13];

    /* Command is the control command to the terminal */
    sprintf(command, "%c[%d;%d;%dm", 0x1B, attr, fg + 30, bg + 40);
    return command;
}

ccolor.h

#include <stdio.h>

#define CC_CONSOLE_COLOR_DEFAULT "\033[0m"
#define CC_FORECOLOR(C) "\033[" #C "m"
#define CC_BACKCOLOR(C) "\033[" #C "m"
#define CC_ATTR(A) "\033[" #A "m"

namespace zkr
{
    class cc
    {
    public:

        class fore
        {
        public:
            static const char *black;
            static const char *blue;
            static const char *red;
            static const char *magenta;
            static const char *green;
            static const char *cyan;
            static const char *yellow;
            static const char *white;
            static const char *console;

            static const char *lightblack;
            static const char *lightblue;
            static const char *lightred;
            static const char *lightmagenta;
            static const char *lightgreen;
            static const char *lightcyan;
            static const char *lightyellow;
            static const char *lightwhite;
        };

        class back
        {
        public:
            static const char *black;
            static const char *blue;
            static const char *red;
            static const char *magenta;
            static const char *green;
            static const char *cyan;
            static const char *yellow;
            static const char *white;
            static const char *console;

            static const char *lightblack;
            static const char *lightblue;
            static const char *lightred;
            static const char *lightmagenta;
            static const char *lightgreen;
            static const char *lightcyan;
            static const char *lightyellow;
            static const char *lightwhite;
        };

        static char *color(int attr, int fg, int bg);
        static const char *console;
        static const char *underline;
        static const char *bold;
    };
}

ccolor.cpp

#include "ccolor.h"

using namespace std;

namespace zkr
{
    enum Color
    {
        Black,
        Red,
        Green,
        Yellow,
        Blue,
        Magenta,
        Cyan,
        White,
        Default = 9
    };

    enum Attributes
    {
        Reset,
        Bright,
        Dim,
        Underline,
        Blink,
        Reverse,
        Hidden
    };

    char *cc::color(int attr, int fg, int bg)
    {
        static char command[13];
        /* Command is the control command to the terminal */
        sprintf(command, "%c[%d;%d;%dm", 0x1B, attr, fg + 30, bg + 40);
        return command;
    }

    const char *cc::console = CC_CONSOLE_COLOR_DEFAULT;
    const char *cc::underline = CC_ATTR(4);
    const char *cc::bold = CC_ATTR(1);

    const char *cc::fore::black = CC_FORECOLOR(30);
    const char *cc::fore::blue = CC_FORECOLOR(34);
    const char *cc::fore::red = CC_FORECOLOR(31);
    const char *cc::fore::magenta = CC_FORECOLOR(35);
    const char *cc::fore::green = CC_FORECOLOR(92);
    const char *cc::fore::cyan = CC_FORECOLOR(36);
    const char *cc::fore::yellow = CC_FORECOLOR(33);
    const char *cc::fore::white = CC_FORECOLOR(37);
    const char *cc::fore::console = CC_FORECOLOR(39);

    const char *cc::fore::lightblack = CC_FORECOLOR(90);
    const char *cc::fore::lightblue = CC_FORECOLOR(94);
    const char *cc::fore::lightred = CC_FORECOLOR(91);
    const char *cc::fore::lightmagenta = CC_FORECOLOR(95);
    const char *cc::fore::lightgreen = CC_FORECOLOR(92);
    const char *cc::fore::lightcyan = CC_FORECOLOR(96);
    const char *cc::fore::lightyellow = CC_FORECOLOR(93);
    const char *cc::fore::lightwhite = CC_FORECOLOR(97);

    const char *cc::back::black = CC_BACKCOLOR(40);
    const char *cc::back::blue = CC_BACKCOLOR(44);
    const char *cc::back::red = CC_BACKCOLOR(41);
    const char *cc::back::magenta = CC_BACKCOLOR(45);
    const char *cc::back::green = CC_BACKCOLOR(42);
    const char *cc::back::cyan = CC_BACKCOLOR(46);
    const char *cc::back::yellow = CC_BACKCOLOR(43);
    const char *cc::back::white = CC_BACKCOLOR(47);
    const char *cc::back::console = CC_BACKCOLOR(49);

    const char *cc::back::lightblack = CC_BACKCOLOR(100);
    const char *cc::back::lightblue = CC_BACKCOLOR(104);
    const char *cc::back::lightred = CC_BACKCOLOR(101);
    const char *cc::back::lightmagenta = CC_BACKCOLOR(105);
    const char *cc::back::lightgreen = CC_BACKCOLOR(102);
    const char *cc::back::lightcyan = CC_BACKCOLOR(106);
    const char *cc::back::lightyellow = CC_BACKCOLOR(103);
    const char *cc::back::lightwhite = CC_BACKCOLOR(107);
}

Get Max value from List<myType>

Easiest way is to use System.Linq as previously described

using System.Linq;

public int GetHighestValue(List<MyTypes> list)
{
    return list.Count > 0 ? list.Max(t => t.Age) : 0; //could also return -1
}

This is also possible with a Dictionary

using System.Linq;

public int GetHighestValue(Dictionary<MyTypes, OtherType> obj)
{
    return obj.Count > 0 ? obj.Max(t => t.Key.Age) : 0; //could also return -1
}

Getting rid of \n when using .readlines()

You can use .rstrip('\n') to only remove newlines from the end of the string:

for i in contents:
    alist.append(i.rstrip('\n'))

This leaves all other whitespace intact. If you don't care about whitespace at the start and end of your lines, then the big heavy hammer is called .strip().

However, since you are reading from a file and are pulling everything into memory anyway, better to use the str.splitlines() method; this splits one string on line separators and returns a list of lines without those separators; use this on the file.read() result and don't use file.readlines() at all:

alist = t.read().splitlines()

Convert Uppercase Letter to Lowercase and First Uppercase in Sentence using CSS

If you can make all characters lowercase on the server than you can apply:

text-transform: capitalize

I don't think text-transform will work with uppercase letters as the input.

Process with an ID #### is not running in visual studio professional 2013 update 3

Close VS. Navigate to the folder of the solution and delete the hidden .vs folder. Restart VS. Hit F5 and IIS Express should load as normal, allowing you to debug.

If this not working, then:

  1. right click your solution and go to properties

  2. Click left menu Web tag

  3. Click checkbox "Override application root Url"

and run again your project.

Modular multiplicative inverse function in Python

Here is my code, it might be sloppy but it seems to work for me anyway.

# a is the number you want the inverse for
# b is the modulus

def mod_inverse(a, b):
    r = -1
    B = b
    A = a
    eq_set = []
    full_set = []
    mod_set = []

    #euclid's algorithm
    while r!=1 and r!=0:
        r = b%a
        q = b//a
        eq_set = [r, b, a, q*-1]
        b = a
        a = r
        full_set.append(eq_set)

    for i in range(0, 4):
        mod_set.append(full_set[-1][i])

    mod_set.insert(2, 1)
    counter = 0

    #extended euclid's algorithm
    for i in range(1, len(full_set)):
        if counter%2 == 0:
            mod_set[2] = full_set[-1*(i+1)][3]*mod_set[4]+mod_set[2]
            mod_set[3] = full_set[-1*(i+1)][1]

        elif counter%2 != 0:
            mod_set[4] = full_set[-1*(i+1)][3]*mod_set[2]+mod_set[4]
            mod_set[1] = full_set[-1*(i+1)][1]

        counter += 1

    if mod_set[3] == B:
        return mod_set[2]%B
    return mod_set[4]%B

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

Here are the commands to restore the old behavior:

# create a script that calls launchctl iterating through /etc/launchd.conf
echo '#!/bin/sh

while read line || [[ -n $line ]] ; do launchctl $line ; done < /etc/launchd.conf;
' > /usr/local/bin/launchd.conf.sh

# make it executable
chmod +x /usr/local/bin/launchd.conf.sh

# launch the script at startup
echo '<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
  <key>Label</key>
  <string>launchd.conf</string>
  <key>ProgramArguments</key>
  <array>
    <string>sh</string>
    <string>-c</string>
    <string>/usr/local/bin/launchd.conf.sh</string>
  </array>
  <key>RunAtLoad</key>
  <true/>
</dict>
</plist>
' > /Library/LaunchAgents/launchd.conf.plist

Now you can specify commands like setenv JAVA_HOME /Library/Java/Home in /etc/launchd.conf.

Checked on El Capitan.

keycode 13 is for which key

Keycode 13 means the Enter key.

If you would want to get more keycodes and what the key the key is, go to: https://keycode.info

What is the right way to debug in iPython notebook?

A native debugger is being made available as an extension to JupyterLab. Released a few weeks ago, this can be installed by getting the relevant extension, as well as xeus-python kernel (which notably comes without the magics well-known to ipykernel users):

jupyter labextension install @jupyterlab/debugger
conda install xeus-python -c conda-forge

This enables a visual debugging experience well-known from other IDEs.

enter image description here

Source: A visual debugger for Jupyter

Sourcetree - undo unpushed commits

If you select the log entry to which you want to revert to then you can click on "Reset to this commit". Only use this option if you didn't push the reverse commit changes. If you're worried about losing the changes then you can use the soft mode which will leave a set of uncommitted changes (what you just changed). Using the mixed resets the working copy but keeps those changes, and a hard will just get rid of the changes entirely. Here's some screenshots:

enter image description here

ITextSharp HTML to PDF?

I came across the same question a few weeks ago and this is the result from what I found. This method does a quick dump of HTML to a PDF. The document will most likely need some format tweaking.

private MemoryStream createPDF(string html)
{
    MemoryStream msOutput = new MemoryStream();
    TextReader reader = new StringReader(html);

    // step 1: creation of a document-object
    Document document = new Document(PageSize.A4, 30, 30, 30, 30);

    // step 2:
    // we create a writer that listens to the document
    // and directs a XML-stream to a file
    PdfWriter writer = PdfWriter.GetInstance(document, msOutput);

    // step 3: we create a worker parse the document
    HTMLWorker worker = new HTMLWorker(document);

    // step 4: we open document and start the worker on the document
    document.Open();
    worker.StartDocument();

    // step 5: parse the html into the document
    worker.Parse(reader);

    // step 6: close the document and the worker
    worker.EndDocument();
    worker.Close();
    document.Close();

    return msOutput;
}

Setting query string using Fetch GET request

var paramsdate=01+'%s'+12+'%s'+2012+'%s';

request.get("https://www.exampleurl.com?fromDate="+paramsDate;

How do I use a pipe to redirect the output of one command to the input of another?

This should work:

for /F "tokens=*" %i in ('temperature') do prismcom.exe usb %i

If running in a batch file, you need to use %%i instead of just %i (in both places).

Observable Finally on Subscribe

The current "pipable" variant of this operator is called finalize() (since RxJS 6). The older and now deprecated "patch" operator was called finally() (until RxJS 5.5).

I think finalize() operator is actually correct. You say:

do that logic only when I subscribe, and after the stream has ended

which is not a problem I think. You can have a single source and use finalize() before subscribing to it if you want. This way you're not required to always use finalize():

let source = new Observable(observer => {
  observer.next(1);
  observer.error('error message');
  observer.next(3);
  observer.complete();
}).pipe(
  publish(),
);

source.pipe(
  finalize(() => console.log('Finally callback')),
).subscribe(
  value => console.log('#1 Next:', value),
  error => console.log('#1 Error:', error),
  () => console.log('#1 Complete')
);

source.subscribe(
  value => console.log('#2 Next:', value),
  error => console.log('#2 Error:', error),
  () => console.log('#2 Complete')
);

source.connect();

This prints to console:

#1 Next: 1
#2 Next: 1
#1 Error: error message
Finally callback
#2 Error: error message

Jan 2019: Updated for RxJS 6

Visual Studio Code Search and Replace with Regular Expressions

Make sure Match Case is selected with Use Regular Expression so this matches. [A-Z]* If match case is not selected, this matches all letters.

Given a class, see if instance has method (Ruby)

class Foo
 def self.fclass_method
 end
 def finstance_method
 end
end

foo_obj = Foo.new
foo_obj.class.methods(false)
=> [:fclass_method] 

foo_obj.class.instance_methods(false)
=> [:fclass_method] 

Hope this helps you!

First Or Create

firstOrCreate() checks for all the arguments to be present before it finds a match.

If you only want to check on a specific field, then use firstOrCreate(['field_name' => 'value']) like

$user = User::firstOrCreate([
    'email' => '[email protected]'
], [
    'firstName' => 'abcd',
    'lastName' => 'efgh',
    'veristyName'=>'xyz',
]);

Then it check only the email

Visual Studio Code Tab Key does not insert a tab

Not sure what operating system you're on, but there was a known issue with the tab key on one of the more recent releases of VS Code for Mac OS X. The bug has been fixed in the latest release (0.10.9).

On Mac OS X, you can check for the latest update by opening VS Code and then going to [Code > Check for Updates].

Sources and more information:

Cosine Similarity between 2 Number Lists

All the answers are great for situations where you cannot use NumPy. If you can, here is another approach:

def cosine(x, y):
    dot_products = np.dot(x, y.T)
    norm_products = np.linalg.norm(x) * np.linalg.norm(y)
    return dot_products / (norm_products + EPSILON)

Also bear in mind about EPSILON = 1e-07 to secure the division.

How do I pass parameters to a jar file at the time of execution?

Incase arguments have spaces in it, you can pass like shown below.

java -jar myjar.jar 'first argument' 'second argument'

Concatenate strings from several rows using Pandas groupby

we can groupby the 'name' and 'month' columns, then call agg() functions of Panda’s DataFrame objects.

The aggregation functionality provided by the agg() function allows multiple statistics to be calculated per group in one calculation.

df.groupby(['name', 'month'], as_index = False).agg({'text': ' '.join})

enter image description here

Adding images or videos to iPhone Simulator

If you need to import more than just one or two photos then take a look at this article that I wrote. It describes an easy way to perform a bulk import of photos and works for iOS 4.x.

Run jQuery function onclick

There's several things you can improve upon here. To start, there's no reason to use an <a> (anchor) tag since you don't have a link.

Every element can be bound to click and hover events... divs, spans, labels, inputs, etc.

I can't really identify what it is you're trying to do, though. You're mixing the goal with your own implementation and, from what I've seen so far, you're not really sure how to do it. Could you better illustrate what it is you're trying to accomplish?

== EDIT ==

The requirements are still very vague. I've implemented a very quick version of what I'm imagining you're saying ... or something close that illustrates how you might be able to do it. Left me know if I'm on the right track.

http://jsfiddle.net/THEtheChad/j9Ump/

How do I install Maven with Yum?

For future reference and for simplicity sake for the lazy people out there that don't want much explanations but just run things and make it work asap:

1) sudo wget https://repos.fedorapeople.org/repos/dchen/apache-maven/epel-apache-maven.repo -O /etc/yum.repos.d/epel-apache-maven.repo

2) sudo sed -i s/\$releasever/6/g /etc/yum.repos.d/epel-apache-maven.repo

3) sudo yum install -y apache-maven

4) mvn --version

Hope you enjoyed this copy & paste session.

Capture close event on Bootstrap Modal

I tried using it and didn't work, guess it's just the modal versioin.

Although, it worked as this:

$("#myModal").on("hide.bs.modal", function () {
    // put your default event here
});

Just to update the answer =)

how to permit an array with strong parameters

It should be like

params.permit(:id => [])

Also since rails version 4+ you can use:

params.permit(id: [])

Best way to check if a character array is empty

The second one is fastest. Using strlen will be close if the string is indeed empty, but strlen will always iterate through every character of the string, so if it is not empty, it will do much more work than you need it to.

As James mentioned, the third option wipes the string out before checking, so the check will always succeed but it will be meaningless.

Process.start: how to get the output?

The solution that worked for me in win and linux is the folling

// GET api/values
        [HttpGet("cifrado/{xml}")]
        public ActionResult<IEnumerable<string>> Cifrado(String xml)
        {
            String nombreXML = DateTime.Now.ToString("ddMMyyyyhhmmss").ToString();
            String archivo = "/app/files/"+nombreXML + ".XML";
            String comando = " --armor --recipient [email protected]  --encrypt " + archivo;
            try{
                System.IO.File.WriteAllText(archivo, xml);                
                //String comando = "C:\\GnuPG\\bin\\gpg.exe --recipient [email protected] --armor --encrypt C:\\Users\\Administrador\\Documents\\pruebas\\nuevo.xml ";
                ProcessStartInfo startInfo = new ProcessStartInfo() {FileName = "/usr/bin/gpg",  Arguments = comando }; 
                Process proc = new Process() { StartInfo = startInfo, };
                proc.StartInfo.RedirectStandardOutput = true;
                proc.StartInfo.RedirectStandardError = true;
                proc.Start();
                proc.WaitForExit();
                Console.WriteLine(proc.StandardOutput.ReadToEnd());
                return new string[] { "Archivo encriptado", archivo + " - "+ comando};
            }catch (Exception exception){
                return new string[] { archivo, "exception: "+exception.ToString() + " - "+ comando };
            }
        }

python "TypeError: 'numpy.float64' object cannot be interpreted as an integer"

N=np.floor(np.divide(l,delta))
...
for j in range(N[i]/2):

N[i]/2 will be a float64 but range() expects an integer. Just cast the call to

for j in range(int(N[i]/2)):

XPath:: Get following Sibling

/html/body/table/tbody/tr[9]/td[1]

In Chrome (possible Safari too) you can inspect an element, then right click on the tag you want to get the xpath for, then you can copy the xpath to select that element.

Unzipping files

Code example is given on the author site's. You can use babelfish to translate the texts (Japanese to English).

As far as I understand Japanese, this zip inflate code is meant to decode ZIP data (streams) not ZIP archive.

How can I implement a tree in Python?

I implemented a rooted tree as a dictionary {child:parent}. So for instance with the root node 0, a tree might look like that:

tree={1:0, 2:0, 3:1, 4:2, 5:3}

This structure made it quite easy to go upward along a path from any node to the root, which was relevant for the problem I was working on.

Database corruption with MariaDB : Table doesn't exist in engine

I had old MySQL and Centos OS (ver 6 I believe) that was not supported.
One day I couldn't access Plesk.
Using Filezilla, I copied files the database files from var/lib/mysql/databasename/ I then purchased a new server with new Centos 8 OS and MariaDB. In Plesk, I created a new database with the same name as my old one.
Using Filezilla, I then pasted the old database files into the newly created database folder. I could see the data in phpmyadmin but it was giving errors such as the ones described here. I happened to have an old sql backup dump file. I imported the dump file and it overwrote those files. I then pasted the old files back into var/lib/mysql/databasename/ I then had to do a repair in Plesk. To my suprise. It worked. I had over 6 months of order data restored and I didn't lose anything.

make bootstrap twitter dialog modal draggable

You can use the code below if you dont want to use jQuery UI or any third party pluggin. It's only plain jQuery.

This answer works well with Bootstrap v3.x . For version 4.x see @User comment below

_x000D_
_x000D_
$(".modal").modal("show");_x000D_
_x000D_
$(".modal-header").on("mousedown", function(mousedownEvt) {_x000D_
    var $draggable = $(this);_x000D_
    var x = mousedownEvt.pageX - $draggable.offset().left,_x000D_
        y = mousedownEvt.pageY - $draggable.offset().top;_x000D_
    $("body").on("mousemove.draggable", function(mousemoveEvt) {_x000D_
        $draggable.closest(".modal-dialog").offset({_x000D_
            "left": mousemoveEvt.pageX - x,_x000D_
            "top": mousemoveEvt.pageY - y_x000D_
        });_x000D_
    });_x000D_
    $("body").one("mouseup", function() {_x000D_
        $("body").off("mousemove.draggable");_x000D_
    });_x000D_
    $draggable.closest(".modal").one("bs.modal.hide", function() {_x000D_
        $("body").off("mousemove.draggable");_x000D_
    });_x000D_
});
_x000D_
.modal-header {_x000D_
    cursor: move;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
_x000D_
<div class="modal fade" tabindex="-1" role="dialog">_x000D_
  <div class="modal-dialog" role="document">_x000D_
    <div class="modal-content">_x000D_
      <div class="modal-header">_x000D_
        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>_x000D_
        <h4 class="modal-title">Modal title</h4>_x000D_
      </div>_x000D_
      <div class="modal-body">_x000D_
        <p>One fine body&hellip;</p>_x000D_
      </div>_x000D_
      <div class="modal-footer">_x000D_
        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>_x000D_
        <button type="button" class="btn btn-primary">Save changes</button>_x000D_
      </div>_x000D_
    </div><!-- /.modal-content -->_x000D_
  </div><!-- /.modal-dialog -->_x000D_
</div>
_x000D_
_x000D_
_x000D_

Remove local git tags that are no longer on the remote repository

Show the difference between local and remote tags:

diff <(git tag | sort) <( git ls-remote --tags origin | cut -f2 | grep -v '\^' | sed 's#refs/tags/##' | sort)
  • git tag gives the list of local tags
  • git ls-remote --tags gives the list of full paths to remote tags
  • cut -f2 | grep -v '\^' | sed 's#refs/tags/##' parses out just the tag name from list of remote tag paths
  • Finally we sort each of the two lists and diff them

The lines starting with "< " are your local tags that are no longer in the remote repo. If they are few, you can remove them manually one by one, if they are many, you do more grep-ing and piping to automate it.

Index of duplicates items in a python list

Wow, everyone's answer is so long. I simply used a pandas dataframe, masking, and the duplicated function (keep=False markes all duplicates as True, not just first or last):

import pandas as pd
import numpy as np
np.random.seed(42)  # make results reproducible

int_df = pd.DataFrame({'int_list': np.random.randint(1, 20, size=10)})
dupes = int_df['int_list'].duplicated(keep=False)
print(int_df['int_list'][dupes].index)

This should return Int64Index([0, 2, 3, 4, 6, 7, 9], dtype='int64').

Python/BeautifulSoup - how to remove all tags from an element?

You can use the decompose method in bs4:

soup = bs4.BeautifulSoup('<body><a href="http://example.com/">I linked to <i>example.com</i></a></body>')

for a in soup.find('a').children:
    if isinstance(a,bs4.element.Tag):
        a.decompose()

print soup

Out: <html><body><a href="http://example.com/">I linked to </a></body></html>

Right click to select a row in a Datagridview and show a menu to delete it

For completness of this question, better to use a Grid event rather than mouse.

First Set your datagrid properties:

SelectionMode to FullRowSelect and RowTemplate / ContextMenuStrip to a context menu.

Create the CellMouseDown event:-

private void myDatagridView_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e)
{
    if (e.Button == MouseButtons.Right)
    {
        int rowSelected = e.RowIndex;
        if (e.RowIndex != -1)
        {
            this.myDatagridView.ClearSelection();
            this.myDatagridView.Rows[rowSelected].Selected = true;
        }
        // you now have the selected row with the context menu showing for the user to delete etc.
    }
}

Enum ToString with user friendly strings

If you want something completely customizable, try out my solution here:

http://www.kevinwilliampang.com/post/Mapping-Enums-To-Strings-and-Strings-to-Enums-in-NET.aspx

Basically, the post outlines how to attach Description attributes to each of your enums and provides a generic way to map from enum to description.

Currently running queries in SQL Server

There's this, from SQL Server DMV's In Action book:

The output shows the spid (process identifier), the ecid (this is similar to a thread within the same spid and is useful for identifying queries running in parallel), the user running the SQL, the status (whether the SQL is running or waiting), the wait status (why it’s waiting), the hostname, the domain name, and the start time (useful for determining how long the batch has been running).

The nice part is the query and parent query. That shows, for example, a stored proc as the parent and the query within the stored proc that is running. It has been very handy for me. I hope this helps someone else.

USE master
GO
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED
SELECT
er.session_Id AS [Spid]
, sp.ecid
, er.start_time
, DATEDIFF(SS,er.start_time,GETDATE()) as [Age Seconds]
, sp.nt_username
, er.status
, er.wait_type
, SUBSTRING (qt.text, (er.statement_start_offset/2) + 1,
((CASE WHEN er.statement_end_offset = -1
THEN LEN(CONVERT(NVARCHAR(MAX), qt.text)) * 2
ELSE er.statement_end_offset
END - er.statement_start_offset)/2) + 1) AS [Individual Query]
, qt.text AS [Parent Query]
, sp.program_name
, sp.Hostname
, sp.nt_domain


FROM sys.dm_exec_requests er
INNER JOIN sys.sysprocesses sp ON er.session_id = sp.spid
CROSS APPLY sys.dm_exec_sql_text(er.sql_handle)as qt
WHERE session_Id > 50
AND session_Id NOT IN (@@SPID)
ORDER BY session_Id, ecid

Cannot use special principal dbo: Error 15405

Fix: Cannot use the special principal ‘sa’. Microsoft SQL Server, Error: 15405

When importing a database in your SQL instance you would find yourself with Cannot use the special principal 'sa'. Microsoft SQL Server, Error: 15405 popping out when setting the sa user as the DBO of the database. To fix this, Open SQL Management Studio and Click New Query. Type:

USE mydatabase
exec sp_changedbowner 'sa', 'true'

Close the new query and after viewing the security of the sa, you will find that that sa is the DBO of the database. (14444)

Source: http://www.noelpulis.com/fix-cannot-use-the-special-principal-sa-microsoft-sql-server-error-15405/

How do you make an array of structs in C?

So to put it all together by using malloc():

int main(int argc, char** argv) {
    typedef struct{
        char* firstName;
        char* lastName;
        int day;
        int month;
        int year;

    }STUDENT;

    int numStudents=3;
    int x;
    STUDENT* students = malloc(numStudents * sizeof *students);
    for (x = 0; x < numStudents; x++){
        students[x].firstName=(char*)malloc(sizeof(char*));
        scanf("%s",students[x].firstName);
        students[x].lastName=(char*)malloc(sizeof(char*));
        scanf("%s",students[x].lastName);
        scanf("%d",&students[x].day);
        scanf("%d",&students[x].month);
        scanf("%d",&students[x].year);
    }

    for (x = 0; x < numStudents; x++)
        printf("first name: %s, surname: %s, day: %d, month: %d, year: %d\n",students[x].firstName,students[x].lastName,students[x].day,students[x].month,students[x].year);

    return (EXIT_SUCCESS);
}

How to initialize a dict with keys from a list and empty value in Python?

nobody cared to give a dict-comprehension solution ?

>>> keys = [1,2,3,5,6,7]
>>> {key: None for key in keys}
{1: None, 2: None, 3: None, 5: None, 6: None, 7: None}

Set a border around a StackPanel.

May be it will helpful:

<Border BorderBrush="Black" BorderThickness="1" HorizontalAlignment="Left" Height="160" Margin="10,55,0,0" VerticalAlignment="Top" Width="492"/>

Fixed point vs Floating point number

The term ‘fixed point’ refers to the corresponding manner in which numbers are represented, with a fixed number of digits after, and sometimes before, the decimal point. With floating-point representation, the placement of the decimal point can ‘float’ relative to the significant digits of the number. For example, a fixed-point representation with a uniform decimal point placement convention can represent the numbers 123.45, 1234.56, 12345.67, etc, whereas a floating-point representation could in addition represent 1.234567, 123456.7, 0.00001234567, 1234567000000000, etc.

Find by key deep in a nested array

Another (somewhat silly) option is to exploit the naturally recursive nature of JSON.stringify, and pass it a replacer function which runs on each nested object during the stringification process:

_x000D_
_x000D_
const input = [{
  'title': "some title",
  'channel_id': '123we',
  'options': [{
    'channel_id': 'abc',
    'image': 'http://asdasd.com/all-inclusive-block-img.jpg',
    'title': 'All-Inclusive',
    'options': [{
      'channel_id': 'dsa2',
      'title': 'Some Recommends',
      'options': [{
        'image': 'http://www.asdasd.com',
        'title': 'Sandals',
        'id': '1',
        'content': {}
      }]
    }]
  }]
}];

console.log(findNestedObj(input, 'id', '1'));

function findNestedObj(entireObj, keyToFind, valToFind) {
  let foundObj;
  JSON.stringify(entireObj, (_, nestedValue) => {
    if (nestedValue && nestedValue[keyToFind] === valToFind) {
      foundObj = nestedValue;
    }
    return nestedValue;
  });
  return foundObj;
};
_x000D_
_x000D_
_x000D_

How to override the [] operator in Python?

You are looking for the __getitem__ method. See http://docs.python.org/reference/datamodel.html, section 3.4.6

How to call a C# function from JavaScript?

Server-side functions are on the server-side, client-side functions reside on the client. What you can do is you have to set hidden form variable and submit the form, then on page use Page_Load handler you can access value of variable and call the server method.

More info can be found here and here

How to paste yanked text into the Vim command line

For pasting something from the system clipboard into the Vim command line ("command mode"), use Ctrl+R followed by +. For me, at least on Ubuntu, Shift+Ins is not working.

PS: I am not sure why Ctrl+R followed by *, which is theoretically the same as Ctrl+R followed by + doesn't seem to work always. I searched and discovered the + version and it seems to work always, at least on my box.

Change NULL values in Datetime format to empty string

CASE and CAST should work:

CASE WHEN mycol IS NULL THEN '' ELSE CONVERT(varchar(50), mycol, 121) END

Test a string for a substring

There are several other ways, besides using the in operator (easiest):

index()

>>> try:
...   "xxxxABCDyyyy".index("test")
... except ValueError:
...   print "not found"
... else:
...   print "found"
...
not found

find()

>>> if "xxxxABCDyyyy".find("ABCD") != -1:
...   print "found"
...
found

re

>>> import re
>>> if re.search("ABCD" , "xxxxABCDyyyy"):
...  print "found"
...
found

Java Replacing multiple different substring in a string at once (or in the most efficient way)

The below is based on Todd Owen's answer. That solution has the problem that if the replacements contain characters that have special meaning in regular expressions, you can get unexpected results. I also wanted to be able to optionally do a case-insensitive search. Here is what I came up with:

/**
 * Performs simultaneous search/replace of multiple strings. Case Sensitive!
 */
public String replaceMultiple(String target, Map<String, String> replacements) {
  return replaceMultiple(target, replacements, true);
}

/**
 * Performs simultaneous search/replace of multiple strings.
 * 
 * @param target        string to perform replacements on.
 * @param replacements  map where key represents value to search for, and value represents replacem
 * @param caseSensitive whether or not the search is case-sensitive.
 * @return replaced string
 */
public String replaceMultiple(String target, Map<String, String> replacements, boolean caseSensitive) {
  if(target == null || "".equals(target) || replacements == null || replacements.size() == 0)
    return target;

  //if we are doing case-insensitive replacements, we need to make the map case-insensitive--make a new map with all-lower-case keys
  if(!caseSensitive) {
    Map<String, String> altReplacements = new HashMap<String, String>(replacements.size());
    for(String key : replacements.keySet())
      altReplacements.put(key.toLowerCase(), replacements.get(key));

    replacements = altReplacements;
  }

  StringBuilder patternString = new StringBuilder();
  if(!caseSensitive)
    patternString.append("(?i)");

  patternString.append('(');
  boolean first = true;
  for(String key : replacements.keySet()) {
    if(first)
      first = false;
    else
      patternString.append('|');

    patternString.append(Pattern.quote(key));
  }
  patternString.append(')');

  Pattern pattern = Pattern.compile(patternString.toString());
  Matcher matcher = pattern.matcher(target);

  StringBuffer res = new StringBuffer();
  while(matcher.find()) {
    String match = matcher.group(1);
    if(!caseSensitive)
      match = match.toLowerCase();
    matcher.appendReplacement(res, replacements.get(match));
  }
  matcher.appendTail(res);

  return res.toString();
}

Here are my unit test cases:

@Test
public void replaceMultipleTest() {
  assertNull(ExtStringUtils.replaceMultiple(null, null));
  assertNull(ExtStringUtils.replaceMultiple(null, Collections.<String, String>emptyMap()));
  assertEquals("", ExtStringUtils.replaceMultiple("", null));
  assertEquals("", ExtStringUtils.replaceMultiple("", Collections.<String, String>emptyMap()));

  assertEquals("folks, we are not sane anymore. with me, i promise you, we will burn in flames", ExtStringUtils.replaceMultiple("folks, we are not winning anymore. with me, i promise you, we will win big league", makeMap("win big league", "burn in flames", "winning", "sane")));

  assertEquals("bcaacbbcaacb", ExtStringUtils.replaceMultiple("abccbaabccba", makeMap("a", "b", "b", "c", "c", "a")));
  assertEquals("bcaCBAbcCCBb", ExtStringUtils.replaceMultiple("abcCBAabCCBa", makeMap("a", "b", "b", "c", "c", "a")));
  assertEquals("bcaacbbcaacb", ExtStringUtils.replaceMultiple("abcCBAabCCBa", makeMap("a", "b", "b", "c", "c", "a"), false));

  assertEquals("c colon  backslash temp backslash  star  dot  star ", ExtStringUtils.replaceMultiple("c:\\temp\\*.*", makeMap(".", " dot ", ":", " colon ", "\\", " backslash ", "*", " star "), false));
}

private Map<String, String> makeMap(String ... vals) {
  Map<String, String> map = new HashMap<String, String>(vals.length / 2);
  for(int i = 1; i < vals.length; i+= 2)
    map.put(vals[i-1], vals[i]);
  return map;
}

jQuery toggle animation

I dont think adding dual functions inside the toggle function works for a registered click event (Unless I'm missing something)

For example:

$('.btnName').click(function() {
 top.$('#panel').toggle(function() {
   $(this).animate({ 
     // style change
   }, 500);
   },
   function() {
   $(this).animate({ 
     // style change back
   }, 500);
 });

How to delete stuff printed to console by System.out.println()?

I've found that in Eclipse Mars, if you can safely assume that the line you replace it with will be at least as long as the line you are erasing, simply printing '\r' (a carriage return) will allow your cursor to move back to the beginning of the line to overwrite any characters you see. I suppose if the new line is shorter, you can just make up the different with spaces.

This method is pretty handy in eclipse for live-updating progress percentages, such as in this code snippet I ripped out of one of my programs. It's part of a program to download media files from a website.

    URL url=new URL(link);
    HttpURLConnection connection=(HttpURLConnection)url.openConnection();
    connection.connect();
    if(connection.getResponseCode()!=HttpURLConnection.HTTP_OK)
    {
        throw new RuntimeException("Response "+connection.getResponseCode()+": "+connection.getResponseMessage()+" on url "+link);
    }
    long fileLength=connection.getContentLengthLong();
    File newFile=new File(ROOT_DIR,link.substring(link.lastIndexOf('/')));
    try(InputStream input=connection.getInputStream();
        OutputStream output=new FileOutputStream(newFile);)
    {
        byte[] buffer=new byte[4096];
        int count=input.read(buffer);
        long totalRead=count;
        System.out.println("Writing "+url+" to "+newFile+" ("+fileLength+" bytes)");
        System.out.printf("%.2f%%",((double)totalRead/(double)fileLength)*100.0);
        while(count!=-1)
        {
            output.write(buffer,0,count);
            count=input.read(buffer);
            totalRead+=count;
            System.out.printf("\r%.2f%%",((double)totalRead/(double)fileLength)*100.0);
        }
        System.out.println("\nFinished index "+INDEX);
    }

Convert .class to .java

I'm guessing that either the class name is wrong - be sure to use the fully-resolved class name, with all packages - or it's not in the CLASSPATH so javap can't find it.

Generate list of all possible permutations of a string

Non recursive solution according to Knuth, Python example:

def nextPermutation(perm):
    k0 = None
    for i in range(len(perm)-1):
        if perm[i]<perm[i+1]:
            k0=i
    if k0 == None:
        return None

    l0 = k0+1
    for i in range(k0+1, len(perm)):
        if perm[k0] < perm[i]:
            l0 = i

    perm[k0], perm[l0] = perm[l0], perm[k0]
    perm[k0+1:] = reversed(perm[k0+1:])
    return perm

perm=list("12345")
while perm:
    print perm
    perm = nextPermutation(perm)

Oracle query to identify columns having special characters

I figured out the answer to above problem. Below query will return rows which have even a signle occurrence of characters besides alphabets, numbers, square brackets, curly brackets,s pace and dot. Please note that position of closing bracket ']' in matching pattern is important.

Right ']' has the special meaning of ending a character set definition. It wouldn't make any sense to end the set before you specified any members, so the way to indicate a literal right ']' inside square brackets is to put it immediately after the left '[' that starts the set definition

SELECT * FROM test WHERE REGEXP_LIKE(sampletext,  '[^]^A-Z^a-z^0-9^[^.^{^}^ ]' );

SQL Server equivalent to Oracle's CREATE OR REPLACE VIEW

For reference from SQL Server 2016 SP1+ you could use CREATE OR ALTER VIEW syntax.

MSDN CREATE VIEW:

CREATE [ OR ALTER ] VIEW [ schema_name . ] view_name [ (column [ ,...n ] ) ]   
[ WITH <view_attribute> [ ,...n ] ]   
AS select_statement   
[ WITH CHECK OPTION ]   
[ ; ]

OR ALTER

Conditionally alters the view only if it already exists.

db<>fiddle demo

How to open some ports on Ubuntu?

If you want to open it for a range and for a protocol

ufw allow 11200:11299/tcp
ufw allow 11200:11299/udp

psql: could not connect to server: No such file or directory (Mac OS X)

@Jagdish Barabari's answer gave me the clue I needed to resolve this. Turns out there were two versions of postgresql installed while only one was running. Purging all postgresql files and reinstalling the latest version resolved this issue for me.

Can you get the number of lines of code from a GitHub repository?

If the question is "can you quickly get NUMBER OF LINES of a github repo", the answer is no as stated by the other answers.

However, if the question is "can you quickly check the SCALE of a project", I usually gauge a project by looking at its size. Of course the size will include deltas from all active commits, but it is a good metric as the order of magnitude is quite close.

E.g.

How big is the "docker" project?

In your browser, enter api.github.com/repos/ORG_NAME/PROJECT_NAME i.e. api.github.com/repos/docker/docker

In the response hash, you can find the size attribute:

{
    ...
    size: 161432,
    ...
}

This should give you an idea of the relative scale of the project. The number seems to be in KB, but when I checked it on my computer it's actually smaller, even though the order of magnitude is consistent. (161432KB = 161MB, du -s -h docker = 65MB)

Running Groovy script from the command line

You need to run the script like this:

groovy helloworld.groovy

Remove 'b' character do in front of a string literal in Python 3

This should do the trick:

pw_bytes.decode("utf-8")

No 'Access-Control-Allow-Origin' - Node / Apache Port Issue

app.all('*', function(req, res,next) {
    /**
     * Response settings
     * @type {Object}
     */
    var responseSettings = {
        "AccessControlAllowOrigin": req.headers.origin,
        "AccessControlAllowHeaders": "Content-Type,X-CSRF-Token, X-Requested-With, Accept, Accept-Version, Content-Length, Content-MD5,  Date, X-Api-Version, X-File-Name",
        "AccessControlAllowMethods": "POST, GET, PUT, DELETE, OPTIONS",
        "AccessControlAllowCredentials": true
    };

    /**
     * Headers
     */
    res.header("Access-Control-Allow-Credentials", responseSettings.AccessControlAllowCredentials);
    res.header("Access-Control-Allow-Origin",  responseSettings.AccessControlAllowOrigin);
    res.header("Access-Control-Allow-Headers", (req.headers['access-control-request-headers']) ? req.headers['access-control-request-headers'] : "x-requested-with");
    res.header("Access-Control-Allow-Methods", (req.headers['access-control-request-method']) ? req.headers['access-control-request-method'] : responseSettings.AccessControlAllowMethods);

    if ('OPTIONS' == req.method) {
        res.send(200);
    }
    else {
        next();
    }


});

Read a file line by line with VB.NET

Like this... I used it to read Chinese characters...

Dim reader as StreamReader = My.Computer.FileSystem.OpenTextFileReader(filetoimport.Text)
Dim a as String

Do
   a = reader.ReadLine
   '
   ' Code here
   '
Loop Until a Is Nothing

reader.Close()

Can I use a min-height for table, tr or td?

It's not a nice solution but try it like this:

<table>
    <tr>
        <td>
            <div>Lorem</div>
        </td>
    </tr>
    <tr>
        <td>
            <div>Ipsum</div>
        </td>
    </tr>
</table>

and set the divs to the min-height:

div {
    min-height: 300px;
}

Hope this is what you want ...

Vim for Windows - What do I type to save and exit from a file?

  • Press i or a to get into insert mode, and type the message of choice

  • Press ESC several times to get out of insert mode, or any other mode you might have run into by accident

    • to save, :wq, :x or ZZ

    • to exit without saving, :q! or ZQ

To reload a file and undo all changes you have made...:

Press several times ESC and then enter :e!.

Start service in Android

startService(new Intent(this, MyService.class));

Just writing this line was not sufficient for me. Service still did not work. Everything had worked only after registering service at manifest

<application
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name" >

    ...

    <service
        android:name=".MyService"
        android:label="My Service" >
    </service>
</application>

CORS with spring-boot and angularjs not working

If originally your program doesn't use spring security and can't afford for a code change, creating a simple reverse proxy can do the trick. In my case, I used Nginx with the following configuration:

http {
  server {
    listen 9090;
    location / {
      if ($request_method = 'OPTIONS') {
      add_header 'Access-Control-Allow-Origin' '*';
      add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
      #
      # Custom headers and headers various browsers *should* be OK with but aren't
      #
      add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range';
      #
      # Tell client that this pre-flight info is valid for 20 days
      #
      add_header 'Access-Control-Max-Age' 1728000;
      add_header 'Content-Type' 'text/plain; charset=utf-8';
      add_header 'Content-Length' 0;
      return 204;
      }
      if ($request_method = 'POST') {
      add_header 'Access-Control-Allow-Origin' '*';
      add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
      add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range';
      add_header 'Access-Control-Expose-Headers' 'Content-Length,Content-Range';
      }
      if ($request_method = 'GET') {
      add_header 'Access-Control-Allow-Origin' '*';
      add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
      add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range';
      add_header 'Access-Control-Expose-Headers' 'Content-Length,Content-Range';
      }

      proxy_pass http://localhost:8080;
    }
  }
}

My program listens to :8080.

REF: CORS on Nginx

How to automatically generate getters and setters in Android Studio

Use Ctrl+Enter on Mac to get list of options to generate setter, getter, constructor etc

enter image description here

How to reference a method in javadoc?

you can use @see to do that:

sample:

interface View {
        /**
         * @return true: have read contact and call log permissions, else otherwise
         * @see #requestReadContactAndCallLogPermissions()
         */
        boolean haveReadContactAndCallLogPermissions();

        /**
         * if not have permissions, request to user for allow
         * @see #haveReadContactAndCallLogPermissions()
         */
        void requestReadContactAndCallLogPermissions();
    }

Do subclasses inherit private fields?

Ok, this is a very interesting problem I researched a lot and came to a conclusion that private members of a superclass are indeed available (but not accessible) in the subclass's objects. To prove this, here is a sample code with a parent class and a child class and I am writing child class object to a txt file and reading a private member named 'bhavesh' in the file, hence proving it is indeed available in the child class but not accessible due to the access modifier.

import java.io.Serializable;
public class ParentClass implements Serializable {
public ParentClass() {

}

public int a=32131,b,c;

private int bhavesh=5555,rr,weq,refw;
}

import java.io.*;
import java.io.Serializable;
public class ChildClass extends ParentClass{
public ChildClass() {
super();
}

public static void main(String[] args) {
ChildClass childObj = new ChildClass();
ObjectOutputStream oos;
try {
        oos = new ObjectOutputStream(new FileOutputStream("C:\\MyData1.txt"));
        oos.writeObject(childObj); //Writing child class object and not parent class object
        System.out.println("Writing complete !");
    } catch (IOException e) {
    }


}
}

Open MyData1.txt and search for the private member named 'bhavesh'. Please let me know what you guys think.

Get Substring - everything before certain char

String str = "223232-1.jpg"
int index = str.IndexOf('-');
if(index > 0) {
    return str.Substring(0, index)
}

What does random.sample() method in python do?

random.sample(population, k)

It is used for randomly sampling a sample of length 'k' from a population. returns a 'k' length list of unique elements chosen from the population sequence or set

it returns a new list and leaves the original population unchanged and the resulting list is in selection order so that all sub-slices will also be valid random samples

I am putting up an example in which I am splitting a dataset randomly. It is basically a function in which you pass x_train(population) as an argument and return indices of 60% of the data as D_test.

import random

def randomly_select_70_percent_of_data_from_1_to_length(x_train):
    return random.sample(range(0, len(x_train)), int(0.6*len(x_train)))

How can I schedule a job to run a SQL query daily?

Using T-SQL: My job is executing stored procedure. You can easy change @command to run your sql.

EXEC msdb.dbo.sp_add_job  
   @job_name = N'MakeDailyJob',   
   @enabled = 1,   
   @description = N'Procedure execution every day' ; 

 EXEC msdb.dbo.sp_add_jobstep  
    @job_name = N'MakeDailyJob',   
    @step_name = N'Run Procedure',   
    @subsystem = N'TSQL',   
    @command = 'exec BackupFromConfig';

 EXEC msdb.dbo.sp_add_schedule  
    @schedule_name = N'Everyday schedule',   
    @freq_type = 4,  -- daily start
    @freq_interval = 1,
    @active_start_time = '230000' ;   -- start time 23:00:00

 EXEC msdb.dbo.sp_attach_schedule  
   @job_name = N'MakeDailyJob',  
   @schedule_name = N'Everyday schedule' ;

 EXEC msdb.dbo.sp_add_jobserver  
   @job_name = N'MakeDailyJob',  
   @server_name = @@servername ;

Where does MAMP keep its php.ini?

I don't know if you ever found an answer to this but I DIDN'T need MAMP PRO to do this. Simply goto the correct path by following what others have said. It's something like...

MAMP-> bin-> php-> php(your php version)-> conf-> php.ini

The key here is where you're editing the file. I was making the mistake of editing the commented part of the ini file. You actually have to scroll down to LINE #472 where it says "display_errors = Off and change it to On. Hope this helps any

How to echo with different colors in the Windows command line

An alternative is to use NodeJS.

Here is an example:

const os = require('os');
const colors = require('colors');

console.log("Operative System:".green,os.type(),os.release());
console.log("Uptime:".blue,os.uptime());

And this is the result:

enter image description here

How to map a composite key with JPA and Hibernate?

Looks like you are doing this from scratch. Try using available reverse engineering tools like Netbeans Entities from Database to at least get the basics automated (like embedded ids). This can become a huge headache if you have many tables. I suggest avoid reinventing the wheel and use as many tools available as possible to reduce coding to the minimum and most important part, what you intent to do.

How to convert an address to a latitude/longitude?

Maptsraction (http://www.mapstraction.com) lets you choose between any number of geocoding services. This could be helpful if you need to do large quantities, as I know Google has a limit to how many you can do a day.

PHP Check for NULL

Make sure that the value of the column is really NULL and not an empty string or 0.

How to run Linux commands in Java?

Runtime run = Runtime.getRuntime();  
//The best possible I found is to construct a command which you want to execute  
//as a string and use that in exec. If the batch file takes command line arguments  
//the command can be constructed a array of strings and pass the array as input to  
//the exec method. The command can also be passed externally as input to the method.  

Process p = null;  
String cmd = "ls";  
try {  
    p = run.exec(cmd);  

    p.getErrorStream();  
    p.waitFor();

}  
catch (IOException e) {  
    e.printStackTrace();  
    System.out.println("ERROR.RUNNING.CMD");  

}finally{
    p.destroy();
}  

Hive External Table Skip First Row

Just append below property in your query and the first header or line int the record will not load or it will be skipped.

Try this

tblproperties ("skip.header.line.count"="1");

How to map an array of objects in React

you must put object in your JSX, It`s easy way to do this just see my simple code here:

const link = [
  {
   name: "Cold Drink",
   link: "/coldDrink"
  },
  {
   name: "Hot Drink",
   link: "/HotDrink"
  },

{ name: "chease Cake", link: "/CheaseCake" } ]; and you must map this array in your code with simple object see this code :

const links = (this.props.link);
{links.map((item, i) => (
 <li key={i}>
   <Link to={item.link}>{item.name}</Link>
 </li>
 ))}

I hope this answer will be helpful for you ...:)

Gradle - Error Could not find method implementation() for arguments [com.android.support:appcompat-v7:26.0.0]

You need to use at least Gradle 3.4 or newer to be able to use implementation. It is not recommended to keep using the deprecated compile since this can result in slower build times. For more details see the official android developer guide:

When your module configures an implementation dependency, it's letting Gradle know that the module does not want to leak the dependency to other modules at compile time. That is, the dependency is available to other modules only at runtime. Using this dependency configuration instead of api or compile can result in significant build time improvements because it reduces the amount of projects that the build system needs to recompile. For example, if an implementation dependency changes its API, Gradle recompiles only that dependency and the modules that directly depend on it. Most app and test modules should use this configuration.

https://developer.android.com/studio/build/gradle-plugin-3-0-0-migration.html#new_configurations

Update: compile will be removed by end of 2018, so make sure that you use only implementation now:

Warning:Configuration 'compile' is obsolete and has been replaced with 'implementation'. It will be removed at the end of 2018

Make sure that the controller has a parameterless public constructor error

In my case, it was because of exception inside the constructor of my injected dependency (in your example - inside DashboardRepository constructor). The exception was caught somewhere inside MVC infrastructure. I found this after I added logs in relevant places.

What is the 'instanceof' operator used for in Java?

public class Animal{ float age; }

public class Lion extends Animal { int claws;}

public class Jungle {
    public static void main(String args[]) {

        Animal animal = new Animal(); 
        Animal animal2 = new Lion(); 
        Lion lion = new Lion(); 
        Animal animal3 = new Animal(); 
        Lion lion2 = new Animal();   //won't compile (can't reference super class object with sub class reference variable) 

        if(animal instanceof Lion)  //false

        if(animal2 instanceof Lion)  //true

        if(lion insanceof Lion) //true

        if(animal3 instanceof Animal) //true 

    }
}

Add ArrayList to another ArrayList in java

Wouldn't it just be a case of:

ArrayList<ArrayList<String>> outer = new ArrayList<ArrayList<String>>();
ArrayList<String> nodeList = new ArrayList<String>();

// Fill in nodeList here...

outer.add(nodeList);

Repeat as necesary.

This should return you a list in the format you specified.

How do I force detach Screen from another SSH session?

try with screen -d -r or screen -D -RR

UTF-8: General? Bin? Unicode?

In general, utf8_general_ci is faster than utf8_unicode_ci, but less correct.

Here is the difference:

For any Unicode character set, operations performed using the _general_ci collation are faster than those for the _unicode_ci collation. For example, comparisons for the utf8_general_ci collation are faster, but slightly less correct, than comparisons for utf8_unicode_ci. The reason for this is that utf8_unicode_ci supports mappings such as expansions; that is, when one character compares as equal to combinations of other characters. For example, in German and some other languages “ß” is equal to “ss”. utf8_unicode_ci also supports contractions and ignorable characters. utf8_general_ci is a legacy collation that does not support expansions, contractions, or ignorable characters. It can make only one-to-one comparisons between characters.

Quoted from: http://dev.mysql.com/doc/refman/5.0/en/charset-unicode-sets.html

For more detailed explanation, please read the following post from MySQL forums: http://forums.mysql.com/read.php?103,187048,188748

As for utf8_bin: Both utf8_general_ci and utf8_unicode_ci perform case-insensitive comparison. In constrast, utf8_bin is case-sensitive (among other differences), because it compares the binary values of the characters.

Amazon Linux: apt-get: command not found

This is one of the command which you can run to install apt-get:

wget http://security.ubuntu.com/ubuntu/pool/main/a/apt/apt_1.4_amd64.deb

Jquery Setting Value of Input Field

change your jquery loading setting to onload in jsfiddle . . .it works . . .

Python: Get the first character of the first string in a list?

Get the first character of a bare python string:

>>> mystring = "hello"
>>> print(mystring[0])
h
>>> print(mystring[:1])
h
>>> print(mystring[3])
l
>>> print(mystring[-1])
o
>>> print(mystring[2:3])
l
>>> print(mystring[2:4])
ll

Get the first character from a string in the first position of a python list:

>>> myarray = []
>>> myarray.append("blah")
>>> myarray[0][:1]
'b'
>>> myarray[0][-1]
'h'
>>> myarray[0][1:3]
'la'

Many people get tripped up here because they are mixing up operators of Python list objects and operators of Numpy ndarray objects:

Numpy operations are very different than python list operations.

Wrap your head around the two conflicting worlds of Python's "list slicing, indexing, subsetting" and then Numpy's "masking, slicing, subsetting, indexing, then numpy's enhanced fancy indexing".

These two videos cleared things up for me:

"Losing your Loops, Fast Numerical Computing with NumPy" by PyCon 2015: https://youtu.be/EEUXKG97YRw?t=22m22s

"NumPy Beginner | SciPy 2016 Tutorial" by Alexandre Chabot LeClerc: https://youtu.be/gtejJ3RCddE?t=1h24m54s

How to replace url parameter with javascript/jquery?

A solution without Regex, a little bit easier on the eye, one I was looking for

This supports ports, hash parameters etc.

Uses browsers attribute element as a parser.

function setUrlParameters(url, parameters) {
    var parser = document.createElement('a');
    parser.href = url;

    url = "";

    if (parser.protocol) {
        url += parser.protocol + "//";
    }

    if (parser.host) {
        url += parser.host;
    }

    if (parser.pathname) {
        url += parser.pathname;
    }

    var queryParts = {};

    if (parser.search) {
        var search = parser.search.substring(1);

        var searchParts = search.split("&");
        for (var i = 0; i < searchParts.length; i++) {
            var searchPart = searchParts[i];

            var whitespaceIndex = searchPart.indexOf("=");

            if (whitespaceIndex !== -1) {
                var key = searchPart.substring(0, whitespaceIndex);
                var value = searchPart.substring(whitespaceIndex + 1);

                queryParts[key] = value;
            } else {
                queryParts[searchPart] = false;
            }
        }
    }

    var parameterKeys = Object.keys(parameters);

    for (var i = 0; i < parameterKeys.length; i++) {
        var parameterKey = parameterKeys[i];

        queryParts[parameterKey] = parameters[parameterKey];
    }


    var queryPartKeys = Object.keys(queryParts);

    var query = "";

    for (var i = 0; i < queryPartKeys.length; i++) {
        if (query.length === 0) {
            query += "?";
        }
        if (query.length > 1) {
            query += "&";
        }

        var queryPartKey = queryPartKeys[i];

        query += queryPartKey;

        if (queryParts[queryPartKey]) {
            query += "=";

            query += queryParts[queryPartKey];
        }
    }

    url += query;

    if (parser.hash) {
        url += parser.hash;
    }

    return url;
}

Fatal error: Call to undefined function mysqli_connect()

I followed below link to fix this problem. Make sure to enable following Module.
php -r 'phpinfo();' | grep -i mysqli
Link : https://askubuntu.com/questions/773601/php-mysqli-extension-in-ubuntu-16-04-not-working-after-upgrade-to-version-7-0-6

JQuery datepicker language

Include language file source in your head script of the HTML body.

<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.1/i18n/jquery-ui-i18n.min.js"></script>

Example on JSFiddle

Javascript Array Alert

If you want to see the array as an array, you can say

alert(JSON.stringify(aCustomers));

instead of all those document.writes.

http://jsfiddle.net/5b2eb/

However, if you want to display them cleanly, one per line, in your popup, do this:

alert(aCustomers.join("\n"));

http://jsfiddle.net/5b2eb/1/

How to destroy a DOM element with jQuery?

If you want to completely destroy the target, you have a couple of options. First you can remove the object from the DOM as described above...

console.log($target);   // jQuery object
$target.remove();       // remove target from the DOM
console.log($target);   // $target still exists

Option 1 - Then replace target with an empty jQuery object (jQuery 1.4+)

$target = $();
console.log($target);   // empty jQuery object

Option 2 - Or delete the property entirely (will cause an error if you reference it elsewhere)

delete $target;
console.log($target);   // error: $target is not defined

More reading: info about empty jQuery object, and info about delete

javac error: Class names are only accepted if annotation processing is explicitly requested

I learned that you also can get this error by storing the source file in a folder named Java

How to change font size in html?

Or add styles inline:

<p style="font-size:18px">Paragraph 1</p>
<p style="font-size:16px">Paragraph 2</p>

What does "pending" mean for request in Chrome Developer Window?

The Network pending state on time, means your request is in progressing state. As soon as it responds the time will be updated with total elapsed time.

This picture shows the network call is in processing state(Pending) This picture shows the network call is in processing state(Pending)

This picture shows the time taken in processing by network call. This picture shows the time taken in processing by network call

Get the time of a datetime using T-SQL?

Just to add that from SQL Server 2008, there is a TIME datatype so from then on you can do:

SELECT CONVERT(TIME, GETDATE())

Might be useful for those that use SQL 2008+ and find this question.

How can I make a TextBox be a "password box" and display stars when using MVVM?

The problem with using the PasswordBox is that it is not very MVVM friendly due to the fact that it works with SecureString and therefore requires a shim to bind it to a String. You also cannot use the clipboard. While all these things are there for a reason, you may not require that level of security. Here is an alternative approach that works with the clipboard, nothing fancy. You make the TextBox text and background transparent and bind the text to a TextBlock underneath it. This textblock converts characters to * using the converter specified.

<Window.Resources>
    <local:TextToPasswordCharConverter x:Key="TextToPasswordCharConverter" />
</Window.Resources>

<Grid Width="200">
    <TextBlock Margin="5,0,0,0" Text="{Binding Text, Converter={StaticResource TextToPasswordCharConverter}, UpdateSourceTrigger=PropertyChanged, Mode=OneWay}" FontFamily="Consolas" VerticalAlignment="Center" />
    <TextBox Foreground="Transparent" Text="{Binding Text, UpdateSourceTrigger=PropertyChanged}" FontFamily="Consolas" Background="Transparent" />
</Grid>

And here is the Value Converter:

class TextToPasswordCharConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        return new String('*', value?.ToString().Length ?? 0);
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

Make sure your Text property on your viewmodel implements INotifyPropertyChanged

Convert String to Uri

What are you going to do with the URI?

If you're just going to use it with an HttpGet for example, you can just use the string directly when creating the HttpGet instance.

HttpGet get = new HttpGet("http://stackoverflow.com");

How to Select Top 100 rows in Oracle?

Try this:

   SELECT *
FROM (SELECT * FROM (
    SELECT 
      id, 
      client_id, 
      create_time,
      ROW_NUMBER() OVER(PARTITION BY client_id ORDER BY create_time DESC) rn 
    FROM order
  ) 
  WHERE rn=1
  ORDER BY create_time desc) alias_name
WHERE rownum <= 100
ORDER BY rownum;

Or TOP:

SELECT TOP 2 * FROM Customers; //But not supported in Oracle

NOTE: I suppose that your internal query is fine. Please share your output of this.

AngularJS - value attribute for select

What you first tried should work, but the HTML is not what we would expect. I added an option to handle the initial "no item selected" case:

<select ng-options="region.code as region.name for region in regions" ng-model="region">
   <option style="display:none" value="">select a region</option>
</select>
<br>selected: {{region}}

The above generates this HTML:

<select ng-options="..." ng-model="region" class="...">
   <option style="display:none" value class>select a region</option>
   <option value="0">Alabama</option>
   <option value="1">Alaska</option>
   <option value="2">American Samoa</option>
</select>

Fiddle

Even though Angular uses numeric integers for the value, the model (i.e., $scope.region) will be set to AL, AK, or AS, as desired. (The numeric value is used by Angular to lookup the correct array entry when an option is selected from the list.)

This may be confusing when first learning how Angular implements its "select" directive.

JavaScript equivalent of PHP’s die

throw new Error("my error message");

How to set Bullet colors in UL/LI html lists via CSS without using any images or span tags

Yet, another solution is to use a :before pseudo element with a border-radius: 50%. This will work in all browsers, including IE 8 and up.

Using the em unit allows responsiveness to font size changes. You can test this, by resizing your jsFiddle window.

ul {
    list-style: none;
    line-height: 1em;
    font-size: 3vw;
}

ul li:before {
    content: "";
    line-height: 1em;
    width: .5em;
    height: .5em;
    background-color: red;
    float: left;
    margin: .25em .25em 0;
    border-radius: 50%;
}

jsFiddle

You can even play with the box-shadow to create some nice shadows, something that will not look nice with the content: "• " solution.

Return array from function

neater:

function BlockID() {
  return {
    "s":"Images/Block_01.png",
    "g":"Images/Block_02.png",
    "C":"Images/Block_03.png",
    "d":"Images/Block_04.png"
   }
}

or just

var images = {
  "s":"Images/Block_01.png",
  "g":"Images/Block_02.png",
  "C":"Images/Block_03.png",
  "d":"Images/Block_04.png"
}

How to get the width and height of an android.widget.ImageView?

Post to the UI thread works for me.

final ImageView iv = (ImageView)findViewById(R.id.scaled_image);

iv.post(new Runnable() {
            @Override
            public void run() {
                int width = iv.getMeasuredWidth();
                int height = iv.getMeasuredHeight();

            }
});

What is the command to truncate a SQL Server log file?

backup log logname with truncate_only followed by a dbcc shrinkfile command

How to change font size on part of the page in LaTeX?

Example:

\Large\begin{verbatim}
   <how to set font size here to 10 px ? />
\end{verbatim}
\normalsize

\Large can be obviously substituted by one of:

\tiny
\scriptsize
\footnotesize
\small
\normalsize
\large
\Large
\LARGE
\huge
\Huge

If you need arbitrary font sizes:

Branch from a previous commit using Git

Go to a particular commit of a git repository

Sometimes when working on a git repository you want to go back to a specific commit (revision) to have a snapshot of your project at a specific time. To do that all you need it the SHA-1 hash of the commit which you can easily find checking the log with the command:

git log --abbrev-commit --pretty=oneline

which will give you a compact list of all the commits and the short version of the SHA-1 hash.

Now that you know the hash of the commit you want to go to you can use one of the following 2 commands:

git checkout HASH

or

git reset --hard HASH

checkout

git checkout <commit> <paths>

Tells git to replace the current state of paths with their state in the given commit. Paths can be files or directories.

If no branch is given, git assumes the HEAD commit.

git checkout <path> // restores path from your last commit. It is a 'filesystem-undo'.

If no path is given, git moves HEAD to the given commit (thereby changing the commit you're sitting and working on).

git checkout branch //means switching branches.

reset

git reset <commit> //re-sets the current pointer to the given commit.

If you are on a branch (you should usually be), HEAD and this branch are moved to commit.

If you are in detached HEAD state, git reset does only move HEAD. To reset a branch, first check it out.

If you wanted to know more about the difference between git reset and git checkout I would recommend to read the official git blog.

Facebook Graph API, how to get users email?

The only way to get the users e-mail address is to request extended permissions on the email field. The user must allow you to see this and you cannot get the e-mail addresses of the user's friends.

http://developers.facebook.com/docs/authentication/permissions

You can do this if you are using Facebook connect by passing scope=email in the get string of your call to the Auth Dialog.

I'd recommend using an SDK instead of file_get_contents as it makes it far easier to perform the Oauth authentication.

Deserializing a JSON into a JavaScript object

You could also use eval() but JSON.parse() is safer and easier way, so why would you?

good and works

var yourJsonObject = JSON.parse(json_as_text);

I don't see any reason why would you prefer to use eval. It only puts your application at risk.

That said - this is also possible.

bad - but also works

var yourJsonObject = eval(json_as_text);

Why is eval a bad idea?

Consider the following example.

Some third party or user provided JSON string data.

var json = `
[{
    "adjacencies": [
        {
          "nodeTo": function(){
            return "delete server files - you have been hacked!";
          }(),
          "nodeFrom": "graphnode1",
          "data": {
            "$color": "#557EAA"
          }
        }
    ],
    "data": {
      "$color": "#EBB056",
      "$type": "triangle",
      "$dim": 9
    },
    "id": "graphnode1",
    "name": "graphnode1"
},{
    "adjacencies": [],
    "data": {
      "$color": "#EBB056",
      "$type": "triangle",
      "$dim": 9
    },
    "id": "graphnode2",
    "name": "graphnode2"
}]
`;

Your server-side script processes that data.

Using JSON.parse:

window.onload = function(){
  var placeholder = document.getElementById('placeholder1');
  placeholder.innerHTML = JSON.parse(json)[0].adjacencies[0].nodeTo;
}

will throw:

Uncaught SyntaxError: Unexpected token u in JSON at position X. 

Function will not get executed.

You are safe.

Using eval():

window.onload = function(){
  var placeholder = document.getElementById('placeholder1');
  placeholder.innerHTML = eval(json)[0].adjacencies[0].nodeTo;
}

will execute the function and return the text.

If I replace that harmless function with one that removes files from your website folder you have been hacked. No errors/warnings will get thrown in this example.

You are NOT safe.

I was able to manipulate a JSON text string so it acts as a function which will execute on the server.

eval(JSON)[0].adjacencies[0].nodeTo expects to process a JSON string but, in reality, we just executed a function on our server.

This could also be prevented if we server-side check all user-provided data before passing it to an eval() function but why not just use the built-in tool for parsing JSON and avoid all this trouble and danger?

jQuery .find() on data from .ajax() call is returning "[object Object]" instead of div

Specify dataType: "html".

If you do not jQuery will guess the requested data type (check: http://api.jquery.com/jQuery.ajax/). My guess is that in your case response was a String rather than a DOMObject. Obviously DOM methods won't work on a String.

You could test that with console.log("type of response: " + typeof response) (or alert("type of response:" + typeof response), in case you don't run Firebug)

Finding the position of bottom of a div with jquery

The bottom is the top + the outerHeight, not the height, as it wouldn't include the margin or padding.

var $bot,
    top,
    bottom;
$bot = $('#bottom');
top = $bot.position().top;
bottom = top + $bot.outerHeight(true); //true is necessary to include the margins

Convert UTC Epoch to local date

Are you just asking to convert a UTC string to a "local" string? You could do:

var utc_string = '2011-09-05 20:05:15';
var local_string = (function(dtstr) {
    var t0 = new Date(dtstr);
    var t1 = Date.parse(t0.toUTCString().replace('GMT', ''));
    var t2 = (2 * t0) - t1;
    return new Date(t2).toString();
})(utc_string);

Find the division remainder of a number

You can find remainder using modulo operator Example

a=14
b=10
print(a%b)

It will print 4

How do you prevent install of "devDependencies" NPM modules for Node.js (package.json)?

I ran into a problem in the docker node:current-slim (running npm 7.0.9) where npm install appeared to ignore --production, --only=prod and --only=production. I found two work-arounds:

  1. use ci instead (RUN npm ci --only=production) which requires an up-to-date package-lock.json
  2. before npm install, brutally edit the package.json with:

RUN node -e 'const fs = require("fs"); const pkg = JSON.parse(fs.readFileSync("./package.json", "utf-8")); delete pkg.devDependencies; fs.writeFileSync("./package.json", JSON.stringify(pkg), "utf-8");'

This won't edit your working package.json, just the one copied to the docker container. Of course, this shouldn't be necessary, but if it is (as it was for me), there's your hack.

How to add spacing between columns?

Simple Way

.row div{
  padding-left: 8px;
  padding-right: 8px;
}

Error: Could not create the Java Virtual Machine Mac OSX Mavericks

Normally this error occurs when you invoke java by supplying the wrong arguments/options. In this case it should be the version option.

java -version

So to double check you can always do java -help, and see if the option exists. In this case, there is no option such as v.

What are the differences between struct and class in C++?

While implied by other answers, it's not explicitly mentioned - that structs are C compatible, depending on usage; classes are not.

This means if you're writing a header that you want to be C compatible then you've no option other than struct (which in the C world can't have functions; but can have function pointers).

Build a basic Python iterator

There are four ways to build an iterative function:

Examples:

# generator
def uc_gen(text):
    for char in text.upper():
        yield char

# generator expression
def uc_genexp(text):
    return (char for char in text.upper())

# iterator protocol
class uc_iter():
    def __init__(self, text):
        self.text = text.upper()
        self.index = 0
    def __iter__(self):
        return self
    def __next__(self):
        try:
            result = self.text[self.index]
        except IndexError:
            raise StopIteration
        self.index += 1
        return result

# getitem method
class uc_getitem():
    def __init__(self, text):
        self.text = text.upper()
    def __getitem__(self, index):
        return self.text[index]

To see all four methods in action:

for iterator in uc_gen, uc_genexp, uc_iter, uc_getitem:
    for ch in iterator('abcde'):
        print(ch, end=' ')
    print()

Which results in:

A B C D E
A B C D E
A B C D E
A B C D E

Note:

The two generator types (uc_gen and uc_genexp) cannot be reversed(); the plain iterator (uc_iter) would need the __reversed__ magic method (which, according to the docs, must return a new iterator, but returning self works (at least in CPython)); and the getitem iteratable (uc_getitem) must have the __len__ magic method:

    # for uc_iter we add __reversed__ and update __next__
    def __reversed__(self):
        self.index = -1
        return self
    def __next__(self):
        try:
            result = self.text[self.index]
        except IndexError:
            raise StopIteration
        self.index += -1 if self.index < 0 else +1
        return result

    # for uc_getitem
    def __len__(self)
        return len(self.text)

To answer Colonel Panic's secondary question about an infinite lazily evaluated iterator, here are those examples, using each of the four methods above:

# generator
def even_gen():
    result = 0
    while True:
        yield result
        result += 2


# generator expression
def even_genexp():
    return (num for num in even_gen())  # or even_iter or even_getitem
                                        # not much value under these circumstances

# iterator protocol
class even_iter():
    def __init__(self):
        self.value = 0
    def __iter__(self):
        return self
    def __next__(self):
        next_value = self.value
        self.value += 2
        return next_value

# getitem method
class even_getitem():
    def __getitem__(self, index):
        return index * 2

import random
for iterator in even_gen, even_genexp, even_iter, even_getitem:
    limit = random.randint(15, 30)
    count = 0
    for even in iterator():
        print even,
        count += 1
        if count >= limit:
            break
    print

Which results in (at least for my sample run):

0 2 4 6 8 10 12 14 16 18 20 22 24 26 28 30 32 34 36 38 40 42 44 46 48 50 52 54
0 2 4 6 8 10 12 14 16 18 20 22 24 26 28 30 32 34 36 38
0 2 4 6 8 10 12 14 16 18 20 22 24 26 28 30
0 2 4 6 8 10 12 14 16 18 20 22 24 26 28 30 32

How to choose which one to use? This is mostly a matter of taste. The two methods I see most often are generators and the iterator protocol, as well as a hybrid (__iter__ returning a generator).

Generator expressions are useful for replacing list comprehensions (they are lazy and so can save on resources).

If one needs compatibility with earlier Python 2.x versions use __getitem__.

Access props inside quotes in React JSX

Best practices are to add getter method for that :

getImageURI() {
  return "images/" + this.props.image;
}

<img className="image" src={this.getImageURI()} />

Then , if you have more logic later on, you can maintain the code smoothly.

Git - remote: Repository not found

Remove the all github.com credential details from the system.

For mac

Delete the github.com password from the Keychain Access.

For window

Delete the credentials from Credential Manager.

Set a default parameter value for a JavaScript function

Yes, using default parameters is fully supported in ES6:

function read_file(file, delete_after = false) {
  // Code
}

or

const read_file = (file, delete_after = false) => {
    // Code
}

but prior in ES5 you could easily do this:

function read_file(file, delete_after) {
  var df = delete_after || false;
  // Code
}

Which means if the value is there, use the value, otherwise, use the second value after || operation which does the same thing...

Note: also there is a big difference between those if you pass a value to ES6 one even the value be falsy, that will be replaced with new value, something like null or ""... but ES5 one only will be replaced if only the passed value is truthy, that's because the way || working...

Does a finally block always get executed in Java?

Here are some conditions which can bypass a finally block:

  1. If the JVM exits while the try or catch code is being executed, then the finally block may not execute. More on sun tutorial
  2. Normal Shutdown - this occurs either when the last non-daemon thread exits OR when Runtime.exit() (some good blog). When a thread exits, the JVM performs an inventory of running threads, and if the only threads that are left are daemon threads, it initiates an orderly shutdown. When the JVM halts, any remaining daemon threads are abandoned finally blocks are not executed, stacks are not unwound the JVM just exits. Daemon threads should be used sparingly few processing activities can be safely abandoned at any time with no cleanup. In particular, it is dangerous to use daemon threads for tasks that might perform any sort of I/O. Daemon threads are best saved for "housekeeping" tasks, such as a background thread that periodically removes expired entries from an in-memory cache (source)

Last non-daemon thread exits example:

public class TestDaemon {
    private static Runnable runnable = new Runnable() {
        @Override
        public void run() {
            try {
                while (true) {
                    System.out.println("Is alive");
                    Thread.sleep(10);
                    // throw new RuntimeException();
                }
            } catch (Throwable t) {
                t.printStackTrace();
            } finally {
                System.out.println("This will never be executed.");
            }
        }
    };

    public static void main(String[] args) throws InterruptedException {
        Thread daemon = new Thread(runnable);
        daemon.setDaemon(true);
        daemon.start();
        Thread.sleep(100);
        // daemon.stop();
        System.out.println("Last non-daemon thread exits.");
    }
}

Output:

Is alive
Is alive
Is alive
Is alive
Is alive
Is alive
Is alive
Is alive
Is alive
Is alive
Last non-daemon thread exits.
Is alive
Is alive
Is alive
Is alive
Is alive

Find first element in a sequence that matches a predicate

J.F. Sebastian's answer is most elegant but requires python 2.6 as fortran pointed out.

For Python version < 2.6, here's the best I can come up with:

from itertools import repeat,ifilter,chain
chain(ifilter(predicate,seq),repeat(None)).next()

Alternatively if you needed a list later (list handles the StopIteration), or you needed more than just the first but still not all, you can do it with islice:

from itertools import islice,ifilter
list(islice(ifilter(predicate,seq),1))

UPDATE: Although I am personally using a predefined function called first() that catches a StopIteration and returns None, Here's a possible improvement over the above example: avoid using filter / ifilter:

from itertools import islice,chain
chain((x for x in seq if predicate(x)),repeat(None)).next()

Android Gradle plugin 0.7.0: "duplicate files during packaging of APK"

Removing .txt after LICENSE removed my error :

packagingOptions {
    exclude 'META-INF/LICENSE'
}

JavaScript: Alert.Show(message) From ASP.NET Code-behind

Try this if you want to display the alert box to appear on the same page, without displaying on a blank page.

ScriptManager.RegisterStartupScript(this, GetType(), "showalert", "alert('Sorry there are no attachments');", true);

How to get character for a given ascii value

Simply Try this:

int n = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("data is: {0}", Convert.ToChar(n));

docker cannot start on windows

1st start Powershell "as Administrator" that will also prevent the error you got from docker version.

The try to start the docker service: start-service docker If that fails delete the docker.pid file you will find with cd $env:programfiles\docker; rm docker.pid
Finally you should change HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Virtualization\Containers\VSmbDisableOplocks to 0 or delete the value.

How do you make Vim unhighlight what you searched for?

I search so often that I've found it useful to map the underscore key to remove the search highlight:

nnoremap <silent> _ :nohl<CR>

How to select rows in a DataFrame between two values, in Python Pandas?

newdf = df.query('closing_price.mean() <= closing_price <= closing_price.std()')

or

mean = closing_price.mean()
std = closing_price.std()

newdf = df.query('@mean <= closing_price <= @std')