Programs & Examples On #Hgsvn

JavaScript: How to find out if the user browser is Chrome?

Update: Please see Jonathan's answer for an updated way to handle this. The answer below may still work, but it could likely trigger some false positives in other browsers.

var isChrome = /Chrome/.test(navigator.userAgent) && /Google Inc/.test(navigator.vendor);

However, as mentioned User Agents can be spoofed so it is always best to use feature-detection (e.g. Modernizer) when handling these issues, as other answers mention.

How to download dependencies in gradle

It is hard to figure out exactly what you are trying to do from the question. I'll take a guess and say that you want to add an extra compile task in addition to those provided out of the box by the java plugin.

The easiest way to do this is probably to specify a new sourceSet called 'speedTest'. This will generate a configuration called 'speedTest' which you can use to specify your dependencies within a dependencies block. It will also generate a task called compileSpeedTestJava for you.

For an example, take a look at defining new source sets in the Java plugin documentation

In general it seems that you have some incorrect assumptions about how dependency management works with Gradle. I would echo the advice of the others to read the 'Dependency Management' chapters of the user guide again :)

Center a H1 tag inside a DIV

<div id="AlertDiv" style="width:600px;height:400px;border:SOLID 1px;">
    <h1 style="width:100%;height:10%;text-align:center;position:relative;top:40%;">Yes</h1>
</div>

You can try the code here:

http://htmledit.squarefree.com/

How do I pass variables and data from PHP to JavaScript?

I'm going to try a simpler answer:

Explanation of the problem

First, let's understand the flow of events when a page is served from our server:

  • First PHP is run, it generates the HTML that is served to the client.
  • Then, the HTML is delivered to the client, after PHP is done with it, I'd like to emphasize that once the code leaves the server - PHP is done with it and can no longer access it.
  • Then, the HTML with JavaScript reaches the client, which can execute JavaScript on that HTML.

So really, the core thing to remember here is that HTTP is stateless. Once a request left the server, the server can not touch it. So, that leaves our options to:

  1. Send more requests from the client after the initial request is done.
  2. Encode what the server had to say in the initial request.

Solutions

That's the core question you should be asking yourself is:

Am I writing a website or an application?

Websites are mainly page based, and the page load times needs to be as fast as possible (for example - Wikipedia). Web applications are more AJAX heavy and perform a lot of round trips to get the client fast information (for example - a stock dashboard).

Website

Sending more requests from the client after the initial request is done is slow as it requires more HTTP requests which have significant overhead. Moreover, it requires asynchronousity as making an AJAX request requires a handler for when it's complete.

I would not recommend making another request unless your site is an application for getting that information from the server.

You want fast response times which have a huge impact on conversion and load times. Making Ajax requests is slow for the initial uptime in this case and unneeded.

You have two ways to tackle the issue

  • Set a cookie - cookies are headers sent in HTTP requests that both the server and client can read.
  • Encode the variable as JSON - JSON looks very close to JavaScript objects and most JSON objects are valid JavaScript variables.

Setting a cookie is really not very difficult, you just assign it a value:

setcookie("MyCookie", $value); // Sets the cookie to the value, remember, do not
                               // Set it with HTTP only to true.

Then, you can read it with JavaScript using document.cookie:

Here is a short hand rolled parser, but the answer I linked to right above this has better tested ones:

var cookies = document.cookie.split(";").
    map(function(el){ return el.split("="); }).
    reduce(function(prev,cur){ prev[cur[0]] = cur[1];return prev },{});

cookies["MyCookie"] // Value set with PHP.

Cookies are good for a little data. This is what tracking services often do.

Once we have more data, we can encode it with JSON inside a JavaScript variable instead:

<script>
    var myServerData = <?=json_encode($value)?>; // Don't forget to sanitize
                                                 //server data
</script>

Assuming $value is json_encodeable on the PHP side (it usually is). This technique is what Stack Overflow does with its chat for example (only using .NET instead of PHP).

Application

If you're writing an application - suddenly the initial load time isn't always as important as the ongoing performance of the application, and it starts to pay off to load data and code separately.

My answer here explains how to load data using AJAX in JavaScript:

function callback(data){
    // What do I do with the response?
}

var httpRequest = new XMLHttpRequest;
httpRequest.onreadystatechange = function(){
    if (httpRequest.readyState === 4) { // Request is done
        if (httpRequest.status === 200) { // successfully
            callback(httpRequest.responseText); // We're calling our method
        }
    }
};
httpRequest.open('GET', "/echo/json");
httpRequest.send();

Or with jQuery:

$.get("/your/url").done(function(data){
    // What do I do with the data?
});

Now, the server just needs to contain a /your/url route/file that contains code that grabs the data and does something with it, in your case:

<$php
     ...
     $val = myService->getValue(); // Makes an API and database call
     echo json_encode($val); // Write it to the output
 $>

This way, our JavaScript file asks for the data and shows it rather than asking for code or for layout. This is cleaner and starts to pay off as the application gets higher. It's also better separation of concerns and it allows testing the client side code without any server side technology involved which is another plus.

Postscript: You have to be very aware of XSS attack vectors when you inject anything from PHP to JavaScript. It's very hard to escape values properly and it's context sensitive. If you're unsure how to deal with XSS, or unaware of it - please read this OWASP article, this one and this question.

How can I check if a string is null or empty in PowerShell?

Note that the "if ($str)" and "IsNullOrEmpty" tests don't work comparably in all instances: an assignment of $str=0 produces false for both, and depending on intended program semantics, this could yield a surprise.

Installed Java 7 on Mac OS X but Terminal is still using version 6

You can execute following command in your terminal :

export PATH="/Library/Internet Plug-Ins/JavaAppletPlugin.plugin/Contents/Home/bin:$PATH"

And this replaces the java old with new one.

jquery draggable: how to limit the draggable area?

Here is a code example to follow. #thumbnail is a DIV parent of the #handle DIV

buildDraggable = function() {
    $( "#handle" ).draggable({
    containment: '#thumbnail',
    drag: function(event) {
        var top = $(this).position().top;
        var left = $(this).position().left;

        ICZoom.panImage(top, left);
    },
});

Invalid date in safari

Though you might hope that browsers would support ISO 8601 (or date-only subsets thereof), this is not the case. All browsers that I know of (at least in the US/English locales I use) are able to parse the horrible US MM/DD/YYYY format.

If you already have the parts of the date, you might instead want to try using Date.UTC(). If you don't, but you must use the YYYY-MM-DD format, I suggest using a regular expression to parse the pieces you know and then pass them to Date.UTC().

Killing a process using Java

You can kill a (SIGTERM) a windows process that was started from Java by calling the destroy method on the Process object. You can also kill any child Processes (since Java 9).

The following code starts a batch file, waits for ten seconds then kills all sub-processes and finally kills the batch process itself.

ProcessBuilder pb = new ProcessBuilder("cmd /c my_script.bat"));
Process p = pb.start();
p.waitFor(10, TimeUnit.SECONDS);

p.descendants().forEach(ph -> {
    ph.destroy();
});

p.destroy();

Undefined symbols for architecture i386: _OBJC_CLASS_$_SKPSMTPMessage", referenced from: error

Change in active architecture worked for me, One of my lib was using i386.

In build settings >> change Build Active Architecture Only to Yes from NO

It worked for me. Hope it helps to others as well.

enter image description here

What is the difference between 'my' and 'our' in Perl?

The perldoc has a good definition of our.

Unlike my, which both allocates storage for a variable and associates a simple name with that storage for use within the current scope, our associates a simple name with a package variable in the current package, for use within the current scope. In other words, our has the same scoping rules as my, but does not necessarily create a variable.

PHP check file extension

$info = pathinfo($pathtofile);
if ($info["extension"] == "jpg") { .... }

What's the proper way to compare a String to an enum value?

Doing an static import of the GestureTypes and then using the valuesOf() method could make it look much cleaner:

enum GestureTypes{ROCK,PAPER,SCISSORS};

and

import static com.example.GestureTypes.*;
public class GestureFactory {

    public static Gesture getInstance(final String gesture) {
        if (ROCK == valueOf(gesture))
            //do somthing
        if (PAPER == valueOf(gesture))
            //do somthing
    }
}

how to pass variable from shell script to sqlplus

You appear to have a heredoc containing a single SQL*Plus command, though it doesn't look right as noted in the comments. You can either pass a value in the heredoc:

sqlplus -S user/pass@localhost << EOF
@/opt/D2RQ/file.sql BUILDING
exit;
EOF

or if BUILDING is $2 in your script:

sqlplus -S user/pass@localhost << EOF
@/opt/D2RQ/file.sql $2
exit;
EOF

If your file.sql had an exit at the end then it would be even simpler as you wouldn't need the heredoc:

sqlplus -S user/pass@localhost @/opt/D2RQ/file.sql $2

In your SQL you can then refer to the position parameters using substitution variables:

...
}',SEM_Models('&1'),NULL,
...

The &1 will be replaced with the first value passed to the SQL script, BUILDING; because that is a string it still needs to be enclosed in quotes. You might want to set verify off to stop if showing you the substitutions in the output.


You can pass multiple values, and refer to them sequentially just as you would positional parameters in a shell script - the first passed parameter is &1, the second is &2, etc. You can use substitution variables anywhere in the SQL script, so they can be used as column aliases with no problem - you just have to be careful adding an extra parameter that you either add it to the end of the list (which makes the numbering out of order in the script, potentially) or adjust everything to match:

sqlplus -S user/pass@localhost << EOF
@/opt/D2RQ/file.sql total_count BUILDING
exit;
EOF

or:

sqlplus -S user/pass@localhost << EOF
@/opt/D2RQ/file.sql total_count $2
exit;
EOF

If total_count is being passed to your shell script then just use its positional parameter, $4 or whatever. And your SQL would then be:

SELECT COUNT(*) as &1
FROM TABLE(SEM_MATCH(
'{
        ?s rdf:type :ProcessSpec .
        ?s ?p ?o
}',SEM_Models('&2'),NULL,
SEM_ALIASES(SEM_ALIAS('','http://VISION/DataSource/SEMANTIC_CACHE#')),NULL));

If you pass a lot of values you may find it clearer to use the positional parameters to define named parameters, so any ordering issues are all dealt with at the start of the script, where they are easier to maintain:

define MY_ALIAS = &1
define MY_MODEL = &2

SELECT COUNT(*) as &MY_ALIAS
FROM TABLE(SEM_MATCH(
'{
        ?s rdf:type :ProcessSpec .
        ?s ?p ?o
}',SEM_Models('&MY_MODEL'),NULL,
SEM_ALIASES(SEM_ALIAS('','http://VISION/DataSource/SEMANTIC_CACHE#')),NULL));

From your separate question, maybe you just wanted:

SELECT COUNT(*) as &1
FROM TABLE(SEM_MATCH(
'{
        ?s rdf:type :ProcessSpec .
        ?s ?p ?o
}',SEM_Models('&1'),NULL,
SEM_ALIASES(SEM_ALIAS('','http://VISION/DataSource/SEMANTIC_CACHE#')),NULL));

... so the alias will be the same value you're querying on (the value in $2, or BUILDING in the original part of the answer). You can refer to a substitution variable as many times as you want.

That might not be easy to use if you're running it multiple times, as it will appear as a header above the count value in each bit of output. Maybe this would be more parsable later:

select '&1' as QUERIED_VALUE, COUNT(*) as TOTAL_COUNT

If you set pages 0 and set heading off, your repeated calls might appear in a neat list. You might also need to set tab off and possibly use rpad('&1', 20) or similar to make that column always the same width. Or get the results as CSV with:

select '&1' ||','|| COUNT(*)

Depends what you're using the results for...

Angular CLI - Please add a @NgModule annotation when using latest

The problem is the import of ProjectsListComponent in your ProjectsModule. You should not import that, but add it to the export array, if you want to use it outside of your ProjectsModule.

Other issues are your project routes. You should add these to an exportable variable, otherwise it's not AOT compatible. And you should -never- import the BrowserModule anywhere else but in your AppModule. Use the CommonModule to get access to the *ngIf, *ngFor...etc directives:

@NgModule({
  declarations: [
     ProjectsListComponent
  ],
  imports: [
    CommonModule,
    RouterModule.forChild(ProjectRoutes)
  ],
  exports: [
     ProjectsListComponent
  ]
})

export class ProjectsModule {}

project.routes.ts

export const ProjectRoutes: Routes = [
      { path: 'projects', component: ProjectsListComponent }
]

How do I find a stored procedure containing <text>?

For any SQL server newer than SQL server 2000:

SELECT object_name = OBJECT_NAME(sm.object_id), o.type_desc, sm.definition  
FROM sys.sql_modules AS sm  
JOIN sys.objects AS o ON sm.object_id = o.object_id  
WHERE sm.definition like '%searchString%'  
ORDER BY  o.type, o.name, o.object_id

If someone is stuck with SQL server 2000, the table sql_modules doesn't exist, so you would use syscomments, you will get multiple records for stored procdedures larger than 4000 characters, but they will have the same c.number field so you can group the parts together to get the full stored procedure text:

    Select o.id, c.number, o.name, c.text  
    from syscomments c 
    inner join sysobjects o on o.id = c.id 
    where c.encrypted = 0 and o.type = 'P'  
      and c.id in  
     (Select id from syscomments where text like '%searchtext%')
    order by objecttype, o.name, o.id, c.number, c.colid        

What is a race condition?

A race condition is an undesirable situation that occurs when a device or system attempts to perform two or more operations at the same time, but because of the nature of the device or system, the operations must be done in the proper sequence in order to be done correctly.

In computer memory or storage, a race condition may occur if commands to read and write a large amount of data are received at almost the same instant, and the machine attempts to overwrite some or all of the old data while that old data is still being read. The result may be one or more of the following: a computer crash, an "illegal operation," notification and shutdown of the program, errors reading the old data, or errors writing the new data.

How to check if a file exists in a shell script

Internally, the rm command must test for file existence anyway,
so why add another test? Just issue

rm filename

and it will be gone after that, whether it was there or not.
Use rm -f is you don't want any messages about non-existent files.

If you need to take some action if the file does NOT exist, then you must test for that yourself. Based on your example code, this is not the case in this instance.

Static methods - How to call a method from another method?

NOTE - it looks like the question has changed some. The answer to the question of how you call an instance method from a static method is that you can't without passing an instance in as an argument or instantiating that instance inside the static method.

What follows is mostly to answer "how do you call a static method from another static method":

Bear in mind that there is a difference between static methods and class methods in Python. A static method takes no implicit first argument, while a class method takes the class as the implicit first argument (usually cls by convention). With that in mind, here's how you would do that:

If it's a static method:

test.dosomethingelse()

If it's a class method:

cls.dosomethingelse()

Error installing mysql2: Failed to build gem native extension

This solved my problem once in Windows:

subst X: "C:\Program files\MySQL\MySQL Server 5.5" 
gem install mysql2 -v 0.x.x --platform=ruby -- --with-mysql-dir=X: --with-mysql-lib=X:\lib\opt 
subst X: /D

Indent List in HTML and CSS

Normally, all lists are being displayed vertically anyways. So do you want to display it horizontally?

Anyways, you asked to override the main css file and set some css locally. You cannot do it inside <ul> with style="", that it would apply on the children (<li>).

Closest thing to locally manipulating your list would be:

<style>
    li {display: inline-block;}
</style>
<ul>
  <li>Coffee</li>
  <li>Tea
    <ul>
        <li>Black tea</li>
        <li>Green tea</li>
    </ul>
  </li>
  <li>Milk</li>
</ul>

How can I do an asc and desc sort using underscore.js?

Descending order using underscore can be done by multiplying the return value by -1.

//Ascending Order:
_.sortBy([2, 3, 1], function(num){
    return num;
}); // [1, 2, 3]


//Descending Order:
_.sortBy([2, 3, 1], function(num){
    return num * -1;
}); // [3, 2, 1]

If you're sorting by strings not numbers, you can use the charCodeAt() method to get the unicode value.

//Descending Order Strings:
_.sortBy(['a', 'b', 'c'], function(s){ 
    return s.charCodeAt() * -1;
});

AngularJS: How can I pass variables between controllers?

The sample above worked like a charm. I just did a modification just in case I need to manage multiple values. I hope this helps!

app.service('sharedProperties', function () {

    var hashtable = {};

    return {
        setValue: function (key, value) {
            hashtable[key] = value;
        },
        getValue: function (key) {
            return hashtable[key];
        }
    }
});

Two constructors

The first line of a constructor is always an invocation to another constructor. You can choose between calling a constructor from the same class with "this(...)" or a constructor from the parent clas with "super(...)". If you don't include either, the compiler includes this line for you: super();

How to make a simple collection view with Swift

UICollectionView is same as UITableView but it gives us the additional functionality of simply creating a grid view, which is a bit problematic in UITableView. It will be a very long post I mention a link from where you will get everything in simple steps.

How do I remove blank elements from an array?

You can Try this

 cities.reject!(&:empty?)

How to detect window.print() finish

window.print behaves synchronously on chrome .. try this in your console

window.print();
console.log("printed");

"printed" doesn't display unless the print dialog is closed(canceled/saved/printed) by the user.

Here is a more detailed explanation about this issue.

I am not sure about IE or Firefox will check and update that later

Difference between SurfaceView and View?

A SurfaceView is a custom view in Android that can be used to drawn inside it.

The main difference between a View and a SurfaceView is that a View is drawn in the UI Thread, which is used for all the user interaction.

If you want to update the UI rapidly enough and render a good amount of information in it, a SurfaceView is a better choice.

But there are a few technical insides to the SurfaceView:

1. They are not hardware accelerated.

2. Normal views are rendered when you call the methods invalidate or postInvalidate(), but this does not mean the view will be immediately updated (A VSYNC will be sent, and the OS decides when it gets updated. The SurfaceView can be immediately updated.

3. A SurfaceView has an allocated surface buffer, so it is more costly

What's the right way to pass form element state to sibling/parent elements?

So, if I'm understanding you correctly, your first solution is suggesting that you're keeping state in your root component? I can't speak for the creators of React, but generally, I find this to be a proper solution.

Maintaining state is one of the reasons (at least I think) that React was created. If you've ever implemented your own state pattern client side for dealing with a dynamic UI that has a lot of interdependent moving pieces, then you'll love React, because it alleviates a lot of this state management pain.

By keeping state further up in the hierarchy, and updating it through eventing, your data flow is still pretty much unidirectional, you're just responding to events in the Root component, you're not really getting the data there via two way binding, you're telling the Root component that "hey, something happened down here, check out the values" or you're passing the state of some data in the child component up in order to update the state. You changed the state in C1, and you want C2 to be aware of it, so, by updating the state in the Root component and re-rendering, C2's props are now in sync since the state was updated in the Root component and passed along.

class Example extends React.Component {
  constructor (props) {
    super(props)
    this.state = { data: 'test' }
  }
  render () {
    return (
      <div>
        <C1 onUpdate={this.onUpdate.bind(this)}/>
        <C2 data={this.state.data}/>
      </div>
    )
  }
  onUpdate (data) { this.setState({ data }) }
}

class C1 extends React.Component {
    render () {
      return (
        <div>
          <input type='text' ref='myInput'/>
          <input type='button' onClick={this.update.bind(this)} value='Update C2'/>
        </div>
      )
    }
    update () {
      this.props.onUpdate(this.refs.myInput.getDOMNode().value)
    }
})

class C2 extends React.Component {
    render () {
      return <div>{this.props.data}</div>
    }
})

ReactDOM.renderComponent(<Example/>, document.body)

Single controller with multiple GET methods in ASP.NET Web API

In VS 2019, this works with ease:

[Route("api/[controller]/[action]")] //above the controller class

And in the code:

[HttpGet]
[ActionName("GetSample1")]
public Ilist<Sample1> GetSample1()
{
    return getSample1();
}
[HttpGet]
[ActionName("GetSample2")]
public Ilist<Sample2> GetSample2()
{
    return getSample2();
}
[HttpGet]
[ActionName("GetSample3")]
public Ilist<Sample3> GetSample3()
{
    return getSample3();
}
[HttpGet]
[ActionName("GetSample4")]
public Ilist<Sample4> GetSample4()
{
    return getSample4();
}

You can have multiple gets like above mentioned.

Spring RestTemplate timeout

I finally got this working.

I think the fact that our project had two different versions of the commons-httpclient jar wasn't helping. Once I sorted that out I found you can do two things...

In code you can put the following:

HttpComponentsClientHttpRequestFactory rf =
    (HttpComponentsClientHttpRequestFactory) restTemplate.getRequestFactory();
rf.setReadTimeout(1 * 1000);
rf.setConnectTimeout(1 * 1000);

The first time this code is called it will set the timeout for the HttpComponentsClientHttpRequestFactory class used by the RestTemplate. Therefore, all subsequent calls made by RestTemplate will use the timeout settings defined above.

Or the better option is to do this:

<bean id="RestOperations" class="org.springframework.web.client.RestTemplate">
    <constructor-arg>
        <bean class="org.springframework.http.client.HttpComponentsClientHttpRequestFactory">
            <property name="readTimeout" value="${application.urlReadTimeout}" />
            <property name="connectTimeout" value="${application.urlConnectionTimeout}" />
        </bean>
    </constructor-arg>
</bean>

Where I use the RestOperations interface in my code and get the timeout values from a properties file.

How to manipulate arrays. Find the average. Beginner Java

Using an enhanced for would be even nicer:

int sum = 0;
for (int d : data) sum += d;

Another thing that will probably give you a big surprise is the wrong result that you will obtain from

double average = sum / data.length;

Reason: on the right-hand side you have integer division and Java will not automatically promote it to floating-point division. It will calculate the integer quotient of sum/data.length and only then promote that integer to a double. A solution would be

double average = 1.0d * sum / data.length;

This will force the dividend into a double, which will automatically propagate to the divisor.

Which characters need to be escaped when using Bash?

I presume that you're talking about bash strings. There are different types of strings which have a different set of requirements for escaping. eg. Single quotes strings are different from double quoted strings.

The best reference is the Quoting section of the bash manual.

It explains which characters needs escaping. Note that some characters may need escaping depending on which options are enabled such as history expansion.

how to check for null with a ng-if values in a view with angularjs?

You should check for !test, here is a fiddle showing that.

<span ng-if="!test">null</span>

how do I initialize a float to its max/min value?

You can use std::numeric_limits which is defined in <limits> to find the minimum or maximum value of types (As long as a specialization exists for the type). You can also use it to retrieve infinity (and put a - in front for negative infinity).

#include <limits>

//...

std::numeric_limits<float>::max();
std::numeric_limits<float>::min();
std::numeric_limits<float>::infinity();

As noted in the comments, min() returns the lowest possible positive value. In other words the positive value closest to 0 that can be represented. The lowest possible value is the negative of the maximum possible value.

There is of course the std::max_element and min_element functions (defined in <algorithm>) which may be a better choice for finding the largest or smallest value in an array.

How to change date format from DD/MM/YYYY or MM/DD/YYYY to YYYY-MM-DD?

We can do something like this

DateTime date_temp_from = DateTime.Parse(from.Value); //from.value" is input by user (dd/MM/yyyy)
DateTime date_temp_to = DateTime.Parse(to.Value); //to.value" is input by user (dd/MM/yyyy)

string date_from = date_temp_from.ToString("yyyy/MM/dd HH:mm");
string date_to = date_temp_to.ToString("yyyy/MM/dd HH:mm");

Thank you

Best way to update data with a RecyclerView adapter

@inmyth's answer is correct, just modify the code a bit, to handle empty list.

public class NewsAdapter extends RecyclerView.Adapter<...> {    
    ...
    private static List mFeedsList;
    ...    
    public void swap(List list){
            if (mFeedsList != null) {
                mFeedsList.clear();
                mFeedsList.addAll(list);
            }
            else {
                mFeedsList = list;
            }
            notifyDataSetChanged();
    }

I am using Retrofit to fetch the list, on Retrofit's onResponse() use,

adapter.swap(feedList);

How to import an existing project from GitHub into Android Studio

In Github click the "Clone or download" button of the project you want to import --> download the ZIP file and unzip it. In Android Studio Go to File -> New Project -> Import Project and select the newly unzipped folder -> press OK. It will build the Gradle automatically.

Good Luck with your project

Generate random numbers using C++11 random library

Stephan T. Lavavej (stl) from Microsoft did a talk at Going Native about how to use the new C++11 random functions and why not to use rand(). In it, he included a slide that basically solves your question. I've copied the code from that slide below.

You can see his full talk here: http://channel9.msdn.com/Events/GoingNative/2013/rand-Considered-Harmful

#include <random>
#include <iostream>

int main() {
    std::random_device rd;
    std::mt19937 mt(rd());
    std::uniform_real_distribution<double> dist(1.0, 10.0);

    for (int i=0; i<16; ++i)
        std::cout << dist(mt) << "\n";
}

We use random_device once to seed the random number generator named mt. random_device() is slower than mt19937, but it does not need to be seeded because it requests random data from your operating system (which will source from various locations, like RdRand for example).


Looking at this question / answer, it appears that uniform_real_distribution returns a number in the range [a, b), where you want [a, b]. To do that, our uniform_real_distibution should actually look like:

std::uniform_real_distribution<double> dist(1, std::nextafter(10, DBL_MAX));

PHP Redirect to another page after form submit

Once had this issue, thought it reasonable to share how I resolved it;

I think the way to do that in php is to use the header function as:

header ("Location: exampleFile.php");

You could just enclose that header file in an if statement so that it redirects only when a certain condition is met, as in:

if (isset($_POST['submit'])){   header("Location: exampleFile.php")   }

Hope that helps.

Node.js Error: connect ECONNREFUSED

Had a similar issue, it turned out the listening port printed was different from what it actually was. Typos in the request string or listening function might make the target server appear to not exist.

Reading file contents on the client-side in javascript in various browsers

Edited to add information about the File API

Since I originally wrote this answer, the File API has been proposed as a standard and implemented in most browsers (as of IE 10, which added support for FileReader API described here, though not yet the File API). The API is a bit more complicated than the older Mozilla API, as it is designed to support asynchronous reading of files, better support for binary files and decoding of different text encodings. There is some documentation available on the Mozilla Developer Network as well as various examples online. You would use it as follows:

var file = document.getElementById("fileForUpload").files[0];
if (file) {
    var reader = new FileReader();
    reader.readAsText(file, "UTF-8");
    reader.onload = function (evt) {
        document.getElementById("fileContents").innerHTML = evt.target.result;
    }
    reader.onerror = function (evt) {
        document.getElementById("fileContents").innerHTML = "error reading file";
    }
}

Original answer

There does not appear to be a way to do this in WebKit (thus, Safari and Chrome). The only keys that a File object has are fileName and fileSize. According to the commit message for the File and FileList support, these are inspired by Mozilla's File object, but they appear to support only a subset of the features.

If you would like to change this, you could always send a patch to the WebKit project. Another possibility would be to propose the Mozilla API for inclusion in HTML 5; the WHATWG mailing list is probably the best place to do that. If you do that, then it is much more likely that there will be a cross-browser way to do this, at least in a couple years time. Of course, submitting either a patch or a proposal for inclusion to HTML 5 does mean some work defending the idea, but the fact that Firefox already implements it gives you something to start with.

c++ array assignment of multiple values

You have to replace the values one by one such as in a for-loop or copying another array over another such as using memcpy(..) or std::copy

e.g.

for (int i = 0; i < arrayLength; i++) {
    array[i] = newValue[i];
}

Take care to ensure proper bounds-checking and any other checking that needs to occur to prevent an out of bounds problem.

Pycharm does not show plot

In Pycharm , at times the Matplotlib.plot won't show up.

So after calling plt.show() check in the right side toolbar for SciView. Inside SciView every generated plots will be stored.

Automatically enter SSH password with script

Use public key authentication: https://help.ubuntu.com/community/SSH/OpenSSH/Keys

In the source host run this only once:

ssh-keygen -t rsa # ENTER to every field
ssh-copy-id myname@somehost

That's all, after that you'll be able to do ssh without password.

Running script upon login mac

Follow this:

  • start Automator.app
  • select Application
  • click Show library in the toolbar (if hidden)
  • add Run shell script (from the Actions/Utilities)
  • copy & paste your script into the window
  • test it
  • save somewhere (for example you can make an Applications folder in your HOME, you will get an your_name.app)

  • go to System Preferences -> Accounts -> Login items

  • add this app
  • test & done ;)

EDIT:

I've recently earned a "Good answer" badge for this answer. While my solution is simple and working, the cleanest way to run any program or shell script at login time is described in @trisweb's answer, unless, you want interactivity.

With automator solution you can do things like next: automator screenshot login application

so, asking to run a script or quit the app, asking passwords, running other automator workflows at login time, conditionally run applications at login time and so on...

Rotate and translate

There is no need for that, as you can use css 'writing-mode' with values 'vertical-lr' or 'vertical-rl' as desired.

.item {
  writing-mode: vertical-rl;
}

CSS:writing-mode

ApiNotActivatedMapError for simple html page using google-places-api

Have you tried following the advice on the linked help page? The help page at http://g.co/mapsJSApiErrors says:

ApiNotActivatedMapError

The Google Maps JavaScript API is not activated on your API project. You may need to enable the Google Maps JavaScript API under APIs in the Google Developers Console.

See Obtaining an API key.

So check that the key you are using has Google Maps JavaScript API enabled.

Is there a JavaScript function that can pad a string to get to a determined length?

ECMAScript 2017 adds a padStart method to the String prototype. This method will pad a string with spaces to a given length. This method also takes an optional string that will be used instead of spaces for padding.

'abc'.padStart(10);         // "       abc"
'abc'.padStart(10, "foo");  // "foofoofabc"
'abc'.padStart(6,"123465"); // "123abc"
'abc'.padStart(8, "0");     // "00000abc"
'abc'.padStart(1);          // "abc"

A padEnd method was also added that works in the same manner.

For browser compatibility (and a useful polyfill) see this link.

How to preserve aspect ratio when scaling image using one (CSS) dimension in IE6?

Adam Luter gave me the idea for this, but it actually turned out to be really simple:

img {
  width:  75px;
  height: auto;
}

IE6 now scales the image fine and this seems to be what all the other browsers use by default.

Thanks for both the answers though!

Angular2 Material Dialog css, dialog size

For the most recent version of Angular as of this post, it seems you must first create a MatDialogConfig object and pass it as a second parameter to dialog.open() because Typescript expects the second parameter to be of type MatDialogConfig.

const matDialogConfig = new MatDialogConfig();
matDialogConfig.width = "600px";
matDialogConfig.height = "480px";
this.dialog.open(MyDialogComponent, matDialogConfig);

python: how to send mail with TO, CC and BCC?

Email headers don't matter to the smtp server. Just add the CC and BCC recipients to the toaddrs when you send your email. For CC, add them to the CC header.

toaddr = '[email protected]'
cc = ['[email protected]','[email protected]']
bcc = ['[email protected]']
fromaddr = '[email protected]'
message_subject = "disturbance in sector 7"
message_text = "Three are dead in an attack in the sewers below sector 7."
message = "From: %s\r\n" % fromaddr
        + "To: %s\r\n" % toaddr
        + "CC: %s\r\n" % ",".join(cc)
        + "Subject: %s\r\n" % message_subject
        + "\r\n" 
        + message_text
toaddrs = [toaddr] + cc + bcc
server = smtplib.SMTP('smtp.sunnydale.k12.ca.us')
server.set_debuglevel(1)
server.sendmail(fromaddr, toaddrs, message)
server.quit()

Groovy Shell warning "Could not open/create prefs root node ..."

The problem is indeed the register key that is missing. It can be created manually

OR

it can be created automagically by running the program as administrator once. That will give the program the permissions required, and when it will be ran as normal it will still work correctly.

Parse error: syntax error, unexpected [

Are you using php 5.4 on your local? the render line is using the new way of initializing arrays. Try replacing ["title" => "Welcome "] with array("title" => "Welcome ")

How to run Gulp tasks sequentially one after the other

I was having this exact same problem and the solution turned out to be pretty easy for me. Basically change your code to the following and it should work. NOTE: the return before gulp.src made all the difference for me.

gulp.task "coffee", ->
    return gulp.src("src/server/**/*.coffee")
        .pipe(coffee {bare: true}).on("error",gutil.log)
        .pipe(gulp.dest "bin")

gulp.task "clean",->
    return gulp.src("bin", {read:false})
        .pipe clean
            force:true

gulp.task 'develop',['clean','coffee'], ->
    console.log "run something else"

Java ArrayList for integers

List of Integer.

List<Integer> list = new ArrayList<>();
int x = 5;
list.add(x);

Install psycopg2 on Ubuntu

This worked for me:

pip install psycopg2-binary

What is the best open source help ticket system?

I recommend OTRS, its very easily customizable, and we also use it for hundreds of employees (University).

DB query builder toArray() laravel 4

Easiest way is using laravel toArray function itself:

    $result = array_map(function ($value) {
        return $value instanceof Arrayable ? $value->toArray() : $value;
    }, $result);

How to replace a whole line with sed?

This might work for you:

cat <<! | sed '/aaa=\(bbb\|ccc\|ddd\)/!s/\(aaa=\).*/\1xxx/'
> aaa=bbb
> aaa=ccc
> aaa=ddd
> aaa=[something else]
!
aaa=bbb
aaa=ccc
aaa=ddd
aaa=xxx

SQL - IF EXISTS UPDATE ELSE INSERT INTO

  1. Create a UNIQUE constraint on your subs_email column, if one does not already exist:

    ALTER TABLE subs ADD UNIQUE (subs_email)
    
  2. Use INSERT ... ON DUPLICATE KEY UPDATE:

    INSERT INTO subs
      (subs_name, subs_email, subs_birthday)
    VALUES
      (?, ?, ?)
    ON DUPLICATE KEY UPDATE
      subs_name     = VALUES(subs_name),
      subs_birthday = VALUES(subs_birthday)
    

You can use the VALUES(col_name) function in the UPDATE clause to refer to column values from the INSERT portion of the INSERT ... ON DUPLICATE KEY UPDATE - dev.mysql.com

  1. Note that I have used parameter placeholders in the place of string literals, as one really should be using parameterised statements to defend against SQL injection attacks.

SVG gradient using CSS

Here is how to set a linearGradient on a target element:

<style type="text/css">
    path{fill:url('#MyGradient')}
</style>
<defs>
    <linearGradient id="MyGradient">
        <stop offset="0%" stop-color="#e4e4e3" ></stop>
        <stop offset="80%" stop-color="#fff" ></stop>
    </linearGradient>
</defs>

How to export html table to excel or pdf in php

If all you want is a simple excel worksheet try this:

header('Content-type: application/excel');
$filename = 'filename.xls';
header('Content-Disposition: attachment; filename='.$filename);

$data = '<html xmlns:x="urn:schemas-microsoft-com:office:excel">
<head>
    <!--[if gte mso 9]>
    <xml>
        <x:ExcelWorkbook>
            <x:ExcelWorksheets>
                <x:ExcelWorksheet>
                    <x:Name>Sheet 1</x:Name>
                    <x:WorksheetOptions>
                        <x:Print>
                            <x:ValidPrinterInfo/>
                        </x:Print>
                    </x:WorksheetOptions>
                </x:ExcelWorksheet>
            </x:ExcelWorksheets>
        </x:ExcelWorkbook>
    </xml>
    <![endif]-->
</head>

<body>
   <table><tr><td>Cell 1</td><td>Cell 2</td></tr></table>
</body></html>';

echo $data;

The key here is the xml data. This will keep excel from complaining about the file.

Call a python function from jinja2

Never saw such simple way at official docs or at stack overflow, but i was amazed when found this:

# jinja2.__version__ == 2.8
from jinja2 import Template

def calcName(n, i):
    return ' '.join([n] * i)

template = Template("Hello {{ calcName('Gandalf', 2) }}")

template.render(calcName=calcName)
# or
template.render({'calcName': calcName})

Angular @ViewChild() error: Expected 2 arguments, but got 1

That also resolved my issue.

@ViewChild('map', {static: false}) googleMap;

Create instance of generic type whose constructor requires a parameter?

You can use the following command:

 T instance = (T)typeof(T).GetConstructor(new Type[0]).Invoke(new object[0]);

Be sure to see the following reference.

Call PHP function from jQuery?

AJAX does the magic:

$(document).ready(function(

    $.ajax({ url: 'script.php?argument=value&foo=bar' });

));

How do I convert from int to Long in Java?

As soon as there is only method Long.valueOf(long), cast from int to long will be done implicitly in case of using Long.valueOf(intValue).

The more clear way to do this is

Integer.valueOf(intValue).longValue()

How to focus on a form input text field on page load using jQuery?

Sure:

<head>
    <script src="jquery-1.3.2.min.js" type="text/javascript"></script>
    <script type="text/javascript">
        $(function() {
            $("#myTextBox").focus();
        });
    </script>
</head>
<body>
    <input type="text" id="myTextBox">
</body>

How to set div's height in css and html

<div style="height: 100px;"> </div>

OR

<div id="foo"/> and set the style as #foo { height: 100px; }
<div class="bar"/> and set the style as .bar{ height: 100px;  }

Concatenating two one-dimensional NumPy arrays

The first parameter to concatenate should itself be a sequence of arrays to concatenate:

numpy.concatenate((a,b)) # Note the extra parentheses.

Adding a new array element to a JSON object

For example here is a element like button for adding item to basket and appropriate attributes for saving in localStorage.

'<a href="#" cartBtn pr_id='+e.id+' pr_name_en="'+e.nameEn+'" pr_price="'+e.price+'" pr_image="'+e.image+'" class="btn btn-primary"><i class="fa fa-shopping-cart"></i>Add to cart</a>'

var productArray=[];


$(document).on('click','[cartBtn]',function(e){
  e.preventDefault();
  $(this).html('<i class="fa fa-check"></i>Added to cart');
  console.log('Item added ');
  var productJSON={"id":$(this).attr('pr_id'), "nameEn":$(this).attr('pr_name_en'), "price":$(this).attr('pr_price'), "image":$(this).attr('pr_image')};


  if(localStorage.getObj('product')!==null){
    productArray=localStorage.getObj('product');
    productArray.push(productJSON);  
    localStorage.setObj('product', productArray);  
  }
  else{
    productArray.push(productJSON);  
    localStorage.setObj('product', productArray);  
  }


});

Storage.prototype.setObj = function(key, value) {
    this.setItem(key, JSON.stringify(value));
}

Storage.prototype.getObj = function(key) {
    var value = this.getItem(key);
    return value && JSON.parse(value);
}

After adding JSON object to Array result is (in LocalStorage):

[{"id":"99","nameEn":"Product Name1","price":"767","image":"1462012597217.jpeg"},{"id":"93","nameEn":"Product Name2","price":"76","image":"1461449637106.jpeg"},{"id":"94","nameEn":"Product Name3","price":"87","image":"1461449679506.jpeg"}]

after this action you can easily send data to server as List in Java

Full code example is here

How do I store a simple cart using localStorage?

html select only one checkbox in a group

There are already a few answers to this based on pure JS but none of them are quite as concise as I would like them to be.

Here is my solution based on using name tags (as with radio buttons) and a few lines of javascript.

_x000D_
_x000D_
function onlyOne(checkbox) {_x000D_
    var checkboxes = document.getElementsByName('check')_x000D_
    checkboxes.forEach((item) => {_x000D_
        if (item !== checkbox) item.checked = false_x000D_
    })_x000D_
}
_x000D_
<input type="checkbox" name="check" onclick="onlyOne(this)">_x000D_
<input type="checkbox" name="check" onclick="onlyOne(this)">_x000D_
<input type="checkbox" name="check" onclick="onlyOne(this)">_x000D_
<input type="checkbox" name="check" onclick="onlyOne(this)">
_x000D_
_x000D_
_x000D_

Constructing pandas DataFrame from values in variables gives "ValueError: If using all scalar values, you must pass an index"

You need to provide iterables as the values for the Pandas DataFrame columns:

df2 = pd.DataFrame({'A':[a],'B':[b]})

The intel x86 emulator accelerator (HAXM installer) revision 6.0.5 is showing not compatible with windows

Try the following

  1. download HAXM from Intel https://software.intel.com/en-us/android/articles/intel-hardware-accelerated-execution-manager.

  2. Unzip the file and Run intelhaxm-android.exe.

  3. Run silent_install.bat.

In my computer Win10 x64 - VS2015 it worked

percentage of two int?

float percent = (n / (v * 1.0f)) *100

git pull aborted with error filename too long

Solution1 - set global config, by running this command:

git config --system core.longpaths true

Solution2 - or you can edit directly your specific git config file like below:

YourRepoFolder -> .git -> config:

[core]
    repositoryformatversion = 0
    filemode = false
    ...
    longpaths = true        <-- (add this line under core section)

Solution3 - when cloning a new repository: here.

How to use the 'og' (Open Graph) meta tag for Facebook share

Facebook uses what's called the Open Graph Protocol to decide what things to display when you share a link. The OGP looks at your page and tries to decide what content to show. We can lend a hand and actually tell Facebook what to take from our page.

The way we do that is with og:meta tags.

The tags look something like this -

  <meta property="og:title" content="Stuffed Cookies" />
  <meta property="og:image" content="http://fbwerks.com:8000/zhen/cookie.jpg" />
  <meta property="og:description" content="The Turducken of Cookies" />
  <meta property="og:url" content="http://fbwerks.com:8000/zhen/cookie.html">

You'll need to place these or similar meta tags in the <head> of your HTML file. Don't forget to substitute the values for your own!

For more information you can read all about how Facebook uses these meta tags in their documentation. Here is one of the tutorials from there - https://developers.facebook.com/docs/opengraph/tutorial/


Facebook gives us a great little tool to help us when dealing with these meta tags - you can use the Debugger to see how Facebook sees your URL, and it'll even tell you if there are problems with it.

One thing to note here is that every time you make a change to the meta tags, you'll need to feed the URL through the Debugger again so that Facebook will clear all the data that is cached on their servers about your URL.

Accessing nested JavaScript objects and arrays by string path

I think you are asking for this:

var part1name = someObject.part1.name;
var part2quantity = someObject.part2.qty;
var part3name1 =  someObject.part3[0].name;

You could be asking for this:

var part1name = someObject["part1"]["name"];
var part2quantity = someObject["part2"]["qty"];
var part3name1 =  someObject["part3"][0]["name"];

Both of which will work


Or maybe you are asking for this

var partName = "part1";
var nameStr = "name";

var part1name = someObject[partName][nameStr];

Finally you could be asking for this

var partName = "part1.name";

var partBits = partName.split(".");

var part1name = someObject[partBits[0]][partBits[1]];

Check if a file exists in jenkins pipeline

You need to use brackets when using the fileExists step in an if condition or assign the returned value to a variable

Using variable:

def exists = fileExists 'file'

if (exists) {
    echo 'Yes'
} else {
    echo 'No'
}

Using brackets:

if (fileExists('file')) {
    echo 'Yes'
} else {
    echo 'No'
}

How to create JSON object using jQuery

I believe he is asking to write the new json to a directory. You will need some Javascript and PHP. So, to piggy back off the other answers:

script.js

var yourObject = {
  test:'test 1',
  testData: [ 
    {testName: 'do',testId:''}
   ],
   testRcd:'value'   
};
var myString = 'newData='+JSON.stringify(yourObject);  //converts json to string and prepends the POST variable name
$.ajax({
   type: "POST",
   url: "buildJson.php", //the name and location of your php file
   data: myString,      //add the converted json string to a document.
   success: function() {alert('sucess');} //just to make sure it got to this point.
});
return false;  //prevents the page from reloading. this helps if you want to bind this whole process to a click event.

buildJson.php

<?php
    $file = "data.json";  //name and location of json file. if the file doesn't exist, it   will be created with this name

    $fh = fopen($file, 'a');  //'a' will append the data to the end of the file. there are other arguemnts for fopen that might help you a little more. google 'fopen php'.

    $new_data = $_POST["newData"]; //put POST data from ajax request in a variable

    fwrite($fh, $new_data);  //write the data with fwrite

    fclose($fh);  //close the dile
?>

How do I select which GPU to run a job on?

Set the following two environment variables:

NVIDIA_VISIBLE_DEVICES=$gpu_id
CUDA_VISIBLE_DEVICES=0

where gpu_id is the ID of your selected GPU, as seen in the host system's nvidia-smi (a 0-based integer) that will be made available to the guest system (e.g. to the Docker container environment).

You can verify that a different card is selected for each value of gpu_id by inspecting Bus-Id parameter in nvidia-smi run in a terminal in the guest system).

More info

This method based on NVIDIA_VISIBLE_DEVICES exposes only a single card to the system (with local ID zero), hence we also hard-code the other variable, CUDA_VISIBLE_DEVICES to 0 (mainly to prevent it from defaulting to an empty string that would indicate no GPU).

Note that the environmental variable should be set before the guest system is started (so no chances of doing it in your Jupyter Notebook's terminal), for instance using docker run -e NVIDIA_VISIBLE_DEVICES=0 or env in Kubernetes or Openshift.

If you want GPU load-balancing, make gpu_id random at each guest system start.

If setting this with python, make sure you are using strings for all environment variables, including numerical ones.

You can verify that a different card is selected for each value of gpu_id by inspecting nvidia-smi's Bus-Id parameter (in a terminal run in the guest system).

The accepted solution based on CUDA_VISIBLE_DEVICES alone does not hide other cards (different from the pinned one), and thus causes access errors if you try to use them in your GPU-enabled python packages. With this solution, other cards are not visible to the guest system, but other users still can access them and share their computing power on an equal basis, just like with CPU's (verified).

This is also preferable to solutions using Kubernetes / Openshift controlers (resources.limits.nvidia.com/gpu), that would impose a lock on the allocated card, removing it from the pool of available resources (so the number of containers with GPU access could not exceed the number of physical cards).

This has been tested under CUDA 8.0, 9.0 and 10.1 in docker containers running Ubuntu 18.04 orchestrated by Openshift 3.11.

Get first letter of a string from column

Cast the dtype of the col to str and you can perform vectorised slicing calling str:

In [29]:
df['new_col'] = df['First'].astype(str).str[0]
df

Out[29]:
   First  Second new_col
0    123     234       1
1     22    4353       2
2     32     355       3
3    453     453       4
4     45     345       4
5    453     453       4
6     56      56       5

if you need to you can cast the dtype back again calling astype(int) on the column

Binding a Button's visibility to a bool value in ViewModel

Assuming AdvancedFormat is a bool, you need to declare and use a BooleanToVisibilityConverter:

<!-- In your resources section of the XAML -->
<BooleanToVisibilityConverter x:Key="BoolToVis" />

<!-- In your Button declaration -->
<Button
 Height="50" Width="50"
 Style="{StaticResource MyButtonStyle}"
 Command="{Binding SmallDisp}" CommandParameter="{Binding}" 
Cursor="Hand" Visibility="{Binding Path=AdvancedFormat, Converter={StaticResource BoolToVis}}"/>

Note the added Converter={StaticResource BoolToVis}.

This is a very common pattern when working with MVVM. In theory you could do the conversion yourself on the ViewModel property (i.e. just make the property itself of type Visibility) though I would prefer not to do that, since now you are messing with the separation of concerns. An item's visbility should really be up to the View.

Iterate two Lists or Arrays with one ForEach statement in C#

Since C# 7, you can use Tuples...

int[] nums = { 1, 2, 3, 4 };
string[] words = { "one", "two", "three", "four" };

foreach (var tuple in nums.Zip(words, (x, y) => (x, y)))
{
    Console.WriteLine($"{tuple.Item1}: {tuple.Item2}");
}

// or...
foreach (var tuple in nums.Zip(words, (x, y) => (Num: x, Word: y)))
{
    Console.WriteLine($"{tuple.Num}: {tuple.Word}");
}

Calling a Variable from another Class

You need to specify an access modifier for your variable. In this case you want it public.

public class Variables
{
    public static string name = "";
}

After this you can use the variable like this.

Variables.name

Exact time measurement for performance testing

System.Diagnostics.Stopwatch is designed for this task.

What is the difference between _tmain() and main() in C++?

_tmain does not exist in C++. main does.

_tmain is a Microsoft extension.

main is, according to the C++ standard, the program's entry point. It has one of these two signatures:

int main();
int main(int argc, char* argv[]);

Microsoft has added a wmain which replaces the second signature with this:

int wmain(int argc, wchar_t* argv[]);

And then, to make it easier to switch between Unicode (UTF-16) and their multibyte character set, they've defined _tmain which, if Unicode is enabled, is compiled as wmain, and otherwise as main.

As for the second part of your question, the first part of the puzzle is that your main function is wrong. wmain should take a wchar_t argument, not char. Since the compiler doesn't enforce this for the main function, you get a program where an array of wchar_t strings are passed to the main function, which interprets them as char strings.

Now, in UTF-16, the character set used by Windows when Unicode is enabled, all the ASCII characters are represented as the pair of bytes \0 followed by the ASCII value.

And since the x86 CPU is little-endian, the order of these bytes are swapped, so that the ASCII value comes first, then followed by a null byte.

And in a char string, how is the string usually terminated? Yep, by a null byte. So your program sees a bunch of strings, each one byte long.

In general, you have three options when doing Windows programming:

  • Explicitly use Unicode (call wmain, and for every Windows API function which takes char-related arguments, call the -W version of the function. Instead of CreateWindow, call CreateWindowW). And instead of using char use wchar_t, and so on
  • Explicitly disable Unicode. Call main, and CreateWindowA, and use char for strings.
  • Allow both. (call _tmain, and CreateWindow, which resolve to main/_tmain and CreateWindowA/CreateWindowW), and use TCHAR instead of char/wchar_t.

The same applies to the string types defined by windows.h: LPCTSTR resolves to either LPCSTR or LPCWSTR, and for every other type that includes char or wchar_t, a -T- version always exists which can be used instead.

Note that all of this is Microsoft specific. TCHAR is not a standard C++ type, it is a macro defined in windows.h. wmain and _tmain are also defined by Microsoft only.

git add, commit and push commands in one?

I ended up adding an alias to my .gitconfig file:

[alias]
    cmp = "!f() { git add -A && git commit -m \"$@\" && git push; }; f"

Usage: git cmp "Long commit message goes here"

Adds all files, then uses the comment for the commit message and pushes it up to origin.

I think it's a better solution because you have control over what the commit message is.

The alias can be also defined from command line, this adds it to your .gitconfig:

git config --global alias.cmp '!f() { git add -A && git commit -m "$@" && git push; }; f'

Exiting out of a FOR loop in a batch file?

As jeb noted, the rest of the loop is skipped but evaluated, which makes the FOR solution too slow for this purpose. An alternative:

set F=1
:nextpart
if not exist "%F%" goto :EOF
echo %F%
set /a F=%F%+1
goto nextpart

You might need to use delayed expansion and call subroutines when using this in loops.

browser.msie error after update to jQuery 1.9.1

You can use :

var MSIE = jQuery.support.leadingWhitespace; // This property is not supported by ie 6-8

$(document).ready(function(){

if (MSIE){
    if (navigator.vendor == 'Apple Computer, Inc.'){
        // some code for this navigator
    } else {
       // some code for others browsers
    }

} else {
    // default code

}});

How to convert a Title to a URL slug in jQuery?

For people already using lodash

Most of these example are really good and cover a lot of cases. But if you 'know' that you only have English text, here's my version that's super easy to read :)

_.words(_.toLower(text)).join('-')

Do I need a content-type header for HTTP GET requests?

Short answer: Most likely, no you do not need a content-type header for HTTP GET requests. But the specs does not seem to rule out a content-type header for HTTP GET, either.

Supporting materials:

  1. "Content-Type" is part of the representation (i.e. payload) metadata. Quoted from RFC 7231 section 3.1:

    3.1. Representation Metadata

    Representation header fields provide metadata about the representation. When a message includes a payload body, the representation header fields describe how to interpret the representation data enclosed in the payload body. ...

    The following header fields convey representation metadata:

    +-------------------+-----------------+
    | Header Field Name | Defined in...   |
    +-------------------+-----------------+
    | Content-Type      | Section 3.1.1.5 |
    | ...               | ...             |
    

    Quoted from RFC 7231 section 3.1.1.5(by the way, the current chosen answer had a typo in the section number):

    The "Content-Type" header field indicates the media type of the associated representation

  2. In that sense, a Content-Type header is not really about an HTTP GET request (or a POST or PUT request, for that matter). It is about the payload inside such a whatever request. So, if there will be no payload, there needs no Content-Type. In practice, some implementation went ahead and made that understandable assumption. Quoted from Adam's comment:

    "While ... the spec doesn't say you can't have Content-Type on a GET, .Net seems to enforce it in it's HttpClient. See this SO q&a."

  3. However, strictly speaking, the specs itself does not rule out the possibility of HTTP GET contains a payload. Quoted from RFC 7231 section 4.3.1:

    4.3.1 GET

    ...

    A payload within a GET request message has no defined semantics; sending a payload body on a GET request might cause some existing implementations to reject the request.

    So, if your HTTP GET happens to include a payload for whatever reason, a Content-Type header is probably reasonable, too.

Python extract pattern matches

You could use something like this:

import re
s = #that big string
# the parenthesis create a group with what was matched
# and '\w' matches only alphanumeric charactes
p = re.compile("name +(\w+) +is valid", re.flags)
# use search(), so the match doesn't have to happen 
# at the beginning of "big string"
m = p.search(s)
# search() returns a Match object with information about what was matched
if m:
    name = m.group(1)
else:
    raise Exception('name not found')

What's the difference between using CGFloat and float?

As @weichsel stated, CGFloat is just a typedef for either float or double. You can see for yourself by Command-double-clicking on "CGFloat" in Xcode — it will jump to the CGBase.h header where the typedef is defined. The same approach is used for NSInteger and NSUInteger as well.

These types were introduced to make it easier to write code that works on both 32-bit and 64-bit without modification. However, if all you need is float precision within your own code, you can still use float if you like — it will reduce your memory footprint somewhat. Same goes for integer values.

I suggest you invest the modest time required to make your app 64-bit clean and try running it as such, since most Macs now have 64-bit CPUs and Snow Leopard is fully 64-bit, including the kernel and user applications. Apple's 64-bit Transition Guide for Cocoa is a useful resource.

Displaying better error message than "No JSON object could be decoded"

I've found that the simplejson module gives more descriptive errors in many cases where the built-in json module is vague. For instance, for the case of having a comma after the last item in a list:

json.loads('[1,2,]')
....
ValueError: No JSON object could be decoded

which is not very descriptive. The same operation with simplejson:

simplejson.loads('[1,2,]')
...
simplejson.decoder.JSONDecodeError: Expecting object: line 1 column 5 (char 5)

Much better! Likewise for other common errors like capitalizing True.

Remove a data connection from an Excel 2010 spreadsheet in compatibility mode

I had the same problem. Please try this:

Sub deleteConn(xlBook)
    For Each Cn In xlBook.Connections
        Cn.Delete
    Next Cn

    For Each xlsheet In xlBook.Worksheets
        For Each Qt In xlsheet.QueryTables
            Qt.Delete
        Next Qt
    Next xlsheet

End Sub

CSS selector based on element text?

I know it's not exactly what you are looking for, but maybe it'll help you.

You can try use a jQuery selector :contains(), add a class and then do a normal style for a class.

Prevent RequireJS from Caching Required Scripts

RequireJS can be configured to append a value to each of the script urls for cache busting.

From the RequireJS documentation (http://requirejs.org/docs/api.html#config):

urlArgs: Extra query string arguments appended to URLs that RequireJS uses to fetch resources. Most useful to cache bust when the browser or server is not configured correctly.

Example, appending "v2" to all scripts:

require.config({
    urlArgs: "bust=v2"
});

For development purposes, you can force RequireJS to bypass the cache by appending a timestamp:

require.config({
    urlArgs: "bust=" + (new Date()).getTime()
});

use mysql SUM() in a WHERE clause

Not tested, but I think this will be close?

SELECT m1.id
FROM mytable m1
INNER JOIN mytable m2 ON m1.id < m2.id
GROUP BY m1.id
HAVING SUM(m1.cash) > 500
ORDER BY m1.id
LIMIT 1,2

The idea is to SUM up all the previous rows, get only the ones where the sum of the previous rows is > 500, then skip one and return the next one.

javascript scroll event for iPhone/iPad?

For iOS you need to use the touchmove event as well as the scroll event like this:

document.addEventListener("touchmove", ScrollStart, false);
document.addEventListener("scroll", Scroll, false);

function ScrollStart() {
    //start of scroll event for iOS
}

function Scroll() {
    //end of scroll event for iOS
    //and
    //start/end of scroll event for other browsers
}

Get the current fragment object

I know it's been a while, but I'll this here in case it helps someone out.

The right answer by far is (and the selected one) the one from CommonsWare. I was having the same problem as posted, the following

MyFragmentClass fragmentList = 
            (MyFragmentClass) getSupportFragmentManager().findFragmentById(R.id.fragementID);

kept on returning null. My mistake was really silly, in my xml file:

<fragment
    android:tag="@+id/fragementID"
    android:name="com.sf.lidgit_android.content.MyFragmentClass"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
/>

The mistake was that I had android:tag INSTEAD OF android:id.

User GETDATE() to put current date into SQL variable

DECLARE @LastChangeDate as date 
SET @LastChangeDate = GETDATE() 

Prevent the keyboard from displaying on activity start

declare this code( android:windowSoftInputMode="stateAlwaysHidden") in manifest inside your activity tag .

like this :

<activity android:name=".MainActivity"
  android:windowSoftInputMode="stateAlwaysHidden">

Where are the Android icon drawables within the SDK?

A huge collection of useful icons is easily accessible like this:

  1. Right click on Drawable folder
  2. Click on New
  3. Click on Vector Asset
  4. In the dialog, click the button in the third row with a random icon, next to the label "Clip Art:". You can pick from the huge collection, then customize size and color.

Convert integer into byte array (Java)

Have a look at the ByteBuffer class.

ByteBuffer b = ByteBuffer.allocate(4);
//b.order(ByteOrder.BIG_ENDIAN); // optional, the initial order of a byte buffer is always BIG_ENDIAN.
b.putInt(0xAABBCCDD);

byte[] result = b.array();

Setting the byte order ensures that result[0] == 0xAA, result[1] == 0xBB, result[2] == 0xCC and result[3] == 0xDD.

Or alternatively, you could do it manually:

byte[] toBytes(int i)
{
  byte[] result = new byte[4];

  result[0] = (byte) (i >> 24);
  result[1] = (byte) (i >> 16);
  result[2] = (byte) (i >> 8);
  result[3] = (byte) (i /*>> 0*/);

  return result;
}

The ByteBuffer class was designed for such dirty hands tasks though. In fact the private java.nio.Bits defines these helper methods that are used by ByteBuffer.putInt():

private static byte int3(int x) { return (byte)(x >> 24); }
private static byte int2(int x) { return (byte)(x >> 16); }
private static byte int1(int x) { return (byte)(x >>  8); }
private static byte int0(int x) { return (byte)(x >>  0); }

How to write to the Output window in Visual Studio?

If this is for debug output then OutputDebugString is what you want. A useful macro :

#define DBOUT( s )            \
{                             \
   std::ostringstream os_;    \
   os_ << s;                   \
   OutputDebugString( os_.str().c_str() );  \
}

This allows you to say things like:

DBOUT( "The value of x is " << x );

You can extend this using the __LINE__ and __FILE__ macros to give even more information.

For those in Windows and wide character land:

#include <Windows.h>
#include <iostream>
#include <sstream>

 #define DBOUT( s )            \
{                             \
   std::wostringstream os_;    \
   os_ << s;                   \
   OutputDebugStringW( os_.str().c_str() );  \
}

Count the number of occurrences of a string in a VARCHAR field?

This is the mysql function using the space technique (tested with mysql 5.0 + 5.5): CREATE FUNCTION count_str( haystack TEXT, needle VARCHAR(32)) RETURNS INTEGER DETERMINISTIC RETURN LENGTH(haystack) - LENGTH( REPLACE ( haystack, needle, space(char_length(needle)-1)) );

How can I make a link from a <td> table cell

This might be the most simple way to make a whole <td> cell an active hyperlink just using HTML.

I never had a satisfactory answer for this question, until about 10 minutes ago, so years in the making #humor.

Tested on Firefox 70, this is a bare-bones example where one full line-width of the cell is active:

<td><a href=""><div><br /></div></a></td>

Obviously the example just links to "this document," so fill in the href="" and replace the <br /> with anything appropriate.

Previously I used a style and class pair that I cobbled together from the answers above (Thanks to you folks.)

Today, working on a different issue, I kept stripping it down until <div>&nbsp;</div> was the only thing left, remove the <div></div> and it stops linking beyond the text. I didn't like the short "_" the &nbsp; displayed and found a single <br /> works without an "extra line" penalty.

If another <td></td> in the <tr> has multiple lines, and makes the row taller with word-wrap for instance, then use multiple <br /> to bring the <td> you want to be active to the correct number of lines and active the full width of each line.

The only problem is it isn't dynamic, but usually the mouse is closer in height than width, so active everywhere on one line is better than just the width of the text.

redirect while passing arguments

You could pass the messages as explicit URL parameter (appropriately encoded), or store the messages into session (cookie) variable before redirecting and then get the variable before rendering the template. For example:

from flask import session, url_for

def do_baz():
    messages = json.dumps({"main":"Condition failed on page baz"})
    session['messages'] = messages
    return redirect(url_for('.do_foo', messages=messages))

@app.route('/foo')
def do_foo():
    messages = request.args['messages']  # counterpart for url_for()
    messages = session['messages']       # counterpart for session
    return render_template("foo.html", messages=json.loads(messages))

(encoding the session variable might not be necessary, flask may be handling it for you, but can't recall the details)

Or you could probably just use Flask Message Flashing if you just need to show simple messages.

How do you reinstall an app's dependencies using npm?

npm updated the CLI command for install and added the --force flag.

npm install --force

The --force (or -f) argument will force npm to fetch remote resources even if a local copy exists on disk.

See npm install

How to detect when a UIScrollView has finished scrolling

func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
    scrollingFinished(scrollView: scrollView)
}

func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
    if decelerate {
        //didEndDecelerating will be called for sure
        return
    }
    scrollingFinished(scrollView: scrollView)        
}

func scrollingFinished(scrollView: UIScrollView) {
   // Your code
}

How do I install Python OpenCV through Conda?

Like others, I had issues with Python 3.5.1/Anaconda 2.4.0 on OS X 10.11..

But I found a compatible package here:

https://anaconda.org/menpo/opencv3

It can be installed via the command line like so:

 conda install -c https://conda.anaconda.org/menpo opencv3

Worked like a charm. First time I've ever gotten OpenCV to work on 3.x!

Change div height on button click

Do this:

function changeHeight() {
document.getElementById('chartdiv').style.height = "200px"
}
<button type="button" onClick="changeHeight();"> Click Me!</button>

ng-model for `<input type="file"/>` (with directive DEMO)

I use this directive:

angular.module('appFilereader', []).directive('appFilereader', function($q) {
    var slice = Array.prototype.slice;

    return {
        restrict: 'A',
        require: '?ngModel',
        link: function(scope, element, attrs, ngModel) {
                if (!ngModel) return;

                ngModel.$render = function() {};

                element.bind('change', function(e) {
                    var element = e.target;

                    $q.all(slice.call(element.files, 0).map(readFile))
                        .then(function(values) {
                            if (element.multiple) ngModel.$setViewValue(values);
                            else ngModel.$setViewValue(values.length ? values[0] : null);
                        });

                    function readFile(file) {
                        var deferred = $q.defer();

                        var reader = new FileReader();
                        reader.onload = function(e) {
                            deferred.resolve(e.target.result);
                        };
                        reader.onerror = function(e) {
                            deferred.reject(e);
                        };
                        reader.readAsDataURL(file);

                        return deferred.promise;
                    }

                }); //change

            } //link
    }; //return
});

and invoke it like this:

<input type="file" ng-model="editItem._attachments_uri.image" accept="image/*" app-filereader />

The property (editItem.editItem._attachments_uri.image) will be populated with the contents of the file you select as a data-uri (!).

Please do note that this script will not upload anything. It will only populate your model with the contents of your file encoded ad a data-uri (base64).

Check out a working demo here: http://plnkr.co/CMiHKv2BEidM9SShm9Vv

.net Core 2.0 - Package was restored using .NetFramework 4.6.1 instead of target framework .netCore 2.0. The package may not be fully compatible

The package is not fully compatible with dotnetcore 2.0 for now.

eg, for 'Microsoft.AspNet.WebApi.Client' it maybe supported in version (5.2.4). See Consume new Microsoft.AspNet.WebApi.Client.5.2.4 package for details.

You could try the standard Client package as Federico mentioned.

If that still not work, then as a workaround you can only create a Console App (.Net Framework) instead of the .net core 2.0 console app.

Reference this thread: Microsoft.AspNet.WebApi.Client supported in .NET Core or not?

How to print binary number via printf

printf() doesn't directly support that. Instead you have to make your own function.

Something like:

while (n) {
    if (n & 1)
        printf("1");
    else
        printf("0");

    n >>= 1;
}
printf("\n");

Using grep to search for hex strings in a file

I just used this:

grep -c $'\x0c' filename

To search for and count a page control character in the file..

So to include an offset in the output:

grep -b -o $'\x0c' filename | less

I am just piping the result to less because the character I am greping for does not print well and the less displays the results cleanly. Output example:

21:^L
23:^L
2005:^L

How do I fix a "Performance counter registry hive consistency" when installing SQL Server R2 Express?

Save the execution file on your desktop Make sure you note the name of your file Go to start and type cmd right click on it

select run as administrator press enter

then you something below

C:\Users\your computer name\Desktop>

If you are seeing

C:\Windows\system32>

make sure you change it using CD

type the name of your file

C:\Users\your computer name\Desktop>the name of the file your copy.exe/ACTION=install /SKIPRULES=PerfMonCounterNotCorruptedCheck

Force youtube embed to start in 720p

(This answer was updated, as the previous method using vq isn't recognized anymore.)

Specifying the height of the video will change the quality accordingly. example for html 5;

<iframe style='width:100%; height:800px;' src='https://www.youtube.com/embed/xxxxxxxx'></iframe>

If you don't want to hardcode the width and height you can add a class to the iframe for css media queries.

Tested on a working server + passes the w3.org nuhtml validator.

convert nan value to zero

This should work:

from numpy import *

a = array([[1, 2, 3], [0, 3, NaN]])
where_are_NaNs = isnan(a)
a[where_are_NaNs] = 0

In the above case where_are_NaNs is:

In [12]: where_are_NaNs
Out[12]: 
array([[False, False, False],
       [False, False,  True]], dtype=bool)

How big can a MySQL database get before performance starts to degrade

It depends on your query and validation.

For example, i worked with a table of 100 000 drugs which has a column generic name where it has more than 15 characters for each drug in that table .I put a query to compare the generic name of drugs between two tables.The query takes more minutes to run.The Same,if you compare the drugs using the drug index,using an id column (as said above), it takes only few seconds.

How do you pull first 100 characters of a string in PHP

$small = substr($big, 0, 100);

For String Manipulation here is a page with a lot of function that might help you in your future work.

How do I determine the size of my array in C?

You can use the & operator. Here is the source code:

#include<stdio.h>
#include<stdlib.h>
int main(){

    int a[10];

    int *p; 

    printf("%p\n", (void *)a); 
    printf("%p\n", (void *)(&a+1));
    printf("---- diff----\n");
    printf("%zu\n", sizeof(a[0]));
    printf("The size of array a is %zu\n", ((char *)(&a+1)-(char *)a)/(sizeof(a[0])));


    return 0;
};

Here is the sample output

1549216672
1549216712
---- diff----
4
The size of array a is 10

Simple check for SELECT query empty result

To summarize the below posts a bit:

If all you care about is if at least one matching row is in the DB then use exists as it is the most efficient way of checking this: it will return true as soon as it finds at least one matching row whereas count, etc will find all matching rows.

If you actually need to use the data for processing or if the query has side effects, or if you need to know the actual total number of rows then checking the ROWCOUNT or count is probably the best way on hand.

simulate background-size:cover on <video> or <img>

object-fit: cover is the best answer with this IE, Safari polyfill.

https://github.com/constancecchen/object-fit-polyfill

It is supporting img, video and picture elements.

Git undo local branch delete

Thanks, this worked.

git branch new_branch_name sha1

git checkout new_branch_name

//can see my old checked in files in my old branch

How do I show my global Git configuration?

The shortest,

git config -l

shows all inherited values from: system, global and local

syntaxerror: "unexpected character after line continuation character in python" math

Well, what do you try to do? If you want to use division, use "/" not "\". If it is something else, explain it in a bit more detail, please.

How to programmatically close a JFrame

If you do not want your application to terminate when a JFrame is closed, use: setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE)

instead of: setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

From the documentation:

DO_NOTHING_ON_CLOSE (defined in WindowConstants): Don't do anything; require the program to handle the operation in the windowClosing method of a registered WindowListener object.

HIDE_ON_CLOSE (defined in WindowConstants): Automatically hide the frame after invoking any registered WindowListener objects.

DISPOSE_ON_CLOSE (defined in WindowConstants): Automatically hide and dispose the frame after invoking any registered WindowListener objects.

EXIT_ON_CLOSE (defined in JFrame): Exit the application using the System exit method. Use this only in applications.

might still be useful: You can use setVisible(false) on your JFrame if you want to display the same frame again. Otherwise call dispose() to remove all of the native screen resources.

copied from Peter Lang

https://stackoverflow.com/a/1944474/3782247

How to prevent a click on a '#' link from jumping to top of page?

Adding something after # sets the focus of page to the element with that ID. Simplest solution is to use #/ even if you are using jQuery. However if you are handling the event in jQuery, event.preventDefault() is the way to go.

How to compile without warnings being treated as errors?

You can make all warnings being treated as such using -Wno-error. You can make specific warnings being treated as such by using -Wno-error=<warning name> where <warning name> is the name of the warning you don't want treated as an error.

If you want to entirely disable all warnings, use -w (not recommended).


Source: http://gcc.gnu.org/onlinedocs/gcc-4.3.2/gcc/Warning-Options.html

What is REST call and how to send a REST call?

REST is somewhat of a revival of old-school HTTP, where the actual HTTP verbs (commands) have semantic meaning. Til recently, apps that wanted to update stuff on the server would supply a form containing an 'action' variable and a bunch of data. The HTTP command would almost always be GET or POST, and would be almost irrelevant. (Though there's almost always been a proscription against using GET for operations that have side effects, in reality a lot of apps don't care about the command used.)

With REST, you might instead PUT /profiles/cHao and send an XML or JSON representation of the profile info. (Or rather, I would -- you would have to update your own profile. :) That'd involve logging in, usually through HTTP's built-in authentication mechanisms.) In the latter case, what you want to do is specified by the URL, and the request body is just the guts of the resource involved.

http://en.wikipedia.org/wiki/Representational_State_Transfer has some details.

Frontend tool to manage H2 database

If you are running it as an embedded database in spring I use the following configuration to enable the built in web client when the main app is running:

<!-- Run H2 web server within application that will access the same in-memory database -->
<bean id="h2Server" class="org.h2.tools.Server" factory-method="createTcpServer" init-method="start" destroy-method="stop" depends-on="h2WebServer">
    <constructor-arg value="-tcp,-tcpAllowOthers,-tcpPort,9092"/>
</bean>
<bean id="h2WebServer" class="org.h2.tools.Server" factory-method="createWebServer" init-method="start" destroy-method="stop">
    <constructor-arg value="-web,-webAllowOthers,-webPort,8082"/>
</bean>

Using isKindOfClass with Swift

Another approach using the new Swift 2 syntax is to use guard and nest it all in one conditional.

guard let touch = object.AnyObject() as? UITouch, let picker = touch.view as? UIPickerView else {
    return //Do Nothing
}
//Do something with picker

Convert UTC to local time in Rails 3

Rails has its own names. See them with:

rake time:zones:us

You can also run rake time:zones:all for all time zones. To see more zone-related rake tasks: rake -D time

So, to convert to EST, catering for DST automatically:

Time.now.in_time_zone("Eastern Time (US & Canada)")

Correlation heatmap

Another alternative is to use the heatmap function in seaborn to plot the covariance. This example uses the Auto data set from the ISLR package in R (the same as in the example you showed).

import pandas.rpy.common as com
import seaborn as sns
%matplotlib inline

# load the R package ISLR
infert = com.importr("ISLR")

# load the Auto dataset
auto_df = com.load_data('Auto')

# calculate the correlation matrix
corr = auto_df.corr()

# plot the heatmap
sns.heatmap(corr, 
        xticklabels=corr.columns,
        yticklabels=corr.columns)

enter image description here

If you wanted to be even more fancy, you can use Pandas Style, for example:

cmap = cmap=sns.diverging_palette(5, 250, as_cmap=True)

def magnify():
    return [dict(selector="th",
                 props=[("font-size", "7pt")]),
            dict(selector="td",
                 props=[('padding', "0em 0em")]),
            dict(selector="th:hover",
                 props=[("font-size", "12pt")]),
            dict(selector="tr:hover td:hover",
                 props=[('max-width', '200px'),
                        ('font-size', '12pt')])
]

corr.style.background_gradient(cmap, axis=1)\
    .set_properties(**{'max-width': '80px', 'font-size': '10pt'})\
    .set_caption("Hover to magify")\
    .set_precision(2)\
    .set_table_styles(magnify())

enter image description here

Is there a way since (iOS 7's release) to get the UDID without using iTunes on a PC/Mac?

Try this online tool http://www.easy-udid.com. I tested it on various iOS devices (iOS 6 and 7) and it works fine. Handful tool to quickly add customer's UDID in developer's profile

DOUBLE vs DECIMAL in MySQL

We have just been going through this same issue, but the other way around. That is, we store dollar amounts as DECIMAL, but now we're finding that, for example, MySQL was calculating a value of 4.389999999993, but when storing this into the DECIMAL field, it was storing it as 4.38 instead of 4.39 like we wanted it to. So, though DOUBLE may cause rounding issues, it seems that DECIMAL can cause some truncating issues as well.

How to change a css class style through Javascript?

If you want to manipulate the actual CSS class instead of modifying the DOM elements or using modifier CSS classes, see https://stackoverflow.com/a/50036923/482916.

How to deal with floating point number precision in JavaScript?

Elegant, Predictable, and Reusable

Let's deal with the problem in an elegant way reusable way. The following seven lines will let you access the floating point precision you desire on any number simply by appending .decimal to the end of the number, formula, or built in Math function.

_x000D_
_x000D_
// First extend the native Number object to handle precision. This populates_x000D_
// the functionality to all math operations._x000D_
_x000D_
Object.defineProperty(Number.prototype, "decimal", {_x000D_
  get: function decimal() {_x000D_
    Number.precision = "precision" in Number ? Number.precision : 3;_x000D_
    var f = Math.pow(10, Number.precision);_x000D_
    return Math.round( this * f ) / f;_x000D_
  }_x000D_
});_x000D_
_x000D_
_x000D_
// Now lets see how it works by adjusting our global precision level and _x000D_
// checking our results._x000D_
_x000D_
console.log("'1/3 + 1/3 + 1/3 = 1' Right?");_x000D_
console.log((0.3333 + 0.3333 + 0.3333).decimal == 1); // true_x000D_
_x000D_
console.log(0.3333.decimal); // 0.333 - A raw 4 digit decimal, trimmed to 3..._x000D_
_x000D_
Number.precision = 3;_x000D_
console.log("Precision: 3");_x000D_
console.log((0.8 + 0.2).decimal); // 1_x000D_
console.log((0.08 + 0.02).decimal); // 0.1_x000D_
console.log((0.008 + 0.002).decimal); // 0.01_x000D_
console.log((0.0008 + 0.0002).decimal); // 0.001_x000D_
_x000D_
Number.precision = 2;_x000D_
console.log("Precision: 2");_x000D_
console.log((0.8 + 0.2).decimal); // 1_x000D_
console.log((0.08 + 0.02).decimal); // 0.1_x000D_
console.log((0.008 + 0.002).decimal); // 0.01_x000D_
console.log((0.0008 + 0.0002).decimal); // 0_x000D_
_x000D_
Number.precision = 1;_x000D_
console.log("Precision: 1");_x000D_
console.log((0.8 + 0.2).decimal); // 1_x000D_
console.log((0.08 + 0.02).decimal); // 0.1_x000D_
console.log((0.008 + 0.002).decimal); // 0_x000D_
console.log((0.0008 + 0.0002).decimal); // 0_x000D_
_x000D_
Number.precision = 0;_x000D_
console.log("Precision: 0");_x000D_
console.log((0.8 + 0.2).decimal); // 1_x000D_
console.log((0.08 + 0.02).decimal); // 0_x000D_
console.log((0.008 + 0.002).decimal); // 0_x000D_
console.log((0.0008 + 0.0002).decimal); // 0
_x000D_
_x000D_
_x000D_

Cheers!

Deprecated Gradle features were used in this build, making it incompatible with Gradle 5.0

Important - Answer work only for REACT-NATIVE VS CODE Terminal

In VisualStudio code, you have to run like below then that warning will be omitted.

react-native run-android warning-mode=all

If you run below then you will get the error in terminal When running react-native run-android --warning-mode all I get error: unknown option --warning-mode'

How to add a button dynamically using jquery

Your append line must be in your test() function

EDIT:

Here are two versions:

Version 1: jQuery listener

$(function(){
    $('button').on('click',function(){
        var r= $('<input type="button" value="new button"/>');
        $("body").append(r);
    });
});

DEMO HERE

Version 2: With a function (like your example)

function createInput(){
    var $input = $('<input type="button" value="new button" />');
    $input.appendTo($("body"));
}

DEMO HERE

Note: This one can be done with either .appendTo or with .append.

How can I compare strings in C using a `switch` statement?

Function pointers are a great way to do this, e.g.

result = switchFunction(someStringKey); //result is an optional return value

...this calls a function that you have set by string key (one function per case):

setSwitchFunction("foo", fooFunc);
setSwitchFunction("bar", barFunc);

Use a pre-existing hashmap/table/dictionary implementation such as khash, return that pointer to a function inside of switchFunction(), and execute it (or just return it from switchFunction() and execute it yourself). If the map implementation doesn't store that, just use a uint64_t instead that you cast accordingly to a pointer.

Adding new files to a subversion repository

  • Checkout a working copy of the repository (or at least the subdirectory that you want to add the files to): svn checkout https://example.org/path/to/repo/bleh
  • Copy the files over there.
  • svn add file1 file2...
  • svn commit

I am not aware of a quicker option.

Note: if you are on the same machine as your Subversion repository, the URL can use the file: specifier with a path in place of https: in the svn checkout command. For example svn checkout file:///path/to/repo/bleh.

PS. as pointed out in the comments and other answers, you can use something like svn import . <URL> if you want to recursively import everything in the current directory. With this option, however, you can't skip over some of the files; it's all or nothing.

What is the easiest way to parse an INI file in Java?

Or with standard Java API you can use java.util.Properties:

Properties props = new Properties();
try (FileInputStream in = new FileInputStream(path)) {
    props.load(in);
}

Create a user with all privileges in Oracle

My issue was, i am unable to create a view with my "scott" user in oracle 11g edition. So here is my solution for this

Error in my case

SQL>create view v1 as select * from books where id=10;

insufficient privileges.

Solution

1)open your cmd and change your directory to where you install your oracle database. in my case i was downloaded in E drive so my location is E:\app\B_Amar\product\11.2.0\dbhome_1\BIN> after reaching in the position you have to type sqlplus sys as sysdba

E:\app\B_Amar\product\11.2.0\dbhome_1\BIN>sqlplus sys as sysdba

2) Enter password: here you have to type that password that you give at the time of installation of oracle software.

3) Here in this step if you want create a new user then you can create otherwise give all the privileges to existing user.

for creating new user

SQL> create user abc identified by xyz;

here abc is user and xyz is password.

giving all the privileges to abc user

SQL> grant all privileges to abc;

 grant succeeded. 

if you are seen this message then all the privileges are giving to the abc user.

4) Now exit from cmd, go to your SQL PLUS and connect to the user i.e enter your username & password.Now you can happily create view.

In My case

in cmd E:\app\B_Amar\product\11.2.0\dbhome_1\BIN>sqlplus sys as sysdba

SQL> grant all privileges to SCOTT;

grant succeeded.

Now I can create views.

Any way to Invoke a private method?

you can do this using ReflectionTestUtils of Spring (org.springframework.test.util.ReflectionTestUtils)

ReflectionTestUtils.invokeMethod(instantiatedObject,"methodName",argument);

Example : if you have a class with a private method square(int x)

Calculator calculator = new Calculator();
ReflectionTestUtils.invokeMethod(calculator,"square",10);

How to apply slide animation between two activities in Android?

Slide up/down with alpha animation with a few note

enter image description here

slide_up.xml

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
    android:duration="@integer/activity_transition_time"
    >
    <translate
        android:fromYDelta="100%p"
        android:toYDelta="0"/>
    <alpha
        android:fromAlpha="0.5"
        android:toAlpha="1"/>
</set>

slide_down.xml

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
    android:duration="@integer/activity_transition_time"
    >
    <translate
        android:fromYDelta="0"
        android:toYDelta="100%p"/>
    <alpha
        android:fromAlpha="1"
        android:toAlpha="0.5"/>
</set>

no_animation.xml

<?xml version="1.0" encoding="utf-8"?>
<translate xmlns:android="http://schemas.android.com/apk/res/android"
    android:duration="@integer/activity_transition_time"
    android:fromYDelta="0"
    android:toYDelta="0"/>

First Activity

startActivity(new Intent(this, SecondActivity.class));
overridePendingTransition(R.anim.slide_up,  R.anim.no_animation); // remember to put it after startActivity, if you put it to above, animation will not working
// document say if we don't want animation we can put 0. However, if we put 0 instead of R.anim.no_animation, the exist activity will become black when animate

Second Activity

finish();
overridePendingTransition(R.anim.no_animation, R.anim.slide_down);

Done

MORE
I try to make the slide animation like iOS animation when present a View Model (like this https://www.youtube.com/watch?v=deZobvh2064) but failed.

Looking at iOS present animation you will see: The animation from bottom with alpha (about 50%) then it go very fast then slower, the animation time is about > 500ms (I use trim video tools for count the animation time https://www.kapwing.com/trim-video so it can not exactly 100%)

Then I try to apply to android.
To make alpha I use <alpha> and success.
To make animation start faster than slower I use android:interpolator="a decelerate interpolator" but it almost failed.

There are 3 default decelerate interpolator in Android
@android:interpolator/decelerate_quad -> factor = 1
@android:interpolator/decelerate_cubic -> factor = 1.5
@android:interpolator/decelerate_quint _> factor = 2.5
(higher factor <=> animation start more faster from start and more slower at end)
Here is a good tutorial http://cogitolearning.co.uk/2013/10/android-animations-tutorial-5-more-on-interpolators/ for understand it

I tried 3 above I can not achieve like iOS, the animation can not start faster like iOS. Then I create a custom decelerateInterpolator wiht factor = 3 like

<?xml version="1.0" encoding="utf-8"?>
<decelerateInterpolator xmlns:android="http://schemas.android.com/apk/res/android"
    android:factor="3" />

and I increase the duration time from 500 -> 750. It working well (very similar to iOS). However, it only working well in some device, in some device the animation is quite slow. Later on, I know that animation may different on different device (eg: some device will faster and some device will slower) so I can not make it the animation similar in all Android device. Therefore I don't use interpolator. I don't know if my testing is exactly 100% or not but I hope this experience help

What does enumerate() mean?

I am assuming that you know how to iterate over elements in some list:

for el in my_list:
    # do something

Now sometimes not only you need to iterate over the elements, but also you need the index for each iteration. One way to do it is:

i = 0
for el in my_list:
    # do somethings, and use value of "i" somehow
    i += 1

However, a nicer way is to user the function "enumerate". What enumerate does is that it receives a list, and it returns a list-like object (an iterable that you can iterate over) but each element of this new list itself contains 2 elements: the index and the value from that original input list: So if you have

arr = ['a', 'b', 'c']

Then the command enumerate(arr) returns something like:

[(0,'a'), (1,'b'), (2,'c')]

Now If you iterate over a list (or an iterable) where each element itself has 2 sub-elements, you can capture both of those sub-elements in the for loop like below:

for index, value in enumerate(arr):
    print(index,value)

which would print out the sub-elements of the output of enumerate.

And in general you can basically "unpack" multiple items from list into multiple variables like below:

idx,value = (2,'c')
print(idx)
print(value)

which would print

2
c

This is the kind of assignment happening in each iteration of that loop with enumerate(arr) as iterable.

Android webview slow

I was having this same issue and I had to work it out. I tried these solutions, but at the end the performance, at least for the scrolling didn't improve at all. So here the workaroud that I did perform and the explanation of why it did work for me.

If you had the chance to explore the drag events, just a little, by creating a "MiWebView" Class, overwriting the "onTouchEvent" method and at least printed the time in which every drag event occurs, you'll see that they are separated in time for (down to) 9ms away. That is a very short time in between events.

Take a look at the WebView Source Code, and just see the onTouchEvent function. It is just impossible for it to be handled by the processor in less than 9ms (Keep on dreaming!!!). That's why you constantly see the "Miss a drag as we are waiting for WebCore's response for touch down." message. The code just can't be handled on time.

How to fix it? First, you can not re-write the onTouchEvent code to improve it, it is just too much. But, you can "mock it" in order to limit the event rate for dragging movements let's say to 40ms or 50ms. (this depends on the processor).

All touch events go like this: ACTION_DOWN -> ACTION_MOVE......ACTION_MOVE -> ACTION_UP. So we need to keep the DOWN and UP movements and filter the MOVE rate (these are the bad guys).

And here is a way to do it (you can add more event types like 2 fingers touch, all I'm interested here is the single finger scrolling).

import android.content.Context;
import android.view.MotionEvent;
import android.webkit.WebView;


public class MyWebView extends WebView{

    public MyWebView(Context context) {
        super(context);
        // TODO Auto-generated constructor stub
    }

    private long lastMoveEventTime = -1;
    private int eventTimeInterval = 40;

    @Override
    public boolean onTouchEvent(MotionEvent ev) {

        long eventTime = ev.getEventTime();
        int action = ev.getAction();

        switch (action){
            case MotionEvent.ACTION_MOVE: {
                if ((eventTime - lastMoveEventTime) > eventTimeInterval){
                    lastMoveEventTime = eventTime;
                    return super.onTouchEvent(ev);
                }
                break;
            }
            case MotionEvent.ACTION_DOWN:
            case MotionEvent.ACTION_UP: {
                return super.onTouchEvent(ev);
            }
        }
        return true;
    }
}

Of course Use this class instead of WebView and you'll see the difference when scrolling.

This is just an approach to a solution, yet still not fully implemented for all lag cases due to screen touching when using WebView. However it is the best solution I found, at least for my specific needs.

Making Maven run all tests, even when some fail

Can you test with surefire 2.6 and either configure Surefire with <testFailureIgnore>true</testFailureIgnore>.

Or on the command line:

mvn install -Dmaven.test.failure.ignore=true

Property 'map' does not exist on type 'Observable<Response>'

Angular 9:

 forkJoin([
  this.http.get().pipe(
    catchError((error) => {
      return of([]);
    })
  ),
  this.http.get().pipe(
    catchError((error) => {
      return of([]);
    })
  ),

PHP's array_map including keys

With PHP5.3 or later:

$test_array = array("first_key" => "first_value", 
                    "second_key" => "second_value");

var_dump(
    array_map(
        function($key) use ($test_array) { return "$key loves ${test_array[$key]}"; },
        array_keys($test_array)
    )
);

window.history.pushState refreshing the browser

window.history.pushState({urlPath:'/page1'},"",'/page1')

Only works after page is loaded, and when you will click on refresh it doesn't mean that there is any real URL.

What you should do here is knowing to which URL you are getting redirected when you reload this page. And on that page you can get the conditions by getting the current URL and making all of your conditions.

LINQ Using Max() to select a single row

More one example:

Follow:

 qryAux = (from q in qryAux where
            q.OrdSeq == (from pp in Sessao.Query<NameTable>() where pp.FieldPk
            == q.FieldPk select pp.OrdSeq).Max() select q);

Equals:

 select t.*   from nametable t  where t.OrdSeq =
        (select max(t2.OrdSeq) from nametable t2 where t2.FieldPk= t.FieldPk)

Laravel whereIn OR whereIn

You could have searched just for whereIn function in the core to see that. Here you are. This must answer all your questions

/**
 * Add a "where in" clause to the query.
 *
 * @param  string  $column
 * @param  mixed   $values
 * @param  string  $boolean
 * @param  bool    $not
 * @return \Illuminate\Database\Query\Builder|static
 */
public function whereIn($column, $values, $boolean = 'and', $not = false)
{
    $type = $not ? 'NotIn' : 'In';

    // If the value of the where in clause is actually a Closure, we will assume that
    // the developer is using a full sub-select for this "in" statement, and will
    // execute those Closures, then we can re-construct the entire sub-selects.
    if ($values instanceof Closure)
    {
        return $this->whereInSub($column, $values, $boolean, $not);
    }

    $this->wheres[] = compact('type', 'column', 'values', 'boolean');

    $this->bindings = array_merge($this->bindings, $values);

    return $this;
}

Look that it has a third boolean param. Good luck.

Can (a== 1 && a ==2 && a==3) ever evaluate to true?

Same, but different, but still same (can be "tested" multiple times):

_x000D_
_x000D_
const a = { valueOf: () => this.n = (this.n || 0) % 3 + 1}_x000D_
    _x000D_
if(a == 1 && a == 2 && a == 3) {_x000D_
  console.log('Hello World!');_x000D_
}_x000D_
_x000D_
if(a == 1 && a == 2 && a == 3) {_x000D_
  console.log('Hello World!');_x000D_
}
_x000D_
_x000D_
_x000D_

My idea started from how Number object type equation works.

Using @property versus getters and setters

I am surprised that nobody has mentioned that properties are bound methods of a descriptor class, Adam Donohue and NeilenMarais get at exactly this idea in their posts -- that getters and setters are functions and can be used to:

  • validate
  • alter data
  • duck type (coerce type to another type)

This presents a smart way to hide implementation details and code cruft like regular expression, type casts, try .. except blocks, assertions or computed values.

In general doing CRUD on an object may often be fairly mundane but consider the example of data that will be persisted to a relational database. ORM's can hide implementation details of particular SQL vernaculars in the methods bound to fget, fset, fdel defined in a property class that will manage the awful if .. elif .. else ladders that are so ugly in OO code -- exposing the simple and elegant self.variable = something and obviate the details for the developer using the ORM.

If one thinks of properties only as some dreary vestige of a Bondage and Discipline language (i.e. Java) they are missing the point of descriptors.

Pycharm and sys.argv arguments

Add the following to the top of your Python file.

import sys

sys.argv = [
    __file__,
    'arg1',
    'arg2'
]

Now, you can simply right click on the Python script.

How to fix 'sudo: no tty present and no askpass program specified' error?

For Ubuntu 16.04 users

There is a file you have to read with:

cat /etc/sudoers.d/README

Placing a file with mode 0440 in /etc/sudoers.d/myuser with following content:

myuser  ALL=(ALL) NOPASSWD: ALL

Should fix the issue.

Do not forget to:

chmod 0440 /etc/sudoers.d/myuser

How do I create a comma-separated list from an array in PHP?

$fruit = array('apple', 'banana', 'pear', 'grape');    
$commasaprated = implode(',' , $fruit);

javascript node.js next()

It is naming convention used when passing callbacks in situations that require serial execution of actions, e.g. scan directory -> read file data -> do something with data. This is in preference to deeply nesting the callbacks. The first three sections of the following article on Tim Caswell's HowToNode blog give a good overview of this:

http://howtonode.org/control-flow

Also see the Sequential Actions section of the second part of that posting:

http://howtonode.org/control-flow-part-ii

What version of javac built my jar?

To expand on Jonathon Faust's and McDowell's answers: If you're on a *nix based system, you can use od (one of the earliest Unix programs1 which should be available practically everywhere) to query the .class file on a binary level:

od -An -j7 -N1 -t dC SomeClassFile.class

This will output the familiar integer values, e.g. 50 for Java 5, 51 for Java 6 and so on.

1 Quote from https://en.wikipedia.org/wiki/Od_(Unix)

is there any way to force copy? copy without overwrite prompt, using windows?

MOVE /-Y Source Destination

Note:/-y will make the announcement of yes/no for overwrite

Open links in new window using AngularJS

this is the code of your button

<a href="AddNewUserAdmin" 
   class="btn btn-info " 
   ng-click="showaddnewuserpage()">
  <span class="glyphicon glyphicon-plus-sign"></span> Add User</a>

in the controller just add this function.

 var app = angular.module('userAPP', []);

app.controller('useraddcontroller', function ($scope, $http, $window) {

$scope.showaddnewuserpage = function () {

    $window.location.href = ('/AddNewUserAdmin');
}

});

.NET data structures: ArrayList, List, HashTable, Dictionary, SortedList, SortedDictionary -- Speed, memory, and when to use each?

They're spelled out pretty well in intellisense. Just type System.Collections. or System.Collections.Generics (preferred) and you'll get a list and short description of what's available.

Calling Java from Python

I'm on OSX 10.10.2, and succeeded in using JPype.

Ran into installation problems with Jnius (others have too), Javabridge installed but gave mysterious errors when I tried to use it, PyJ4 has this inconvenience of having to start a Gateway server in Java first, JCC wouldn't install. Finally, JPype ended up working. There's a maintained fork of JPype on Github. It has the major advantages that (a) it installs properly and (b) it can very efficiently convert java arrays to numpy array (np_arr = java_arr[:])

The installation process was:

git clone https://github.com/originell/jpype.git
cd jpype
python setup.py install

And you should be able to import jpype

The following demo worked:

import jpype as jp
jp.startJVM(jp.getDefaultJVMPath(), "-ea")
jp.java.lang.System.out.println("hello world")
jp.shutdownJVM() 

When I tried calling my own java code, I had to first compile (javac ./blah/HelloWorldJPype.java), and I had to change the JVM path from the default (otherwise you'll get inexplicable "class not found" errors). For me, this meant changing the startJVM command to:

jp.startJVM('/Library/Java/JavaVirtualMachines/jdk1.7.0_79.jdk/Contents/MacOS/libjli.dylib', "-ea")
c = jp.JClass('blah.HelloWorldJPype')  
# Where my java class file is in ./blah/HelloWorldJPype.class
...

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

You can try this:

((BigDecimal) volume).intValue();

I use java.math.BigDecimal convert to int (primitive type).

It is worked for me.

How to access a dictionary element in a Django template?

You could use a namedtuple instead of a dict. This is a shorthand for using a data class. Instead of

person = {'name':  'John', 'age':  14}

...do:

from collections import namedtuple
Person = namedtuple('person', ['name', 'age'])
p = Person(name='John', age=14)
p.name # 'John'

This is the same as writing a class that just holds data. In general I would avoid using dicts in django templates because they are awkward.

JavaScript: how to change form action attribute value based on selection?

If you only want to change form's action, I prefer changing action on-form-submit, rather than on-input-change. It fires only once.

$('#search-form').submit(function(){
  var formAction = $("#selectsearch").val() == "people" ? "user" : "content";
  $("#search-form").attr("action", "/search/" + formAction);
}); 

Android: upgrading DB version and adding new table

Your code looks correct. My suggestion is that the database already thinks it's upgraded. If you executed the project after incrementing the version number, but before adding the execSQL call, the database on your test device/emulator may already believe it's at version 2.

A quick way to verify this would be to change the version number to 3 -- if it upgrades after that, you know it was just because your device believed it was already upgraded.

How to perform .Max() on a property of all objects in a collection and return the object with maximum value

In NHibernate (with NHibernate.Linq) you could do it as follows:

return session.Query<T>()
              .Single(a => a.Filter == filter &&
                           a.Id == session.Query<T>()
                                          .Where(a2 => a2.Filter == filter)
                                          .Max(a2 => a2.Id));

Which will generate SQL like follows:

select *
from TableName foo
where foo.Filter = 'Filter On String'
and foo.Id = (select cast(max(bar.RowVersion) as INT)
              from TableName bar
              where bar.Name = 'Filter On String')

Which seems pretty efficient to me.

Repeat command automatically in Linux

Running commands periodically without cron is possible when we go with while.

As a command:

while true ; do command ; sleep 100 ; done &
[ ex: # while true;  do echo `date` ; sleep 2 ; done & ]

Example:

while true
do echo "Hello World"
sleep 100
done &

Do not forget the last & as it will put your loop in the background. But you need to find the process id with command "ps -ef | grep your_script" then you need to kill it. So kindly add the '&' when you running the script.

# ./while_check.sh &

Here is the same loop as a script. Create file "while_check.sh" and put this in it:

#!/bin/bash
while true; do 
    echo "Hello World" # Substitute this line for whatever command you want.
    sleep 100
done

Then run it by typing bash ./while_check.sh &

MongoDB logging all queries

This was asked a long time ago but this may still help someone:

MongoDB profiler logs all the queries in the capped collection system.profile. See this: database profiler

  1. Start mongod instance with --profile=2 option that enables logging all queries OR if mongod instances is already running, from mongoshell, run db.setProfilingLevel(2) after selecting database. (it can be verified by db.getProfilingLevel(), which should return 2)
  2. After this, I have created a script which utilises mongodb's tailable cursor to tail this system.profile collection and write the entries in a file. To view the logs I just need to tail it:tail -f ../logs/mongologs.txt. This script can be started in background and it will log all the operation on the db in the file.

My code for tailable cursor for the system.profile collection is in nodejs; it logs all the operations along with queries happening in every collection of MyDb:

const MongoClient = require('mongodb').MongoClient;
const assert = require('assert');
const fs = require('fs');
const file = '../logs/mongologs'
// Connection URL
const url = 'mongodb://localhost:27017';

// Database Name
const dbName = 'MyDb';
//Mongodb connection

MongoClient.connect(url, function (err, client) {
   assert.equal(null, err);
   const db = client.db(dbName);
   listen(db, {})
});

function listen(db, conditions) {
var filter = { ns: { $ne: 'MyDb.system.profile' } }; //filter for query
//e.g. if we need to log only insert queries, use {op:'insert'}
//e.g. if we need to log operation on only 'MyCollection' collection, use {ns: 'MyDb.MyCollection'}
//we can give a lot of filters, print and check the 'document' variable below

// set MongoDB cursor options
var cursorOptions = {
    tailable: true,
    awaitdata: true,
    numberOfRetries: -1
};

// create stream and listen
var stream = db.collection('system.profile').find(filter, cursorOptions).stream();

// call the callback
stream.on('data', function (document) {
    //this will run on every operation/query done on our database
    //print 'document' to check the keys based on which we can filter
    //delete data which we dont need in our log file

    delete document.execStats;
    delete document.keysExamined;
    //-----
    //-----

    //append the log generated in our log file which can be tailed from command line
    fs.appendFile(file, JSON.stringify(document) + '\n', function (err) {
        if (err) (console.log('err'))
    })

});

}

For tailable cursor in python using pymongo, refer the following code which filters for MyCollection and only insert operation:

import pymongo
import time
client = pymongo.MongoClient()
oplog = client.MyDb.system.profile
first = oplog.find().sort('$natural', pymongo.ASCENDING).limit(-1).next()

ts = first['ts']
while True:
    cursor = oplog.find({'ts': {'$gt': ts}, 'ns': 'MyDb.MyCollection', 'op': 'insert'},
                        cursor_type=pymongo.CursorType.TAILABLE_AWAIT)
    while cursor.alive:
        for doc in cursor:
            ts = doc['ts']
            print(doc)
            print('\n')
        time.sleep(1)

Note: Tailable cursor only works with capped collections. It cannot be used to log operations on a collection directly, instead use filter: 'ns': 'MyDb.MyCollection'

Note: I understand that the above nodejs and python code may not be of much help for some. I have just provided the codes for reference.

Use this link to find documentation for tailable cursor in your languarge/driver choice Mongodb Drivers

Another feature that i have added after this logrotate.

Extracting text OpenCV

this is a VB.NET version of the answer from dhanushka using EmguCV.

A few functions and structures in EmguCV need different consideration than the C# version with OpenCVSharp

Imports Emgu.CV
Imports Emgu.CV.Structure
Imports Emgu.CV.CvEnum
Imports Emgu.CV.Util

        Dim input_file As String = "C:\your_input_image.png"
        Dim large As Mat = New Mat(input_file)
        Dim rgb As New Mat
        Dim small As New Mat
        Dim grad As New Mat
        Dim bw As New Mat
        Dim connected As New Mat
        Dim morphanchor As New Point(0, 0)

        '//downsample and use it for processing
        CvInvoke.PyrDown(large, rgb)
        CvInvoke.CvtColor(rgb, small, ColorConversion.Bgr2Gray)

        '//morphological gradient
        Dim morphKernel As Mat = CvInvoke.GetStructuringElement(ElementShape.Ellipse, New Size(3, 3), morphanchor)
        CvInvoke.MorphologyEx(small, grad, MorphOp.Gradient, morphKernel, New Point(0, 0), 1, BorderType.Isolated, New MCvScalar(0))

        '// binarize
        CvInvoke.Threshold(grad, bw, 0, 255, ThresholdType.Binary Or ThresholdType.Otsu)

        '// connect horizontally oriented regions
        morphKernel = CvInvoke.GetStructuringElement(ElementShape.Rectangle, New Size(9, 1), morphanchor)
        CvInvoke.MorphologyEx(bw, connected, MorphOp.Close, morphKernel, morphanchor, 1, BorderType.Isolated, New MCvScalar(0))

        '// find contours
        Dim mask As Mat = Mat.Zeros(bw.Size.Height, bw.Size.Width, DepthType.Cv8U, 1)  '' MatType.CV_8UC1
        Dim contours As New VectorOfVectorOfPoint
        Dim hierarchy As New Mat

        CvInvoke.FindContours(connected, contours, hierarchy, RetrType.Ccomp, ChainApproxMethod.ChainApproxSimple, Nothing)

        '// filter contours
        Dim idx As Integer
        Dim rect As Rectangle
        Dim maskROI As Mat
        Dim r As Double
        For Each hierarchyItem In hierarchy.GetData
            rect = CvInvoke.BoundingRectangle(contours(idx))
            maskROI = New Mat(mask, rect)
            maskROI.SetTo(New MCvScalar(0, 0, 0))

            '// fill the contour
            CvInvoke.DrawContours(mask, contours, idx, New MCvScalar(255), -1)

            '// ratio of non-zero pixels in the filled region
            r = CvInvoke.CountNonZero(maskROI) / (rect.Width * rect.Height)

            '/* assume at least 45% of the area Is filled if it contains text */
            '/* constraints on region size */
            '/* these two conditions alone are Not very robust. better to use something 
            'Like the number of significant peaks in a horizontal projection as a third condition */
            If r > 0.45 AndAlso rect.Height > 8 AndAlso rect.Width > 8 Then
                'draw green rectangle
                CvInvoke.Rectangle(rgb, rect, New MCvScalar(0, 255, 0), 2)
            End If
            idx += 1
        Next
        rgb.Save(IO.Path.Combine(Application.StartupPath, "rgb.jpg"))

Pass multiple parameters in Html.BeginForm MVC

There are two options here.

  1. a hidden field within the form, or
  2. Add it to the route values parameter in the begin form method.

Edit

@Html.Hidden("clubid", ViewBag.Club.id)

or

 @using(Html.BeginForm("action", "controller",
                       new { clubid = @Viewbag.Club.id }, FormMethod.Post, null)

Create a pointer to two-dimensional array

You can always avoid fiddling around with the compiler by declaring the array as linear and doing the (row,col) to array index calculation by yourself.

static uint8_t l_matrix[200];

void test(int row, int col, uint8_t val)

{

   uint8_t* matrix_ptr = l_matrix;
   matrix_ptr [col+y*row] = val; // to assign a value

}

this is what the compiler would have done anyway.

How do I update Homebrew?

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

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

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

At original time of writing to uninstall:

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

Edit: As of 2020 to uninstall:

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

Changing file permission in Python

You can use, pathlib also

from pathlib import Path

fl = Path("file_name")

fl.chmod(0o444)

Clearing Magento Log Data

you can disable or set date and time for log setting.

System > Configuration > Advanced > System > Log Cleaning

Detect WebBrowser complete page loading

It doesn't seem to trigger DocumentCompleted/Navigated events for external Javascript or CSS files, but it will for iframes. As PK says, compare the WebBrowserDocumentCompletedEventArgs.Url property (I don't have the karma to make a comment yet).

XPath: select text node

Having the following XML:

<node>Text1<subnode/>text2</node> 

How do I select either the first or the second text node via XPath?

Use:

/node/text()

This selects all text-node children of the top element (named "node") of the XML document.

/node/text()[1]

This selects the first text-node child of the top element (named "node") of the XML document.

/node/text()[2]

This selects the second text-node child of the top element (named "node") of the XML document.

/node/text()[someInteger]

This selects the someInteger-th text-node child of the top element (named "node") of the XML document. It is equivalent to the following XPath expression:

/node/text()[position() = someInteger]

Change WPF window background image in C# code

The problem is the way you are using it in code. Just try the below code

public partial class MainView : Window
{
    public MainView()
    {
        InitializeComponent();

        ImageBrush myBrush = new ImageBrush();
        myBrush.ImageSource =
            new BitmapImage(new Uri("pack://application:,,,/icon.jpg", UriKind.Absolute));
        this.Background = myBrush;
    }
}

You can find more details regarding this in
http://msdn.microsoft.com/en-us/library/aa970069.aspx

How to override application.properties during production in Spring-Boot?

I have found the following has worked for me:

java -jar my-awesome-java-prog.jar --spring.config.location=file:/path-to-config-dir/

with file: added.

LATE EDIT

Of course, this command line is never run as it is in production.

Rather I have

  • [possibly several layers of] shell scripts in source control with place holders for all parts of the command that could change (name of the jar, path to config...)
  • ansible deployment scripts that will deploy the shell scripts and replace the place holders by the actual value.

Moving from JDK 1.7 to JDK 1.8 on Ubuntu

Just use these command lines:

sudo add-apt-repository ppa:webupd8team/java
sudo apt-get update
sudo apt-get install oracle-java8-installer

If needed, you can also follow this Ubuntu tutorial.

How to loop through all the files in a directory in c # .net?

try below code

Directory.GetFiles(txtFolderPath.Text, "*ProfileHandler.cs",SearchOption.AllDirectories)

Round float to x decimals?

Use the built-in function round():

In [23]: round(66.66666666666,4)
Out[23]: 66.6667

In [24]: round(1.29578293,6)
Out[24]: 1.295783

help on round():

round(number[, ndigits]) -> floating point number

Round a number to a given precision in decimal digits (default 0 digits). This always returns a floating point number. Precision may be negative.

Calling a Fragment method from a parent Activity

((HomesFragment)getSupportFragmentManager().findFragmentById(R.id.fragment_container)).filterValidation();

Why does this code using random strings print "hello world"?

As multi-threading is very easy with Java, here is a variant that searches for a seed using all cores available: http://ideone.com/ROhmTA

import java.util.ArrayList;
import java.util.Random;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;

public class SeedFinder {

  static class SearchTask implements Callable<Long> {

    private final char[] goal;
    private final long start, step;

    public SearchTask(final String goal, final long offset, final long step) {
      final char[] goalAsArray = goal.toCharArray();
      this.goal = new char[goalAsArray.length + 1];
      System.arraycopy(goalAsArray, 0, this.goal, 0, goalAsArray.length);
      this.start = Long.MIN_VALUE + offset;
      this.step = step;
    }

    @Override
    public Long call() throws Exception {
      final long LIMIT = Long.MAX_VALUE - this.step;
      final Random random = new Random();
      int position, rnd;
      long seed = this.start;

      while ((Thread.interrupted() == false) && (seed < LIMIT)) {
        random.setSeed(seed);
        position = 0;
        rnd = random.nextInt(27);
        while (((rnd == 0) && (this.goal[position] == 0))
                || ((char) ('`' + rnd) == this.goal[position])) {
          ++position;
          if (position == this.goal.length) {
            return seed;
          }
          rnd = random.nextInt(27);
        }
        seed += this.step;
      }

      throw new Exception("No match found");
    }
  }

  public static void main(String[] args) {
    final String GOAL = "hello".toLowerCase();
    final int NUM_CORES = Runtime.getRuntime().availableProcessors();

    final ArrayList<SearchTask> tasks = new ArrayList<>(NUM_CORES);
    for (int i = 0; i < NUM_CORES; ++i) {
      tasks.add(new SearchTask(GOAL, i, NUM_CORES));
    }

    final ExecutorService executor = Executors.newFixedThreadPool(NUM_CORES, new ThreadFactory() {

      @Override
      public Thread newThread(Runnable r) {
        final Thread result = new Thread(r);
        result.setPriority(Thread.MIN_PRIORITY); // make sure we do not block more important tasks
        result.setDaemon(false);
        return result;
      }
    });
    try {
      final Long result = executor.invokeAny(tasks);
      System.out.println("Seed for \"" + GOAL + "\" found: " + result);
    } catch (Exception ex) {
      System.err.println("Calculation failed: " + ex);
    } finally {
      executor.shutdownNow();
    }
  }
}

How to update a claim in ASP.NET Identity?

Multiple Cookies,Multiple Claims

public class ClaimsCookie
    {
        private readonly ClaimsPrincipal _user;
        private readonly HttpContext _httpContext;
        public ClaimsCookie(ClaimsPrincipal user, HttpContext httpContext = null)
        {
            _user = user;
            _httpContext = httpContext;
        }

        public string GetValue(CookieName cookieName, KeyName keyName)
        {
            var principal = _user as ClaimsPrincipal;
            var cp = principal.Identities.First(i => i.AuthenticationType == ((CookieName)cookieName).ToString());
            return cp.FindFirst(((KeyName)keyName).ToString()).Value;
        }
        public async void SetValue(CookieName cookieName, KeyName[] keyName, string[] value)
        {
            if (keyName.Length != value.Length)
            {
                return;
            }
            var principal = _user as ClaimsPrincipal;
            var cp = principal.Identities.First(i => i.AuthenticationType == ((CookieName)cookieName).ToString());
            for (int i = 0; i < keyName.Length; i++)
            {
                if (cp.FindFirst(((KeyName)keyName[i]).ToString()) != null)
                {
                    cp.RemoveClaim(cp.FindFirst(((KeyName)keyName[i]).ToString()));
                    cp.AddClaim(new Claim(((KeyName)keyName[i]).ToString(), value[i]));
                }

            }
            await _httpContext.SignOutAsync(CookieName.UserProfilCookie.ToString());
            await _httpContext.SignInAsync(CookieName.UserProfilCookie.ToString(), new ClaimsPrincipal(cp),
                new AuthenticationProperties
                {
                    IsPersistent = bool.Parse(cp.FindFirst(KeyName.IsPersistent.ToString()).Value),
                    AllowRefresh = true
                });
        }
        public enum CookieName
        {
            CompanyUserProfilCookie = 0, UserProfilCookie = 1, AdminPanelCookie = 2
        }
        public enum KeyName
        {
            Id, Name, Surname, Image, IsPersistent
        }
    }

Serial Port (RS -232) Connection in C++

Please take a look here:

1) You can use this with Windows (incl. MinGW) as well as Linux. Alternative you can only use the code as an example.

2) Step-by-step tutorial how to use serial ports on windows

3) You can use this literally on MinGW

Here's some very, very simple code (without any error handling or settings):

#include <windows.h>

/* ... */


// Open serial port
HANDLE serialHandle;

serialHandle = CreateFile("\\\\.\\COM1", GENERIC_READ | GENERIC_WRITE, 0, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);

// Do some basic settings
DCB serialParams = { 0 };
serialParams.DCBlength = sizeof(serialParams);

GetCommState(serialHandle, &serialParams);
serialParams.BaudRate = baudrate;
serialParams.ByteSize = byteSize;
serialParams.StopBits = stopBits;
serialParams.Parity = parity;
SetCommState(serialHandle, &serialParams);

// Set timeouts
COMMTIMEOUTS timeout = { 0 };
timeout.ReadIntervalTimeout = 50;
timeout.ReadTotalTimeoutConstant = 50;
timeout.ReadTotalTimeoutMultiplier = 50;
timeout.WriteTotalTimeoutConstant = 50;
timeout.WriteTotalTimeoutMultiplier = 10;

SetCommTimeouts(serialHandle, &timeout);

Now you can use WriteFile() / ReadFile() to write / read bytes. Don't forget to close your connection:

CloseHandle(serialHandle);

Putting HTML inside Html.ActionLink(), plus No Link Text?

A custom HtmlHelper extension is another option. Note: ParameterDictionary is my own type. You could substitute a RouteValueDictionary but you'd have to construct it differently.

public static string ActionLinkSpan( this HtmlHelper helper, string linkText, string actionName, string controllerName, object htmlAttributes )
{
    TagBuilder spanBuilder = new TagBuilder( "span" );
    spanBuilder.InnerHtml = linkText;

    return BuildNestedAnchor( spanBuilder.ToString(), string.Format( "/{0}/{1}", controllerName, actionName ), htmlAttributes );
}

private static string BuildNestedAnchor( string innerHtml, string url, object htmlAttributes )
{
    TagBuilder anchorBuilder = new TagBuilder( "a" );
    anchorBuilder.Attributes.Add( "href", url );
    anchorBuilder.MergeAttributes( new ParameterDictionary( htmlAttributes ) );
    anchorBuilder.InnerHtml = innerHtml;

    return anchorBuilder.ToString();
}

Execute specified function every X seconds

You can do this easily by adding a Timer to your form (from the designer) and setting it's Tick-function to run your isonline-function.

How do I alter the precision of a decimal column in Sql Server?

Go to enterprise manager, design table, click on your field.

Make a decimal column

In the properties at the bottom there is a precision property

JavaScript for...in vs for

I'd use the different methods based on how I wanted to reference the items.

Use foreach if you just want the current item.

Use for if you need an indexer to do relative comparisons. (I.e. how does this compare to the previous/next item?)

I have never noticed a performance difference. I'd wait until having a performance issue before worrying about it.

How to parse XML using vba

Here is a short sub to parse a MicroStation Triforma XML file that contains data for structural steel shapes.

'location of triforma structural files
'c:\programdata\bentley\workspace\triforma\tf_imperial\data\us.xml

Sub ReadTriformaImperialData()
Dim txtFileName As String
Dim txtFileLine As String
Dim txtFileNumber As Long

Dim Shape As String
Shape = "w12x40"

txtFileNumber = FreeFile
txtFileName = "c:\programdata\bentley\workspace\triforma\tf_imperial\data\us.xml"

Open txtFileName For Input As #txtFileNumber

Do While Not EOF(txtFileNumber)
Line Input #txtFileNumber, txtFileLine
    If InStr(1, UCase(txtFileLine), UCase(Shape)) Then
        P1 = InStr(1, UCase(txtFileLine), "D=")
        D = Val(Mid(txtFileLine, P1 + 3))

        P2 = InStr(1, UCase(txtFileLine), "TW=")
        TW = Val(Mid(txtFileLine, P2 + 4))

        P3 = InStr(1, UCase(txtFileLine), "WIDTH=")
        W = Val(Mid(txtFileLine, P3 + 7))

        P4 = InStr(1, UCase(txtFileLine), "TF=")
        TF = Val(Mid(txtFileLine, P4 + 4))

        Close txtFileNumber
        Exit Do
    End If
Loop
End Sub

From here you can use the values to draw the shape in MicroStation 2d or do it in 3d and extrude it to a solid.