Programs & Examples On #Passthru

UTF-8 output from PowerShell

Not an expert on encoding, but after reading these...

... it seems fairly clear that the $OutputEncoding variable only affects data piped to native applications.

If sending to a file from withing PowerShell, the encoding can be controlled by the -encoding parameter on the out-file cmdlet e.g.

write-output "hello" | out-file "enctest.txt" -encoding utf8

Nothing else you can do on the PowerShell front then, but the following post may well help you:.

Obtaining ExitCode using Start-Process and WaitForExit instead of -Wait

There are two things to remember here. One is to add the -PassThru argument and two is to add the -Wait argument. You need to add the wait argument because of this defect: http://connect.microsoft.com/PowerShell/feedback/details/520554/start-process-does-not-return-exitcode-property

-PassThru [<SwitchParameter>]
    Returns a process object for each process that the cmdlet started. By d
    efault, this cmdlet does not generate any output.

Once you do this a process object is passed back and you can look at the ExitCode property of that object. Here is an example:

$process = start-process ping.exe -windowstyle Hidden -ArgumentList "-n 1 -w 127.0.0.1" -PassThru -Wait
$process.ExitCode

# This will print 1

If you run it without -PassThru or -Wait, it will print out nothing.

The same answer is here: How do I run a Windows installer and get a succeed/fail value in PowerShell?

Capturing standard out and error with Start-Process

IMPORTANT:

We have been using the function as provided above by LPG.

However, this contains a bug you might encounter when you start a process that generates a lot of output. Due to this you might end up with a deadlock when using this function. Instead use the adapted version below:

Function Execute-Command ($commandTitle, $commandPath, $commandArguments)
{
  Try {
    $pinfo = New-Object System.Diagnostics.ProcessStartInfo
    $pinfo.FileName = $commandPath
    $pinfo.RedirectStandardError = $true
    $pinfo.RedirectStandardOutput = $true
    $pinfo.UseShellExecute = $false
    $pinfo.Arguments = $commandArguments
    $p = New-Object System.Diagnostics.Process
    $p.StartInfo = $pinfo
    $p.Start() | Out-Null
    [pscustomobject]@{
        commandTitle = $commandTitle
        stdout = $p.StandardOutput.ReadToEnd()
        stderr = $p.StandardError.ReadToEnd()
        ExitCode = $p.ExitCode
    }
    $p.WaitForExit()
  }
  Catch {
     exit
  }
}

Further information on this issue can be found at MSDN:

A deadlock condition can result if the parent process calls p.WaitForExit before p.StandardError.ReadToEnd and the child process writes enough text to fill the redirected stream. The parent process would wait indefinitely for the child process to exit. The child process would wait indefinitely for the parent to read from the full StandardError stream.

PHP exec() vs system() vs passthru()

It really all comes down to how you want to handle output that the command might return and whether you want your PHP script to wait for the callee program to finish or not.

  • exec executes a command and passes output to the caller (or returns it in an optional variable).

  • passthru is similar to the exec() function in that it executes a command . This function should be used in place of exec() or system() when the output from the Unix command is binary data which needs to be passed directly back to the browser.

  • system executes an external program and displays the output, but only the last line.

If you need to execute a command and have all the data from the command passed directly back without any interference, use the passthru() function.

How to add extra whitespace in PHP?

for adding space character you can use

<? 
echo "\x20\x20\x20"; 
 ?>

How to fill in proxy information in cntlm config file?

Once you generated the file, and changed your password, you can run as below,

cntlm -H

Username will be the same. it will ask for password, give it, then copy the PassNTLMv2, edit the cntlm.ini, then just run the following

cntlm -v

How to get multiple select box values using jQuery?

Get selected values in comma separator

var Accessids = "";
$(".multi_select .btn-group>ul>li input:checked").each(function(i,obj)
{
    Accessids=Accessids+$(obj).val()+",";
});
Accessids = Accessids.substring(0,Accessids.length - 1);
console.log(Accessids);

Ruby function to remove all white spaces?

My personal preference is using the method .tr

as in:

string = "this is a string to smash together"

string.tr(' ', '') # => "thisisastringtosmashtogether"

Thanks to @FrankScmitt for pointing out that to make this delete all whitespace(not just spaces) you would need to write it as such:

string = "this is a string with tabs\t and a \nnewline"

string.tr(" \n\t", '') # => "thisisastringwithtabsandanewline"

Using CSS :before and :after pseudo-elements with inline CSS?

You can't specify inline styles for pseudo-elements.

This is because pseudo-elements, like pseudo-classes (see my answer to this other question), are defined in CSS using selectors as abstractions of the document tree that can't be expressed in HTML. An inline style attribute, on the other hand, is specified within HTML for a particular element.

Since inline styles can only occur in HTML, they will only apply to the HTML element that they're defined on, and not to any pseudo-elements it generates.

As an aside, the main difference between pseudo-elements and pseudo-classes in this aspect is that properties that are inherited by default will be inherited by :before and :after from the generating element, whereas pseudo-class styles just don't apply at all. In your case, for example, if you place text-align: justify in an inline style attribute for a td element, it will be inherited by td:after. The caveat is that you can't declare td:after with the inline style attribute; you must do it in the stylesheet.

What are Covering Indexes and Covered Queries in SQL Server?

A covered query is a query where all the columns in the query's result set are pulled from non-clustered indexes.

A query is made into a covered query by the judicious arrangement of indexes.

A covered query is often more performant than a non-covered query in part because non-clustered indexes have more rows per page than clustered indexes or heap indexes, so fewer pages need to be brought into memory in order to satisfy the query. They have more rows per page because only part of the table row is part of the index row.

A covering index is an index which is used in a covered query. There is no such thing as an index which, in and of itself, is a covering index. An index may be a covering index with respect to query A, while at the same time not being a covering index with respect to query B.

Generating Request/Response XML from a WSDL

Parasoft is a tool which can do this. I've done this very thing using this tool in my past work place. You can generate a request in Parasoft SOATest and get a response in Parasoft Virtualize. It does cost though. However Parasoft Virtualize now has a free community edition from which you can generate response messages from a WSDL. You can download from parasoft community edition

Best way to implement keyboard shortcuts in a Windows Forms application?

You probably forgot to set the form's KeyPreview property to True. Overriding the ProcessCmdKey() method is the generic solution:

protected override bool ProcessCmdKey(ref Message msg, Keys keyData) {
  if (keyData == (Keys.Control | Keys.F)) {
    MessageBox.Show("What the Ctrl+F?");
    return true;
  }
  return base.ProcessCmdKey(ref msg, keyData);
}

openCV program compile error "libopencv_core.so.2.4: cannot open shared object file: No such file or directory" in ubuntu 12.04

Add this link:

/usr/local/lib/*.so.*

The total is:

g++ -o main.out main.cpp -I /usr/local/include -I /usr/local/include/opencv -I /usr/local/include/opencv2 -L /usr/local/lib /usr/local/lib/*.so /usr/local/lib/*.so.*

Delaying a jquery script until everything else has loaded

From here:

// Add jQuery 
var GM_JQ = document.createElement('script'); 
GM_JQ.src = 'http://jquery.com/src/jquery-latest.js';
GM_JQ.type = 'text/javascript'; 
document.getElementsByTagName('head')[0].appendChild(GM_JQ); 

// Check if jQuery's loaded 
function GM_wait() 
{ 
    if(typeof unsafeWindow.jQuery == 'undefined') 
    { 
        window.setTimeout(GM_wait,100); 
    } 
    else 
    { 
        $ = unsafeWindow.jQuery; 
        letsJQuery(); 
    } 
} 

GM_wait(); 

// All your GM code must be inside this function 
function letsJQuery() 
{
    // Do your jQuery stuff in here    
} 

This will wait until jQuery is loaded to use it, but you can use the same concept, setting variables in your other scripts (or checking them if they're not your script) to wait until they're loaded to use them.

For example, on my site, I use this for asynchronous JS loading and waiting until they're finished before doing anything with them using jQuery:

<script type="text/javascript" language="JavaScript"> 
    function js(url){
        s = document.createElement("script");
        s.type = "text/javascript";
        s.src = url;
        document.getElementsByTagName("head")[0].appendChild(s);
    }       

    js("/js/jquery-ui.js");
    js("/js/jrails.js");
    js("/js/jquery.jgrowl-min.js");
    js("/js/jquery.scrollTo-min.js");
    js("/js/jquery.corner-min.js");
    js("/js/jquery.cookie-min.js");
    js("/js/application-min.js");

    function JS_wait() {
        if (typeof $.cookie == 'undefined' || // set in jquery.cookie-min.js
            typeof getLastViewedAnchor == 'undefined' || // set in application-min.js
            typeof getLastViewedArchive == 'undefined' || // set in application-min.js 
            typeof getAntiSpamValue == 'undefined') // set in application-min.js
        { 
            window.setTimeout(JS_wait, 100); 
        }
        else 
        { 
            JS_ready(); 
        }
    }

    function JS_ready() {
        // snipped
    };

    $(document).ready(JS_wait);
</script> 

How to convert a std::string to const char* or char*?

C++17

C++17 (upcoming standard) changes the synopsis of the template basic_string adding a non const overload of data():

charT* data() noexcept;

Returns: A pointer p such that p + i == &operator for each i in [0,size()].


CharT const * from std::basic_string<CharT>

std::string const cstr = { "..." };
char const * p = cstr.data(); // or .c_str()

CharT * from std::basic_string<CharT>

std::string str = { "..." };
char * p = str.data();

C++11

CharT const * from std::basic_string<CharT>

std::string str = { "..." };
str.c_str();

CharT * from std::basic_string<CharT>

From C++11 onwards, the standard says:

  1. The char-like objects in a basic_string object shall be stored contiguously. That is, for any basic_string object s, the identity &*(s.begin() + n) == &*s.begin() + n shall hold for all values of n such that 0 <= n < s.size().

  1. const_reference operator[](size_type pos) const;
    reference operator[](size_type pos);

    Returns: *(begin() + pos) if pos < size(), otherwise a reference to an object of type CharT with value CharT(); the referenced value shall not be modified.


  1. const charT* c_str() const noexcept;
    const charT* data() const noexcept;

    Returns: A pointer p such that p + i == &operator[](i) for each i in [0,size()].

There are severable possible ways to get a non const character pointer.

1. Use the contiguous storage of C++11

std::string foo{"text"};
auto p = &*foo.begin();

Pro

  • Simple and short
  • Fast (only method with no copy involved)

Cons

  • Final '\0' is not to be altered / not necessarily part of the non-const memory.

2. Use std::vector<CharT>

std::string foo{"text"};
std::vector<char> fcv(foo.data(), foo.data()+foo.size()+1u);
auto p = fcv.data();

Pro

  • Simple
  • Automatic memory handling
  • Dynamic

Cons

  • Requires string copy

3. Use std::array<CharT, N> if N is compile time constant (and small enough)

std::string foo{"text"};
std::array<char, 5u> fca;
std::copy(foo.data(), foo.data()+foo.size()+1u, fca.begin());

Pro

  • Simple
  • Stack memory handling

Cons

  • Static
  • Requires string copy

4. Raw memory allocation with automatic storage deletion

std::string foo{ "text" };
auto p = std::make_unique<char[]>(foo.size()+1u);
std::copy(foo.data(), foo.data() + foo.size() + 1u, &p[0]);

Pro

  • Small memory footprint
  • Automatic deletion
  • Simple

Cons

  • Requires string copy
  • Static (dynamic usage requires lots more code)
  • Less features than vector or array

5. Raw memory allocation with manual handling

std::string foo{ "text" };
char * p = nullptr;
try
{
  p = new char[foo.size() + 1u];
  std::copy(foo.data(), foo.data() + foo.size() + 1u, p);
  // handle stuff with p
  delete[] p;
}
catch (...)
{
  if (p) { delete[] p; }
  throw;
}

Pro

  • Maximum 'control'

Con

  • Requires string copy
  • Maximum liability / susceptibility for errors
  • Complex

How do I convert a string to a number in PHP?

$a = "10";

$b = (int)$a;

You can use this to convert a string to an int in PHP.

Missing Authentication Token while accessing API Gateway?

If you are using an API with endpoint of type PRIVATE, be sure of:

  1. You are invoking the API from within your AWS account (example: from an EC2 instance created in your account)

  2. Put necessary credential (access and secret keys) in the EC2 instance in route ~/.aws/credentials (this route is for linux instances) If IAM user use MFA aws_session_token value will be required too.

  3. Use vpce (vpc endpoint) based URL. Example: curl https://vpce-0c0471b7test-jkznizi5.execute-api.us-east-1.vpce.amazonaws.com/dev/api/v1/status

  4. Your EC2 instance have a security group than allow outbound traffic to another security group owned by the vpce like: EC2 instance sg

  5. Your vpce security group allow inbound traffic from another security group (previous sg from ec2 instance) owned by the EC2 instance like: vpce sg

See: https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-private-apis.html

Switching users inside Docker image to a non-root user

There's no real way to do this. As a result, things like mysqld_safe fail, and you can't install mysql-server in a Debian docker container without jumping through 40 hoops because.. well... it aborts if it's not root.

You can use USER, but you won't be able to apt-get install if you're not root.

Remove multiple items from a Python list in just one statement

You Can use this -

Suppose we have a list, l = [1,2,3,4,5]

We want to delete last two items in a single statement

del l[3:]

We have output:

l = [1,2,3]

Keep it Simple

Javascript/DOM: How to remove all events of a DOM object?

Use the event listener's own function remove(). For example:

getEventListeners().click.forEach((e)=>{e.remove()})

CSS3 selector to find the 2nd div of the same class

First you must select the parent element and set :nth-of-type(n) for the parent and then select the element you want. something like this :

#topmenu li:nth-of-type(2) ul.childUl {

This will select the second submenu from topmenu. #topmenu li is the parent element.

HTML:

<ul id="topmenu">
    <li>
        <ul class="childUl">
            <li></li>
            <li></li>
            <li></li>
        </ul>
    </li>
    <li>
        <ul class="childUl">
            <li></li>
            <li></li>
            <li></li>
        </ul>
    </li>
    <li>
        <ul class="childUl">
            <li></li>
            <li></li>
            <li></li>
        </ul>
    </li>

AttributeError: 'str' object has no attribute

The problem is in your playerMovement method. You are creating the string name of your room variables (ID1, ID2, ID3):

letsago = "ID" + str(self.dirDesc.values())

However, what you create is just a str. It is not the variable. Plus, I do not think it is doing what you think its doing:

>>>str({'a':1}.values())
'dict_values([1])'

If you REALLY needed to find the variable this way, you could use the eval function:

>>>foo = 'Hello World!'
>>>eval('foo')
'Hello World!'

or the globals function:

class Foo(object):
    def __init__(self):
        super(Foo, self).__init__()
    def test(self, name):
        print(globals()[name])

foo = Foo()
bar = 'Hello World!'
foo.text('bar')

However, instead I would strongly recommend you rethink you class(es). Your userInterface class is essentially a Room. It shouldn't handle player movement. This should be within another class, maybe GameManager or something like that.

Is there a query language for JSON?

  1. Google has a project called lovefield; just found out about it, and it looks interesting, though it is more involved than just dropping in underscore or lodash.

    https://github.com/google/lovefield

Lovefield is a relational query engine written in pure JavaScript. It also provides help with persisting data on the browser side, e.g. using IndexedDB to store data locally. It provides SQL-like syntax and works cross-browser (currently supporting Chrome 37+, Firefox 31+, IE 10+, and Safari 5.1+...


  1. Another interesting recent entry in this space called jinqJs.

    http://www.jinqjs.com/

    Briefly reviewing the examples, it looks promising, and the API document appears to be well written.


function isChild(row) {
  return (row.Age < 18 ? 'Yes' : 'No');
}

var people = [
  {Name: 'Jane', Age: 20, Location: 'Smithtown'},
  {Name: 'Ken', Age: 57, Location: 'Islip'},
  {Name: 'Tom', Age: 10, Location: 'Islip'}
];

var result = new jinqJs()
  .from(people)
  .orderBy('Age')
  .select([{field: 'Name'}, 
     {field: 'Age', text: 'Your Age'}, 
     {text: 'Is Child', value: isChild}]);

jinqJs is a small, simple, lightweight and extensible javaScript library that has no dependencies. jinqJs provides a simple way to perform SQL like queries on javaScript arrays, collections and web services that return a JSON response. jinqJs is similar to Microsoft's Lambda expression for .Net, and it provides similar capabilities to query collections using a SQL like syntax and predicate functionality. jinqJs’s purpose is to provide a SQL like experience to programmers familiar with LINQ queries.

Naming convention - underscore in C++ and C# variables

The underscore is simply a convention; nothing more. As such, its use is always somewhat different to each person. Here's how I understand them for the two languages in question:

In C++, an underscore usually indicates a private member variable.

In C#, I usually see it used only when defining the underlying private member variable for a public property. Other private member variables would not have an underscore. This usage has largely gone to the wayside with the advent of automatic properties though.

Before:

private string _name;
public string Name
{
    get { return this._name; }
    set { this._name = value; }
}

After:

public string Name { get; set; }

How to find common elements from multiple vectors?

intersect_all <- function(a,b,...){
  all_data <- c(a,b,...)
  require(plyr)
  count_data<- length(list(a,b,...))
  freq_dist <- count(all_data)
  intersect_data <- freq_dist[which(freq_dist$freq==count_data),"x"]
  intersect_data
}


intersect_all(a,b,c)

UPDATE EDIT A simpler code

intersect_all <- function(a,b,...){
  Reduce(intersect, list(a,b,...))
}

intersect_all(a,b,c)

Iterate over object attributes in python

class someclass:
        x=1
        y=2
        z=3
        def __init__(self):
           self.current_idx = 0
           self.items = ["x","y","z"]
        def next(self):
            if self.current_idx < len(self.items):
                self.current_idx += 1
                k = self.items[self.current_idx-1]
                return (k,getattr(self,k))
            else:
                raise StopIteration
        def __iter__(self):
           return self

then just call it as an iterable

s=someclass()
for k,v in s:
    print k,"=",v

Remove URL parameters without refreshing page

TL;DR

1- To modify current URL and add / inject it (the new modified URL) as a new URL entry to history list, use pushState:

window.history.pushState({}, document.title, "/" + "my-new-url.html");

2- To replace current URL without adding it to history entries, use replaceState:

window.history.replaceState({}, document.title, "/" + "my-new-url.html");

3- Depending on your business logic, pushState will be useful in cases such as:

  • you want to support the browser's back button

  • you want to create a new URL, add/insert/push the new URL to history entries, and make it current URL

  • allowing users to bookmark the page with the same parameters (to show the same contents)

  • to programmatically access the data through the stateObj then parse from the anchor


As I understood from your comment, you want to clean your URL without redirecting again.

Note that you cannot change the whole URL. You can just change what comes after the domain's name. This means that you cannot change www.example.com/ but you can change what comes after .com/

www.example.com/old-page-name => can become =>  www.example.com/myNewPaage20180322.php

Background

We can use:

1- The pushState() method if you want to add a new modified URL to history entries.

2- The replaceState() method if you want to update/replace current history entry.

.replaceState() operates exactly like .pushState() except that .replaceState() modifies the current history entry instead of creating a new one. Note that this doesn't prevent the creation of a new entry in the global browser history.


.replaceState() is particularly useful when you want to update the state object or URL of the current history entry in response to some user action.


Code

To do that I will use The pushState() method for this example which works similarly to the following format:

var myNewURL = "my-new-URL.php";//the new URL
window.history.pushState("object or string", "Title", "/" + myNewURL );

Feel free to replace pushState with replaceState based on your requirements.

You can substitute the paramter "object or string" with {} and "Title" with document.title so the final statment will become:

window.history.pushState({}, document.title, "/" + myNewURL );

Results

The previous two lines of code will make a URL such as:

https://domain.tld/some/randome/url/which/will/be/deleted/

To become:

https://domain.tld/my-new-url.php

Action

Now let's try a different approach. Say you need to keep the file's name. The file name comes after the last / and before the query string ?.

http://www.someDomain.com/really/long/address/keepThisLastOne.php?name=john

Will be:

http://www.someDomain.com/keepThisLastOne.php

Something like this will get it working:

 //fetch new URL
 //refineURL() gives you the freedom to alter the URL string based on your needs. 
var myNewURL = refineURL();

//here you pass the new URL extension you want to appear after the domains '/'. Note that the previous identifiers or "query string" will be replaced. 
window.history.pushState("object or string", "Title", "/" + myNewURL );


//Helper function to extract the URL between the last '/' and before '?' 
//If URL is www.example.com/one/two/file.php?user=55 this function will return 'file.php' 
 //pseudo code: edit to match your URL settings  

   function refineURL()
{
    //get full URL
    var currURL= window.location.href; //get current address
    
    //Get the URL between what's after '/' and befor '?' 
    //1- get URL after'/'
    var afterDomain= currURL.substring(currURL.lastIndexOf('/') + 1);
    //2- get the part before '?'
    var beforeQueryString= afterDomain.split("?")[0];  
 
    return beforeQueryString;     
}

UPDATE:

For one liner fans, try this out in your console/firebug and this page URL will change:

    window.history.pushState("object or string", "Title", "/"+window.location.href.substring(window.location.href.lastIndexOf('/') + 1).split("?")[0]);

This page URL will change from:

http://stackoverflow.com/questions/22753052/remove-url-parameters-without-refreshing-page/22753103#22753103

To

http://stackoverflow.com/22753103#22753103

Note: as Samuel Liew indicated in the comments below, this feature has been introduced only for HTML5.

An alternative approach would be to actually redirect your page (but you will lose the query string `?', is it still needed or the data has been processed?).

window.location.href =  window.location.href.split("?")[0]; //"http://www.newurl.com";

Note 2:

Firefox seems to ignore window.history.pushState({}, document.title, ''); when the last argument is an empty string. Adding a slash ('/') worked as expected and removed the whole query part of the url string. Chrome seems to be fine with an empty string.

How to test my servlet using JUnit

First off, in a real application, you would never get database connection info in a servlet; you would configure it in your app server.

There are ways, however, of testing Servlets without having a container running. One is to use mock objects. Spring provides a set of very useful mocks for things like HttpServletRequest, HttpServletResponse, HttpServletSession, etc:

http://static.springsource.org/spring/docs/3.0.x/api/org/springframework/mock/web/package-summary.html

Using these mocks, you could test things like

What happens if username is not in the request?

What happens if username is in the request?

etc

You could then do stuff like:

import static org.junit.Assert.assertEquals;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.junit.Before;
import org.junit.Test;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;

public class MyServletTest {
    private MyServlet servlet;
    private MockHttpServletRequest request;
    private MockHttpServletResponse response;

    @Before
    public void setUp() {
        servlet = new MyServlet();
        request = new MockHttpServletRequest();
        response = new MockHttpServletResponse();
    }

    @Test
    public void correctUsernameInRequest() throws ServletException, IOException {
        request.addParameter("username", "scott");
        request.addParameter("password", "tiger");

        servlet.doPost(request, response);

        assertEquals("text/html", response.getContentType());

        // ... etc
    }
}

IOCTL Linux device driver

The ioctl function is useful for implementing a device driver to set the configuration on the device. e.g. a printer that has configuration options to check and set the font family, font size etc. ioctl could be used to get the current font as well as set the font to a new one. A user application uses ioctl to send a code to a printer telling it to return the current font or to set the font to a new one.

int ioctl(int fd, int request, ...)
  1. fd is file descriptor, the one returned by open;
  2. request is request code. e.g GETFONT will get the current font from the printer, SETFONT will set the font on the printer;
  3. the third argument is void *. Depending on the second argument, the third may or may not be present, e.g. if the second argument is SETFONT, the third argument can be the font name such as "Arial";

int request is not just a macro. A user application is required to generate a request code and the device driver module to determine which configuration on device must be played with. The application sends the request code using ioctl and then uses the request code in the device driver module to determine which action to perform.

A request code has 4 main parts

    1. A Magic number - 8 bits
    2. A sequence number - 8 bits
    3. Argument type (typically 14 bits), if any.
    4. Direction of data transfer (2 bits).  

If the request code is SETFONT to set font on a printer, the direction for data transfer will be from user application to device driver module (The user application sends the font name "Arial" to the printer). If the request code is GETFONT, direction is from printer to the user application.

In order to generate a request code, Linux provides some predefined function-like macros.

1._IO(MAGIC, SEQ_NO) both are 8 bits, 0 to 255, e.g. let us say we want to pause printer. This does not require a data transfer. So we would generate the request code as below

#define PRIN_MAGIC 'P'
#define NUM 0
#define PAUSE_PRIN __IO(PRIN_MAGIC, NUM) 

and now use ioctl as

ret_val = ioctl(fd, PAUSE_PRIN);

The corresponding system call in the driver module will receive the code and pause the printer.

  1. __IOW(MAGIC, SEQ_NO, TYPE) MAGIC and SEQ_NO are the same as above, and TYPE gives the type of the next argument, recall the third argument of ioctl is void *. W in __IOW indicates that the data flow is from user application to driver module. As an example, suppose we want to set the printer font to "Arial".
#define PRIN_MAGIC 'S'
#define SEQ_NO 1
#define SETFONT __IOW(PRIN_MAGIC, SEQ_NO, unsigned long)

further,

char *font = "Arial";
ret_val = ioctl(fd, SETFONT, font); 

Now font is a pointer, which means it is an address best represented as unsigned long, hence the third part of _IOW mentions type as such. Also, this address of font is passed to corresponding system call implemented in device driver module as unsigned long and we need to cast it to proper type before using it. Kernel space can access user space and hence this works. other two function-like macros are __IOR(MAGIC, SEQ_NO, TYPE) and __IORW(MAGIC, SEQ_NO, TYPE) where the data flow will be from kernel space to user space and both ways respectively.

Please let me know if this helps!

How to loop through a checkboxlist and to find what's checked and not checked?

Try something like this:

foreach (ListItem listItem in clbIncludes.Items)
{
    if (listItem.Selected) { 
        //do some work 
    }
    else { 
        //do something else 
    }
}

How to iterate through a String

How about this

for (int i = 0; i < str.length(); i++) { 
    System.out.println(str.substring(i, i + 1)); 
} 

Adding Only Untracked Files

To add all untracked files git command is

git add -A

Also if you want to get more details about various available options , you can type command

git add -i

instead of first command , with this you will get more options including option to add all untracked files as shown below :

$ git add -i warning: LF will be replaced by CRLF in README.txt. The file will have its original line endings in your working directory. warning: LF will be replaced by CRLF in package.json.

* Commands * 1: status 2: update 3: revert 4: add untracked 5: patch 6: diff 7: quit 8: help What now> a

FileNotFoundException while getting the InputStream object from HttpURLConnection

FileNotFound is just an unfortunate exception used to indicate that the web server returned a 404.

PHP Echo text Color

This is an old question, but no one responded to the question regarding centering text in a terminal.

/**
 * Centers a string of text in a terminal window
 *
 * @param string $text The text to center
 * @param string $pad_string If set, the string to pad with (eg. '=' for a nice header)
 *
 * @return string The padded result, ready to echo
 */
function center($text, $pad_string = ' ') {
    $window_size = (int) `tput cols`;
    return str_pad($text, $window_size, $pad_string, STR_PAD_BOTH)."\n";
}

echo center('foo');
echo center('bar baz', '=');

How to display raw JSON data on a HTML page

Note that the link you provided does is not an HTML page, but rather a JSON document. The formatting is done by the browser.

You have to decide if:

  1. You want to show the raw JSON (not an HTML page), as in your example
  2. Show an HTML page with formatted JSON

If you want 1., just tell your application to render a response body with the JSON, set the MIME type (application/json), etc. In this case, formatting is dealt by the browser (and/or browser plugins)

If 2., it's a matter of rendering a simple minimal HTML page with the JSON where you can highlight it in several ways:

  • server-side, depending on your stack. There are solutions for almost every language
  • client-side with Javascript highlight libraries.

If you give more details about your stack, it's easier to provide examples or resources.

EDIT: For client side JS highlighting you can try higlight.js, for instance.

Bootstrap 3 Carousel Not Working

Well, Bootstrap Carousel has various parameters to control.

i.e.

Interval: Specifies the delay (in milliseconds) between each slide.

pause: Pauses the carousel from going through the next slide when the mouse pointer enters the carousel, and resumes the sliding when the mouse pointer leaves the carousel.

wrap: Specifies whether the carousel should go through all slides continuously, or stop at the last slide

For your reference:

enter image description here

Fore more details please click here...

Hope this will help you :)

Note: This is for the further help.. I mean how can you customise or change default behaviour once carousel is loaded.

How to parse/format dates with LocalDateTime? (Java 8)

All the answers are good. The java8+ have these patterns for parsing and formatting timezone: V, z, O, X, x, Z.

Here's they are, for parsing, according to rules from the documentation :

   Symbol  Meaning                     Presentation      Examples
   ------  -------                     ------------      -------
   V       time-zone ID                zone-id           America/Los_Angeles; Z; -08:30
   z       time-zone name              zone-name         Pacific Standard Time; PST
   O       localized zone-offset       offset-O          GMT+8; GMT+08:00; UTC-08:00;
   X       zone-offset 'Z' for zero    offset-X          Z; -08; -0830; -08:30; -083015; -08:30:15;
   x       zone-offset                 offset-x          +0000; -08; -0830; -08:30; -083015; -08:30:15;
   Z       zone-offset                 offset-Z          +0000; -0800; -08:00;

But how about formatting? Here's a sample for a date (assuming ZonedDateTime) that show these patters behavior for different formatting patters:

// The helper function:
static void printInPattern(ZonedDateTime dt, String pattern) {
    System.out.println(pattern + ": " + dt.format(DateTimeFormatter.ofPattern(pattern)));
}        

// The date:
String strDate = "2020-11-03 16:40:44 America/Los_Angeles";
DateTimeFormatter format = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss zzzz");
ZonedDateTime dt = ZonedDateTime.parse(strDate, format);
// 2020-11-03T16:40:44-08:00[America/Los_Angeles]

// Rules:
// printInPattern(dt, "V");     // exception!
printInPattern(dt, "VV");       // America/Los_Angeles
// printInPattern(dt, "VVV");   // exception!
// printInPattern(dt, "VVVV");  // exception!
printInPattern(dt, "z");        // PST
printInPattern(dt, "zz");       // PST
printInPattern(dt, "zzz");      // PST
printInPattern(dt, "zzzz");     // Pacific Standard Time
printInPattern(dt, "O");        // GMT-8
// printInPattern(dt, "OO");    // exception!
// printInPattern(dt, "OO0");   // exception!
printInPattern(dt, "OOOO");     // GMT-08:00
printInPattern(dt, "X");        // -08
printInPattern(dt, "XX");       // -0800
printInPattern(dt, "XXX");      // -08:00
printInPattern(dt, "XXXX");     // -0800
printInPattern(dt, "XXXXX");    // -08:00
printInPattern(dt, "x");        // -08
printInPattern(dt, "xx");       // -0800
printInPattern(dt, "xxx");      // -08:00
printInPattern(dt, "xxxx");     // -0800
printInPattern(dt, "xxxxx");    // -08:00
printInPattern(dt, "Z");        // -0800
printInPattern(dt, "ZZ");       // -0800
printInPattern(dt, "ZZZ");      // -0800
printInPattern(dt, "ZZZZ");     // GMT-08:00
printInPattern(dt, "ZZZZZ");    // -08:00

In the case of positive offset the + sign character is used everywhere(where there is - now) and never omitted.

This well works for new java.time types. If you're about to use these for java.util.Date or java.util.Calendar - not all going to work as those types are broken(and so marked as deprecated, please don't use them)

Update Top 1 record in table sql server

When TOP is used with INSERT, UPDATE, MERGE, or DELETE, the referenced rows are not arranged in any order and the ORDER BY clause can not be directly specified in these statements. If you need to use TOP to insert, delete, or modify rows in a meaningful chronological order, you must use TOP together with an ORDER BY clause that is specified in a subselect statement.

TOP cannot be used in an UPDATE and DELETE statements on partitioned views.

TOP cannot be combined with OFFSET and FETCH in the same query expression (in the same query scope). For more information, see http://technet.microsoft.com/en-us/library/ms189463.aspx

How to sort by two fields in Java?

You need to implement your own Comparator, and then use it: for example

Arrays.sort(persons, new PersonComparator());

Your Comparator could look a bit like this:

public class PersonComparator implements Comparator<? extends Person> {

  public int compare(Person p1, Person p2) {
     int nameCompare = p1.name.compareToIgnoreCase(p2.name);
     if (nameCompare != 0) {
        return nameCompare;
     } else {
       return Integer.valueOf(p1.age).compareTo(Integer.valueOf(p2.age));
     }
  }
}

The comparator first compares the names, if they are not equals it returns the result from comparing them, else it returns the compare result when comparing the ages of both persons.

This code is only a draft: because the class is immutable you could think of building an singleton of it, instead creating a new instance for each sorting.

Creating and appending text to txt file in VB.NET

Why not just use the following simple call (with any exception handling added)?

File.AppendAllText(strFile, "Start Error Log for today")


EDITED ANSWER
This should answer the question fully!

If File.Exists(strFile)
  File.AppendAllText(strFile, String.Format("Error Message in  Occured at-- {0:dd-MMM-yyyy}{1}", Date.Today, Environment.NewLine))
Else
  File.AppendAllText(strFile, "Start Error Log for today{0}Error Message in  Occured at-- {1:dd-MMM-yyyy}{0}", Environment.NewLine, Date.Today)
End If

How to get first and last element in an array in java?

This is the given array.

    int myIntegerNumbers[] = {1,2,3,4,5,6,7,8,9,10};

// If you want print the last element in the array.

    int lastNumerOfArray= myIntegerNumbers[9];
    Log.i("MyTag", lastNumerOfArray + "");

// If you want to print the number of element in the array.

    Log.i("MyTag", "The number of elements inside" +
            "the array " +myIntegerNumbers.length);

// Second method to print the last element inside the array.

    Log.i("MyTag", "The last elements inside " +
            "the array " + myIntegerNumbers[myIntegerNumbers.length-1]);

Pointers, smart pointers or shared pointers?

Sydius outlined the types fairly well:

  • Normal pointers are just that - they point to some thing in memory somewhere. Who owns it? Only the comments will let you know. Who frees it? Hopefully the owner at some point.
  • Smart pointers are a blanket term that cover many types; I'll assume you meant scoped pointer which uses the RAII pattern. It is a stack-allocated object that wraps a pointer; when it goes out of scope, it calls delete on the pointer it wraps. It "owns" the contained pointer in that it is in charge of deleteing it at some point. They allow you to get a raw reference to the pointer they wrap for passing to other methods, as well as releasing the pointer, allowing someone else to own it. Copying them does not make sense.
  • Shared pointers is a stack-allocated object that wraps a pointer so that you don't have to know who owns it. When the last shared pointer for an object in memory is destructed, the wrapped pointer will also be deleted.

How about when you should use them? You will either make heavy use of scoped pointers or shared pointers. How many threads are running in your application? If the answer is "potentially a lot", shared pointers can turn out to be a performance bottleneck if used everywhere. The reason being that creating/copying/destructing a shared pointer needs to be an atomic operation, and this can hinder performance if you have many threads running. However, it won't always be the case - only testing will tell you for sure.

There is an argument (that I like) against shared pointers - by using them, you are allowing programmers to ignore who owns a pointer. This can lead to tricky situations with circular references (Java will detect these, but shared pointers cannot) or general programmer laziness in a large code base.

There are two reasons to use scoped pointers. The first is for simple exception safety and cleanup operations - if you want to guarantee that an object is cleaned up no matter what in the face of exceptions, and you don't want to stack allocate that object, put it in a scoped pointer. If the operation is a success, you can feel free to transfer it over to a shared pointer, but in the meantime save the overhead with a scoped pointer.

The other case is when you want clear object ownership. Some teams prefer this, some do not. For instance, a data structure may return pointers to internal objects. Under a scoped pointer, it would return a raw pointer or reference that should be treated as a weak reference - it is an error to access that pointer after the data structure that owns it is destructed, and it is an error to delete it. Under a shared pointer, the owning object can't destruct the internal data it returned if someone still holds a handle on it - this could leave resources open for much longer than necessary, or much worse depending on the code.

jQuery get the id/value of <li> element after click function

If You Have Multiple li elements inside an li element then this will definitely help you, and i have checked it and it works....

<script>
$("li").on('click', function() {
          alert(this.id);
          return false;
      });
</script>

org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'customerService' is defined

Please make sure that your applicationContext.xml file is loaded by specifying it in your web.xml file:

    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/applicationContext.xml</param-value>
    </context-param>

How to add,set and get Header in request of HttpClient?

You can test-drive this code exactly as is using the public GitHub API (don't go over the request limit):

public class App {

    public static void main(String[] args) throws IOException {

        CloseableHttpClient client = HttpClients.custom().build();

        // (1) Use the new Builder API (from v4.3)
        HttpUriRequest request = RequestBuilder.get()
                .setUri("https://api.github.com")
                // (2) Use the included enum
                .setHeader(HttpHeaders.CONTENT_TYPE, "application/json")
                // (3) Or your own
                .setHeader("Your own very special header", "value")
                .build();

        CloseableHttpResponse response = client.execute(request);

        // (4) How to read all headers with Java8
        List<Header> httpHeaders = Arrays.asList(response.getAllHeaders());
        httpHeaders.stream().forEach(System.out::println);

        // close client and response
    }
}

How do I open a URL from C++?

Use libcurl, here is a simple example.

EDIT: If this is about starting a web browser from C++, you can invoke a shell command with system on a POSIX system:

system("<mybrowser> http://google.com");

By replacing <mybrowser> with the browser you want to launch.

How do I add a custom script to my package.json file that runs a javascript file?

Lets say in scripts you want to run 2 commands with a single command:

"scripts":{
  "start":"any command",
  "singleCommandToRunTwoCommand":"some command here && npm start"
}

Now go to your terminal and run there npm run singleCommandToRunTwoCommand.

How to remove certain characters from a string in C++?

Using std::wstring and wchar_t (requires the Unicode header):

//#include <tchar.h>
std::wstring phone(L"(555) 555-5555");

...fancy static range initializer next; not necessary to setup badChars2 this exact same way. It's overkill; more academic than anything else:

const wchar_t *tmp = L"()-"; 
const std::set<wchar_t> badChars2(tmp,tmp + sizeof(tmp)-1);

Simple, concise lambda:

  1. Uses phone in the lambda capture list.
  2. Uses Erase-remove idiom
  3. Removes all bad characters from phone

    for_each(badChars2.begin(), badChars2.end(), [&phone](wchar_t n){
         phone.erase(std::remove(phone.begin(), phone.end(), n), phone.end());
    });
    wcout << phone << endl;
    

Output: "555 5555555"

Insert string at specified position

Try it, it will work for any number of substrings

<?php
    $string = 'bcadef abcdef';
    $substr = 'a';
    $attachment = '+++';

    //$position = strpos($string, 'a');

    $newstring = str_replace($substr, $substr.$attachment, $string);

    // bca+++def a+++bcdef
?>

How to get twitter bootstrap modal to close (after initial launch)

According the documentaion hide / toggle should work. But it don't.

Here is how I did it

$('#modal-id').modal('toggle'); //Hide the modal dialog
$('.modal-backdrop').remove(); //Hide the backdrop
$("body").removeClass( "modal-open" ); //Put scroll back on the Body

Angularjs action on click of button

The calculation occurs immediately since the calculation call is bound in the template, which displays its result when quantity changes.

Instead you could try the following approach. Change your markup to the following:

<div ng-controller="myAppController" style="text-align:center">
  <p style="font-size:28px;">Enter Quantity:
      <input type="text" ng-model="quantity"/>
  </p>
  <button ng-click="calculateQuantity()">Calculate</button>
  <h2>Total Cost: Rs.{{quantityResult}}</h2>
</div>

Next, update your controller:

myAppModule.controller('myAppController', function($scope,calculateService) {
  $scope.quantity=1;
  $scope.quantityResult = 0;

  $scope.calculateQuantity = function() {
    $scope.quantityResult = calculateService.calculate($scope.quantity, 10);
  };
});

Here's a JSBin example that demonstrates the above approach.

The problem with this approach is the calculated result remains visible with the old value till the button is clicked. To address this, you could hide the result whenever the quantity changes.

This would involve updating the template to add an ng-change on the input, and an ng-if on the result:

<input type="text" ng-change="hideQuantityResult()" ng-model="quantity"/>

and

<h2 ng-if="showQuantityResult">Total Cost: Rs.{{quantityResult}}</h2>

In the controller add:

$scope.showQuantityResult = false;

$scope.calculateQuantity = function() {
  $scope.quantityResult = calculateService.calculate($scope.quantity, 10);
  $scope.showQuantityResult = true;
};

$scope.hideQuantityResult = function() {
  $scope.showQuantityResult = false;
}; 

These updates can be seen in this JSBin demo.

Installing PG gem on OS X - failure to build native extension

Same error for me and I didn't experience it until I downloaded OS X 10.9 (Mavericks). Sigh, another OS upgrade headache.

Here's how I fixed it (with homebrew):

  • Install another build of Xcode Tools (typing brew update in the terminal will prompt you to update the Xcode build tools)
  • brew update
  • brew install postgresql

After that gem install pg worked for me.

Creating files in C++

#include <iostream>
#include <fstream>

int main() {
  std::ofstream o("Hello.txt");

  o << "Hello, World\n" << std::endl;

  return 0;
}

Is there a way to select sibling nodes?

1) Add selected class to target element
2) Find all children of parent element excluding target element
3) Remove class from target element

 <div id = "outer">
            <div class="item" id="inner1">Div 1 </div>
            <div class="item" id="inner2">Div 2 </div>
            <div class="item" id="inner3">Div 3 </div>
            <div class="item" id="inner4">Div 4 </div>
           </div>



function getSiblings(target) {
    target.classList.add('selected');
    let siblings = document.querySelecttorAll('#outer .item:not(.currentlySelected)')
    target.classList.remove('selected'); 
return siblings
    }

JUnit Testing private variables?

I can't tell if you've found some special case code which requires you to test against private fields. But in my experience you never have to test something private - always public. Maybe you could give an example of some code where you need to test private?

How would you implement an LRU cache in Java?

Here is my implementation for LRU. I have used PriorityQueue, which basically works as FIFO and not threadsafe. Used Comparator based on the page time creation and based on the performs the ordering of the pages for the least recently used time.

Pages for consideration : 2, 1, 0, 2, 8, 2, 4

Page added into cache is : 2
Page added into cache is : 1
Page added into cache is : 0
Page: 2 already exisit in cache. Last accessed time updated
Page Fault, PAGE: 1, Replaced with PAGE: 8
Page added into cache is : 8
Page: 2 already exisit in cache. Last accessed time updated
Page Fault, PAGE: 0, Replaced with PAGE: 4
Page added into cache is : 4

OUTPUT

LRUCache Pages
-------------
PageName: 8, PageCreationTime: 1365957019974
PageName: 2, PageCreationTime: 1365957020074
PageName: 4, PageCreationTime: 1365957020174

enter code here

import java.util.Comparator;
import java.util.Iterator;
import java.util.PriorityQueue;


public class LRUForCache {
    private PriorityQueue<LRUPage> priorityQueue = new PriorityQueue<LRUPage>(3, new LRUPageComparator());
    public static void main(String[] args) throws InterruptedException {

        System.out.println(" Pages for consideration : 2, 1, 0, 2, 8, 2, 4");
        System.out.println("----------------------------------------------\n");

        LRUForCache cache = new LRUForCache();
        cache.addPageToQueue(new LRUPage("2"));
        Thread.sleep(100);
        cache.addPageToQueue(new LRUPage("1"));
        Thread.sleep(100);
        cache.addPageToQueue(new LRUPage("0"));
        Thread.sleep(100);
        cache.addPageToQueue(new LRUPage("2"));
        Thread.sleep(100);
        cache.addPageToQueue(new LRUPage("8"));
        Thread.sleep(100);
        cache.addPageToQueue(new LRUPage("2"));
        Thread.sleep(100);
        cache.addPageToQueue(new LRUPage("4"));
        Thread.sleep(100);

        System.out.println("\nLRUCache Pages");
        System.out.println("-------------");
        cache.displayPriorityQueue();
    }


    public synchronized void  addPageToQueue(LRUPage page){
        boolean pageExists = false;
        if(priorityQueue.size() == 3){
            Iterator<LRUPage> iterator = priorityQueue.iterator();

            while(iterator.hasNext()){
                LRUPage next = iterator.next();
                if(next.getPageName().equals(page.getPageName())){
                    /* wanted to just change the time, so that no need to poll and add again.
                       but elements ordering does not happen, it happens only at the time of adding
                       to the queue

                       In case somebody finds it, plz let me know.
                     */
                    //next.setPageCreationTime(page.getPageCreationTime()); 

                    priorityQueue.remove(next);
                    System.out.println("Page: " + page.getPageName() + " already exisit in cache. Last accessed time updated");
                    pageExists = true;
                    break;
                }
            }
            if(!pageExists){
                // enable it for printing the queue elemnts
                //System.out.println(priorityQueue);
                LRUPage poll = priorityQueue.poll();
                System.out.println("Page Fault, PAGE: " + poll.getPageName()+", Replaced with PAGE: "+page.getPageName());

            }
        }
        if(!pageExists){
            System.out.println("Page added into cache is : " + page.getPageName());
        }
        priorityQueue.add(page);

    }

    public void displayPriorityQueue(){
        Iterator<LRUPage> iterator = priorityQueue.iterator();
        while(iterator.hasNext()){
            LRUPage next = iterator.next();
            System.out.println(next);
        }
    }
}

class LRUPage{
    private String pageName;
    private long pageCreationTime;
    public LRUPage(String pagename){
        this.pageName = pagename;
        this.pageCreationTime = System.currentTimeMillis();
    }

    public String getPageName() {
        return pageName;
    }

    public long getPageCreationTime() {
        return pageCreationTime;
    }

    public void setPageCreationTime(long pageCreationTime) {
        this.pageCreationTime = pageCreationTime;
    }

    @Override
    public boolean equals(Object obj) {
        LRUPage page = (LRUPage)obj; 
        if(pageCreationTime == page.pageCreationTime){
            return true;
        }
        return false;
    }

    @Override
    public int hashCode() {
        return (int) (31 * pageCreationTime);
    }

    @Override
    public String toString() {
        return "PageName: " + pageName +", PageCreationTime: "+pageCreationTime;
    }
}


class LRUPageComparator implements Comparator<LRUPage>{

    @Override
    public int compare(LRUPage o1, LRUPage o2) {
        if(o1.getPageCreationTime() > o2.getPageCreationTime()){
            return 1;
        }
        if(o1.getPageCreationTime() < o2.getPageCreationTime()){
            return -1;
        }
        return 0;
    }
}

Ubuntu - Run command on start-up with "sudo"

You can add the command in the /etc/rc.local script that is executed at the end of startup.

Write the command before exit 0. Anything written after exit 0 will never be executed.

Browser Caching of CSS files

It's probably worth noting that IE won't cache css files called by other css files using the @import method. So, for example, if your html page links to "master.css" which pulls in "reset.css" via @import, then reset.css will not be cached by IE.

Tooltips with Twitter Bootstrap

That's because these things (I mean tooltip etc) are jQuery plug-ins. And yes, they assume some basic knowledge about jQuery. I would suggest you to look for at least a basic tutorial about jQuery.

You'll always have to define which elements should have a tooltip. And I don't understand why Bootstrap should provide the class, you define those classes or yourself. Maybe you were hoping that bootstrap did automatically some magic? This magic however, can cause a lot of problems as well (unwanted side effects).

This magic can be easily achieved to just write $(".myclass").tooltip(), this line of code does exact what you want. The only thing you have to do is attach the myclass class to those elements that need to apply the tooltip thingy. (Just make sure you run that line of code after your DOM has been loaded. See below.)

$(document).ready(function() {
    $(".myclass").tooltip();
});

EDIT: apparently you can't use the class tooltip (probably because it is somewhere internally used!).

I'm just wondering why bootstrap doesn't run the code you specified with some class I can include.

The thing you want produces almost the same code as you have to do now. The biggest reason however they did not do that, is because it causes a lot of trouble. One person wants to assign it to an element with an ID; others want to assign it to elements with a specified classname; and again others want to assign it to one specified element achieved through some selection process. Those 3 options cause extra complexity, while it is already provided by jQuery. I haven't seen many plugins do what you want (just because it is needless; it really doesn't save you code).

Valid values for android:fontFamily and what they map to?

Where do these values come from? The documentation for android:fontFamily does not list this information in any place

These are indeed not listed in the documentation. But they are mentioned here under the section 'Font families'. The document lists every new public API for Android Jelly Bean 4.1.

In the styles.xml file in the application I'm working on somebody listed this as the font family, and I'm pretty sure it's wrong:

Yes, that's wrong. You don't reference the font file, you have to use the font name mentioned in the linked document above. In this case it should have been this:

<item name="android:fontFamily">sans-serif</item>

Like the linked answer already stated, 12 variants are possible:

Added in Android Jelly Bean (4.1) - API 16 :

Regular (default):

<item name="android:fontFamily">sans-serif</item>
<item name="android:textStyle">normal</item> 

Italic:

<item name="android:fontFamily">sans-serif</item>
<item name="android:textStyle">italic</item>

Bold:

<item name="android:fontFamily">sans-serif</item>
<item name="android:textStyle">bold</item>

Bold-italic:

<item name="android:fontFamily">sans-serif</item>
<item name="android:textStyle">bold|italic</item>

Light:

<item name="android:fontFamily">sans-serif-light</item>
<item name="android:textStyle">normal</item>

Light-italic:

<item name="android:fontFamily">sans-serif-light</item>
<item name="android:textStyle">italic</item>

Thin :

<item name="android:fontFamily">sans-serif-thin</item>
<item name="android:textStyle">normal</item>

Thin-italic :

<item name="android:fontFamily">sans-serif-thin</item>
<item name="android:textStyle">italic</item>

Condensed regular:

<item name="android:fontFamily">sans-serif-condensed</item>
<item name="android:textStyle">normal</item>

Condensed italic:

<item name="android:fontFamily">sans-serif-condensed</item>
<item name="android:textStyle">italic</item>

Condensed bold:

<item name="android:fontFamily">sans-serif-condensed</item>
<item name="android:textStyle">bold</item>

Condensed bold-italic:

<item name="android:fontFamily">sans-serif-condensed</item>
<item name="android:textStyle">bold|italic</item>

Added in Android Lollipop (v5.0) - API 21 :

Medium:

<item name="android:fontFamily">sans-serif-medium</item>
<item name="android:textStyle">normal</item>

Medium-italic:

<item name="android:fontFamily">sans-serif-medium</item>
<item name="android:textStyle">italic</item>

Black:

<item name="android:fontFamily">sans-serif-black</item>
<item name="android:textStyle">italic</item>

For quick reference, this is how they all look like:

create array from mysql query php

$type_array = array();    
while($row = mysql_fetch_assoc($result)) {
    $type_array[] = $row['type'];
}

Best way to concatenate List of String objects?

Have you seen this Coding Horror blog entry?

The Sad Tragedy of Micro-Optimization Theater

I am not shure whether or not it is "neater", but from a performance-standpoint it probably won't matter much.

Newline in markdown table?

Just for those that are trying to do this on Jira. Just add \\ at the end of each line and a new line will be created:

|Something|Something else \\ that's rather long|Something else|

Will render this:

enter image description here

Source: Text breaks on Jira

How to clear the interpreter console?

Wiper is cool, good thing about it is I don't have to type '()' around it. Here is slight variation to it

# wiper.py
import os
class Cls(object):
    def __repr__(self):
        os.system('cls')
        return ''

The usage is quite simple:

>>> cls = Cls()
>>> cls # this will clear console.

How do I check if a given string is a legal/valid file name under Windows?

For .Net Frameworks prior to 3.5 this should work:

Regular expression matching should get you some of the way. Here's a snippet using the System.IO.Path.InvalidPathChars constant;

bool IsValidFilename(string testName)
{
    Regex containsABadCharacter = new Regex("[" 
          + Regex.Escape(System.IO.Path.InvalidPathChars) + "]");
    if (containsABadCharacter.IsMatch(testName)) { return false; };

    // other checks for UNC, drive-path format, etc

    return true;
}

For .Net Frameworks after 3.0 this should work:

http://msdn.microsoft.com/en-us/library/system.io.path.getinvalidpathchars(v=vs.90).aspx

Regular expression matching should get you some of the way. Here's a snippet using the System.IO.Path.GetInvalidPathChars() constant;

bool IsValidFilename(string testName)
{
    Regex containsABadCharacter = new Regex("["
          + Regex.Escape(new string(System.IO.Path.GetInvalidPathChars())) + "]");
    if (containsABadCharacter.IsMatch(testName)) { return false; };

    // other checks for UNC, drive-path format, etc

    return true;
}

Once you know that, you should also check for different formats, eg c:\my\drive and \\server\share\dir\file.ext

Get the Id of current table row with Jquery

Create a class in css name it .buttoncontact, add the class attribute to your buttons

function ClickedRow() {
    $(document).on('click', '.buttoncontact', function () {
        var row = $(this).parents('tr').attr('id');
        var rowtext = $(this).closest('tr').text();
        alert(row);      
    });
}

Why do we have to normalize the input for an artificial neural network?

The reason normalization is needed is because if you look at how an adaptive step proceeds in one place in the domain of the function, and you just simply transport the problem to the equivalent of the same step translated by some large value in some direction in the domain, then you get different results. It boils down to the question of adapting a linear piece to a data point. How much should the piece move without turning and how much should it turn in response to that one training point? It makes no sense to have a changed adaptation procedure in different parts of the domain! So normalization is required to reduce the difference in the training result. I haven't got this written up, but you can just look at the math for a simple linear function and how it is trained by one training point in two different places. This problem may have been corrected in some places, but I am not familiar with them. In ALNs, the problem has been corrected and I can send you a paper if you write to wwarmstrong AT shaw.ca

login to remote using "mstsc /admin" with password

to be secured, you should execute 3 commands :

cmdkey /generic:"server-address" /user:"username" /pass:"password"
mstsc /v:server-address
cmdkey /delete:server-address

first command to save the credential

second command to open remote desktop

and the third command to delete the credential

all of these commands can be saved in a batch file(bat).

How to recursively list all the files in a directory in C#?

In Framework 2.0 you can use (It list files of root folder, it's best the most popular answer):

static void DirSearch(string dir)
{
    try
    {
        foreach (string f in Directory.GetFiles(dir))
            Console.WriteLine(f);
        foreach (string d in Directory.GetDirectories(dir))
        {
            Console.WriteLine(d);
            DirSearch(d);
        }

    }
    catch (System.Exception ex)
    {
        Console.WriteLine(ex.Message);
    }
}

Specifing width of a flexbox flex item: width or basis?

The bottom statement is equivalent to:

.half {
   flex-grow: 0;
   flex-shrink: 0;
   flex-basis: 50%;
}

Which, in this case, would be equivalent as the box is not allowed to flex and therefore retains the initial width set by flex-basis.

Flex-basis defines the default size of an element before the remaining space is distributed so if the element were allowed to flex (grow/shrink) it may not be 50% of the width of the page.

I've found that I regularly return to https://css-tricks.com/snippets/css/a-guide-to-flexbox/ for help regarding flexbox :)

cvc-elt.1: Cannot find the declaration of element 'MyElement'

Your schema is for its target namespace http://www.example.org/Test so it defines an element with name MyElement in that target namespace http://www.example.org/Test. Your instance document however has an element with name MyElement in no namespace. That is why the validating parser tells you it can't find a declaration for that element, you haven't provided a schema for elements in no namespace.

You either need to change the schema to not use a target namespace at all or you need to change the instance to use e.g. <MyElement xmlns="http://www.example.org/Test">A</MyElement>.

Node.js Error: Cannot find module express

Run npm install express body-parser cookie-parser multer --save command in the same directory with your source code nodejs file to resolve this issue. P/s: check your directory after run command to understand more!

GitHub - List commits by author

If the author has a GitHub account, just click the author's username from anywhere in the commit history, and the commits you can see will be filtered down to those by that author:

Screenshot showing where to click to filter down commits

You can also click the 'n commits' link below their name on the repo's "contributors" page:

Another screenshot

Alternatively, you can directly append ?author=<theusername> or ?author=<emailaddress> to the URL. For example, https://github.com/jquery/jquery/commits/master?author=dmethvin or https://github.com/jquery/jquery/commits/[email protected] both give me:

Screenshot with only Dave Methvin's commits

For authors without a GitHub account, only filtering by email address will work, and you will need to manually add ?author=<emailaddress> to the URL - the author's name will not be clickable from the commits list.


You can also get the list of commits by a particular author from the command line using

git log --author=[your git name]

Example:

git log --author=Prem

Default password of mysql in ubuntu server 16.04

The only option that worked for me is the one described in this link.

In summary (in case the website goes down), it says:

To install MySQL:

sudo apt update
sudo apt install mysql-server

On the next prompt, you will be asked to set a password for the MySQL root user. Once you do that the script will also ask you to remove the anonymous user, restrict root user access to the local machine and remove the test database. You should answer “Y” (yes) to all questions.

sudo mysql_secure_installation

Then

sudo mysql

ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY 'very_strong_password';
FLUSH PRIVILEGES;

After that you can exit:

exit

Now you can easily login with (Remember to type your very_strong_password):

mysql -u root -p
# type the password now.

This was the only option that worked for me after many hours trying the options above.

PDO's query vs execute

query runs a standard SQL statement and requires you to properly escape all data to avoid SQL Injections and other issues.

execute runs a prepared statement which allows you to bind parameters to avoid the need to escape or quote the parameters. execute will also perform better if you are repeating a query multiple times. Example of prepared statements:

$sth = $dbh->prepare('SELECT name, colour, calories FROM fruit
    WHERE calories < :calories AND colour = :colour');
$sth->bindParam(':calories', $calories);
$sth->bindParam(':colour', $colour);
$sth->execute();
// $calories or $color do not need to be escaped or quoted since the
//    data is separated from the query

Best practice is to stick with prepared statements and execute for increased security.

See also: Are PDO prepared statements sufficient to prevent SQL injection?

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'MyController':

I have been getting similar error, and just want to share with you. maybe it will help someone.

If you want to use EntityManagerFactory to get an EntityManager, make sure that you will use:

<persistence-unit name="name" transaction-type="RESOURCE_LOCAL">

and not:

<persistence-unit name="name" transaction-type="JPA">

in persistance.xml

clean and rebuild project, it should help.

invalid command code ., despite escaping periods, using sed

You simply forgot to supply an argument to -i. Just change -i to -i ''.

Of course that means you don't want your files to be backed up; otherwise supply your extension of choice, like -i .bak.

How to get the last element of an array in Ruby?

One other way, using the splat operator:

*a, last = [1, 3, 4, 5]

STDOUT:
a: [1, 3, 4]
last: 5

This declaration has no storage class or type specifier in C++

This is a mistake:

m.check(side);

That code has to go inside a function. Your class definition can only contain declarations and functions.

Classes don't "run", they provide a blueprint for how to make an object.

The line Message m; means that an Orderbook will contain Message called m, if you later create an Orderbook.

How to center a WPF app on screen?

There is no WPF equivalent. System.Windows.Forms.Screen is still part of the .NET framework and can be used from WPF though.

See this question for more details, but you can use the calls relating to screens by using the WindowInteropHelper class to wrap your WPF control.

How to implement a simple scenario the OO way

You might implement your class model by composition, having the book object have a map of chapter objects contained within it (map chapter number to chapter object). Your search function could be given a list of books into which to search by asking each book to search its chapters. The book object would then iterate over each chapter, invoking the chapter.search() function to look for the desired key and return some kind of index into the chapter. The book's search() would then return some data type which could combine a reference to the book and some way to reference the data that it found for the search. The reference to the book could be used to get the name of the book object that is associated with the collection of chapter search hits.

Cut off text in string after/before separator in powershell

Using regex, the result is in $matches[1]:

$str = "test.txt ; 131 136 80 89 119 17 60 123 210 121 188 42 136 200 131 198"
$str -match "^(.*?)\s\;"
$matches[1]
test.txt

Round float to x decimals?

Default rounding in python and numpy:

In: [round(i) for i in np.arange(10) + .5]
Out: [0, 2, 2, 4, 4, 6, 6, 8, 8, 10]

I used this to get integer rounding to be applied to a pandas series:

import decimal

and use this line to set the rounding to "half up" a.k.a rounding as taught in school: decimal.getcontext().rounding = decimal.ROUND_HALF_UP

Finally I made this function to apply it to a pandas series object

def roundint(value):
    return value.apply(lambda x: int(decimal.Decimal(x).to_integral_value()))

So now you can do roundint(df.columnname)

And for numbers:

In: [int(decimal.Decimal(i).to_integral_value()) for i in np.arange(10) + .5]
Out: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Credit: kares

What Vim command(s) can be used to quote/unquote words?

I don't know any builtin vim command for this, but using r"f'r" to change from ' to " and r'f"r' to change from " to ' works if you stand on the first ' or ". The command r' replaces whatever character is under your cursor with ', and f" moves you forward to the next ".

Free Rest API to retrieve current datetime as string (timezone irrelevant)

If you're using Rails, you can just make an empty file in the public folder and use ajax to get that. Then parse the headers for the Date header. Files in the Public folder bypass the Rails stack, and so have lower latency.

How to remove all the occurrences of a char in c++ string

I guess the method std:remove works but it was giving some compatibility issue with the includes so I ended up writing this little function:

string removeCharsFromString(const string str, char* charsToRemove )
{
    char c[str.length()+1]; // + terminating char
    const char *p = str.c_str();
    unsigned int z=0, size = str.length();
    unsigned int x;
    bool rem=false;

    for(x=0; x<size; x++)
    {
        rem = false;
        for (unsigned int i = 0; charsToRemove[i] != 0; i++)
        {
            if (charsToRemove[i] == p[x])
            {
                rem = true;
                break;
            }
        }
        if (rem == false) c[z++] = p[x];
    }

    c[z] = '\0';
    return string(c);
}

Just use as

myString = removeCharsFromString(myString, "abc\r");

and it will remove all the occurrence of the given char list.

This might also be a bit more efficient as the loop returns after the first match, so we actually do less comparison.

Spring: How to inject a value to static field?

First of all, public static non-final fields are evil. Spring does not allow injecting to such fields for a reason.

Your workaround is valid, you don't even need getter/setter, private field is enough. On the other hand try this:

@Value("${my.name}")
public void setPrivateName(String privateName) {
    Sample.name = privateName;
}  

(works with @Autowired/@Resource). But to give you some constructive advice: Create a second class with private field and getter instead of public static field.

How to call a method after bean initialization is complete?

To expand on the @PostConstruct suggestion in other answers, this really is the best solution, in my opinion.

  • It keeps your code decoupled from the Spring API (@PostConstruct is in javax.*)
  • It explicitly annotates your init method as something that needs to be called to initialize the bean
  • You don't need to remember to add the init-method attribute to your spring bean definition, spring will automatically call the method (assuming you register the annotation-config option somewhere else in the context, anyway).

Text inset for UITextField?

You can adjust the positioning of the text within a text field by making it a subclass of UITextField and overriding the -textRectForBounds: method.

How to copy a file from one directory to another using PHP?

copy will do this. Please check the php-manual. Simple Google search should answer your last two questions ;)

Python regex to match dates

Well, from my understanding, simply for matching this format in a given string, I prefer this regular expression:

pattern='[0-9|/]+'

to match the format in a more strict way, the following works:

pattern='(?:[0-9]{2}/){2}[0-9]{2}'

Personally, I cannot agree with unutbu's answer since sometimes we use regular expression for "finding" and "extract", not only "validating".

Python Git Module experiences?

This is a pretty old question, and while looking for Git libraries, I found one that was made this year (2013) called Gittle.

It worked great for me (where the others I tried were flaky), and seems to cover most of the common actions.

Some examples from the README:

from gittle import Gittle

# Clone a repository
repo_path = '/tmp/gittle_bare'
repo_url = 'git://github.com/FriendCode/gittle.git'
repo = Gittle.clone(repo_url, repo_path)

# Stage multiple files
repo.stage(['other1.txt', 'other2.txt'])

# Do the commit
repo.commit(name="Samy Pesse", email="[email protected]", message="This is a commit")

# Authentication with RSA private key
key_file = open('/Users/Me/keys/rsa/private_rsa')
repo.auth(pkey=key_file)

# Do push
repo.push()

How to save and load numpy.array() data properly?

The most reliable way I have found to do this is to use np.savetxt with np.loadtxt and not np.fromfile which is better suited to binary files written with tofile. The np.fromfile and np.tofile methods write and read binary files whereas np.savetxt writes a text file. So, for example:

a = np.array([1, 2, 3, 4])
np.savetxt('test1.txt', a, fmt='%d')
b = np.loadtxt('test1.txt', dtype=int)
a == b
# array([ True,  True,  True,  True], dtype=bool)

Or:

a.tofile('test2.dat')
c = np.fromfile('test2.dat', dtype=int)
c == a
# array([ True,  True,  True,  True], dtype=bool)

I use the former method even if it is slower and creates bigger files (sometimes): the binary format can be platform dependent (for example, the file format depends on the endianness of your system).

There is a platform independent format for NumPy arrays, which can be saved and read with np.save and np.load:

np.save('test3.npy', a)    # .npy extension is added if not given
d = np.load('test3.npy')
a == d
# array([ True,  True,  True,  True], dtype=bool)

Firebase onMessageReceived not called when app in background

Here is more clear concepts about firebase message. I found it from their support team.

Firebase has three message types:

Notification messages : Notification message works on background or foreground. When app is in background, Notification messages are delivered to the system tray. If the app is in the foreground, messages are handled by onMessageReceived() or didReceiveRemoteNotification callbacks. These are essentially what is referred to as Display messages.

Data messages: On Android platform, data message can work on background and foreground. The data message will be handled by onMessageReceived(). A platform specific note here would be: On Android, the data payload can be retrieved in the Intent used to launch your activity. To elaborate, if you have "click_action":"launch_Activity_1", you can retrieve this intent through getIntent() from only Activity_1.

Messages with both notification and data payloads: When in the background, apps receive the notification payload in the notification tray, and only handle the data payload when the user taps on the notification. When in the foreground, your app receives a message object with both payloads available. Secondly, the click_action parameter is often used in notification payload and not in data payload. If used inside data payload, this parameter would be treated as custom key-value pair and therefore you would need to implement custom logic for it to work as intended.

Also, I recommend you to use onMessageReceived method (see Data message) to extract the data bundle. From your logic, I checked the bundle object and haven't found expected data content. Here is a reference to a similar case which might provide more clarity.

From server side, firebase notification should bellow format:

Server side should send "notification" object. Lacks of "notification" object in my TargetActivity didn't getting message using getIntent().

Correct message format is given bellow:

{
 "data": {
  "body": "here is body",
  "title": "Title"
 },
"notification": {
  "body": "here is body",
  "title": "Title",
  "click_action": "YOUR_ACTION"
 },
 "to": "ffEseX6vwcM:APA91bF8m7wOF MY FCM ID 07j1aPUb"
}

Here is more clear concepts about firebase message. I found it from their support team.

For more info visit my this thread and this thread

scroll up and down a div on button click using jquery

You can use this simple plugin to add scrollUp and scrollDown to your jQuery

https://github.com/phpust/JQueryScrollDetector

How to write a confusion matrix in Python?

A Dependency Free Multiclass Confusion Matrix

# A Simple Confusion Matrix Implementation
def confusionmatrix(actual, predicted, normalize = False):
    """
    Generate a confusion matrix for multiple classification
    @params:
        actual      - a list of integers or strings for known classes
        predicted   - a list of integers or strings for predicted classes
        normalize   - optional boolean for matrix normalization
    @return:
        matrix      - a 2-dimensional list of pairwise counts
    """
    unique = sorted(set(actual))
    matrix = [[0 for _ in unique] for _ in unique]
    imap   = {key: i for i, key in enumerate(unique)}
    # Generate Confusion Matrix
    for p, a in zip(predicted, actual):
        matrix[imap[p]][imap[a]] += 1
    # Matrix Normalization
    if normalize:
        sigma = sum([sum(matrix[imap[i]]) for i in unique])
        matrix = [row for row in map(lambda i: list(map(lambda j: j / sigma, i)), matrix)]
    return matrix

The approach here is to pair up the unique classes found in the actual vector into a 2-dimensional list. From there, we simply iterate through the zipped actual and predicted vectors and populate the counts using the indices to access the matrix positions.

Usage

cm = confusionmatrix(
    [1, 1, 2, 0, 1, 1, 2, 0, 0, 1], # actual
    [0, 1, 1, 0, 2, 1, 2, 2, 0, 2]  # predicted
)

# And The Output
print(cm)
[[2, 1, 0], [0, 2, 1], [1, 2, 1]]

Note: the actual classes are along the columns and the predicted classes are along the rows.

# Actual
# 0  1  2
  #  #  #   
[[2, 1, 0], # 0
 [0, 2, 1], # 1  Predicted
 [1, 2, 1]] # 2

Class Names Can be Strings or Integers

cm = confusionmatrix(
    ["B", "B", "C", "A", "B", "B", "C", "A", "A", "B"], # actual
    ["A", "B", "B", "A", "C", "B", "C", "C", "A", "C"]  # predicted
)

# And The Output
print(cm)
[[2, 1, 0], [0, 2, 1], [1, 2, 1]]

You Can Also Return The Matrix With Proportions (Normalization)

cm = confusionmatrix(
    ["B", "B", "C", "A", "B", "B", "C", "A", "A", "B"], # actual
    ["A", "B", "B", "A", "C", "B", "C", "C", "A", "C"], # predicted
    normalize = True
)

# And The Output
print(cm)
[[0.2, 0.1, 0.0], [0.0, 0.2, 0.1], [0.1, 0.2, 0.1]]

A More Robust Solution

Since writing this post, I've updated my library implementation to be a class that uses a confusion matrix representation internally to compute statistics, in addition to pretty printing the confusion matrix itself. See this Gist.

Example Usage

# Actual & Predicted Classes
actual      = ["A", "B", "C", "C", "B", "C", "C", "B", "A", "A", "B", "A", "B", "C", "A", "B", "C"]
predicted   = ["A", "B", "B", "C", "A", "C", "A", "B", "C", "A", "B", "B", "B", "C", "A", "A", "C"]

# Initialize Performance Class
performance = Performance(actual, predicted)

# Print Confusion Matrix
performance.tabulate()

With the output:

===================================
        A?      B?      C?

A?      3       2       1

B?      1       4       1

C?      1       0       4

Note: class? = Predicted, class? = Actual
===================================

And for the normalized matrix:

# Print Normalized Confusion Matrix
performance.tabulate(normalized = True)

With the normalized output:

===================================
        A?      B?      C?

A?      17.65%  11.76%  5.88%

B?      5.88%   23.53%  5.88%

C?      5.88%   0.00%   23.53%

Note: class? = Predicted, class? = Actual
===================================

Select first empty cell in column F starting from row 1. (without using offset )

NextRow = Application.WorksheetFunction.CountA(Range("A:A")) + 1

PivotTable to show values, not sum of values

Another easier way to do it is to upload your file to google sheets, then add a pivot, for the columns and rows select the same as you would with Excel, however, for values select Calculated Field and then in the formula type in =

In my case the column header is URL

Multiple IF statements between number ranges

It's a little tricky because of the nested IFs but here is my answer (confirmed in Google Spreadsheets):

=IF(AND(A2>=0,    A2<500),  "Less than 500", 
 IF(AND(A2>=500,  A2<1000), "Between 500 and 1000", 
 IF(AND(A2>=1000, A2<1500), "Between 1000 and 1500", 
 IF(AND(A2>=1500, A2<2000), "Between 1500 and 2000", "Undefined"))))

How do I run a shell script without using "sh" or "bash" commands?

Add . (current directory) to your PATH variable.
You can do this by editing your .profile file.
put following line in your .profile file
PATH=$PATH:.

Just make sure to add Shebang (#!/bin/bash) line at the starting of your script and make the script executable(using chmod +x <File Name>).

What is the opposite of evt.preventDefault();

function(evt) {evt.preventDefault();}

and its opposite

function(evt) {return true;}

cheers!

Word-wrap in an HTML table

A long shot, but double-check with Firebug (or similar) that you aren't accidentally inheriting the following rule:

white-space:nowrap;

This may override your specified line break behaviour.

Excel select a value from a cell having row number calculated

You could use the INDIRECT function. This takes a string and converts it into a range

More info here

=INDIRECT("K"&A2)

But it's preferable to use INDEX as it is less volatile.

=INDEX(K:K,A2)

This returns a value or the reference to a value from within a table or range

More info here

Put either function into cell B2 and fill down.

Passing an array/list into a Python function

You don't need to use the asterisk to accept a list.

Simply give the argument a name in the definition, and pass in a list like

def takes_list(a_list):
    for item in a_list:
         print item

XAMPP keeps showing Dashboard/Welcome Page instead of the Configuration Page

Open the htdocs folder there will be index.php file. In that file script is written to go in dashboard folder and show dashboard. So you just have to comment it or delete that script and write any code save it and run http://localhost now dashboard screen will not open and you will see what you have written in that file.

top align in html table?

Some CSS :

table td, table td * {
    vertical-align: top;
}

add string to String array

Since Java arrays hold a fixed number of values, you need to create a new array with a length of 5 in this case. A better solution would be to use an ArrayList and simply add strings to the array.

Example:

ArrayList<String> scripts = new ArrayList<String>();
scripts.add("test3");
scripts.add("test4");
scripts.add("test5");

// Then later you can add more Strings to the ArrayList
scripts.add("test1");
scripts.add("test2");

How can I convert NSDictionary to NSData and vice versa?

NSDictionary -> NSData:

NSData *myData = [NSKeyedArchiver archivedDataWithRootObject:myDictionary];

NSData -> NSDictionary:

NSDictionary *myDictionary = (NSDictionary*) [NSKeyedUnarchiver unarchiveObjectWithData:myData];

In Python, how do I loop through the dictionary and change the value if it equals something?

You could create a dict comprehension of just the elements whose values are None, and then update back into the original:

tmp = dict((k,"") for k,v in mydict.iteritems() if v is None)
mydict.update(tmp)

Update - did some performance tests

Well, after trying dicts of from 100 to 10,000 items, with varying percentage of None values, the performance of Alex's solution is across-the-board about twice as fast as this solution.

How to add parameters to an external data query in Excel which can't be displayed graphically?

Excel's interface for SQL Server queries will not let you have a custom parameters.  A way around this is to create a generic Microsoft Query, then add parameters, then paste your parametorized query in the connection's properties.  Here are the detailed steps for Excel 2010:

  1. Open Excel
  2. Goto Data tab
  3. From the From Other Sources button choose From Microsoft Query
  4. The "Choose Data Source" window will appear.  Choose a datasource and click OK.
  5. The Query Qizard
    1. Choose Column: window will appear.  The goal is to create a generic query. I recommend choosing one column from a small table.
    2. Filter Data: Just click Next
    3. Sort Order: Just click Next
    4. Finish: Just click Finish.
  6. The "Import Data" window will appear:
    1. Click the Properties... button.
      1. Choose the Definition tab
      2. In the "Command text:" section add a WHERE clause that includes Excel parameters.  It's important to add all the parameters that you want now.  For example, if I want two parameters I could add this:
        WHERE 1 = ? and 2 = ?
      3. Click OK to get back to the "Import Data" window
    2. Choose PivotTable Report
    3. Click OK
  7. You will be prompted to enter the parameters value for each parameter.
  8. Once you have enter the parameters you will be at your pivot table
  9. Go batck to the Data tab and click the connections Properties button
    1. Click the Definition tab
    2. In the "Command text:" section, Paste in the real SQL Query that you want with the same number of parameters that you defined earlier.
    3. Click the Parameters... button 
      1. enter the Prompt values for each parameter
      2. Click OK
    4. Click OK to close the properties window
  10. Congratulations, you now have parameters.

How to know elastic search installed version from kibana?

from the Chrome Rest client make a GET request or curl -XGET 'http://localhost:9200' in console

rest client: http://localhost:9200

{
    "name": "node",
    "cluster_name": "elasticsearch-cluster",
    "version": {
        "number": "2.3.4",
        "build_hash": "dcxbgvzdfbbhfxbhx",
        "build_timestamp": "2016-06-30T11:24:31Z",
        "build_snapshot": false,
        "lucene_version": "5.5.0"
    },
    "tagline": "You Know, for Search"
}

where number field denotes the elasticsearch version. Here elasticsearch version is 2.3.4

What is the difference between Serializable and Externalizable in Java?

The Externalizable interface was not actually provided to optimize the serialization process performance! but to provide means of implementing your own custom processing and offer complete control over the format and contents of the stream for an object and its super types!

Examples of this is the implementation of AMF (ActionScript Message Format) remoting to transfer native action script objects over the network.

node.js require() cache - possible to invalidate?

rewire is great for this use case, you get a new instance with each call. Easy dependency injection for node.js unit testing.

rewire adds a special setter and getter to modules so you can modify their behaviour for better unit testing. You may

inject mocks for other modules or globals like process leak private variables override variables within the module. rewire does not load the file and eval the contents to emulate node's require mechanism. In fact it uses node's own require to load the module. Thus your module behaves exactly the same in your test environment as under regular circumstances (except your modifications).

Good news to all caffeine-addicts: rewire works also with Coffee-Script. Note that in this case CoffeeScript needs to be listed in your devDependencies.

What is the meaning of 'No bundle URL present' in react-native?

Be sure that your ATS settings are correct in .plist file.

You can find the file at /ios/{{project_name}}/Info.plist

localhost must be defined as exception request target like this:

<key>NSAppTransportSecurity</key>
    <dict>
    <key>NSExceptionDomains</key>
    <dict>
        <key>localhost</key>
        <dict>
            <key>NSExceptionAllowsInsecureHTTPLoads</key>
            <true/>
        </dict>
    </dict>
</dict>

*(dont forget to remove this on release version..)

Questions every good Database/SQL developer should be able to answer

  • What are the downsides of using adhoc/on-the-fly SQL statements and what would you do instead?

This area can have a huge impact on performance and security of the db. Get this wrong, and you could end up in a world of pain.

  • In what situations would you use adhoc/on-the-fly SQL statements?

Because there is always an exception to the rule :)

Joda DateTime to Timestamp conversion

//This Works just fine
DateTime dt = new DateTime();
Log.d("ts",String.valueOf(dt.now()));               
dt=dt.plusYears(3);
dt=dt.minusDays(7);
Log.d("JODA DateTime",String.valueOf(dt));
Timestamp ts= new Timestamp(dt.getMillis());
Log.d("Coverted to java.sql.Timestamp",String.valueOf(ts));

How to read a .xlsx file using the pandas Library in iPython?

Instead of using a sheet name, in case you don't know or can't open the excel file to check in ubuntu (in my case, Python 3.6.7, ubuntu 18.04), I use the parameter index_col (index_col=0 for the first sheet)

import pandas as pd
file_name = 'some_data_file.xlsx' 
df = pd.read_excel(file_name, index_col=0)
print(df.head()) # print the first 5 rows

Dart: mapping a list (list.map)

I try this same method, but with a different list with more values in the function map. My problem was to forget a return statement. This is very important :)

 bottom: new TabBar(
      controller: _controller,
      isScrollable: true,
      tabs:
        moviesTitles.map((title) { return Tab(text: title)}).toList()
      ,
    ),

How to make a query with group_concat in sql server

Select
      A.maskid
    , A.maskname
    , A.schoolid
    , B.schoolname
    , STUFF((
          SELECT ',' + T.maskdetail
          FROM dbo.maskdetails T
          WHERE A.maskid = T.maskid
          FOR XML PATH('')), 1, 1, '') as maskdetail 
FROM dbo.tblmask A
JOIN dbo.school B ON B.ID = A.schoolid
Group by  A.maskid
    , A.maskname
    , A.schoolid
    , B.schoolname

Apache won't run in xampp

In my case I simply had to run the control panel as administrator

Remove x-axis label/text in chart.js

(this question is a duplicate of In chart.js, Is it possible to hide x-axis label/text of bar chart if accessing from mobile?) They added the option, 2.1.4 (and maybe a little earlier) has it

var myLineChart = new Chart(ctx, {
    type: 'line',
    data: data,
    options: {
        scales: {
            xAxes: [{
                ticks: {
                    display: false
                }
            }]
        }
    }
}

RAW POST using cURL in PHP

I just found the solution, kind of answering to my own question in case anyone else stumbles upon it.

$ch = curl_init();

curl_setopt($ch, CURLOPT_URL,            "http://url/url/url" );
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1 );
curl_setopt($ch, CURLOPT_POST,           1 );
curl_setopt($ch, CURLOPT_POSTFIELDS,     "body goes here" ); 
curl_setopt($ch, CURLOPT_HTTPHEADER,     array('Content-Type: text/plain')); 

$result=curl_exec ($ch);

Angularjs error Unknown provider

bmleite has the correct answer about including the module.

If that is correct in your situation, you should also ensure that you are not redefining the modules in multiple files.

Remember:

angular.module('ModuleName', [])   // creates a module.

angular.module('ModuleName')       // gets you a pre-existing module.

So if you are extending a existing module, remember not to overwrite when trying to fetch it.

Triggering change detection manually in Angular

I was able to update it with markForCheck()

Import ChangeDetectorRef

import { ChangeDetectorRef } from '@angular/core';

Inject and instantiate it

constructor(private ref: ChangeDetectorRef) { 
}

Finally mark change detection to take place

this.ref.markForCheck();

Here's an example where markForCheck() works and detectChanges() don't.

https://plnkr.co/edit/RfJwHqEVJcMU9ku9XNE7?p=preview

EDIT: This example doesn't portray the problem anymore :( I believe it might be running a newer Angular version where it's fixed.

(Press STOP/RUN to run it again)

How to manipulate arrays. Find the average. Beginner Java

Well, to calculate the average of an array, you can consider using for loop instead of while loop.

So as per your question let me assume an array as arrNumbers ( here i'm considering the same array elements as in your question )

int arrNumbers[] = new int[]{1, 3, 2, 5, 8};
int sum = 0;

for(int a = 0; a < arrNumbers.length; a++)
{
   sum = sum + arrNumbers[a];
}

double average = sum / arrNumbers.length;

System.out.println("Average is: " + average);

You can use scanner class as well. It's left to you.

git push to specific branch

The answers in question you linked-to are all about configuring git so that you can enter very short git push commands and have them do whatever you want. Which is great, if you know what you want and how to spell that in Git-Ese, but you're new to git! :-)

In your case, Petr Mensik's answer is the (well, "a") right one. Here's why:

The command git push remote roots around in your .git/config file to find the named "remote" (e.g., origin). The config file lists:

  • where (URL-wise) that remote "lives" (e.g., ssh://hostname/path)
  • where pushes go, if different
  • what gets pushed, if you didn't say what branch(es) to push
  • what gets fetched when you run git fetch remote

When you first cloned the repo—whenever that was—git set up default values for some of these. The URL is whatever you cloned from and the rest, if set or unset, are all "reasonable" defaults ... or, hmm, are they?

The issue with these is that people have changed their minds, over time, as to what is "reasonable". So now (depending on your version of git and whether you've configured things in detail), git may print a lot of warnings about defaults changing in the future. Adding the name of the "branch to push"—amd_qlp_tester—(1) shuts it up, and (2) pushes just that one branch.

If you want to push more conveniently, you could do that with:

git push origin

or even:

git push

but whether that does what you want, depends on whether you agree with "early git authors" that the original defaults are reasonable, or "later git authors" that the original defaults aren't reasonable. So, when you want to do all the configuration stuff (eventually), see the question (and answers) you linked-to.

As for the name origin/amd_qlp_tester in the first place: that's actually a local entity (a name kept inside your repo), even though it's called a "remote branch". It's git's best guess at "where amd_qlp_tester is over there". Git updates it when it can.

Global variables in Javascript across multiple files

//Javascript file 1

localStorage.setItem('Data',10);

//Javascript file 2

var number=localStorage.getItem('Data');

Don't forget to link your JS files in html :)

Collision Detection between two images in Java

I think your problem is that you are not using good OO design for your player and enemies. Create two classes:

public class Player
{
    int X;
    int Y;
    int Width;
    int Height;

    // Getters and Setters
}

public class Enemy
{
    int X;
    int Y;
    int Width;
    int Height;

    // Getters and Setters
}

Your Player should have X,Y,Width,and Height variables.

Your enemies should as well.

In your game loop, do something like this (C#):

foreach (Enemy e in EnemyCollection)
{
    Rectangle r = new Rectangle(e.X,e.Y,e.Width,e.Height);
    Rectangle p = new Rectangle(player.X,player.Y,player.Width,player.Height);

    // Assuming there is an intersect method, otherwise just handcompare the values
    if (r.Intersects(p))
    {
       // A Collision!
       // we know which enemy (e), so we can call e.DoCollision();
       e.DoCollision();
    }
}

To speed things up, don't bother checking if the enemies coords are offscreen.

How do function pointers in C work?

Function pointers in C can be used to perform object-oriented programming in C.

For example, the following lines is written in C:

String s1 = newString();
s1->set(s1, "hello");

Yes, the -> and the lack of a new operator is a dead give away, but it sure seems to imply that we're setting the text of some String class to be "hello".

By using function pointers, it is possible to emulate methods in C.

How is this accomplished?

The String class is actually a struct with a bunch of function pointers which act as a way to simulate methods. The following is a partial declaration of the String class:

typedef struct String_Struct* String;

struct String_Struct
{
    char* (*get)(const void* self);
    void (*set)(const void* self, char* value);
    int (*length)(const void* self);
};

char* getString(const void* self);
void setString(const void* self, char* value);
int lengthString(const void* self);

String newString();

As can be seen, the methods of the String class are actually function pointers to the declared function. In preparing the instance of the String, the newString function is called in order to set up the function pointers to their respective functions:

String newString()
{
    String self = (String)malloc(sizeof(struct String_Struct));

    self->get = &getString;
    self->set = &setString;
    self->length = &lengthString;

    self->set(self, "");

    return self;
}

For example, the getString function that is called by invoking the get method is defined as the following:

char* getString(const void* self_obj)
{
    return ((String)self_obj)->internal->value;
}

One thing that can be noticed is that there is no concept of an instance of an object and having methods that are actually a part of an object, so a "self object" must be passed in on each invocation. (And the internal is just a hidden struct which was omitted from the code listing earlier -- it is a way of performing information hiding, but that is not relevant to function pointers.)

So, rather than being able to do s1->set("hello");, one must pass in the object to perform the action on s1->set(s1, "hello").

With that minor explanation having to pass in a reference to yourself out of the way, we'll move to the next part, which is inheritance in C.

Let's say we want to make a subclass of String, say an ImmutableString. In order to make the string immutable, the set method will not be accessible, while maintaining access to get and length, and force the "constructor" to accept a char*:

typedef struct ImmutableString_Struct* ImmutableString;

struct ImmutableString_Struct
{
    String base;

    char* (*get)(const void* self);
    int (*length)(const void* self);
};

ImmutableString newImmutableString(const char* value);

Basically, for all subclasses, the available methods are once again function pointers. This time, the declaration for the set method is not present, therefore, it cannot be called in a ImmutableString.

As for the implementation of the ImmutableString, the only relevant code is the "constructor" function, the newImmutableString:

ImmutableString newImmutableString(const char* value)
{
    ImmutableString self = (ImmutableString)malloc(sizeof(struct ImmutableString_Struct));

    self->base = newString();

    self->get = self->base->get;
    self->length = self->base->length;

    self->base->set(self->base, (char*)value);

    return self;
}

In instantiating the ImmutableString, the function pointers to the get and length methods actually refer to the String.get and String.length method, by going through the base variable which is an internally stored String object.

The use of a function pointer can achieve inheritance of a method from a superclass.

We can further continue to polymorphism in C.

If for example we wanted to change the behavior of the length method to return 0 all the time in the ImmutableString class for some reason, all that would have to be done is to:

  1. Add a function that is going to serve as the overriding length method.
  2. Go to the "constructor" and set the function pointer to the overriding length method.

Adding an overriding length method in ImmutableString may be performed by adding an lengthOverrideMethod:

int lengthOverrideMethod(const void* self)
{
    return 0;
}

Then, the function pointer for the length method in the constructor is hooked up to the lengthOverrideMethod:

ImmutableString newImmutableString(const char* value)
{
    ImmutableString self = (ImmutableString)malloc(sizeof(struct ImmutableString_Struct));

    self->base = newString();

    self->get = self->base->get;
    self->length = &lengthOverrideMethod;

    self->base->set(self->base, (char*)value);

    return self;
}

Now, rather than having an identical behavior for the length method in ImmutableString class as the String class, now the length method will refer to the behavior defined in the lengthOverrideMethod function.

I must add a disclaimer that I am still learning how to write with an object-oriented programming style in C, so there probably are points that I didn't explain well, or may just be off mark in terms of how best to implement OOP in C. But my purpose was to try to illustrate one of many uses of function pointers.

For more information on how to perform object-oriented programming in C, please refer to the following questions:

How to use a variable for a key in a JavaScript object literal?

Given code:

var thetop = 'top';
<something>.stop().animate(
    { thetop : 10 }, 10
);

Translation:

var thetop = 'top';
var config = { thetop : 10 }; // config.thetop = 10
<something>.stop().animate(config, 10);

As you can see, the { thetop : 10 } declaration doesn't make use of the variable thetop. Instead it creates an object with a key named thetop. If you want the key to be the value of the variable thetop, then you will have to use square brackets around thetop:

var thetop = 'top';
var config = { [thetop] : 10 }; // config.top = 10
<something>.stop().animate(config, 10);

The square bracket syntax has been introduced with ES6. In earlier versions of JavaScript, you would have to do the following:

var thetop = 'top';
var config = (
  obj = {},
  obj['' + thetop] = 10,
  obj
); // config.top = 10
<something>.stop().animate(config, 10);

Creating an iframe with given HTML dynamically

Do this

...
var el = document.getElementById('targetFrame');

var frame_win = getIframeWindow(el);

console.log(frame_win);
...

getIframeWindow is defined here

function getIframeWindow(iframe_object) {
  var doc;

  if (iframe_object.contentWindow) {
    return iframe_object.contentWindow;
  }

  if (iframe_object.window) {
    return iframe_object.window;
  } 

  if (!doc && iframe_object.contentDocument) {
    doc = iframe_object.contentDocument;
  } 

  if (!doc && iframe_object.document) {
    doc = iframe_object.document;
  }

  if (doc && doc.defaultView) {
   return doc.defaultView;
  }

  if (doc && doc.parentWindow) {
    return doc.parentWindow;
  }

  return undefined;
}

numpy matrix vector multiplication

Simplest solution

Use numpy.dot or a.dot(b). See the documentation here.

>>> a = np.array([[ 5, 1 ,3], 
                  [ 1, 1 ,1], 
                  [ 1, 2 ,1]])
>>> b = np.array([1, 2, 3])
>>> print a.dot(b)
array([16, 6, 8])

This occurs because numpy arrays are not matrices, and the standard operations *, +, -, / work element-wise on arrays. Instead, you could try using numpy.matrix, and * will be treated like matrix multiplication.


Other Solutions

Also know there are other options:

  • As noted below, if using python3.5+ the @ operator works as you'd expect:

    >>> print(a @ b)
    array([16, 6, 8])
    
  • If you want overkill, you can use numpy.einsum. The documentation will give you a flavor for how it works, but honestly, I didn't fully understand how to use it until reading this answer and just playing around with it on my own.

    >>> np.einsum('ji,i->j', a, b)
    array([16, 6, 8])
    
  • As of mid 2016 (numpy 1.10.1), you can try the experimental numpy.matmul, which works like numpy.dot with two major exceptions: no scalar multiplication but it works with stacks of matrices.

    >>> np.matmul(a, b)
    array([16, 6, 8])
    
  • numpy.inner functions the same way as numpy.dot for matrix-vector multiplication but behaves differently for matrix-matrix and tensor multiplication (see Wikipedia regarding the differences between the inner product and dot product in general or see this SO answer regarding numpy's implementations).

    >>> np.inner(a, b)
    array([16, 6, 8])
    
    # Beware using for matrix-matrix multiplication though!
    >>> b = a.T
    >>> np.dot(a, b)
    array([[35,  9, 10],
           [ 9,  3,  4],
           [10,  4,  6]])
    >>> np.inner(a, b) 
    array([[29, 12, 19],
           [ 7,  4,  5],
           [ 8,  5,  6]])
    

Rarer options for edge cases

  • If you have tensors (arrays of dimension greater than or equal to one), you can use numpy.tensordot with the optional argument axes=1:

    >>> np.tensordot(a, b, axes=1)
    array([16,  6,  8])
    
  • Don't use numpy.vdot if you have a matrix of complex numbers, as the matrix will be flattened to a 1D array, then it will try to find the complex conjugate dot product between your flattened matrix and vector (which will fail due to a size mismatch n*m vs n).

How do I tell if a variable has a numeric value in Perl?

Check out the CPAN module Regexp::Common. I think it does exactly what you need and handles all the edge cases (e.g. real numbers, scientific notation, etc). e.g.

use Regexp::Common;
if ($var =~ /$RE{num}{real}/) { print q{a number}; }

GDB: Listing all mapped memory regions for a crashed process

In GDB 7.2:

(gdb) help info proc
Show /proc process information about any running process.
Specify any process id, or use the program being debugged by default.
Specify any of the following keywords for detailed info:
  mappings -- list of mapped memory regions.
  stat     -- list a bunch of random process info.
  status   -- list a different bunch of random process info.
  all      -- list all available /proc info.

You want info proc mappings, except it doesn't work when there is no /proc (such as during pos-mortem debugging).

Try maintenance info sections instead.

What happens if you don't commit a transaction to a database (say, SQL Server)?

Example for Transaction

begin tran tt

Your sql statements

if error occurred rollback tran tt else commit tran tt

As long as you have not executed commit tran tt , data will not be changed

Redirect all output to file using Bash on Linux?

If the server is started on the same terminal, then it's the server's stderr that is presumably being written to the terminal and which you are not capturing.

The best way to capture everything would be to run:

script output.txt

before starting up either the server or the client. This will launch a new shell with all terminal output redirected out output.txt as well as the terminal. Then start the server from within that new shell, and then the client. Everything that you see on the screen (both your input and the output of everything writing to the terminal from within that shell) will be written to the file.

When you are done, type "exit" to exit the shell run by the script command.

Deleting a pointer in C++

Pointers are similar to normal variables in that you don't need to delete them. They are removed from memory at the end of a functions execution and/or the end of the program.

You can however use pointers to allocate a 'block' of memory, for example like this:

int *some_integers = new int[20000]

This will allocate memory space for 20000 integers. Useful, because the Stack has a limited size and you might want to mess about with a big load of 'ints' without a stack overflow error.

Whenever you call new, you should then 'delete' at the end of your program, because otherwise you will get a memory leak, and some allocated memory space will never be returned for other programs to use. To do this:

delete [] some_integers;

Hope that helps.

Best way to remove an event handler in jQuery?

if you set the onclick via html you need to removeAttr ($(this).removeAttr('onclick'))

if you set it via jquery (as the after the first click in my examples above) then you need to unbind($(this).unbind('click'))

Running python script inside ipython

In python there is no difference between modules and scripts; You can execute both scripts and modules. The file must be on the pythonpath AFAIK because python must be able to find the file in question. If python is executed from a directory, then the directory is automatically added to the pythonpath.

Refer to What is the best way to call a Python script from another Python script? for more information about modules vs scripts

There is also a builtin function execfile(filename) that will do what you want

MySQL select with CONCAT condition

SELECT needefield, CONCAT(firstname, ' ',lastname) as firstlast 
FROM users 
WHERE CONCAT(firstname, ' ', lastname) = "Bob Michael Jones"

Pandas - replacing column values

You can also try using apply with get method of dictionary, seems to be little faster than replace:

data['sex'] = data['sex'].apply({1:'Male', 0:'Female'}.get)

Testing with timeit:

%%timeit
data['sex'].replace([0,1],['Female','Male'],inplace=True)

Result:

The slowest run took 5.83 times longer than the fastest. This could mean that an intermediate result is being cached.
1000 loops, best of 3: 510 µs per loop

Using apply:

%%timeit
data['sex'] = data['sex'].apply({1:'Male', 0:'Female'}.get)

Result:

The slowest run took 5.92 times longer than the fastest. This could mean that an intermediate result is being cached.
1000 loops, best of 3: 331 µs per loop

Note: apply with dictionary should be used if all the possible values of the columns in the dataframe are defined in the dictionary else, it will have empty for those not defined in dictionary.

javascript, for loop defines a dynamic variable name

You cannot create different "variable names" but you can create different object properties. There are many ways to do whatever it is you're actually trying to accomplish. In your case I would just do

for (var i = myArray.length - 1; i >= 0; i--) {    console.log(eval(myArray[i])); }; 

More generally you can create object properties dynamically, which is the type of flexibility you're thinking of.

var result = {}; for (var i = myArray.length - 1; i >= 0; i--) {     result[myArray[i]] = eval(myArray[i]);   }; 

I'm being a little handwavey since I don't actually understand language theory, but in pure Javascript (including Node) references (i.e. variable names) are happening at a higher level than at runtime. More like at the call stack; you certainly can't manufacture them in your code like you produce objects or arrays. Browsers do actually let you do this anyway though it's terrible practice, via

window['myVarName'] = 'namingCollisionsAreFun';  

(per comment)

Can we locate a user via user's phone number in Android?

Quick answer: No, at least not with native SMS service.

Long answer: Sure, but the receiver's phone should have the correct setup first. An app that detects incoming sms, and if a keyword matches, reports its current location to your server, which then pushes that info to the sender.

How many significant digits do floats and doubles have in java?

A normal math answer.

Understanding that a floating point number is implemented as some bits representing the exponent and the rest, most for the digits (in the binary system), one has the following situation:

With a high exponent, say 10²³ if the least significant bit is changed, a large difference between two adjacent distinghuishable numbers appear. Furthermore the base 2 decimal point makes that many base 10 numbers can only be approximated; 1/5, 1/10 being endless numbers.

So in general: floating point numbers should not be used if you care about significant digits. For monetary amounts with calculation, e,a, best use BigDecimal.

For physics floating point doubles are adequate, floats almost never. Furthermore the floating point part of processors, the FPU, can even use a bit more precission internally.

Maven: Failed to read artifact descriptor

I have a project

 A/
 |--a1
 |--a2

Now there is another project in our org

 B/
 |--b1
 |--b2
 |--b3

(Every module a1, b1 etc. and Parent projects A, B have their own pom.xml as per standard maven rules of parent and child)

Both projects are checked out on my local eclipse (from SVN). I am actively working on A.

I came to know that there is a good common functionality (b4) developed in B and I needed to use it.

 B/
 |--b1
 |--b2
 |--b3
 |--b4 (NEW)

Developer of b4 have deployed this b4 module as an artifact in our org's repository. I included the dependancy to my module's POM i.e. a2's pom.xml. Eclipse downloaded the reuqired artifact from repo and I could import the classes in it.

Now issue starts... I needed to check the source code of b4 for some purpose and as I already had B checked out on my local eclipse I updated it from SVN and checked out module b4. I also ran pom.xml of module b4 with targets like clean, package etc. After some time when I finishedd my coding I needed to create a JAR of my module a2. I ran "package" on a2's pom.xml and BAM!! errors n errors for a2 module.. These errors were also not very user friendly. Only thing is there was b4's name for sure in logs.

Solution: After trying for many solutions for many hours, I ran "mvn -U clean install" from console in my B's project directoty (i.e. in ../codebase/B). As B is the parent, clean install command ran for all modules including b4 and it ran successfully. After this I ran "mvn -U clean install" for my parent project which is A. And this worked! a2 module got compiled, installed, (packaged later) succesfully.

Here important point was if b4 is in your workspace do not only install b4. You will need to clean-install complete B. I came up to this solution after reading answer from Zuill

EDIT: One more thing here to note that if I didn't had B project checked out in Local environment then this issue might not have occurred for me. I tend to think that this happened cause I had B checked out in my local workspace.

Link to Flask static files with url_for

You have by default the static endpoint for static files. Also Flask application has the following arguments:

static_url_path: can be used to specify a different path for the static files on the web. Defaults to the name of the static_folder folder.

static_folder: the folder with static files that should be served at static_url_path. Defaults to the 'static' folder in the root path of the application.

It means that the filename argument will take a relative path to your file in static_folder and convert it to a relative path combined with static_url_default:

url_for('static', filename='path/to/file')

will convert the file path from static_folder/path/to/file to the url path static_url_default/path/to/file.

So if you want to get files from the static/bootstrap folder you use this code:

<link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='bootstrap/bootstrap.min.css') }}">

Which will be converted to (using default settings):

<link rel="stylesheet" type="text/css" href="static/bootstrap/bootstrap.min.css">

Also look at url_for documentation.

How to replace all double quotes to single quotes using jquery?

You can also use replaceAll(search, replaceWith) [MDN].

Then, make sure you have a string by wrapping one type of quotes by a different type:

 'a "b" c'.replaceAll('"', "'")
 // result: "a 'b' c"
    
 'a "b" c'.replaceAll(`"`, `'`)
 // result: "a 'b' c"

 // Using RegEx. You MUST use a global RegEx(Meaning it'll match all occurrences).
 'a "b" c'.replaceAll(/\"/g, "'")
 // result: "a 'b' c"

Important(!) if you choose regex:

when using a regexp you have to set the global ("g") flag; otherwise, it will throw a TypeError: "replaceAll must be called with a global RegExp".

Convert an int to ASCII character

"I have int i = 6; and I want char c = '6' by conversion. Any simple way to suggest?"

There are only 10 numbers. So write a function that takes an int from 0-9 and returns the ascii code. Just look it up in an ascii table and write a function with ifs or a select case.

Jenkins Slave port number for firewall

A slave isn't a server, it's a client type application. Network clients (almost) never use a specific port. Instead, they ask the OS for a random free port. This works much better since you usually run clients on many machines where the current configuration isn't known in advance. This prevents thousands of "client wouldn't start because port is already in use" bug reports every day.

You need to tell the security department that the slave isn't a server but a client which connects to the server and you absolutely need to have a rule which says client:ANY -> server:FIXED. The client port number should be >= 1024 (ports 1 to 1023 need special permissions) but I'm not sure if you actually gain anything by adding a rule for this - if an attacker can open privileged ports, they basically already own the machine.

If they argue, then ask them why they don't require the same rule for all the web browsers which people use in your company.

Bootstrap - Removing padding or margin when screen size is smaller

Heres what I do for Bootstrap 3/4

Use container-fluid instead of container.

Add this to my CSS

@media (min-width: 1400px) {
    .container-fluid{
        max-width: 1400px;
    }   
}

This removes margins below 1400px width screen

Connect to Active Directory via LDAP

ldapConnection is the server adres: ldap.example.com Ldap.Connection.Path is the path inside the ADS that you like to use insert in LDAP format.

OU=Your_OU,OU=other_ou,dc=example,dc=com

You start at the deepest OU working back to the root of the AD, then add dc=X for every domain section until you have everything including the top level domain

Now i miss a parameter to authenticate, this works the same as the path for the username

CN=username,OU=users,DC=example,DC=com

Introduction to LDAP

How to present a modal atop the current view in Swift

First, remove all explicit setting of modal presentation style in code and do the following:

  1. In the storyboard set the ModalViewController's modalPresentation style to Over Current context

img1

  1. Check the checkboxes in the Root/Presenting ViewController - Provide Context and Define Context. They seem to be working even unchecked.

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

Server.MapPath - Physical path given, virtual path expected

if you already know your folder is: E:\ftproot\sales then you do not need to use Server.MapPath, this last one is needed if you only have a relative virtual path like ~/folder/folder1 and you want to know the real path in the disk...

Add space between HTML elements only using CSS

span.middle {
    margin: 0 10px 0 10px; /*top right bottom left */
}

<span>text</span> <span class="middle">text</span> <span>text</span>

What is the difference between __str__ and __repr__?

My rule of thumb: __repr__ is for developers, __str__ is for customers.

How to use apply a custom drawable to RadioButton?

if you want to change the only icon of radio button then you can only add android:button="@drawable/ic_launcher" to your radio button and for making sensitive on click then you have to use the selector

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

<item android:drawable="@drawable/image_what_you_want_on_select_state" android:state_checked="true"/>
<item android:drawable="@drawable/image_what_you_want_on_un_select_state"    android:state_checked="false"/>


 </selector>

and set to your radio android:background="@drawable/name_of_selector"

MySQL: how to get the difference between two timestamps in seconds

You could use the TIMEDIFF() and the TIME_TO_SEC() functions as follows:

SELECT TIME_TO_SEC(TIMEDIFF('2010-08-20 12:01:00', '2010-08-20 12:00:00')) diff;
+------+
| diff |
+------+
|   60 |
+------+
1 row in set (0.00 sec)

You could also use the UNIX_TIMESTAMP() function as @Amber suggested in an other answer:

SELECT UNIX_TIMESTAMP('2010-08-20 12:01:00') - 
       UNIX_TIMESTAMP('2010-08-20 12:00:00') diff;
+------+
| diff |
+------+
|   60 |
+------+
1 row in set (0.00 sec)

If you are using the TIMESTAMP data type, I guess that the UNIX_TIMESTAMP() solution would be slightly faster, since TIMESTAMP values are already stored as an integer representing the number of seconds since the epoch (Source). Quoting the docs:

When UNIX_TIMESTAMP() is used on a TIMESTAMP column, the function returns the internal timestamp value directly, with no implicit “string-to-Unix-timestamp” conversion.

Keep in mind that TIMEDIFF() return data type of TIME. TIME values may range from '-838:59:59' to '838:59:59' (roughly 34.96 days)

How to use radio buttons in ReactJS?

Any changes to the rendering should be change via the state or props (react doc).

So here I register the event of the input, and then change the state, which will then trigger the render to show on the footer.

var SearchResult = React.createClass({
  getInitialState: function () {
    return {
      site: '',
      address: ''
    };
  },
  onSiteChanged: function (e) {
    this.setState({
      site: e.currentTarget.value
      });
  },

  onAddressChanged: function (e) {
    this.setState({
      address: e.currentTarget.value
      });
  },

  render: function(){
       var resultRows = this.props.data.map(function(result){
           return (
               <tbody>
                    <tr>
                        <td><input type="radio" name="site_name" 
                                   value={result.SITE_NAME} 
                                   checked={this.state.site === result.SITE_NAME} 
                                   onChange={this.onSiteChanged} />{result.SITE_NAME}</td>
                        <td><input type="radio" name="address" 
                                   value={result.ADDRESS}  
                                   checked={this.state.address === result.ADDRESS} 
                                   onChange={this.onAddressChanged} />{result.ADDRESS}</td>
                    </tr>
               </tbody>
           );
       }, this);
       return (
           <table className="table">
               <thead>
                   <tr>
                       <th>Name</th>
                       <th>Address</th>
                   </tr>
               </thead>
                {resultRows}
               <tfoot>
                   <tr>
                       <td>chosen site name {this.state.site} </td>
                       <td>chosen address {this.state.address} </td>
                   </tr>
               </tfoot>
           </table>
       );
  }
});

jsbin

How to convert string to integer in PowerShell

Use:

$filelist = @("11", "1", "2")
$filelist | sort @{expression={[int]$_}} | % {$newName = [string]([int]$_ + 1)}
New-Item $newName -ItemType Directory

javascript jquery radio button click

There are several ways to do this. Having a container around the radio buttons is highly recommended regardless, but you can also put a class directly on the buttons. With this HTML:

<ul id="shapeList" class="radioList">
<li><label>Shape:</label></li>
<li><input id="shapeList_0" class="shapeButton" type="radio" value="Circular" name="shapeList" /><label for="shapeList_0">Circular</label></li>
<li><input id="shapeList_1" class="shapeButton" type="radio" value="Rectangular" name="shapeList" /><label for="shapeList_1">Rectangular</label></li>
</ul>

you can select by class:

$(".shapeButton").click(SetShape);

or select by container ID:

$("#shapeList").click(SetShape);

In either case, the event will trigger on clicking either the radio button or the label for it, though oddly in the latter case (Selecting by "#shapeList"), clicking on the label will trigger the click function twice for some reason, at least in FireFox; selecting by class won't do that.

SetShape is a function, and looks like this:

function SetShape() {
    var Shape = $('.shapeButton:checked').val();
//dostuff
}

This way, you can have labels on your buttons, and can have multiple radio button lists on the same page that do different things. You can even have each individual button in the same list do different things by setting up different behavior in SetShape() based on the button's value.

Adding an assets folder in Android Studio

You can click on the Project window, press Alt-Insert, and select Folder->Assets Folder. Android Studio will add it automatically to the correct location.

You are most likely looking at your Project with the new(ish) "Android View". Note that this is a view and not the actual folder structure on disk (which hasn't changed since the introduction of Gradle as the new build tool). You can switch to the old "Project View" by clicking on the word "Android" at the top of the Project window and selecting "Project".

Regular expression for exact match of a string

In malfaux's answer '^' and '$' has been used to detect the beginning and the end of the text.
These are usually used to detect the beginning and the end of a line.
However this may be the correct way in this case.
But if you wish to match an exact word the more elegant way is to use '\b'. In this case following pattern will match the exact phrase'123456'.

/\b123456\b/

Installing specific package versions with pip

One way, as suggested in this post, is to mention version in pip as:

pip install -Iv MySQL_python==1.2.2

i.e. Use == and mention the version number to install only that version. -I, --ignore-installed ignores already installed packages.

How to read a large file line by line?

Best way to read large file, line by line is to use python enumerate function

with open(file_name, "rU") as read_file:
    for i, row in enumerate(read_file, 1):
        #do something
        #i in line of that line
        #row containts all data of that line

Checkbox Check Event Listener

Since I don't see the jQuery tag in the OP, here is a javascript only option :

document.addEventListener("DOMContentLoaded", function (event) {
    var _selector = document.querySelector('input[name=myCheckbox]');
    _selector.addEventListener('change', function (event) {
        if (_selector.checked) {
            // do something if checked
        } else {
            // do something else otherwise
        }
    });
});

See JSFIDDLE

How do you do dynamic / dependent drop downs in Google Sheets?

Here you have another solution based on the one provided by @tarheel

function onEdit() {
    var sheetWithNestedSelectsName = "Sitemap";
    var columnWithNestedSelectsRoot = 1;
    var sheetWithOptionPossibleValuesSuffix = "TabSections";

    var activeSpreadsheet = SpreadsheetApp.getActiveSpreadsheet();
    var activeSheet = SpreadsheetApp.getActiveSheet();

    // If we're not in the sheet with nested selects, exit!
    if ( activeSheet.getName() != sheetWithNestedSelectsName ) {
        return;
    }

    var activeCell = SpreadsheetApp.getActiveRange();

    // If we're not in the root column or a content row, exit!
    if ( activeCell.getColumn() != columnWithNestedSelectsRoot || activeCell.getRow() < 2 ) {
        return;
    }

    var sheetWithActiveOptionPossibleValues = activeSpreadsheet.getSheetByName( activeCell.getValue() + sheetWithOptionPossibleValuesSuffix );

    // Get all possible values
    var activeOptionPossibleValues = sheetWithActiveOptionPossibleValues.getSheetValues( 1, 1, -1, 1 );

    var possibleValuesValidation = SpreadsheetApp.newDataValidation();
    possibleValuesValidation.setAllowInvalid( false );
    possibleValuesValidation.requireValueInList( activeOptionPossibleValues, true );

    activeSheet.getRange( activeCell.getRow(), activeCell.getColumn() + 1 ).setDataValidation( possibleValuesValidation.build() );
}

It has some benefits over the other approach:

  • You don't need to edit the script every time you add a "root option". You only have to create a new sheet with the nested options of this root option.
  • I've refactored the script providing more semantic names for the variables and so on. Furthermore, I've extracted some parameters to variables in order to make it easier to adapt to your specific case. You only have to set the first 3 values.
  • There's no limit of nested option values (I've used the getSheetValues method with the -1 value).

So, how to use it:

  1. Create the sheet where you'll have the nested selectors
  2. Go to the "Tools" > "Script Editor…" and select the "Blank project" option
  3. Paste the code attached to this answer
  4. Modify the first 3 variables of the script setting up your values and save it
  5. Create one sheet within this same document for each possible value of the "root selector". They must be named as the value + the specified suffix.

Enjoy!

How to automatically update an application without ClickOnce?

This is the code to update the file but not to install This program is made through dos for copying files to the latest date and run your program automatically. may help you

open notepad and save file below with ext .bat

xcopy \\IP address\folder_share_name\*.* /s /y /d /q  
start "label" /b "youraplicationname.exe"

How to correctly link php-fpm and Nginx Docker containers?

New Answer

Docker Compose has been updated. They now have a version 2 file format.

Version 2 files are supported by Compose 1.6.0+ and require a Docker Engine of version 1.10.0+.

They now support the networking feature of Docker which when run sets up a default network called myapp_default

From their documentation your file would look something like the below:

version: '2'

services:
  web:
    build: .
    ports:
      - "8000:8000"
  fpm:
    image: phpfpm
  nginx
    image: nginx

As these containers are automatically added to the default myapp_default network they would be able to talk to each other. You would then have in the Nginx config:

fastcgi_pass fpm:9000;

Also as mentioned by @treeface in the comments remember to ensure PHP-FPM is listening on port 9000, this can be done by editing /etc/php5/fpm/pool.d/www.conf where you will need listen = 9000.

Old Answer

I have kept the below here for those using older version of Docker/Docker compose and would like the information.

I kept stumbling upon this question on google when trying to find an answer to this question but it was not quite what I was looking for due to the Q/A emphasis on docker-compose (which at the time of writing only has experimental support for docker networking features). So here is my take on what I have learnt.

Docker has recently deprecated its link feature in favour of its networks feature

Therefore using the Docker Networks feature you can link containers by following these steps. For full explanations on options read up on the docs linked previously.

First create your network

docker network create --driver bridge mynetwork

Next run your PHP-FPM container ensuring you open up port 9000 and assign to your new network (mynetwork).

docker run -d -p 9000 --net mynetwork --name php-fpm php:fpm

The important bit here is the --name php-fpm at the end of the command which is the name, we will need this later.

Next run your Nginx container again assign to the network you created.

docker run --net mynetwork --name nginx -d -p 80:80 nginx:latest

For the PHP and Nginx containers you can also add in --volumes-from commands etc as required.

Now comes the Nginx configuration. Which should look something similar to this:

server {
    listen 80;
    server_name localhost;

    root /path/to/my/webroot;

    index index.html index.htm index.php;

    location / {
        try_files $uri $uri/ /index.php?$query_string;
    }

    location ~ \.php$ {
        fastcgi_split_path_info ^(.+\.php)(/.+)$;
        fastcgi_pass php-fpm:9000; 
        fastcgi_index index.php;
        include fastcgi_params;
    }
}

Notice the fastcgi_pass php-fpm:9000; in the location block. Thats saying contact container php-fpm on port 9000. When you add containers to a Docker bridge network they all automatically get a hosts file update which puts in their container name against their IP address. So when Nginx sees that it will know to contact the PHP-FPM container you named php-fpm earlier and assigned to your mynetwork Docker network.

You can add that Nginx config either during the build process of your Docker container or afterwards its up to you.

Using SVG as background image

You have set a fixed width and height in your svg tag. This is probably the root of your problem. Try not removing those and set the width and height (if needed) using CSS instead.

POST request not allowed - 405 Not Allowed - nginx, even with headers included

I have tried the solution which redirects 405 to 200, and in production environment(in my case, it's Google Load Balancing with Nginx Docker container), this hack causes some 502 errors(Google Load Balancing error code: backend_early_response_with_non_error_status).

In the end, I have made this work properly by replacing Nginx with OpenResty which is completely compatible with Nginx and have more plugins.

With ngx_coolkit, Now Nginx(OpenResty) could serve static files with POST request properly, here is the config file in my case:

server {
  listen 80;

  location / {
    override_method GET;
    proxy_pass http://127.0.0.1:8080;
  }
}

server {
  listen 8080;
  location / {
    root /var/www/web-static;
    index index.html;
    add_header Cache-Control no-cache;
  }
}

In the above config, I use override_method offered by ngx_coolkit to override the HTTP Method to GET.

Javascript how to split newline

Since you are using textarea, you may find \n or \r (or \r\n) for line breaks. So, the following is suggested:

$('#keywords').val().split(/\r|\n/)

ref: check whether string contains a line break

Read response body in JAX-RS client from a post request

Try this:

String output = response.getEntity(String.class);

EDIT

Thanks to @Martin Spamer to mention that it will work for Jersey 1.x jars only. For Jersey 2.x use

String output = response.readEntity(String.class);

How to install easy_install in Python 2.7.1 on Windows 7

I recently used ez_setup.py as well and I did a tutorial on how to install it. The tutorial has snapshots and simple to follow. You can find it below:

Installing easy_install Using ez_setup.py

I hope you find this helpful.

Python object.__repr__(self) should be an expression?

'repr' means represention. First,we create an instance of class coordinate.

x = Coordinate(3, 4) 

Then if we input x into console,th output is

<__main__.Coordinate at 0x7fcd40ab27b8>

If you use repr():

>>> repr(x)
Coordinate(3, 4)

the output is as same as 'Coordinate(3, 4)',except it is a string.You can use it to recreate a instance of coordinate.

In conclusion,repr() meathod is print out a string,which is the representation of the obeject.

MySQL Insert into multiple tables? (Database normalization?)

What would happen, if you want to create many such records ones (to register 10 users, not just one)? I find the following solution (just 5 queryes):

Step I: Create temporary table to store new data.

CREATE TEMPORARY TABLE tmp (id bigint(20) NOT NULL, ...)...;

Next, fill this table with values.

INSERT INTO tmp (username, password, bio, homepage) VALUES $ALL_VAL

Here, instead of $ALL_VAL you place list of values: ('test1','test1','bio1','home1'),...,('testn','testn','bion','homen')

Step II: Send data to 'user' table.

INSERT IGNORE INTO users (username, password)
SELECT username, password FROM tmp;

Here, "IGNORE" can be used, if you allow some users already to be inside. Optionaly you can use UPDATE similar to step III, before this step, to find whom users are already inside (and mark them in tmp table). Here we suppouse, that username is declared as PRIMARY in users table.

Step III: Apply update to read all users id from users to tmp table. THIS IS ESSENTIAL STEP.

UPDATE tmp JOIN users ON tmp.username=users.username SET tmp.id=users.id

Step IV: Create another table, useing read id for users

INSERT INTO profiles (userid, bio, homepage) 
SELECT id, bio, homepage FROM tmp

for loop in Python

You should also know that in Python, iterating over integer indices is bad style, and also slower than the alternative. If you just want to look at each of the items in a list or dict, loop directly through the list or dict.

mylist = [1,2,3]
for item in mylist:
    print item

mydict  = {1:'one', 2:'two', 3:'three'}
for key in mydict:
    print key, mydict[key]

This is actually faster than using the above code with range(), and removes the extraneous i variable.

If you need to edit items of a list in-place, then you do need the index, but there's still a better way:

for i, item in enumerate(mylist):
    mylist[i] = item**2

Again, this is both faster and considered more readable. This one of the main shifts in thinking you need to make when coming from C++ to Python.

ImportError: No module named mysql.connector using Python2

I had a file named mysql.py in the folder. That's why it gave an error because it tried to call it in the import process.

import mysql.connector

I solved the problem by changing the file name.

java: ArrayList - how can I check if an index exists?

Quick and dirty test for whether an index exists or not. in your implementation replace list With your list you are testing.

public boolean hasIndex(int index){
    if(index < list.size())
        return true;
    return false;
}

or for 2Dimensional ArrayLists...

public boolean hasRow(int row){
    if(row < _matrix.size())
        return true;
    return false;
}

How do I pass multiple attributes into an Angular.js attribute directive?

The directive can access any attribute that is defined on the same element, even if the directive itself is not the element.

Template:

<div example-directive example-number="99" example-function="exampleCallback()"></div>

Directive:

app.directive('exampleDirective ', function () {
    return {
        restrict: 'A',   // 'A' is the default, so you could remove this line
        scope: {
            callback : '&exampleFunction',
        },
        link: function (scope, element, attrs) {
            var num = scope.$eval(attrs.exampleNumber);
            console.log('number=',num);
            scope.callback();  // calls exampleCallback()
        }
    };
});

fiddle

If the value of attribute example-number will be hard-coded, I suggest using $eval once, and storing the value. Variable num will have the correct type (a number).

How to compare strings in C conditional preprocessor-directives

If your strings are compile time constants (as in your case) you can use the following trick:

#define USER_JACK strcmp(USER, "jack")
#define USER_QUEEN strcmp(USER, "queen")
#if $USER_JACK == 0
#define USER_VS USER_QUEEN
#elif USER_QUEEN == 0
#define USER_VS USER_JACK
#endif

The compiler can tell the result of the strcmp in advance and will replace the strcmp with its result, thus giving you a #define that can be compared with preprocessor directives. I don't know if there's any variance between compilers/dependance on compiler options, but it worked for me on GCC 4.7.2.

EDIT: upon further investigation, it look like this is a toolchain extension, not GCC extension, so take that into consideration...

JPanel setBackground(Color.BLACK) does nothing

You need to create a new Jpanel object in the Board constructor. for example

public Board(){
    JPanel pane = new JPanel();
    pane.setBackground(Color.ORANGE);// sets the background to orange
} 

How do I format {{$timestamp}} as MM/DD/YYYY in Postman?

In PostMan we have ->Pre-request Script. Paste the Below snippet.

const dateNow = new Date();
postman.setGlobalVariable("todayDate", dateNow.toLocaleDateString());

And now we are ready to use.

{
"firstName": "SANKAR",
"lastName": "B",
"email": "[email protected]",
"creationDate": "{{todayDate}}"
}

If you are using JPA Entity classes then use the below snippet

    @JsonFormat(pattern="MM/dd/yyyy")
    @Column(name = "creation_date")
    private Date creationDate;

enter image description here enter image description here

Parsing GET request parameters in a URL that contains another URL

While creating url encode them with urlencode

$val=urlencode('http://google.com/?var=234&key=234')

<a href="http://localhost/test.php?id=<?php echo $val ?>">Click here</a>

and while fetching decode it wiht urldecode

cor shows only NA or 1 for correlations - Why?

NAs also appear if there are attributes with zero variance (with all elements equal); see for instance:

cor(cbind(a=runif(10),b=rep(1,10)))

which returns:

   a  b
a  1 NA
b NA  1
Warning message:
In cor(cbind(a = runif(10), b = rep(1, 10))) :
  the standard deviation is zero

MVC ajax json post to controller action method

Below is how I got this working.

The Key point was: I needed to use the ViewModel associated with the view in order for the runtime to be able to resolve the object in the request.

[I know that that there is a way to bind an object other than the default ViewModel object but ended up simply populating the necessary properties for my needs as I could not get it to work]

[HttpPost]  
  public ActionResult GetDataForInvoiceNumber(MyViewModel myViewModel)  
  {            
     var invoiceNumberQueryResult = _viewModelBuilder.HydrateMyViewModelGivenInvoiceDetail(myViewModel.InvoiceNumber, myViewModel.SelectedCompanyCode);
     return Json(invoiceNumberQueryResult, JsonRequestBehavior.DenyGet);
  }

The JQuery script used to call this action method:

var requestData = {
         InvoiceNumber: $.trim(this.value),
         SelectedCompanyCode: $.trim($('#SelectedCompanyCode').val())
      };


      $.ajax({
         url: '/en/myController/GetDataForInvoiceNumber',
         type: 'POST',
         data: JSON.stringify(requestData),
         dataType: 'json',
         contentType: 'application/json; charset=utf-8',
         error: function (xhr) {
            alert('Error: ' + xhr.statusText);
         },
         success: function (result) {
            CheckIfInvoiceFound(result);
         },
         async: true,
         processData: false
      });

jQuery - find table row containing table cell containing specific text

   <input type="text" id="text" name="search">
<table id="table_data">
        <tr class="listR"><td>PHP</td></tr>
        <tr class="listR"><td>MySql</td></tr>
        <tr class="listR"><td>AJAX</td></tr>
        <tr class="listR"><td>jQuery</td></tr>
        <tr class="listR"><td>JavaScript</td></tr>
        <tr class="listR"><td>HTML</td></tr>
        <tr class="listR"><td>CSS</td></tr>
        <tr class="listR"><td>CSS3</td></tr>
</table>

$("#textbox").on('keyup',function(){
        var f = $(this).val();
      $("#table_data tr.listR").each(function(){
            if ($(this).text().search(new RegExp(f, "i")) < 0) {
                $(this).fadeOut();
             } else {
                 $(this).show();
            }
        });
    });

Demo You can perform by search() method with use RegExp matching text

Java HTML Parsing

You can also use XWiki HTML Cleaner:

It uses HTMLCleaner and extends it to generate valid XHTML 1.1 content.

Remove specific characters from a string in Javascript

Another way to do it:

rnum = rnum.split("F0").pop()

It splits the string into two: ["", "123456"], then selects the last element.

How to completely hide the navigation bar in iPhone / HTML5

Simple javascript document navigation to "#" will do it.

window.onload = function()
{
document.location.href = "#";
}

This will force the navigation bar to remove itself on load.

symfony 2 twig limit the length of the text and put three dots

You can limit in following way. First is starting index and second is number of characters.

**{{ results['text'][4:2] }}**

Jenkins/Hudson - accessing the current build number?

As per Jenkins Documentation,

BUILD_NUMBER

is used. This number is identify how many times jenkins run this build process $BUILD_NUMBER is general syntax for it.

Allowing Untrusted SSL Certificates with HttpClient

Have a look at the WebRequestHandler Class and its ServerCertificateValidationCallback Property:

using (var handler = new WebRequestHandler())
{
    handler.ServerCertificateValidationCallback = ...

    using (var client = new HttpClient(handler))
    {
        ...
    }
}

Android: long click on a button -> perform actions

To get both functions working for a clickable image that will respond to both short and long clicks, I tried the following that seems to work perfectly:

    image = (ImageView) findViewById(R.id.imageViewCompass);
    image.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
            shortclick();
        }
     });

    image.setOnLongClickListener(new View.OnLongClickListener() {
    public boolean onLongClick(View v) {
        longclick();
        return true;
    }
});

//Then the functions that are called:

 public void shortclick()
{
 Toast.makeText(this, "Why did you do that? That hurts!!!", Toast.LENGTH_LONG).show();

}

 public void longclick()
{
 Toast.makeText(this, "Why did you do that? That REALLY hurts!!!", Toast.LENGTH_LONG).show();

}

It seems that the easy way of declaring the item in XML as clickable and then defining a function to call on the click only applies to short clicks - you must have a listener to differentiate between short and long clicks.

Android view layout_width - how to change programmatically?

try using

View view_instance = (View)findViewById(R.id.nutrition_bar_filled);
view_instance.setWidth(10);

use Layoutparams to do so where you can set width and height like below.

LayoutParams lp = new LayoutParams(10,LayoutParams.wrap_content);
View_instance.setLayoutParams(lp);

How do I truncate a .NET string?

In C# 8 the new Ranges feature can be used...

value = value[..Math.Min(30, value.Length)];

what does -zxvf mean in tar -zxvf <filename>?

Instead of wading through the description of all the options, you can jump to 3.4.3 Short Options Cross Reference under the info tar command.

x means --extract. v means --verbose. f means --file. z means --gzip. You can combine one-letter arguments together, and f takes an argument, the filename. There is something you have to watch out for:

Short options' letters may be clumped together, but you are not required to do this (as compared to old options; see below). When short options are clumped as a set, use one (single) dash for them all, e.g., ''tar' -cvf'. Only the last option in such a set is allowed to have an argument(1).


This old way of writing 'tar' options can surprise even experienced users. For example, the two commands:

 tar cfz archive.tar.gz file
 tar -cfz archive.tar.gz file

are quite different. The first example uses 'archive.tar.gz' as the value for option 'f' and recognizes the option 'z'. The second example, however, uses 'z' as the value for option 'f' -- probably not what was intended.

Vue.js data-bind style backgroundImage not working

The accepted answer didn't seem to solve the problem for me, but this did

Ensure your backgroundImage declarations are wrapped in url( and quotes so the style works correctly, no matter the file name.

ES2015 Style:

<div :style="{ backgroundImage: `url('${image}')` }"></div>

Or without ES2015:

<div :style="{ backgroundImage: 'url(\'' + image + '\')' }"></div>

Source: vuejs/vue-loader issue #646

Creating .pem file for APNS?

I never remember the openssl command needed to create a .pem file, so I made this bash script to simplify the process:

#!/bin/bash
if [ $# -eq 2 ]
then
    echo "Signing $1..."

    if ! openssl pkcs12 -in $1 -out $2 -nodes -clcerts; then
        echo "Error signing certificate."
    else
        echo "Certificate created successfully: $2"
    fi
else
    if [ $# -gt 2 ]
    then
        echo "Too many arguments"
        echo "Syntax: $0 <input.p12> <output.pem>"
    else
        echo "Missing arguments"
        echo "Syntax: $0 <input.p12> <output.pem>"
    fi
fi

Name it, for example, signpem.sh and save it on your user's folder (/Users/<username>?). After creating the file, do a chmod +x signpem.sh to make it executable and then you can run:

~/signpem myCertificate.p12 myCertificate.pem

And myCertificate.pem will be created.

Async image loading from url inside a UITableView cell - image changes to wrong image while scrolling

Swift 3

I write my own light implementation for image loader with using NSCache. No cell image flickering!

ImageCacheLoader.swift

typealias ImageCacheLoaderCompletionHandler = ((UIImage) -> ())

class ImageCacheLoader {
    
    var task: URLSessionDownloadTask!
    var session: URLSession!
    var cache: NSCache<NSString, UIImage>!
    
    init() {
        session = URLSession.shared
        task = URLSessionDownloadTask()
        self.cache = NSCache()
    }
    
    func obtainImageWithPath(imagePath: String, completionHandler: @escaping ImageCacheLoaderCompletionHandler) {
        if let image = self.cache.object(forKey: imagePath as NSString) {
            DispatchQueue.main.async {
                completionHandler(image)
            }
        } else {
            /* You need placeholder image in your assets, 
               if you want to display a placeholder to user */
            let placeholder = #imageLiteral(resourceName: "placeholder")
            DispatchQueue.main.async {
                completionHandler(placeholder)
            }
            let url: URL! = URL(string: imagePath)
            task = session.downloadTask(with: url, completionHandler: { (location, response, error) in
                if let data = try? Data(contentsOf: url) {
                    let img: UIImage! = UIImage(data: data)
                    self.cache.setObject(img, forKey: imagePath as NSString)
                    DispatchQueue.main.async {
                        completionHandler(img)
                    }
                }
            })
            task.resume()
        }
    }
}

Usage example

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    
    let cell = tableView.dequeueReusableCell(withIdentifier: "Identifier")
    
    cell.title = "Cool title"

    imageLoader.obtainImageWithPath(imagePath: viewModel.image) { (image) in
        // Before assigning the image, check whether the current cell is visible
        if let updateCell = tableView.cellForRow(at: indexPath) {
            updateCell.imageView.image = image
        }
    }    
    return cell
}

How to make a variadic macro (variable number of arguments)

I don't think that's possible, you could fake it with double parens ... just as long you don't need the arguments individually.

#define macro(ARGS) some_complicated (whatever ARGS)
// ...
macro((a,b,c))
macro((d,e))