Programs & Examples On #Raytracing

Ray tracing is a physics-based method for simulating photorealistic 3D scenes. Light rays are drawn from the eye through each pixel of the desired image, and the rays' interactions with the scene determine the displayed pixel color.

Is it possible to run CUDA on AMD GPUs?

You can run NVIDIA® CUDA™ code on Mac, and indeed on OpenCL 1.2 GPUs in general, using Coriander . Disclosure: I'm the author. Example usage:

cocl cuda_sample.cu
./cuda_sample

Result: enter image description here

How can I pass request headers with jQuery's getJSON() method?

I think you could set the headers and still use getJSON() like this:

$.ajaxSetup({
  headers : {
    'Authorization' : 'Basic faskd52352rwfsdfs',
    'X-PartnerKey' : '3252352-sdgds-sdgd-dsgs-sgs332fs3f'
  }
});
$.getJSON('http://localhost:437/service.svc/logins/jeffrey/house/fas6347/devices?format=json', function(json) { alert("Success"); }); 

Return from lambda forEach() in java

I suggest you to first try to understand Java 8 in the whole picture, most importantly in your case it will be streams, lambdas and method references.

You should never convert existing code to Java 8 code on a line-by-line basis, you should extract features and convert those.

What I identified in your first case is the following:

  • You want to add elements of an input structure to an output list if they match some predicate.

Let's see how we do that, we can do it with the following:

List<Player> playersOfTeam = players.stream()
    .filter(player -> player.getTeam().equals(teamName))
    .collect(Collectors.toList());

What you do here is:

  1. Turn your input structure into a stream (I am assuming here that it is of type Collection<Player>, now you have a Stream<Player>.
  2. Filter out all unwanted elements with a Predicate<Player>, mapping every player to the boolean true if it is wished to be kept.
  3. Collect the resulting elements in a list, via a Collector, here we can use one of the standard library collectors, which is Collectors.toList().

This also incorporates two other points:

  1. Code against interfaces, so code against List<E> over ArrayList<E>.
  2. Use diamond inference for the type parameter in new ArrayList<>(), you are using Java 8 after all.

Now onto your second point:

You again want to convert something of legacy Java to Java 8 without looking at the bigger picture. This part has already been answered by @IanRoberts, though I think that you need to do players.stream().filter(...)... over what he suggested.

WELD-001408: Unsatisfied dependencies for type Customer with qualifiers @Default

You need to annotate your Customer class with @Named or @Model annotation:

package de.java2enterprise.onlineshop.model;
@Model
public class Customer {
    private String email;
    private String password;
}

or create/modify beans.xml:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://xmlns.jcp.org/xml/ns/javaee"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/beans_1_1.xsd"
   bean-discovery-mode="all">
</beans>

How to check if "Radiobutton" is checked?

Just as you would with a CheckBox

RadioButton rb;

rb = (RadioButton) findViewById(R.id.rb);

rb.isChecked();

How to clear mysql screen console in windows?

For Window 10

Use the command system cls and this will clear the MYSQL Command Line window in Windows

How to change ViewPager's page?

slide to right

viewPager.arrowScroll(View.FOCUS_RIGHT);

slide to left

viewPager.arrowScroll(View.FOCUS_LEFT);

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

I know the OP is asking for a CSS-only solution. But in case anyone landing here from the Magic Google ends up requiring a JavaScript solution, here's a one-liner:

capitalize = str => str[0].toUpperCase() + str.substr(1);

e.g.:

capitalize('foo bar baz'); // -> 'Foo bar baz'

Is an HTTPS query string secure?

Yes, from the moment on you establish a HTTPS connection everyting is secure. The query string (GET) as the POST is sent over SSL.

PHP cURL custom headers

curl_setopt($ch, CURLOPT_HTTPHEADER, array(
    'X-Apple-Tz: 0',
    'X-Apple-Store-Front: 143444,12'
));

http://www.php.net/manual/en/function.curl-setopt.php

How can you customize the numbers in an ordered list?

The CSS for styling lists is here, but is basically:

li {
    list-style-type: decimal;
    list-style-position: inside;
}

However, the specific layout you're after can probably only be achieved by delving into the innards of the layout with something like this (note that I haven't actually tried it):

ol { counter-reset: item }
li { display: block }
li:before { content: counter(item) ") "; counter-increment: item }

Get list of a class' instance methods

According to Ruby Doc instance_methods

Returns an array containing the names of the public and protected instance methods in the receiver. For a module, these are the public and protected methods; for a class, they are the instance (not singleton) methods. If the optional parameter is false, the methods of any ancestors are not included. I am taking the official documentation example.

module A
  def method1()  
    puts "method1 say hi"
  end
end
class B
  include A #mixin
  def method2()  
     puts "method2 say hi"
  end
end
class C < B #inheritance
  def method3() 
     puts "method3 say hi"
  end
end

Let's see the output.

A.instance_methods(false)
  => [:method1]

A.instance_methods
  => [:method1]
B.instance_methods
 => [:method2, :method1, :nil?, :===, ...# ] # methods inherited from parent class, most important :method1 is also visible because we mix module A in class B

B.instance_methods(false)
  => [:method2]
C.instance_methods
  => [:method3, :method2, :method1, :nil?, :===, ...#] # same as above
C.instance_methods(false)
 => [:method3]

ListBox with ItemTemplate (and ScrollBar!)

Thnaks for answer. I tried it myself too to an Empty Project and - lo behold allmighty creator of heaven and seven seas - it worked. I originally had ListBox inside which was inside of root . For some reason ListBox doesn't like being inside of StackPanel, at all! =)

-pom-

Passing route control with optional parameter after root in express?

Express version:

"dependencies": {
    "body-parser": "^1.19.0",
    "express": "^4.17.1"
  }

Optional parameter are very much handy, you can declare and use them easily using express:

app.get('/api/v1/tours/:cId/:pId/:batchNo?', (req, res)=>{
    console.log("category Id: "+req.params.cId);
    console.log("product ID: "+req.params.pId);
    if (req.params.batchNo){
        console.log("Batch No: "+req.params.batchNo);
    }
});

In the above code batchNo is optional. Express will count it optional because after in URL construction, I gave a '?' symbol after batchNo '/:batchNo?'

Now I can call with only categoryId and productId or with all three-parameter.

http://127.0.0.1:3000/api/v1/tours/5/10
//or
http://127.0.0.1:3000/api/v1/tours/5/10/8987

enter image description here enter image description here

Can you create nested WITH clauses for Common Table Expressions?

These answers are pretty good, but as far as getting the items to order properly, you'd be better off looking at this article http://dataeducation.com/dr-output-or-how-i-learned-to-stop-worrying-and-love-the-merge

Here's an example of his query.

WITH paths AS ( 
    SELECT 
        EmployeeID, 
        CONVERT(VARCHAR(900), CONCAT('.', EmployeeID, '.')) AS FullPath 
    FROM EmployeeHierarchyWide 
    WHERE ManagerID IS NULL

    UNION ALL

    SELECT 
        ehw.EmployeeID, 
        CONVERT(VARCHAR(900), CONCAT(p.FullPath, ehw.EmployeeID, '.')) AS FullPath 
    FROM paths AS p 
        JOIN EmployeeHierarchyWide AS ehw ON ehw.ManagerID = p.EmployeeID 
) 
SELECT * FROM paths order by FullPath

Run a Docker image as a container

$ docker images
REPOSITORY                TAG                 IMAGE ID            CREATED            
jamesmedice/marketplace   latest              e78c49b5f380        2 days ago          
jamesmedice/marketplace   v1.0.0              *e78c49b5f380*        2 days ago          


$ docker run -p 6001:8585 *e78c49b5f380*

Find index of a value in an array

int keyIndex = Array.FindIndex(words, w => w.IsKey);

That actually gets you the integer index and not the object, regardless of what custom class you have created

Showing an image from console in Python

You cannot display images in a console window. You need a graphical toolkit such as Tkinter, PyGTK, PyQt, PyKDE, wxPython, PyObjC or PyFLTK. There are plenty of tutorial how to create siomple windows and loading images iun python.

Modify request parameter with servlet filter

Based on all your remarks here is my proposal that worked for me :

 private final class CustomHttpServletRequest extends HttpServletRequestWrapper {

    private final Map<String, String[]> queryParameterMap;
    private final Charset requestEncoding;

    public CustomHttpServletRequest(HttpServletRequest request) {
        super(request);
        queryParameterMap = getCommonQueryParamFromLegacy(request.getParameterMap());

        String encoding = request.getCharacterEncoding();
        requestEncoding = (encoding != null ? Charset.forName(encoding) : StandardCharsets.UTF_8);
    }

    private final Map<String, String[]> getCommonQueryParamFromLegacy(Map<String, String[]> paramMap) {
        Objects.requireNonNull(paramMap);

        Map<String, String[]> commonQueryParamMap = new LinkedHashMap<>(paramMap);

        commonQueryParamMap.put(CommonQueryParams.PATIENT_ID, new String[] { paramMap.get(LEGACY_PARAM_PATIENT_ID)[0] });
        commonQueryParamMap.put(CommonQueryParams.PATIENT_BIRTHDATE, new String[] { paramMap.get(LEGACY_PARAM_PATIENT_BIRTHDATE)[0] });
        commonQueryParamMap.put(CommonQueryParams.KEYWORDS, new String[] { paramMap.get(LEGACY_PARAM_STUDYTYPE)[0] });

        String lowerDateTime = null;
        String upperDateTime = null;

        try {
            String studyDateTime = new SimpleDateFormat("yyyy-MM-dd").format(new SimpleDateFormat("dd-MM-yyyy").parse(paramMap.get(LEGACY_PARAM_STUDY_DATE_TIME)[0]));

            lowerDateTime = studyDateTime + "T23:59:59";
            upperDateTime = studyDateTime + "T00:00:00";

        } catch (ParseException e) {
            LOGGER.error("Can't parse StudyDate from query parameters : {}", e.getLocalizedMessage());
        }

        commonQueryParamMap.put(CommonQueryParams.LOWER_DATETIME, new String[] { lowerDateTime });
        commonQueryParamMap.put(CommonQueryParams.UPPER_DATETIME, new String[] { upperDateTime });

        legacyQueryParams.forEach(commonQueryParamMap::remove);
        return Collections.unmodifiableMap(commonQueryParamMap);

    }

    @Override
    public String getParameter(String name) {
        String[] params = queryParameterMap.get(name);
        return params != null ? params[0] : null;
    }

    @Override
    public String[] getParameterValues(String name) {
        return queryParameterMap.get(name);
    }

    @Override
    public Map<String, String[]> getParameterMap() {
            return queryParameterMap; // unmodifiable to uphold the interface contract.
        }

        @Override
        public Enumeration<String> getParameterNames() {
            return Collections.enumeration(queryParameterMap.keySet());
        }

        @Override
        public String getQueryString() {
            // @see : https://stackoverflow.com/a/35831692/9869013
            // return queryParameterMap.entrySet().stream().flatMap(entry -> Stream.of(entry.getValue()).map(value -> entry.getKey() + "=" + value)).collect(Collectors.joining("&")); // without encoding !!
            return queryParameterMap.entrySet().stream().flatMap(entry -> encodeMultiParameter(entry.getKey(), entry.getValue(), requestEncoding)).collect(Collectors.joining("&"));
        }

        private Stream<String> encodeMultiParameter(String key, String[] values, Charset encoding) {
            return Stream.of(values).map(value -> encodeSingleParameter(key, value, encoding));
        }

        private String encodeSingleParameter(String key, String value, Charset encoding) {
            return urlEncode(key, encoding) + "=" + urlEncode(value, encoding);
        }

        private String urlEncode(String value, Charset encoding) {
            try {
                return URLEncoder.encode(value, encoding.name());
            } catch (UnsupportedEncodingException e) {
                throw new IllegalArgumentException("Cannot url encode " + value, e);
            }
        }

        @Override
        public ServletInputStream getInputStream() throws IOException {
            throw new UnsupportedOperationException("getInputStream() is not implemented in this " + CustomHttpServletRequest.class.getSimpleName() + " wrapper");
        }

    }

note : queryString() requires to process ALL the values for each KEY and don't forget to encodeUrl() when adding your own param values, if required

As a limitation, if you call request.getParameterMap() or any method that would call request.getReader() and begin reading, you will prevent any further calls to request.setCharacterEncoding(...)

Centering floating divs within another div

With Flexbox you can easily horizontally (and vertically) center floated children inside a div.

So if you have simple markup like so:

<div class="wpr">
    <span></span>
    <span></span>
    <span></span>
    <span></span>
    <span></span>
</div>

with CSS:

.wpr
{
    width: 400px;
    height: 100px;
    background: pink;
    padding: 10px 30px;
}

.wpr span
{
    width: 50px;
    height: 50px;
    background: green;
    float: left; /* **children floated left** */
    margin: 0 5px;
}

(This is the (expected - and undesirable) RESULT)

Now add the following rules to the wrapper:

display: flex;
justify-content: center; /* align horizontal */

and the floated children get aligned center (DEMO)

Just for fun, to get vertical alignment as well just add:

align-items: center; /* align vertical */

DEMO

How do I fix this "TypeError: 'str' object is not callable" error?

You are trying to use the string as a function:

"Your new price is: $"(float(price) * 0.1)

Because there is nothing between the string literal and the (..) parenthesis, Python interprets that as an instruction to treat the string as a callable and invoke it with one argument:

>>> "Hello World!"(42)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'str' object is not callable

Seems you forgot to concatenate (and call str()):

easygui.msgbox("Your new price is: $" + str(float(price) * 0.1))

The next line needs fixing as well:

easygui.msgbox("Your new price is: $" + str(float(price) * 0.2))

Alternatively, use string formatting with str.format():

easygui.msgbox("Your new price is: ${:.2f}".format(float(price) * 0.1))
easygui.msgbox("Your new price is: ${:.2f}".format(float(price) * 0.2))

where {:02.2f} will be replaced by your price calculation, formatting the floating point value as a value with 2 decimals.

How to split/partition a dataset into training and test datasets for, e.g., cross validation?

If you want to split the data set once in two halves, you can use numpy.random.shuffle, or numpy.random.permutation if you need to keep track of the indices:

import numpy
# x is your dataset
x = numpy.random.rand(100, 5)
numpy.random.shuffle(x)
training, test = x[:80,:], x[80:,:]

or

import numpy
# x is your dataset
x = numpy.random.rand(100, 5)
indices = numpy.random.permutation(x.shape[0])
training_idx, test_idx = indices[:80], indices[80:]
training, test = x[training_idx,:], x[test_idx,:]

There are many ways to repeatedly partition the same data set for cross validation. One strategy is to resample from the dataset, with repetition:

import numpy
# x is your dataset
x = numpy.random.rand(100, 5)
training_idx = numpy.random.randint(x.shape[0], size=80)
test_idx = numpy.random.randint(x.shape[0], size=20)
training, test = x[training_idx,:], x[test_idx,:]

Finally, sklearn contains several cross validation methods (k-fold, leave-n-out, ...). It also includes more advanced "stratified sampling" methods that create a partition of the data that is balanced with respect to some features, for example to make sure that there is the same proportion of positive and negative examples in the training and test set.

Declaring functions in JSP?

You need to enclose that in <%! %> as follows:

<%!

public String getQuarter(int i){
String quarter;
switch(i){
        case 1: quarter = "Winter";
        break;

        case 2: quarter = "Spring";
        break;

        case 3: quarter = "Summer I";
        break;

        case 4: quarter = "Summer II";
        break;

        case 5: quarter = "Fall";
        break;

        default: quarter = "ERROR";
}

return quarter;
}

%>

You can then invoke the function within scriptlets or expressions:

<%
     out.print(getQuarter(4));
%>

or

<%= getQuarter(17) %>

Python: How to get values of an array at certain index positions?

Just index using you ind_pos

ind_pos = [1,5,7]
print (a[ind_pos]) 
[88 85 16]


In [55]: a = [0,88,26,3,48,85,65,16,97,83,91]

In [56]: import numpy as np

In [57]: arr = np.array(a)

In [58]: ind_pos = [1,5,7]

In [59]: arr[ind_pos]
Out[59]: array([88, 85, 16])

MySQL - SELECT * INTO OUTFILE LOCAL ?

Re: SELECT * INTO OUTFILE

Check if MySQL has permissions to write a file to the OUTFILE directory on the server.

Removing double quotes from variables in batch file creates problems with CMD environment

I learned from this link, if you are using XP or greater that this will simply work by itself:

SET params = %~1

I could not get any of the other solutions here to work on Windows 7.

To iterate over them, I did this:

FOR %%A IN (%params%) DO (    
   ECHO %%A    
)

Note: You will only get double quotes if you pass in arguments separated by a space typically.

How to make the first option of <select> selected with jQuery

If you are going to use the first option as a default like

<select>
    <option value="">Please select an option below</option>
    ...

then you can just use:

$('select').val('');

It is nice and simple.

Is it possible to style a mouseover on an image map using CSS?

You could use Canvas

in HTML, simply add a canva

<canvas id="locations" width="400" height="300" style="border:1px solid #d3d3d3;">
Your browser can't read canvas</canvas>

And in Javascript (only an example, that will draw a rectangle on the picture)

var c = document.getElementById("locations");
var ctx = c.getContext("2d");
var img = new Image(); 
img.src = '{main_photo}';
img.onload = function() {    // after the pic is loaded
    ctx.drawImage(this,0,0); // add the picture
    ctx.beginPath();         // start the rectangle
    ctx.moveTo(50,50);
    ctx.lineTo(200,50);
    ctx.lineTo(200,200);
    ctx.lineTo(50,200);
    ctx.lineTo(50,50);

    ctx.strokeStyle = "sienna"; // set color
    ctx.stroke();               // apply color
    ctx.lineWidth = 5;
    // ctx.closePath();
};

How do I find out my root MySQL password?

Here is the best way to set your root password : Source Link Step 3 is working perfectly for me.

Commands for You

  1. sudo mysql
  2. SELECT user,authentication_string,plugin,host FROM mysql.user;
  3. ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY 'password';
  4. FLUSH PRIVILEGES;
  5. SELECT user,authentication_string,plugin,host FROM mysql.user;
  6. exit

Now you can use the Password for the root user is 'password' :

  1. mysql -u root -p
  2. CREATE USER 'sammy'@'localhost' IDENTIFIED BY 'password';
  3. GRANT ALL PRIVILEGES ON . TO 'sammy'@'localhost' WITH GRANT OPTION;
  4. FLUSH PRIVILEGES;
  5. exit

Test your MySQL Service and Version:

systemctl status mysql.service
sudo mysqladmin -p -u root version

Unicode character in PHP string

As mentioned by others, PHP 7 introduces support for the \u Unicode syntax directly.

As also mentioned by others, the only way to obtain a string value from any sensible Unicode character description in PHP, is by converting it from something else (e.g. JSON parsing, HTML parsing or some other form). But this comes at a run-time performance cost.

However, there is one other option. You can encode the character directly in PHP with \x binary escaping. The \x escape syntax is also supported in PHP 5.

This is especially useful if you prefer not to enter the character directly in a string through its natural form. For example, if it is an invisible control character, or other hard to detect whitespace.

First, a proof example:

// Unicode Character 'HAIR SPACE' (U+200A)
$htmlEntityChar = "&#8202;";
$realChar = html_entity_decode($htmlEntityChar);
$phpChar = "\xE2\x80\x8A";
echo 'Proof: ';
var_dump($realChar === $phpChar); // bool(true)

Note that, as mentioned by Pacerier in another answer, this binary code is unique to a specific character encoding. In the above example, \xE2\x80\x8A is the binary coding for U+200A in UTF-8.

The next question is, how do you get from U+200A to \xE2\x80\x8A?

Below is a PHP script to generate the escape sequence for any character, based on either a JSON string, HTML entity, or any other method once you have it as a native string.

function str_encode_utf8binary($str) {
    /** @author Krinkle 2018 */
    $output = '';
    foreach (str_split($str) as $octet) {
        $ordInt = ord($octet);
        // Convert from int (base 10) to hex (base 16), for PHP \x syntax
        $ordHex = base_convert($ordInt, 10, 16);
        $output .= '\x' . $ordHex;
    }
    return $output;
}

function str_convert_html_to_utf8binary($str) {
    return str_encode_utf8binary(html_entity_decode($str));
}
function str_convert_json_to_utf8binary($str) {
    return str_encode_utf8binary(json_decode($str));
}

// Example for raw string: Unicode Character 'INFINITY' (U+221E)
echo str_encode_utf8binary('8') . "\n";
// \xe2\x88\x9e

// Example for HTML: Unicode Character 'HAIR SPACE' (U+200A)
echo str_convert_html_to_utf8binary('&#8202;') . "\n";
// \xe2\x80\x8a

// Example for JSON: Unicode Character 'HAIR SPACE' (U+200A)
echo str_convert_json_to_utf8binary('"\u200a"') . "\n";
// \xe2\x80\x8a

Disable future dates after today in Jquery Ui Datepicker

You can simply do this

$(function() {
    $( "#datepicker" ).datepicker({  maxDate: new Date });
  });

JSFiddle

FYI: while checking the documentation, found that it also accepts numeric values too.

Number: A number of days from today. For example 2 represents two days from today and -1 represents yesterday.

so 0 represents today. Therefore you can do this too

 $( "#datepicker" ).datepicker({  maxDate: 0 });

Regex to match string containing two names in any order

You can do:

\bjack\b.*\bjames\b|\bjames\b.*\bjack\b

JS. How to replace html element with another element/text, represented in string?

Using jQuery you can do this:

var str = '<td>1</td><td>2</td>';
$('#__TABLE__').replaceWith(str);

http://jsfiddle.net/hZBeW/4/

Or in pure javascript:

var str = '<td>1</td><td>2</td>';
var tdElement = document.getElementById('__TABLE__');
var trElement = tdElement.parentNode;
trElement.removeChild(tdElement);
trElement.innerHTML = str + trElement.innerHTML;

http://jsfiddle.net/hZBeW/1/

Open file in a relative location in Python

If the file is in your parent folder, eg. follower.txt, you can simply use open('../follower.txt', 'r').read()

intl extension: installing php_intl.dll

If you have the msvcp110.dll missing file error. You have to download the right .dll or just go here http://www.microsoft.com/es-es/download/confirmation.aspx?id=30679 and install the vcredist_x64.exe and vcredist_x86.exe, it worked for me.

how to show confirmation alert with three buttons 'Yes' 'No' and 'Cancel' as it shows in MS Word

This cannot be done with the native javascript dialog box, but a lot of javascript libraries include more flexible dialogs. You can use something like jQuery UI's dialog box for this.

See also these very similar questions:

Here's an example, as demonstrated in this jsFiddle:

<html><head>
    <script type="text/javascript" src="http://code.jquery.com/jquery-1.7.1.js"></script>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.16/jquery-ui.js"></script>
    <link rel="stylesheet" type="text/css" href="/css/normalize.css">
    <link rel="stylesheet" type="text/css" href="/css/result-light.css">
    <link rel="stylesheet" type="text/css" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.17/themes/base/jquery-ui.css">
</head>
<body>
    <a class="checked" href="http://www.google.com">Click here</a>
    <script type="text/javascript">

        $(function() {
            $('.checked').click(function(e) {
                e.preventDefault();
                var dialog = $('<p>Are you sure?</p>').dialog({
                    buttons: {
                        "Yes": function() {alert('you chose yes');},
                        "No":  function() {alert('you chose no');},
                        "Cancel":  function() {
                            alert('you chose cancel');
                            dialog.dialog('close');
                        }
                    }
                });
            });
        });

    </script>
</body><html>

Why did a network-related or instance-specific error occur while establishing a connection to SQL Server?

I solved this issue by running the following command in an elevated command prompt as specified in this post.

net start mssqlserver

Crystal Reports 13 And Asp.Net 3.5

I believe you are not the only one who has problems when trying to deploy Crystal Report for VS 2010. Based on the error message you had, have you checked:

  1. Please make sure you just have one CR version installed on your system. If you do have other CR version installed, consider to uninstall it so that your application is not "confused" about the CR version.

  2. You need to make sure you download the correct CR version. Since you are using VS 2010, you need to refer to CRforVS_redist_install_64bit_13_0_1.zip (for 64 bit machine) or CRforVS_redist_install_32bit_13_0_1.zip (for 32 bit machine). These two are the redistributable packages. You can download full package from the below link as well: CRforVS_13_0_1.exe Note: It is sometimes necessary to install 32bit CR runtime even on 64bit OS

  3. Make sure you setup FULL TRUST permission on your root folder

  4. The LOCAL SERVICE permission must be setup on your application pool

  5. Make sure the aspnet_client folder exists on your root folder.

If you can make sure all the 5 points above, your Crystal Report should work without any fuss.

Another important thing to note down here is that if you host your Crystal Report with a shared host, you need to check it with them of whether they really support Crystal Report. If you still have problems, you can switch to http://www.asphostcentral.com, who provides Crystal Report support.

Good luck!

jquery $(window).width() and $(window).height() return different values when viewport has not been resized

Try to use a

  • $(window).load event

or

  • $(document).ready

    because the initial values may be inconstant because of changes that occur during the parsing or during the DOM load.

How to retrieve a user environment variable in CMake (Windows)

Environment variables (that you modify using the System Properties) are only propagated to subshells when you create a new subshell.

If you had a command line prompt (DOS or cygwin) open when you changed the User env vars, then they won't show up.

You need to open a new command line prompt after you change the user settings.

The equivalent in Unix/Linux is adding a line to your .bash_rc: you need to start a new shell to get the values.

Docker: "no matching manifest for windows/amd64 in the manifest list entries"

I had this same issue on Windows 10. I bypassed it by running the Docker daemon in experimental mode:

  1. Right click Docker icon in the Windows System Tray
  2. Go to Settings
  3. Daemon
  4. Advanced
  5. Set the "experimental": true
  6. Restart Docker

Android ListView Text Color

if you didnot set your activity style it shows you black background .if you want to make changes such as white background, black text of listview then it is difficult process.

ADD android:theme="@style/AppTheme" in Android Manifest.

PL/SQL block problem: No data found error

Might be worth checking online for the errata section for your book.

There's an example of handling this exception here http://www.dba-oracle.com/sf_ora_01403_no_data_found.htm

How do I view the SQL generated by the Entity Framework?

There are two ways:

  1. To view the SQL that will be generated, simply call ToTraceString(). You can add it into your watch window and set a breakpoint to see what the query would be at any given point for any LINQ query.
  2. You can attach a tracer to your SQL server of choice, which will show you the final query in all its gory detail. In the case of MySQL, the easiest way to trace the queries is simply to tail the query log with tail -f. You can learn more about MySQL's logging facilities in the official documentation. For SQL Server, the easiest way is to use the included SQL Server profiler.

Get the new record primary key ID from MySQL insert query?

If you are using PHP: On a PDO object you can simple invoke the lastInsertId method after your insert.

Otherwise with a LAST_INSERT_ID you can get the value like this: SELECT LAST_INSERT_ID();

Replace comma with newline in sed on MacOS?

This works on MacOS Mountain Lion (10.8), Solaris 10 (SunOS 5.10) and RHE Linux (Red Hat Enterprise Linux Server release 5.3, Tikanga)...

$ sed 's/{pattern}/\^J/g' foo.txt > foo2.txt

... where the ^J is done by doing ctrl+v+j. Do mind the \ before the ^J.

PS, I know the sed in RHEL is GNU, the MacOS sed is FreeBSD based, and although I'm not sure about the Solaris sed, I believe this will work pretty much with any sed. YMMV tho'...

Side-by-side plots with ggplot2

Yes, methinks you need to arrange your data appropriately. One way would be this:

X <- data.frame(x=rep(x,2),
                y=c(3*x+eps, 2*x+eps),
                case=rep(c("first","second"), each=100))

qplot(x, y, data=X, facets = . ~ case) + geom_smooth()

I am sure there are better tricks in plyr or reshape -- I am still not really up to speed on all these powerful packages by Hadley.

How do you get the Git repository's name in some Git repository?

Unfortunately, it seems that Git has no such command built in. But you can easily add it yourself with Git aliases and some shell magic.

As pointed out by this answer, you can use git rev-parse --show-toplevel to show the root of your current Git folder.

If you want to use this regularly, it's probably more convenient to define it as an alias. For this, used git config alias.root '!echo "$(git rev-parse --show-toplevel)"'. After this, you can use git root to see the root folder of the repository you're currently in.

If you want to use another subcommand name than root, simply replace the second part of alias.root in the above command with whatever you want.

For details on aliases in Git, see also the git config man page.

What is an application binary interface (ABI)?

You actually don't need an ABI at all if--

  • Your program doesn't have functions, and--
  • Your program is a single executable that is running alone (i.e. an embedded system) where it's literally the only thing running and it doesn't need to talk to anything else.

An oversimplified summary:

API: "Here are all the functions you may call."

ABI: "This is how to call a function."

The ABI is set of rules that compilers and linkers adhere to in order to compile your program so that will work properly. ABIs cover multiple topics:

  • Arguably the biggest and most important part of an ABI is the procedure call standard sometimes known as the "calling convention". Calling conventions standardize how "functions" are translated to assembly code.
  • ABIs also dictate the how the names of exposed functions in libraries should be represented so that other code can call those libraries and know what arguments should be passed. This is called "name mangling".
  • ABIs also dictate what type of data types can be used, how they must be aligned, and other low-level details.

Taking a deeper look at calling convention, which I consider to be the core of an ABI:

The machine itself has no concept of "functions". When you write a function in a high-level language like c, the compiler generates a line of assembly code like _MyFunction1:. This is a label, which will eventually get resolved into an address by the assembler. This label marks the "start" of your "function" in the assembly code. In high-level code, when you "call" that function, what you're really doing is causing the CPU to jump to the address of that label and continue executing there.

In preparation for the jump, the compiler must do a bunch of important stuff. The calling convention is like a checklist that the compiler follows to do all this stuff:

  • First, the compiler inserts a little bit of assembly code to save the current address, so that when your "function" is done, the CPU can jump back to the right place and continue executing.
  • Next, the compiler generates assembly code to pass the arguments.
    • Some calling conventions dictate that arguments should be put on the stack (in a particular order of course).
    • Other conventions dictate that the arguments should be put in particular registers (depending on their data types of course).
    • Still other conventions dictate that a specific combination of stack and registers should be used.
  • Of course, if there was anything important in those registers before, those values are now overwritten and lost forever, so some calling conventions may dictate that the compiler should save some of those registers prior to putting the arguments in them.
  • Now the compiler inserts a jump instruction telling the CPU to go to that label it made previously (_MyFunction1:). At this point, you can consider the CPU to be "in" your "function".
  • At the end of the function, the compiler puts some assembly code that will make the CPU write the return value in the correct place. The calling convention will dictate whether the return value should be put into a particular register (depending on its type), or on the stack.
  • Now it's time for clean-up. The calling convention will dictate where the compiler places the cleanup assembly code.
    • Some conventions say that the caller must clean up the stack. This means that after the "function" is done and the CPU jumps back to where it was before, the very next code to be executed should be some very specific cleanup code.
    • Other conventions say that the some particular parts of the cleanup code should be at the end of the "function" before the jump back.

There are many different ABIs / calling conventions. Some main ones are:

  • For the x86 or x86-64 CPU (32-bit environment):
    • CDECL
    • STDCALL
    • FASTCALL
    • VECTORCALL
    • THISCALL
  • For the x86-64 CPU (64-bit environment):
    • SYSTEMV
    • MSNATIVE
    • VECTORCALL
  • For the ARM CPU (32-bit)
    • AAPCS
  • For the ARM CPU (64-bit)
    • AAPCS64

Here is a great page that actually shows the differences in the assembly generated when compiling for different ABIs.

Another thing to mention is that an ABI isn't only relevant inside your program's executable module. It's also used by the linker to make sure your program calls library functions correctly. You have multiple shared libraries running on your computer, and as long as your compiler knows what ABI they each use, it can call functions from them properly without blowing up the stack.

Your compiler understanding how to call library functions is extremely important. On a hosted platform (that is, one where an OS loads programs), your program can't even blink without making a kernel call.

What is <scope> under <dependency> in pom.xml for?

The <scope> element can take 6 values: compile, provided, runtime, test, system and import.

This scope is used to limit the transitivity of a dependency, and also to affect the classpath used for various build tasks.

compile

This is the default scope, used if none is specified. Compile dependencies are available in all classpaths of a project. Furthermore, those dependencies are propagated to dependent projects.

provided

This is much like compile, but indicates you expect the JDK or a container to provide the dependency at runtime. For example, when building a web application for the Java Enterprise Edition, you would set the dependency on the Servlet API and related Java EE APIs to scope provided because the web container provides those classes. This scope is only available on the compilation and test classpath, and is not transitive.

runtime

This scope indicates that the dependency is not required for compilation, but is for execution. It is in the runtime and test classpaths, but not the compile classpath.

test

This scope indicates that the dependency is not required for normal use of the application, and is only available for the test compilation and execution phases.

system

This scope is similar to provided except that you have to provide the JAR which contains it explicitly. The artifact is always available and is not looked up in a repository.

import (only available in Maven 2.0.9 or later)

This scope is only used on a dependency of type pom in the section. It indicates that the specified POM should be replaced with the dependencies in that POM's section. Since they are replaced, dependencies with a scope of import do not actually participate in limiting the transitivity of a dependency.

To answer the second part of your question:

How can we use it for running test?

Note that the test scope allows to use dependencies only for the test phase.

Read the documentation for full details.

MongoDB query multiple collections at once

One solution: add isAdmin: 0/1 flag to your post collection document.

Other solution: use DBrefs

jQuery: click function exclude children.

Here is an example. Green square is parent and yellow square is child element.

Hope that this helps.

_x000D_
_x000D_
var childElementClicked;_x000D_
_x000D_
$("#parentElement").click(function(){_x000D_
_x000D_
  $("#childElement").click(function(){_x000D_
     childElementClicked = true;_x000D_
  });_x000D_
_x000D_
  if( childElementClicked != true ) {_x000D_
_x000D_
   // It is clicked on parent but not on child._x000D_
      // Now do some action that you want._x000D_
      alert('Clicked on parent');_x000D_
   _x000D_
  }else{_x000D_
      alert('Clicked on child');_x000D_
    }_x000D_
    _x000D_
    childElementClicked = false;_x000D_
 _x000D_
});
_x000D_
#parentElement{_x000D_
width:200px;_x000D_
height:200px;_x000D_
background-color:green;_x000D_
position:relative;_x000D_
}_x000D_
_x000D_
#childElement{_x000D_
margin-top:50px;_x000D_
margin-left:50px;_x000D_
width:100px;_x000D_
height:100px;_x000D_
background-color:yellow;_x000D_
position:absolute;_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<div id="parentElement">_x000D_
  <div id="childElement">_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to create hyperlink to call phone number on mobile devices?

I used:

Tel: <a href="tel:+123 123456789">+123 123456789</a>

and the result is:

Tel: +123 123456789

Where "Tel:" stands for pure text and only the number is coded and clickable.

Why calling react setState method doesn't mutate the state immediately?

Watch out the react lifecycle methods!

I worked for several hours to find out that getDerivedStateFromProps will be called after every setState().

How can I change the value of the elements in a vector?

Well, you could always run a transform over the vector:

std::transform(v.begin(), v.end(), v.begin(), [mean](int i) -> int { return i - mean; });

You could always also devise an iterator adapter that returns the result of an operation applied to the dereference of its component iterator when it's dereferenced. Then you could just copy the vector to the output stream:

std::copy(adapter(v.begin(), [mean](int i) -> { return i - mean; }), v.end(), std::ostream_iterator<int>(cout, "\n"));

Or, you could use a for loop...but that's kind of boring.

AngularJS: How to clear query parameters in the URL?

At the time of writing, and as previously mentioned by @Bosh, html5mode must be true in order to be able to set $location.search() and have it be reflected back into the window’s visual URL.

See https://github.com/angular/angular.js/issues/1521 for more info.

But if html5mode is true you can easily clear the URL’s query string with:

$location.search('');

or

$location.search({});

This will also alter the window’s visual URL.

(Tested in AngularJS version 1.3.0-rc.1 with html5Mode(true).)

Running windows shell commands with python

Simple Import os package and run below command.

import os
os.system("python test.py")

Initialize empty vector in structure - c++

Both std::string and std::vector<T> have constructors initializing the object to be empty. You could use std::vector<unsigned char>() but I'd remove the initializer.

Integration Testing POSTing an entire object to Spring MVC controller

Another way to solve with Reflection, but without marshalling:

I have this abstract helper class:

public abstract class MvcIntegrationTestUtils {

       public static MockHttpServletRequestBuilder postForm(String url,
                 Object modelAttribute, String... propertyPaths) {

              try {
                     MockHttpServletRequestBuilder form = post(url).characterEncoding(
                           "UTF-8").contentType(MediaType.APPLICATION_FORM_URLENCODED);

                     for (String path : propertyPaths) {
                            form.param(path, BeanUtils.getProperty(modelAttribute, path));
                     }

                     return form;

              } catch (Exception e) {
                     throw new RuntimeException(e);
              }
     }
}

You use it like this:

// static import (optional)
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;

// in your test method, populate your model attribute object (yes, works with nested properties)
BlogSetup bgs = new BlogSetup();
      bgs.getBlog().setBlogTitle("Test Blog");
      bgs.getUser().setEmail("[email protected]");
    bgs.getUser().setFirstName("Administrator");
      bgs.getUser().setLastName("Localhost");
      bgs.getUser().setPassword("password");

// finally put it together
mockMvc.perform(
            postForm("/blogs/create", bgs, "blog.blogTitle", "user.email",
                    "user.firstName", "user.lastName", "user.password"))
            .andExpect(status().isOk())

I have deduced it is better to be able to mention the property paths when building the form, since I need to vary that in my tests. For example, I might want to check if I get a validation error on a missing input and I'll leave out the property path to simulate the condition. I also find it easier to build my model attributes in a @Before method.

The BeanUtils is from commons-beanutils:

    <dependency>
        <groupId>commons-beanutils</groupId>
        <artifactId>commons-beanutils</artifactId>
        <version>1.8.3</version>
        <scope>test</scope>
    </dependency>

How to extract text from an existing docx file using python-docx

Without Installing python-docx

docx is basically is a zip file with several folders and files within it. In the link below you can find a simple function to extract the text from docx file, without the need to rely on python-docx and lxml the latter being sometimes hard to install:

http://etienned.github.io/posts/extract-text-from-word-docx-simply/

MySQL vs MongoDB 1000 reads

On Single Server, MongoDb would not be any faster than mysql MyISAM on both read and write, given table/doc sizes are small 1 GB to 20 GB.
MonoDB will be faster on Parallel Reduce on Multi-Node clusters, where Mysql can NOT scale horizontally.

Biggest advantage to using ASP.Net MVC vs web forms

You don't feel bad about using 'non post-back controls' anymore - and figuring how to smush them into a traditional asp.net environment.

This means that modern (free to use) javascript controls such this or this or this can all be used without that trying to fit a round peg in a square hole feel.

How to change the Title of the window in Qt?

I know this is years later but I ran into the same problem. The solution I found was to change the window title in main.cpp. I guess once the w.show(); is called the window title can no longer be changed. In my case I just wanted the title to reflect the current directory and it works.

int main(int argc, char *argv[]) 
{
QApplication a(argc, argv);
MainWindow w;
w.setWindowTitle(QDir::currentPath());
w.show();

return a.exec();
}

JavaScript: remove event listener

You could use a named function expression (in this case the function is named abc), like so:

let click = 0;
canvas.addEventListener('click', function abc(event) {
    click++;
    if (click >= 50) {
        // remove event listener function `abc`
        canvas.removeEventListener('click', abc);
    }
    // More code here ...
}

Quick and dirty working example: http://jsfiddle.net/8qvdmLz5/2/.

More information about named function expressions: http://kangax.github.io/nfe/.

How to stop java process gracefully?

Here is a bit tricky, but portable solution:

  • In your application implement a shutdown hook
  • When you want to shut down your JVM gracefully, install a Java Agent that calls System.exit() using the Attach API.

I implemented the Java Agent. It is available on Github: https://github.com/everit-org/javaagent-shutdown

Detailed description about the solution is available here: https://everitorg.wordpress.com/2016/06/15/shutting-down-a-jvm-process/

Linux command to check if a shell script is running or not

Give an option to ps to display all the processes, an example is:

ps -A | grep "myshellscript.sh"

Check http://www.cyberciti.biz/faq/show-all-running-processes-in-linux/ for more info

And as Basile Starynkevitch mentioned in the comment pgrep is another solution.

console.log not working in Angular2 Component (Typescript)

Also try to update your browser because Angular need latest browser. check: https://angular.io/guide/browser-support

I fixed console.log issue after updating latest browser.

How to ping an IP address

You can not simply ping in Java as it relies on ICMP, which is sadly not supported in Java

http://mindprod.com/jgloss/ping.html

Use sockets instead

Hope it helps

set height of imageview as matchparent programmatically

You can use the MATCH_PARENT constant or its numeric value -1.

In CSS Flexbox, why are there no "justify-items" and "justify-self" properties?

The justify-self and justify-items properties are not implemented in flexbox. This is due to the one-dimensional nature of flexbox, and that there may be multiple items along the axis, making it impossible to justify a single item. To align items along the main, inline axis in flexbox you use the justify-content property.

Reference: Box alignment in CSS Grid Layout

How do I access my SSH public key?

cat ~/.ssh/id_rsa.pub or cat ~/.ssh/id_dsa.pub

You can list all the public keys you have by doing:

$ ls ~/.ssh/*.pub

What is the difference between ( for... in ) and ( for... of ) statements?

Another difference between the two loops, which nobody has mentioned before:

Destructuring for...in is deprecated. Use for...of instead.

Source

So if we want to use destructuring in a loop, for get both index and value of each array element, we should to use the for...of loop with the Array method entries():

for (const [idx, el] of arr.entries()) {
    console.log( idx + ': ' + el );
}

Why does this iterative list-growing code give IndexError: list assignment index out of range?

You could also use a list comprehension:

j = [l for l in i]

or make a copy of it using the statement:

j = i[:]

Codeigniter unset session

I use the old PHP way..It unsets all session variables and doesn't require to specify each one of them in an array. And after unsetting the variables we destroy the session.

session_unset();
session_destroy();

Using sed to split a string with a delimiter

Using simply :

$ tr ':' $'\n' <<< string1:string2:string3:string4:string5
string1
string2
string3
string4
string5

If you really need :

$ sed 's/:/\n/g' <<< string1:string2:string3:string4:string5
string1
string2
string3
string4
string5

Creating a JavaScript cookie on a domain and reading it across sub domains

You want:

document.cookie = cookieName +"=" + cookieValue + ";domain=.example.com;path=/;expires=" + myDate;

As per the RFC 2109, to have a cookie available to all subdomains, you must put a . in front of your domain.

Setting the path=/ will have the cookie be available within the entire specified domain(aka .example.com).

Maximum call stack size exceeded on npm install

npm cache clean returns below message

As of npm@5, the npm cache self-heals from corruption issues and data extracted from the cache is guaranteed to be valid. If you want to make sure everything is consistent, use 'npm cache verify' instead. On the other hand, if you're debugging an issue with the installer, you can use npm install --cache /tmp/empty-cache to use a temporary cache instead of nuking the actual one.

If you run npm cache verify, as specified above, then it actually runs cache verification and garbage collection which fixes the problem.

Cache verified and compressed (~\AppData\Roaming\npm-cache_cacache): Content verified: 6183 (447214684 bytes) Content garbage-collected: 16 (653745 bytes) Index entries: 9633

Disable browser 'Save Password' functionality

Another solution is to make the POST using an hidden form where all the input are of type hidden. The visible form will use input of type "password". The latter form will never be submitted and so the browser can't intercept at all the operation of login.

How can I create a text box for a note in markdown?

Here's a simple latex-based example.

---
header-includes:
    - \usepackage[most]{tcolorbox}
    - \definecolor{light-yellow}{rgb}{1, 0.95, 0.7}
    - \newtcolorbox{myquote}{colback=light-yellow,grow to right by=-10mm,grow to left by=-10mm, boxrule=0pt,boxsep=0pt,breakable}
    - \newcommand{\todo}[1]{\begin{myquote} \textbf{TODO:} \emph{#1} \end{myquote}}
---

blah blah

\todo{something}

blah

which results in: enter image description here

Unfortunately because this is latex, you can no-longer include markdown inside the TODO box (which is not a huge problem, usually), and it won't work when converting to formats other than PDF (e.g. html).

CSS class for pointer cursor

As of June 2020, adding role='button' to any HTML tag would add cursor: "pointer" to the element styling.

<span role="button">Non-button element button</span>

Official discussion on this feature - https://github.com/twbs/bootstrap/issues/23709

Documentation link - https://getbootstrap.com/docs/4.5/content/reboot/#pointers-on-buttons

How to make a vertical SeekBar in Android?

This worked for me, just put it into any layout you want to.

<FrameLayout
    android:layout_width="32dp"
    android:layout_height="192dp">

    <SeekBar
        android:layout_width="192dp"
        android:layout_height="32dp"
        android:layout_gravity="center"
        android:rotation="270" />

</FrameLayout>

Google server putty connect 'Disconnected: No supported authentication methods available (server sent: publickey)

This problem mainly caused by your connected username not have the access to the shell in GCE. So you use the following steps to solve this issue.

gcloud auth list

If you are using the correct login. please follow the below steps. otherwise use

gcloud auth revoke --all
gcloud auth login [your-iam-user]

and you get the token or it automatically detect the token.

gcloud compute --project "{projectid}" ssh --zone "{zone_name}" "{instance_name}" .

if you dont know this above line click to compute engine-> ssh dropdown arrow-> view google command-> copy that code and use it

Now it update your metadata and it is available in your computer's folder Users->username

~/.ssh/google_compute_engine.ppk
~/.ssh/google_compute_engine.pub

Then you create a new ppk file using puttygen and you give the username, which you want like my_work_space. Then save the publickey and privatekey in a folder.

Next step: Copy the public key data from puttygen and create new ssh key in gcloud metadata

cloud console ->compute engine->metadata->ssh key->add new item->paste the key and save it

and now return your shell commandline tool then enter

sudo chown -R my_work_space /home/my_work_space

now you connect this private key using sftp to anywhere. and it opens the files without showing the permission errors

:) happy hours.

How to set default value to all keys of a dict object in python?

In case you actually mean what you seem to ask, I'll provide this alternative answer.

You say you want the dict to return a specified value, you do not say you want to set that value at the same time, like defaultdict does. This will do so:

class DictWithDefault(dict):
    def __init__(self, default, **kwargs):
        self.default = default
        super(DictWithDefault, self).__init__(**kwargs)

    def __getitem__(self, key):
        if key in self:
            return super(DictWithDefault, self).__getitem__(key)
        return self.default

Use like this:

d = DictWIthDefault(99, x=5, y=3)
print d["x"]   # 5
print d[42]    # 99
42 in d        # False
d[42] = 3
42 in d        # True

Alternatively, you can use a standard dict like this:

d = {3: 9, 4: 2}
default = 99
print d.get(3, default)  # 9
print d.get(42, default) # 99

How to remove outliers in boxplot in R?

See ?boxplot for all the help you need.

 outline: if ‘outline’ is not true, the outliers are not drawn (as
          points whereas S+ uses lines).

boxplot(x,horizontal=TRUE,axes=FALSE,outline=FALSE)

And for extending the range of the whiskers and suppressing the outliers inside this range:

   range: this determines how far the plot whiskers extend out from the
          box.  If ‘range’ is positive, the whiskers extend to the most
          extreme data point which is no more than ‘range’ times the
          interquartile range from the box. A value of zero causes the
          whiskers to extend to the data extremes.

# change the value of range to change the whisker length
boxplot(x,horizontal=TRUE,axes=FALSE,range=2)

Jquery: how to trigger click event on pressing enter key

Just include preventDefault() function in the code,

$("#txtSearchProdAssign").keydown(function (e) 
{
   if (e.keyCode == 13) 
   {
       e.preventDefault();
       $('input[name = butAssignProd]').click();
   }
});

ImportError: cannot import name

Instead of using local imports, you may import the entire module instead of the particular object. Then, in your app module, call mod_login.mod_login

app.py

from flask import Flask
import mod_login

# ...

do_stuff_with(mod_login.mod_login)

mod_login.py

from app import app

mod_login = something

Unable to locate tools.jar

A JRE doesn't have a tools.jar, you need a JDK. Set your JAVA_HOME and PATH variables so that they point to a JDK, not a JRE.

Installing MySQL in Docker fails with error message "Can't connect to local MySQL server through socket"

In my case I tried to connect to DB (which was inside docker) like this:

mysql -ppass -u root

but got same error as OP.

Specifying host and port helped:

mysql --host 0.0.0.0 --port 3306 -ppass -u root

how to change text in Android TextView

@user264892

I found that when using a String variable I needed to either prefix with an String of "" or explicitly cast to CharSequence.

So instead of:

String Status = "Asking Server...";
txtStatus.setText(Status);

try:

String Status = "Asking Server...";
txtStatus.setText((CharSequence) Status);

or:

String Status = "Asking Server...";    
txtStatus.setText("" + Status);

or, since your string is not dynamic, even better:

txtStatus.setText("AskingServer...");

Specify the from user when sending email using the mail command

None of the above worked for me. And it took me long to figure it out, hopefully this helps the next guy.

I'm using Ubuntu 12.04 LTS with mailutils v2.1.

I found this solutions somewhere on the net, don't know where, can't find it again:

-aFrom:[email protected]

Full Command used:

cat /root/Reports/ServerName-Report-$DATE.txt | mail -s "Server-Name-Report-$DATE" [email protected] -aFrom:[email protected]

How to debug on a real device (using Eclipse/ADT)

in devices which has Android 4.3 and above you should follow these steps:

How to enable Developer Options:

Launch Settings menu.
Find the open the ‘About Device’ menu.
Scroll down to ‘Build Number’.
Next, tap on the ‘build number’ section seven times.
After the seventh tap you will be told that you are now a developer.
Go back to Settings menu and the Developer Options menu will now be displayed.

In order to enable the USB Debugging you will simply need to open Developer Options, scroll down and tick the box that says ‘USB Debugging’. That’s it.

Docker: How to delete all local Docker images

To delete all images:

docker rmi -f $(docker images -a | awk {'print $3'})

Explanation:

docker images -a | awk {'print $3'}

This command will return all image id's and then used to delete image using its id.

Switching a DIV background image with jQuery

If you use a CSS sprite for the background images, you could bump the background offset +/- n pixels depending on whether you were expanding or collapsing. Not a toggle, but closer to it than having to switch background image URLs.

Why does Maven have such a bad rep?

It deserves the reputation it has got. Not everyone needs the rigid structure that Maven's developers thought is appropriate for every single project. It is so inflexible. And what is 'Pro' for many people, the dependency management, is IMHO its biggest 'con'. I am absolutely not comfortable with maven downloading the jars from the network and lose my sleep over incompatibilities (yea, the offline mode exists, but then why should I have all those hundreds of xml files and checksums). I decide which libraries I use and many projects have serious concerns about builds dependant on network connection.

Further worse, when things do not work, you are absolutely lost. The documentation sucks, the community is clueless.

Getting first value from map in C++

You can use the iterator that is returned by the begin() method of the map template:

std::map<K,V> myMap;
std::pair<K,V> firstEntry = *myMap.begin()

But remember that the std::map container stores its content in an ordered way. So the first entry is not always the first entry that has been added.

Github "Updates were rejected because the remote contains work that you do not have locally."

The issue is because the local is not up-to-date with the master branch that is why we are supposed to pull the code before pushing it to the git

git add .
git commit -m 'Comments to be added'
git pull origin master
git push origin master

Meaning of .Cells(.Rows.Count,"A").End(xlUp).row

[A1].End(xlUp)
[A1].End(xlDown)
[A1].End(xlToLeft)
[A1].End(xlToRight)

is the VBA equivalent of being in Cell A1 and pressing Ctrl + Any arrow key. It will continue to travel in that direction until it hits the last cell of data, or if you use this command to move from a cell that is the last cell of data it will travel until it hits the next cell containing data.

If you wanted to find that last "used" cell in Column A, you could go to A65536 (for example, in an XL93-97 workbook) and press Ctrl + Up to "snap" to the last used cell. Or in VBA you would write:

Range("A65536").End(xlUp) which again can be re-written as Range("A" & Rows.Count).End(xlUp) for compatibility reasons across workbooks with different numbers of rows.

Get top most UIViewController

in SWIFT 5.2

you can use underneath code:

import UIKit

extension UIWindow {
    static func getTopViewController() -> UIViewController? {
        if #available(iOS 13, *){
            let keyWindow = UIApplication.shared.windows.filter {$0.isKeyWindow}.first
            
            if var topController = keyWindow?.rootViewController {
                while let presentedViewController = topController.presentedViewController {
                    topController = presentedViewController
                }
                return topController
            }
        } else {
            if var topController = UIApplication.shared.keyWindow?.rootViewController {
                while let presentedViewController = topController.presentedViewController {
                    topController = presentedViewController
                }
                return topController
            }
        }
        return nil
    }
}

How do I call the base class constructor?

There is no super() in C++. You have to call the Base Constructor explicitly by name.

How to convert SQL Server's timestamp column to datetime format

Using cast you can get date from a timestamp field:

SELECT CAST(timestamp_field AS DATE) FROM tbl_name

How to make a drop down list in yii2?

Have a look this:

use yii\helpers\ArrayHelper; // load classes
use app\models\Course;
    .....
$dataList=ArrayHelper::map(Course::find()->asArray()->all(), 'id', 'name');
<?=$form->field($model, 'center_id')->dropDownList($dataList, 
         ['prompt'=>'-Choose a Course-']) ?>

Change icons of checked and unchecked for Checkbox for Android

Kind of a mix:

Set it in your layout file :-

 <CheckBox android:layout_width="wrap_content"
           android:layout_height="wrap_content" 
           android:text="new checkbox"
           android:background="@drawable/checkbox_background" 
           android:button="@drawable/checkbox" />

where the @drawable/checkbox will look like:

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

<selector xmlns:android="http://schemas.android.com/apk/res/android">
 <item android:state_checked="true" android:state_focused="true"
  android:drawable="@drawable/checkbox_on_background_focus_yellow" />
 <item android:state_checked="false" android:state_focused="true"
  android:drawable="@drawable/checkbox_off_background_focus_yellow" />
 <item android:state_checked="false"
  android:drawable="@drawable/checkbox_off_background" />
 <item android:state_checked="true"
  android:drawable="@drawable/checkbox_on_background" />
</selector>

Printing column separated by comma using Awk command line

If your only requirement is to print the third field of every line, with each field delimited by a comma, you can use cut:

cut -d, -f3 file
  • -d, sets the delimiter to a comma
  • -f3 specifies that only the third field is to be printed

Asp Net Web API 2.1 get client IP address

If you're self-hosting with Asp.Net 2.1 using the OWIN Self-host NuGet package you can use the following code:

 private string getClientIp(HttpRequestMessage request = null)
    {
        if (request == null)
        {
            return null;
        }

        if (request.Properties.ContainsKey("MS_OwinContext"))
        {
            return ((OwinContext) request.Properties["MS_OwinContext"]).Request.RemoteIpAddress;
        }
        return null;
    }

How to echo or print an array in PHP?

This will do

foreach($results['data'] as $result) {
    echo $result['type'], '<br>';
}

How do I remove all non alphanumeric characters from a string except dash?

There is a much easier way with Regex.

private string FixString(string str)
{
    return string.IsNullOrEmpty(str) ? str : Regex.Replace(str, "[\\D]", "");
}

How to edit an Android app?

Generally speaking, a software product isn't your "property already", as you said in the comment. Most of the times (I won't be irresponsible to say anything in open), it's licensed to you. A license to use some thing is not the same thing as owning (property rights) that very same thing.

That's because there are authorship, copyright, intellectual property rights applicable to it. I don't know how things work in United States (or in your country), but it's generally accepted that the work of a mind, a creative work, must not be changed in its nature as such to make the expression of art to be different than that expression that the author intended. That applies for example, in some cases, to architectural work (in most countries, you can't change the appearance of a building to "desfigure" the work of art of the architect, without his prior consent). Exceptions are made, obviously, when the author expressly authorizes such changes (e.g., Creative Commons licenses, open source licenses etc.).

Anyway, that's why you see in most EULAs the typical sentence: "this software is licensed, not sold". That's the purpose and reason why.

Now that you understand the reasons why you can't wander around changing other people's art, let me be technical.

There are possible ways to decompile Java programs. You can use dex2jar, it provides a somewhat good start for you to start looking for things and changes. And perhaps rebuild the code by mounting back the pieces together. Good luck, as most people obfuscate their codes to make that harder.

However, let me say that it's still forbidden to change programs, as I said above. And it's extremely unethical. It makes me sad that people do that with no scruples (not saying it's your case, just warning you). It shouldn't need people to be at the other side to understand that. Or maybe that's just me, who lives in a country where piracy is rampant.

The tools are always out there. But the conscience, unfortunately, not always.

edit: in case it isn't clear enough already, I do NOT approve the use of these programs. I use them myself to check how hard my own applications are to be reverse engineered. But I also think that explaning is always better than denial (better be here).

AttributeError: 'module' object has no attribute 'urlretrieve'

As you're using Python 3, there is no urllib module anymore. It has been split into several modules.

This would be equivalent to urlretrieve:

import urllib.request
data = urllib.request.urlretrieve("http://...")

urlretrieve behaves exactly the same way as it did in Python 2.x, so it'll work just fine.

Basically:

  • urlretrieve saves the file to a temporary file and returns a tuple (filename, headers)
  • urlopen returns a Request object whose read method returns a bytestring containing the file contents

How to convert Map keys to array?

I need something similiar with angular reactive form:

let myMap = new Map().set(0, {status: 'VALID'}).set(1, {status: 'INVALID'});
let mapToArray = Array.from(myMap.values());
let isValid = mapToArray.every(x => x.status === 'VALID');

How to escape the equals sign in properties files

Moreover, Please refer to load(Reader reader) method from Property class on javadoc

In load(Reader reader) method documentation it says

The key contains all of the characters in the line starting with the first non-white space character and up to, but not including, the first unescaped '=', ':', or white space character other than a line terminator. All of these key termination characters may be included in the key by escaping them with a preceding backslash character; for example,

\:\=

would be the two-character key ":=". Line terminator characters can be included using \r and \n escape sequences. Any white space after the key is skipped; if the first non-white space character after the key is '=' or ':', then it is ignored and any white space characters after it are also skipped. All remaining characters on the line become part of the associated element string; if there are no remaining characters, the element is the empty string "". Once the raw character sequences constituting the key and element are identified, escape processing is performed as described above.

Hope that helps.

How to determine the first and last iteration in a foreach loop?

The most efficient answer from @morg, unlike foreach, only works for proper arrays, not hash map objects. This answer avoids the overhead of a conditional statement for every iteration of the loop, as in most of these answers (including the accepted answer) by specifically handling the first and last element, and looping over the middle elements.

The array_keys function can be used to make the efficient answer work like foreach:

$keys = array_keys($arr);
$numItems = count($keys);
$i=0;

$firstItem=$arr[$keys[0]];

# Special handling of the first item goes here

$i++;
while($i<$numItems-1){
    $item=$arr[$keys[$i]];
    # Handling of regular items
    $i++;
}

$lastItem=$arr[$keys[$i]];

# Special handling of the last item goes here

$i++;

I haven't done benchmarking on this, but no logic has been added to the loop, which is were the biggest hit to performance happens, so I'd suspect that the benchmarks provided with the efficient answer are pretty close.

If you wanted to functionalize this kind of thing, I've taken a swing at such an iterateList function here. Although, you might want to benchmark the gist code if you're super concerned about efficiency. I'm not sure how much overhead all the function invocation introduces.

Why does JPA have a @Transient annotation?

If you just want a field won't get persisted, both transient and @Transient work. But the question is why @Transient since transient already exists.

Because @Transient field will still get serialized!

Suppose you create a entity, doing some CPU-consuming calculation to get a result and this result will not save in database. But you want to sent the entity to other Java applications to use by JMS, then you should use @Transient, not the JavaSE keyword transient. So the receivers running on other VMs can save their time to re-calculate again.

Php artisan make:auth command is not defined

In short and precise, all you need to do is

composer require laravel/ui --dev

php artisan ui vue --auth and then the migrate php artisan migrate.

Just for an overview of Laravel Authentication

Laravel Authentication facilities comes with Guard and Providers, Guards define how users are authenticated for each request whereas Providers define how users are retrieved from you persistent storage.

Database Consideration - By default Laravel includes an App\User Eloquent Model in your app directory.

Auth Namespace - App\Http\Controllers\Auth

Controllers - RegisterController, LoginController, ForgotPasswordController and ResetPasswordController, all names are meaningful and easy to understand!

Routing - Laravel/ui package provides a quick way to scaffold all the routes and views you need for authentication using a few simple commands (as mentioned in the start instead of make:auth).

You can disable any newly created controller, e. g. RegisterController and modify your route declaration like, Auth::routes(['register' => false]); For further detail please look into the Laravel Documentation.

How can I reverse the order of lines in a file?

Also worth mentioning: tac (the, ahem, reverse of cat). Part of coreutils.

Flipping one file into another

tac a.txt > b.txt

How to escape double quotes in a title attribute

The escape code &#34; can also be used instead of &quot;.

Set a persistent environment variable from cmd.exe

Use the SETX command (note the 'x' suffix) to set variables that persist after the cmd window has been closed.

For example, to set an env var "foo" with value of "bar":

setx foo bar

Though it's worth reading the 'notes' that are displayed if you print the usage (setx /?), in particular:

2) On a local system, variables created or modified by this tool will be available in future command windows but not in the current CMD.exe command window.

3) On a remote system, variables created or modified by this tool will be available at the next logon session.

In PowerShell, the [Environment]::SetEnvironmentVariable command.

What's the difference between interface and @interface in java?

The @ symbol denotes an annotation type definition.

That means it is not really an interface, but rather a new annotation type -- to be used as a function modifier, such as @override.

See this javadocs entry on the subject.

How to change column width in DataGridView?

You could set the width of the abbrev column to a fixed pixel width, then set the width of the description column to the width of the DataGridView, minus the sum of the widths of the other columns and some extra margin (if you want to prevent a horizontal scrollbar from appearing on the DataGridView):

dataGridView1.Columns[1].Width = 108;  // or whatever width works well for abbrev
dataGridView1.Columns[2].Width = 
    dataGridView1.Width 
    - dataGridView1.Columns[0].Width 
    - dataGridView1.Columns[1].Width 
    - 72;  // this is an extra "margin" number of pixels

If you wanted the description column to always take up the "remainder" of the width of the DataGridView, you could put something like the above code in a Resize event handler of the DataGridView.

SQL Server loop - how do I loop through a set of records

This is what I've been doing if you need to do something iterative... but it would be wise to look for set operations first. Also, do not do this because you don't want to learn cursors.

select top 1000 TableID
into #ControlTable 
from dbo.table
where StatusID = 7

declare @TableID int

while exists (select * from #ControlTable)
begin

    select top 1 @TableID = TableID
    from #ControlTable
    order by TableID asc

    -- Do something with your TableID

    delete #ControlTable
    where TableID = @TableID

end

drop table #ControlTable

Best way to represent a fraction in Java?

Once you've created a fraction object why would you want to allow other objects to set the numerator or the denominator? I would think these should be read only. It makes the object immutable...

Also...setting the denominator to zero should throw an invalid argument exception (I don't know what it is in Java)

How to add a default "Select" option to this ASP.NET DropDownList control?

If you want to make the first item unselectable, try this:

DropDownList1.Items.Insert(0, new ListItem("Select", "-1"));
DropDownList1.Items[0].Attributes.Add("disabled", "disabled");

how to concatenate two dictionaries to create a new one in Python?

Here's a one-liner (imports don't count :) that can easily be generalized to concatenate N dictionaries:

Python 3

from itertools import chain
dict(chain.from_iterable(d.items() for d in (d1, d2, d3)))

and:

from itertools import chain
def dict_union(*args):
    return dict(chain.from_iterable(d.items() for d in args))

Python 2.6 & 2.7

from itertools import chain
dict(chain.from_iterable(d.iteritems() for d in (d1, d2, d3))

Output:

>>> from itertools import chain
>>> d1={1:2,3:4}
>>> d2={5:6,7:9}
>>> d3={10:8,13:22}
>>> dict(chain.from_iterable(d.iteritems() for d in (d1, d2, d3)))
{1: 2, 3: 4, 5: 6, 7: 9, 10: 8, 13: 22}

Generalized to concatenate N dicts:

from itertools import chain
def dict_union(*args):
    return dict(chain.from_iterable(d.iteritems() for d in args))

I'm a little late to this party, I know, but I hope this helps someone.

Change tab bar tint color on iOS 7

Try the below:

[[UITabBar appearance] setTintColor:[UIColor redColor]];
[[UITabBar appearance] setBarTintColor:[UIColor yellowColor]];

To tint the non active buttons, put the below code in your VC's viewDidLoad:

UITabBarItem *tabBarItem = [yourTabBarController.tabBar.items objectAtIndex:0];

UIImage *unselectedImage = [UIImage imageNamed:@"icon-unselected"];
UIImage *selectedImage = [UIImage imageNamed:@"icon-selected"];

[tabBarItem setImage: [unselectedImage imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal]];
[tabBarItem setSelectedImage: selectedImage];

You need to do this for all the tabBarItems, and yes I know it is ugly and hope there will be cleaner way to do this.

Swift:

UITabBar.appearance().tintColor = UIColor.red

tabBarItem.image = UIImage(named: "unselected")?.withRenderingMode(.alwaysOriginal)
tabBarItem.selectedImage = UIImage(named: "selected")?.withRenderingMode(.alwaysOriginal)

How can I get the client's IP address in ASP.NET MVC?

I had trouble using the above, and I needed the IP address from a controller. I used the following in the end:

System.Web.HttpContext.Current.Request.UserHostAddress

How can I get an object's absolute position on the page in Javascript?

I would definitely suggest using element.getBoundingClientRect().

https://developer.mozilla.org/en-US/docs/Web/API/element.getBoundingClientRect

Summary

Returns a text rectangle object that encloses a group of text rectangles.

Syntax

var rectObject = object.getBoundingClientRect();

Returns

The returned value is a TextRectangle object which is the union of the rectangles returned by getClientRects() for the element, i.e., the CSS border-boxes associated with the element.

The returned value is a TextRectangle object, which contains read-only left, top, right and bottom properties describing the border-box, in pixels, with the top-left relative to the top-left of the viewport.

Here's a browser compatibility table taken from the linked MDN site:

+---------------+--------+-----------------+-------------------+-------+--------+
|    Feature    | Chrome | Firefox (Gecko) | Internet Explorer | Opera | Safari |
+---------------+--------+-----------------+-------------------+-------+--------+
| Basic support | 1.0    | 3.0 (1.9)       | 4.0               | (Yes) | 4.0    |
+---------------+--------+-----------------+-------------------+-------+--------+

It's widely supported, and is really easy to use, not to mention that it's really fast. Here's a related article from John Resig: http://ejohn.org/blog/getboundingclientrect-is-awesome/

You can use it like this:

var logo = document.getElementById('hlogo');
var logoTextRectangle = logo.getBoundingClientRect();

console.log("logo's left pos.:", logoTextRectangle.left);
console.log("logo's right pos.:", logoTextRectangle.right);

Here's a really simple example: http://jsbin.com/awisom/2 (you can view and edit the code by clicking "Edit in JS Bin" in the upper right corner).

Or here's another one using Chrome's console: Using element.getBoundingClientRect() in Chrome

Note:

I have to mention that the width and height attributes of the getBoundingClientRect() method's return value are undefined in Internet Explorer 8. It works in Chrome 26.x, Firefox 20.x and Opera 12.x though. Workaround in IE8: for width, you could subtract the return value's right and left attributes, and for height, you could subtract bottom and top attributes (like this).

Getting ssh to execute a command in the background on target machine

Redirect fd's

Output needs to be redirected with &>/dev/null which redirects both stderr and stdout to /dev/null and is a synonym of >/dev/null 2>/dev/null or >/dev/null 2>&1.

Parantheses

The best way is to use sh -c '( ( command ) & )' where command is anything.

ssh askapache 'sh -c "( ( nohup chown -R ask:ask /www/askapache.com &>/dev/null ) & )"'

Nohup Shell

You can also use nohup directly to launch the shell:

ssh askapache 'nohup sh -c "( ( chown -R ask:ask /www/askapache.com &>/dev/null ) & )"'

Nice Launch

Another trick is to use nice to launch the command/shell:

ssh askapache 'nice -n 19 sh -c "( ( nohup chown -R ask:ask /www/askapache.com &>/dev/null ) & )"'

Can I use return value of INSERT...RETURNING in another INSERT?

You can use the lastval() function:

Return value most recently obtained with nextval for any sequence

So something like this:

INSERT INTO Table1 (name) VALUES ('a_title');
INSERT INTO Table2 (val)  VALUES (lastval());

This will work fine as long as no one calls nextval() on any other sequence (in the current session) between your INSERTs.

As Denis noted below and I warned about above, using lastval() can get you into trouble if another sequence is accessed using nextval() between your INSERTs. This could happen if there was an INSERT trigger on Table1 that manually called nextval() on a sequence or, more likely, did an INSERT on a table with a SERIAL or BIGSERIAL primary key. If you want to be really paranoid (a good thing, they really are you to get you after all), then you could use currval() but you'd need to know the name of the relevant sequence:

INSERT INTO Table1 (name) VALUES ('a_title');
INSERT INTO Table2 (val)  VALUES (currval('Table1_id_seq'::regclass));

The automatically generated sequence is usually named t_c_seq where t is the table name and c is the column name but you can always find out by going into psql and saying:

=> \d table_name;

and then looking at the default value for the column in question, for example:

id | integer | not null default nextval('people_id_seq'::regclass)

FYI: lastval() is, more or less, the PostgreSQL version of MySQL's LAST_INSERT_ID. I only mention this because a lot of people are more familiar with MySQL than PostgreSQL so linking lastval() to something familiar might clarify things.

Error in installation a R package

The solution indicated by Guannan Shen has one drawback that usually goes unnoticed.

When you run sudo R in order to run install.packages() as superuser, the directories in which you install the library end up belonging to root user, a.k.a., the superuser.

So, next time you need to update your libraries, you will not remember that you ran sudo, therefore leaving root as the owner of the files and directories; that eventually causes the error when trying to move files, because no one can overwrite root but themself.

That can be averted by running

sudo chown -R yourusername:yourusername *

in the directory lib that contains your local libraries, replacing yourusername by the adequated value in your installation. Then you try installing once again.

Jquery how to find an Object by attribute in an Array

I have created a util service for my angular application. It have two function which use very often.

For example you have object.

First getting value from object recursively without throwing undefined error.

{prop: { nestedProp1: {nestedProp2: somevalue}}}; get nestedProp2 2 without undefined checks.

Second filter array on basis

[{prop: { nestedProp1: {nestedProp2: somevalue1}}}, {prop: { nestedProp1: {nestedProp2: somevalue2}}}];

Find object from array with nestedProp2=somevalue2

app.service('UtilService', function(httpService) {
this.mapStringKeyVal = function(map, field) {
    var lastIdentifiedVal = null;
    var parentVal = map;
    field.split('.').forEach(function(val){
        if(parentVal[val]){
            lastIdentifiedVal = parentVal[val]; 
            parentVal = parentVal[val]; 
        }
    });
    return lastIdentifiedVal;
}


this.arrayPropFilter = function(array, field,value) {
    var lastIdentifiedVal = null;
    var mapStringKeyVal = this.mapStringKeyVal;
    array.forEach(function(arrayItem){
        var valueFound = mapStringKeyVal(arrayItem,field);
        if(!lastIdentifiedVal  && valueFound && valueFound==value){
            lastIdentifiedVal = arrayItem;
        }
    });
    return lastIdentifiedVal;
}});

For solution for current question. inject UtilService and call,

UtilService.arrayPropFilter(purposeArray,'purpose','daily');

Or more advanced

UtilService.arrayPropFilter(purposeArray,'purpose.nestedProp1.nestedProp2','daily');

Regex to validate password strength

I would suggest adding

(?!.*pass|.*word|.*1234|.*qwer|.*asdf) exclude common passwords

Missing visible-** and hidden-** in Bootstrap v4

The hidden-* and visible-* classes no longer exist in Bootstrap 4. The same fucntion can be achieved in Bootstrap 4 by using the d-* for the specific tiers.

In Python, how to check if a string only contains certain characters?

EDIT: Changed the regular expression to exclude A-Z

Regular expression solution is the fastest pure python solution so far

reg=re.compile('^[a-z0-9\.]+$')
>>>reg.match('jsdlfjdsf12324..3432jsdflsdf')
True
>>> timeit.Timer("reg.match('jsdlfjdsf12324..3432jsdflsdf')", "import re; reg=re.compile('^[a-z0-9\.]+$')").timeit()
0.70509696006774902

Compared to other solutions:

>>> timeit.Timer("set('jsdlfjdsf12324..3432jsdflsdf') <= allowed", "import string; allowed = set(string.ascii_lowercase + string.digits + '.')").timeit()
3.2119350433349609
>>> timeit.Timer("all(c in allowed for c in 'jsdlfjdsf12324..3432jsdflsdf')", "import string; allowed = set(string.ascii_lowercase + string.digits + '.')").timeit()
6.7066690921783447

If you want to allow empty strings then change it to:

reg=re.compile('^[a-z0-9\.]*$')
>>>reg.match('')
False

Under request I'm going to return the other part of the answer. But please note that the following accept A-Z range.

You can use isalnum

test_str.replace('.', '').isalnum()

>>> 'test123.3'.replace('.', '').isalnum()
True
>>> 'test123-3'.replace('.', '').isalnum()
False

EDIT Using isalnum is much more efficient than the set solution

>>> timeit.Timer("'jsdlfjdsf12324..3432jsdflsdf'.replace('.', '').isalnum()").timeit()
0.63245487213134766

EDIT2 John gave an example where the above doesn't work. I changed the solution to overcome this special case by using encode

test_str.replace('.', '').encode('ascii', 'replace').isalnum()

And it is still almost 3 times faster than the set solution

timeit.Timer("u'ABC\u0131\u0661'.encode('ascii', 'replace').replace('.','').isalnum()", "import string; allowed = set(string.ascii_lowercase + string.digits + '.')").timeit()
1.5719811916351318

In my opinion using regular expressions is the best to solve this problem

Most Pythonic way to provide global configuration variables in config.py?

Let's be honest, we should probably consider using a Python Software Foundation maintained library:

https://docs.python.org/3/library/configparser.html

Config example: (ini format, but JSON available)

[DEFAULT]
ServerAliveInterval = 45
Compression = yes
CompressionLevel = 9
ForwardX11 = yes

[bitbucket.org]
User = hg

[topsecret.server.com]
Port = 50022
ForwardX11 = no

Code example:

>>> import configparser
>>> config = configparser.ConfigParser()
>>> config.read('example.ini')
>>> config['DEFAULT']['Compression']
'yes'
>>> config['DEFAULT'].getboolean('MyCompression', fallback=True) # get_or_else

Making it globally-accessible:

import configpaser
class App:
 __conf = None

 @staticmethod
 def config():
  if App.__conf is None:  # Read only once, lazy.
   App.__conf = configparser.ConfigParser()
   App.__conf.read('example.ini')
  return App.__conf

if __name__ == '__main__':
 App.config()['DEFAULT']['MYSQL_PORT']
 # or, better:
 App.config().get(section='DEFAULT', option='MYSQL_PORT', fallback=3306)
 ....

Downsides:

  • Uncontrolled global mutable state.

Click through div to underlying elements

it doesn't work that way. the work around is to manually check the coordinates of the mouse click against the area occupied by each element.

area occupied by an element can found found by 1. getting the location of the element with respect to the top left of the page, and 2. the width and the height. a library like jQuery makes this pretty simple, although it can be done in plain js. adding an event handler for mousemove on the document object will provide continuous updates of the mouse position from the top and left of the page. deciding if the mouse is over any given object consists of checking if the mouse position is between the left, right, top and bottom edges of an element.

What's the correct way to communicate between controllers in AngularJS?

Since defineProperty has browser compatibility issue, I think we can think about using a service.

angular.module('myservice', [], function($provide) {
    $provide.factory('msgBus', ['$rootScope', function($rootScope) {
        var msgBus = {};
        msgBus.emitMsg = function(msg) {
        $rootScope.$emit(msg);
        };
        msgBus.onMsg = function(msg, scope, func) {
            var unbind = $rootScope.$on(msg, func);
            scope.$on('$destroy', unbind);
        };
        return msgBus;
    }]);
});

and use it in controller like this:

  • controller 1

    function($scope, msgBus) {
        $scope.sendmsg = function() {
            msgBus.emitMsg('somemsg')
        }
    }
    
  • controller 2

    function($scope, msgBus) {
        msgBus.onMsg('somemsg', $scope, function() {
            // your logic
        });
    }
    

casting Object array to Integer array error

Ross, you can use Arrays.copyof() or Arrays.copyOfRange() too.

Integer[] integerArray = Arrays.copyOf(a, a.length, Integer[].class);
Integer[] integerArray = Arrays.copyOfRange(a, 0, a.length, Integer[].class);

Here the reason to hitting an ClassCastException is you can't treat an array of Integer as an array of Object. Integer[] is a subtype of Object[] but Object[] is not a Integer[].

And the following also will not give an ClassCastException.

Object[] a = new Integer[1];
Integer b=1;
a[0]=b;
Integer[] c = (Integer[]) a;

TypeError: $(...).on is not a function

The usual cause of this is that you're also using Prototype, MooTools, or some other library that makes use of the $ symbol, and you're including that library after jQuery, and so that library is "winning" (taking $ for itself). So the return value of $ isn't a jQuery instance, and so it doesn't have jQuery methods on it (like on).

You can use jQuery with those other libraries, but if you do, you have to use the jQuery symbol rather than its alias $, e.g.:

jQuery('body').on(...);

And it's usually best if you add this immediately after your script tag including jQuery, before the one including the other library:

<script>jQuery.noConflict();</script>

...although it's not required if you load the other library after jQuery (it is if you load the other library first).

Using multiple full-function DOM manipulation libraries on the same page isn't ideal, though, just in terms of page weight. So if you can stick with just Prototype/MooTools/whatever or just jQuery, that's usually better.

Regex to Match Symbols: !$%^&*()_+|~-=`{}[]:";'<>?,./

Answer

/[\W\S_]/

Explanation

This creates a character class removing the word characters, space characters, and adding back the underscore character (as underscore is a "word" character). All that is left is the special characters. Capital letters represent the negation of their lowercase counterparts.

\W will select all non "word" characters equivalent to [^a-zA-Z0-9_]
\S will select all non "whitespace" characters equivalent to [ \t\n\r\f\v]
_ will select "_" because we negate it when using the \W and need to add it back in

Jinja2 template not rendering if-elif-else statement properly

You are testing if the values of the variables error and Already are present in RepoOutput[RepoName.index(repo)]. If these variables don't exist then an undefined object is used.

Both of your if and elif tests therefore are false; there is no undefined object in the value of RepoOutput[RepoName.index(repo)].

I think you wanted to test if certain strings are in the value instead:

{% if "error" in RepoOutput[RepoName.index(repo)] %}
    <td id="error"> {{ RepoOutput[RepoName.index(repo)] }} </td>
{% elif "Already" in RepoOutput[RepoName.index(repo) %}
    <td id="good"> {{ RepoOutput[RepoName.index(repo)] }} </td>
{% else %}
    <td id="error"> {{ RepoOutput[RepoName.index(repo)] }} </td>
{% endif %}
</tr>

Other corrections I made:

  • Used {% elif ... %} instead of {$ elif ... %}.
  • moved the </tr> tag out of the if conditional structure, it needs to be there always.
  • put quotes around the id attribute

Note that most likely you want to use a class attribute instead here, not an id, the latter must have a value that must be unique across your HTML document.

Personally, I'd set the class value here and reduce the duplication a little:

{% if "Already" in RepoOutput[RepoName.index(repo)] %}
    {% set row_class = "good" %}
{% else %}
    {% set row_class = "error" %}
{% endif %}
<td class="{{ row_class }}"> {{ RepoOutput[RepoName.index(repo)] }} </td>

Remove leading or trailing spaces in an entire column of data

I was able to use Find & Replace with the "Find what:" input field set to:

" * "

(space asterisk space with no double-quotes)

and "Replace with:" set to:

""

(nothing)

Read response headers from API response - Angular 5 + TypeScript

Try this simple code.

1. Components side code: to get both body and header property. Here there's a token in body and Authorization in the header.

loginUser() {
    this.userService.loginTest(this.loginCred).
    subscribe(res => {
        let output1 = res;
        console.log(output1.body.token);
        console.log(output1.headers.get('Authorization'));
    })
}

2. Service side code: sending login data in the body and observe the response in Observable any which be subscribed in the component side.

loginTest(loginCred: LoginParams): Observable<any> {
    const header1= {'Content-Type':'application/json',};
    const body =  JSON.stringify(loginCred);
    return this.http.post<any>(this.baseURL+'signin',body,{
        headers: header1,
        observe: 'response',
        responseType: 'json'
    });
}

How to calculate the inverse of the normal cumulative distribution function in python?

NORMSINV (mentioned in a comment) is the inverse of the CDF of the standard normal distribution. Using scipy, you can compute this with the ppf method of the scipy.stats.norm object. The acronym ppf stands for percent point function, which is another name for the quantile function.

In [20]: from scipy.stats import norm

In [21]: norm.ppf(0.95)
Out[21]: 1.6448536269514722

Check that it is the inverse of the CDF:

In [34]: norm.cdf(norm.ppf(0.95))
Out[34]: 0.94999999999999996

By default, norm.ppf uses mean=0 and stddev=1, which is the "standard" normal distribution. You can use a different mean and standard deviation by specifying the loc and scale arguments, respectively.

In [35]: norm.ppf(0.95, loc=10, scale=2)
Out[35]: 13.289707253902945

If you look at the source code for scipy.stats.norm, you'll find that the ppf method ultimately calls scipy.special.ndtri. So to compute the inverse of the CDF of the standard normal distribution, you could use that function directly:

In [43]: from scipy.special import ndtri

In [44]: ndtri(0.95)
Out[44]: 1.6448536269514722

Named placeholders in string formatting

I am the author of a small library that does exactly what you want:

Student student = new Student("Andrei", 30, "Male");

String studStr = template("#{id}\tName: #{st.getName}, Age: #{st.getAge}, Gender: #{st.getGender}")
                    .arg("id", 10)
                    .arg("st", student)
                    .format();
System.out.println(studStr);

Or you can chain the arguments:

String result = template("#{x} + #{y} = #{z}")
                    .args("x", 5, "y", 10, "z", 15)
                    .format();
System.out.println(result);

// Output: "5 + 10 = 15"

How to initialize a List<T> to a given size (as opposed to capacity)?

You can use Linq to cleverly initialize your list with a default value. (Similar to David B's answer.)

var defaultStrings = (new int[10]).Select(x => "my value").ToList();

Go one step farther and initialize each string with distinct values "string 1", "string 2", "string 3", etc:

int x = 1;
var numberedStrings = (new int[10]).Select(x => "string " + x++).ToList();

Magento addFieldToFilter: Two fields, match as OR, not AND

Here is my solution in Enterprise 1.11 (should work in CE 1.6):

    $collection->addFieldToFilter('max_item_count',
                    array(
                        array('gteq' => 10),
                        array('null' => true),
                    )
            )
            ->addFieldToFilter('max_item_price',
                    array(
                        array('gteq' => 9.99),
                        array('null' => true),
                    )
            )
            ->addFieldToFilter('max_item_weight',
                    array(
                        array('gteq' => 1.5),
                        array('null' => true),
                    )
            );

Which results in this SQL:

    SELECT `main_table`.*
    FROM `shipping_method_entity` AS `main_table`
    WHERE (((max_item_count >= 10) OR (max_item_count IS NULL)))
      AND (((max_item_price >= 9.99) OR (max_item_price IS NULL)))
      AND (((max_item_weight >= 1.5) OR (max_item_weight IS NULL)))

Getting multiple values with scanf()

int a[1000] ;
for(int i = 0 ; i <= 3 , i++)
scanf("%d" , &a[i]) ;

How to install pandas from pip on windows cmd?

Please Ensure you are using a virtualEnv this is how :

virtualenv -p python3 envname

source env/bin/activate
pip install pandas

on windows you have to add scripts exe in the CLASSPATH in order to use pip command

C:\Python34\Scripts\pip3.exe

i suggest you to use MINGW he can gives you a better environment to work with python

What is the size of an enum in C?

While the previous answers are correct, some compilers have options to break the standard and use the smallest type that will contain all values.

Example with GCC (documentation in the GCC Manual):

enum ord {
    FIRST = 1,
    SECOND,
    THIRD
} __attribute__ ((__packed__));
STATIC_ASSERT( sizeof(enum ord) == 1 )

How do I make a fixed size formatted string in python?

Sure, use the .format method. E.g.,

print('{:10s} {:3d}  {:7.2f}'.format('xxx', 123, 98))
print('{:10s} {:3d}  {:7.2f}'.format('yyyy', 3, 1.0))
print('{:10s} {:3d}  {:7.2f}'.format('zz', 42, 123.34))

will print

xxx        123    98.00
yyyy         3     1.00
zz          42   123.34

You can adjust the field sizes as desired. Note that .format works independently of print to format a string. I just used print to display the strings. Brief explanation:

10s format a string with 10 spaces, left justified by default

3d format an integer reserving 3 spaces, right justified by default

7.2f format a float, reserving 7 spaces, 2 after the decimal point, right justfied by default.

There are many additional options to position/format strings (padding, left/right justify etc), String Formatting Operations will provide more information.

Update for f-string mode. E.g.,

text, number, other_number = 'xxx', 123, 98
print(f'{text:10} {number:3d}  {other_number:7.2f}')

For right alignment

print(f'{text:>10} {number:3d}  {other_number:7.2f}')

Drop columns whose name contains a specific string from pandas DataFrame

the shortest way to do is is :

resdf = df.filter(like='Test',axis=1)

How do I enable Java in Microsoft Edge web browser?

You cannot open Java Applets (nor any other NPAPI plugin) in Microsoft Edge - they aren't supported and won't be added in the future.

Further you should be aware that in the next release of Google Chrome (v45 - due September 2015) NPAPI plugins will also no longer be supported.

Work-arounds

There are a couple of things that you can do:

Use Internet Explorer 11
You will find that in Windows 10 you will already have Internet Explorer 11 installed. IE 11 continues to support NPAPI (incl Java Applets). IE11 is squirrelled away (c:\program files\internet explorer\iexplore.exe). Just pin this exe to your task bar for easy access.

Use FireFox
You can also install and use a Firefox 32-bit Extended Support Release in Win10. Firefox have disabled NPAPI by default, but this can be overridden. This will only be supported until early 2018.

How to write the Fibonacci Sequence?

Efficient Pythonic generator of the Fibonacci sequence

I found this question while trying to get the shortest Pythonic generation of this sequence (later realizing I had seen a similar one in a Python Enhancement Proposal), and I haven't noticed anyone else coming up with my specific solution (although the top answer gets close, but still less elegant), so here it is, with comments describing the first iteration, because I think that may help readers understand:

def fib():
    a, b = 0, 1
    while True:            # First iteration:
        yield a            # yield 0 to start with and then
        a, b = b, a + b    # a will now be 1, and b will also be 1, (0 + 1)

and usage:

for index, fibonacci_number in zip(range(10), fib()):
     print('{i:3}: {f:3}'.format(i=index, f=fibonacci_number))

prints:

  0:   0
  1:   1
  2:   1
  3:   2
  4:   3
  5:   5
  6:   8
  7:  13
  8:  21
  9:  34
 10:  55

(For attribution purposes, I recently noticed a similar implementation in the Python documentation on modules, even using the variables a and b, which I now recall having seen before writing this answer. But I think this answer demonstrates better usage of the language.)

Recursively defined implementation

The Online Encyclopedia of Integer Sequences defines the Fibonacci Sequence recursively as

F(n) = F(n-1) + F(n-2) with F(0) = 0 and F(1) = 1

Succinctly defining this recursively in Python can be done as follows:

def rec_fib(n):
    '''inefficient recursive function as defined, returns Fibonacci number'''
    if n > 1:
        return rec_fib(n-1) + rec_fib(n-2)
    return n

But this exact representation of the mathematical definition is incredibly inefficient for numbers much greater than 30, because each number being calculated must also calculate for every number below it. You can demonstrate how slow it is by using the following:

for i in range(40):
    print(i, rec_fib(i))

Memoized recursion for efficiency

It can be memoized to improve speed (this example takes advantage of the fact that a default keyword argument is the same object every time the function is called, but normally you wouldn't use a mutable default argument for exactly this reason):

def mem_fib(n, _cache={}):
    '''efficiently memoized recursive function, returns a Fibonacci number'''
    if n in _cache:
        return _cache[n]
    elif n > 1:
        return _cache.setdefault(n, mem_fib(n-1) + mem_fib(n-2))
    return n

You'll find the memoized version is much faster, and will quickly exceed your maximum recursion depth before you can even think to get up for coffee. You can see how much faster it is visually by doing this:

for i in range(40):
    print(i, mem_fib(i))

(It may seem like we can just do the below, but it actually doesn't let us take advantage of the cache, because it calls itself before setdefault is called.)

def mem_fib(n, _cache={}):
    '''don't do this'''
    if n > 1:  
        return _cache.setdefault(n, mem_fib(n-1) + mem_fib(n-2))
    return n

Recursively defined generator:

As I have been learning Haskell, I came across this implementation in Haskell:

fib@(0:tfib) = 0:1: zipWith (+) fib tfib

The closest I think I can get to this in Python at the moment is:

from itertools import tee

def fib():
    yield 0
    yield 1
    # tee required, else with two fib()'s algorithm becomes quadratic
    f, tf = tee(fib()) 
    next(tf)
    for a, b in zip(f, tf):
        yield a + b

This demonstrates it:

[f for _, f in zip(range(999), fib())]

It can only go up to the recursion limit, though. Usually, 1000, whereas the Haskell version can go up to the 100s of millions, although it uses all 8 GB of my laptop's memory to do so:

> length $ take 100000000 fib 
100000000

Consuming the iterator to get the nth fibonacci number

A commenter asks:

Question for the Fib() function which is based on iterator: what if you want to get the nth, for instance 10th fib number?

The itertools documentation has a recipe for this:

from itertools import islice

def nth(iterable, n, default=None):
    "Returns the nth item or a default value"
    return next(islice(iterable, n, None), default)

and now:

>>> nth(fib(), 10)
55

Name node is in safe mode. Not able to leave

If you use Hadoop version 2.6.1 above, while the command works, it complains that its depreciated. I actually could not use the hadoop dfsadmin -safemode leave because I was running Hadoop in a Docker container and that command magically fails when run in the container, so what I did was this. I checked doc and found dfs.safemode.threshold.pct in documentation that says

Specifies the percentage of blocks that should satisfy the minimal replication requirement defined by dfs.replication.min. Values less than or equal to 0 mean not to wait for any particular percentage of blocks before exiting safemode. Values greater than 1 will make safe mode permanent.

so I changed the hdfs-site.xml into the following (In older Hadoop versions, apparently you need to do it in hdfs-default.xml:

<configuration>
    <property>
        <name>dfs.safemode.threshold.pct</name>
        <value>0</value>
    </property>
</configuration>

Add IIS 7 AppPool Identities as SQL Server Logons

If you're going across machines, you either need to be using NETWORK SERVICE, LOCAL SYSTEM, a domain account, or a SQL 2008 R2 (if you have it) Managed Service Account (which is my preference if you had such an infrastructure). You can not use an account which is not visible to the Active Directory domain.

Why is document.body null in my javascript?

Your script is being executed before the body element has even loaded.

There are a couple ways to workaround this.

  • Wrap your code in a DOM Load callback:

    Wrap your logic in an event listener for DOMContentLoaded.

    In doing so, the callback will be executed when the body element has loaded.

    document.addEventListener('DOMContentLoaded', function () {
        // ...
        // Place code here.
        // ...
    });
    

    Depending on your needs, you can alternatively attach a load event listener to the window object:

    window.addEventListener('load', function () {
        // ...
        // Place code here.
        // ...
    });
    

    For the difference between between the DOMContentLoaded and load events, see this question.

  • Move the position of your <script> element, and load JavaScript last:

    Right now, your <script> element is being loaded in the <head> element of your document. This means that it will be executed before the body has loaded. Google developers recommends moving the <script> tags to the end of your page so that all the HTML content is rendered before the JavaScript is processed.

    <!DOCTYPE html>
    <html>
    <head></head>
    <body>
      <p>Some paragraph</p>
      <!-- End of HTML content in the body tag -->
    
      <script>
        <!-- Place your script tags here. -->
      </script>
    </body>
    </html>
    

Codeigniter - no input file specified

Godaddy hosting it seems fixed on .htaccess, myself it is working

RewriteRule ^(.*)$ index.php/$1 [L]

to

RewriteRule ^(.*)$ index.php?/$1 [QSA,L]

CSS3 scrollbar styling on a div

You're setting overflow: hidden. This will hide anything that's too large for the <div>, meaning scrollbars won't be shown. Give your <div> an explicit width and/or height, and change overflow to auto:

.scroll {
   width: 200px;
   height: 400px;
   overflow: scroll;
}

If you only want to show a scrollbar if the content is longer than the <div>, change overflow to overflow: auto. You can also only show one scrollbar by using overflow-y or overflow-x.

Oracle SELECT TOP 10 records

try

SELECT * FROM users FETCH NEXT 10 ROWS ONLY;

How to handle the modal closing event in Twitter Bootstrap?

If your modal div is dynamically added then use( For bootstrap 3 and 4)

$(document).on('hide.bs.modal','#modal-id', function () {
                alert('');
 //Do stuff here
});

This will work for non-dynamic content also.

How to redirect output of systemd service to a file

Short answer:

StandardOutput=file:/var/log1.log
StandardError=file:/var/log2.log

If you don't want the files to be cleared every time the service is run, use append instead:

StandardOutput=append:/var/log1.log
StandardError=append:/var/log2.log

Real world use of JMS/message queues?

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

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

How to initialize var?

Thank you Mr.Snake, Found this helpfull for another trick i was looking for :) (Not enough rep to comment)

Shorthand assignment of nullable types. Like this:

var someDate = !Convert.IsDBNull(dataRow["SomeDate"])
                    ? Convert.ToDateTime(dataRow["SomeDate"])
                    : (DateTime?) null;

How do I update a formula with Homebrew?

You will first need to update the local formulas by doing

brew update

and then upgrade the package by doing

brew upgrade formula-name

An example would be if i wanted to upgrade mongodb, i would do something like this, assuming mongodb was already installed :

brew update && brew upgrade mongodb && brew cleanup mongodb

Serving favicon.ico in ASP.NET MVC

Found that in .Net Core, placing the favicon.ico in /lib rather than wwwroot fixes the issue

Fastest Way to Find Distance Between Two Lat/Long Points

Have a read of Geo Distance Search with MySQL, a solution based on implementation of Haversine Formula to MySQL. This is a complete solution description with theory, implementation and further performance optimization. Although the spatial optimization part didn't work correctly in my case.

I noticed two mistakes in this:

  1. the use of abs in the select statement on p8. I just omitted abs and it worked.

  2. the spatial search distance function on p27 does not convert to radians or multiply longitude by cos(latitude), unless his spatial data is loaded with this in consideration (cannot tell from context of article), but his example on p26 indicates that his spatial data POINT is not loaded with radians or degrees.

Copying the cell value preserving the formatting from one cell to another in excel using VBA

To copy formatting:

Range("F10").Select
Selection.Copy
Range("I10:J10").Select ' note that we select the whole merged cell
Selection.PasteSpecial Paste:=xlPasteFormats

copying the formatting will break the merged cells, so you can use this to put the cell back together

Range("I10:J10").Select
Selection.Merge

To copy a cell value, without copying anything else (and not using copy/paste), you can address the cells directly

Range("I10").Value = Range("F10").Value

other properties (font, color, etc ) can also be copied by addressing the range object properties directly in the same way

Running sites on "localhost" is extremely slow

Run the Process Monitor to see what resources(Network, File, Registry, Threads) are being consumed and see any unnecessary resource(remote https, costly file reads) are being consumed

I had similar problem. When I run the process monitor I found that my fusion log is enabled so there are many into the disk which delayed the loading of dll after disabling fusion log IIS Express it is faster.

enter image description here

Creating a simple login form

Check it - You can try this code for your login form design as you ask thank you.

Explain css -

First, we define property font style and width And after that I have defined form id to set background image and the border And after that I have to define the header text in tag and after that I have added new and define by.New to set background properties and width. Thanks

Create a file index.html

<!DOCTYPE html>
<html>
   <head>
      <link rel="stylesheet" href="style.css">
   </head>
   <body>
      <div id="login_form">
         <div class="new"><span>enter login details</span></div>
         <!-- This is your header text-->
         <form name="f1" method="post" action="login.php" id="f1">
            <table>
               <tr>
                  <td class="f1_label">User Name :</td>
                  <!-- This is your first Input Box Label-->
                  <td>
                     <input type="text" name="username" value="" /><!-- This is your first Input Box-->
                  </td>
               </tr>
               <tr>
                  <td class="f1_label">Password  :</td>
                  <!-- This is your Second Input Box Label-->
                  <td>
                     <input type="password" name="password" value=""  /><!-- This is your Second Input Box -->
                  </td>
               </tr>
               <tr>
                  <td>
                     <input type="submit" name="login" value="Log In" style="font-size:18px; " /><!-- This is your submit button -->
                  </td>
               </tr>
            </table>
         </form>
      </div>
   </body>
</html>

Create css file style.css

body {
    font-style: italic;
    width: 50%;
    margin: 0px auto;
}

#login_form {}

#f1 {
    background-color: #FFF;
    border-style: solid;
    border-width: 1px;
    padding: 23px 1px 20px 114px;
}

.f1_label {
    white-space: nowrap;
}

span {
    color: white;
}

.new {
    background: black;
    text-align: center;
}

SQL alias for SELECT statement

You can do this using the WITH clause of the SELECT statement:

;
WITH my_select As (SELECT ... FROM ...) 
SELECT * FROM foo
WHERE id IN (SELECT MAX(id) FROM my_select GROUP BY name)

That's the ANSI/ISO SQL Syntax. I know that SQL Server, Oracle and DB2 support it. Not sure about the others...

How to get file path in iPhone app

You need to add your tiles into your resource bundle. I mean add all those files to your project make sure to copy all files to project directory option checked.

Update just one gem with bundler

The way to do this is to run the following command:

bundle update --source gem-name

How to cherry-pick multiple commits

If you have selective revisions to merge, say A, C, F, J from A,B,C,D,E,F,G,H,I,J commits, simply use below command:

git cherry-pick A C F J

How to make zsh run as a login shell on Mac OS X (in iTerm)?

Have you tried editing the shell entry in account settings.

Go to the Accounts preferences, unlock, and right-click on your user account for the Advanced Settings dialog. Your shell should be /bin/zsh, and you can edit that invocation appropriately (i.e. add the --login argument).

How to get the scroll bar with CSS overflow on iOS

I have done some testing and using CSS3 to redefine the scrollbars works and you get to keep your Overflow:scroll; or Overflow:auto

I ended up with something like this...

::-webkit-scrollbar {
    width: 15px;
    height: 15px;
    border-bottom: 1px solid #eee; 
    border-top: 1px solid #eee;
}
::-webkit-scrollbar-thumb {
    border-radius: 8px;
    background-color: #C3C3C3;
    border: 2px solid #eee;
}

::-webkit-scrollbar-track {
    -webkit-box-shadow: inset 0 0 6px rgba(0,0,0,0.2); 
} 

The only down side which I have not yet been able to figure out is how to interact with the scrollbars on iProducts but you can interact with the content to scroll it

How to Correctly Use Lists in R?

One reason lists work as they do (ordered) is to address the need for an ordered container that can contain any type at any node, which vectors do not do. Lists are re-used for a variety of purposes in R, including forming the base of a data.frame, which is a list of vectors of arbitrary type (but the same length).

Why do these two expressions not return the same result?

x = list(1, 2, 3, 4); x2 = list(1:4)

To add to @Shane's answer, if you wanted to get the same result, try:

x3 = as.list(1:4)

Which coerces the vector 1:4 into a list.

Getting hold of the outer class object from the inner class object

Here's the example:

// Test
public void foo() {
    C c = new C();
    A s;
    s = ((A.B)c).get();
    System.out.println(s.getR());
}

// classes
class C {}

class A {
   public class B extends C{
     A get() {return A.this;}
   }
   public String getR() {
     return "This is string";
   }
}

JavaScript Object Id

If you want to lookup/associate an object with a unique identifier without modifying the underlying object, you can use a WeakMap:

// Note that object must be an object or array,
// NOT a primitive value like string, number, etc.
var objIdMap=new WeakMap, objectCount = 0;
function objectId(object){
  if (!objIdMap.has(object)) objIdMap.set(object,++objectCount);
  return objIdMap.get(object);
}

var o1={}, o2={}, o3={a:1}, o4={a:1};
console.log( objectId(o1) ) // 1
console.log( objectId(o2) ) // 2
console.log( objectId(o1) ) // 1
console.log( objectId(o3) ) // 3
console.log( objectId(o4) ) // 4
console.log( objectId(o3) ) // 3

Using a WeakMap instead of Map ensures that the objects can still be garbage-collected.

MySQL - UPDATE query with LIMIT

In addition to the nested approach above, you can accomplish the application of theLIMIT using JOIN on the same table:

UPDATE `table_name`
INNER JOIN (SELECT `id` from `table_name` order by `id` limit 0,100) as t2 using (`id`)
SET `name` = 'test'

In my experience the mysql query optimizer is happier with this structure.

Bootstrap number validation

you can use PATTERN:

<input class="form-control" minlength="1" pattern="[0-9]*" [(ngModel)]="value" #name="ngModel">

<div *ngIf="name.invalid && (name.dirty || name.touched)" class="text-danger">
  <div *ngIf="name.errors?.pattern">Is not a number</div>
</div>

Find most frequent value in SQL column

For use with SQL Server.

As there is no limit command support in that.

Yo can use the top 1 command to find the maximum occurring value in the particular column in this case (value)

SELECT top1 
    `value`,
    COUNT(`value`) AS `value_occurrence` 
FROM     
    `my_table`
GROUP BY 
    `value`
ORDER BY 
    `value_occurrence` DESC;

The entitlements specified...profile. (0xE8008016). Error iOS 4.2

Just putting in my 5 cents here. For me none of the above worked, so I was forced to stress down and actually look at every part of the process with fresh eyes.

In rushing this I forgot that I was trying to install my app on a totally new device.

So my error was that I hadn't updated my provisioning profile by ticking off my new device int the "Devices" section of the provisioning profile setup in the Provisioning Portal.

Apparently not including your device in the provisioning profile also generates this error message.

How to change default text file encoding in Eclipse?

To change the default encoding used for all workspaces you can do the following:

Create a defaults.ini file in the Eclipse configuration folder. For example, if Eclipse is installed in C:/Eclipse create C:/Eclipse/configuration/defaults.ini. The file should contain:

org.eclipse.core.resources/encoding=UTF-8

If you want to set the line terminator to UNIX values you can also add:

org.eclipse.core.runtime/line.separator=\n

In eclipse.ini in the Eclipse install folder (e.g., C:/Eclipse) add the following lines:

-plugincustomization 
D:/Java/Eclipse/configuration/defaults.ini

You might need to play around with where you put it. Inserting it before the "-product" option seemed to work.

Push method in React Hooks (useState)?

Most recommended method is using wrapper function and spread operator together. For example, if you have initialized a state called name like this,

const [names, setNames] = useState([])

You can push to this array like this,

setNames(names => [...names, newName])

Hope that helps.

How to stop text from taking up more than 1 line?

Just to be crystal clear, this works nicely with paragraphs and headers etc. You just need to specify display: block.

For instance:

<h5 style="display: block; text-overflow: ellipsis; white-space: nowrap; overflow: hidden">
  This is a really long title, but it won't exceed the parent width
</h5>

(forgive the inline styles)

onchange file input change img src and change image color

in your HTML : <input type="file" id="yourFile"> don't forget to reference your js file or put the following script between <script></script> in your script :

var fileToRead = document.getElementById("yourFile");

fileToRead.addEventListener("change", function(event) {
    var files = fileToRead.files;
    if (files.length) {
        console.log("Filename: " + files[0].name);
        console.log("Type: " + files[0].type);
        console.log("Size: " + files[0].size + " bytes");
    }

}, false);

jQuery validate Uncaught TypeError: Cannot read property 'nodeName' of null

Extract from the oficial docs:

Requires that the parent form is validated, that is, $( "form" ).validate() is called first

more about... rules

Algorithm to return all combinations of k elements from n

We can use the concept of bits to do this. Let we have a string of "abc," and we want to have all combinations of the elements with length 2 (i.e "ab" , "ac","bc".)

We can find the set bits in numbers ranging from 1 to 2^n (exclusive). Here 1 to 7, and wherever we have set bits = 2, we can print the corresponding value from string.

for example:

  • 1 - 001
  • 2 - 010
  • 3 - 011 -> print ab (str[0] , str[1])
  • 4 - 100
  • 5 - 101 -> print ac (str[0] , str[2])
  • 6 - 110 -> print ab (str[1] , str[2])
  • 7 - 111.


Code sample:

public class StringCombinationK {   
    static void combk(String s , int k){
        int n = s.length();
        int num = 1<<n;
        int j=0;
        int count=0;

        for(int i=0;i<num;i++){
            if (countSet(i)==k){
                setBits(i,j,s);
                count++;
                System.out.println();
            }
        }

        System.out.println(count);
    }

    static void setBits(int i,int j,String s){ // print the corresponding string value,j represent the index of set bit
        if(i==0){
            return;
        }

        if(i%2==1){
            System.out.print(s.charAt(j));                  
        }

        setBits(i/2,j+1,s);
    }

    static int countSet(int i){ //count number of set bits
        if( i==0){
            return 0;
        }

        return (i%2==0? 0:1) + countSet(i/2);
    }

    public static void main(String[] arhs){
        String s = "abcdefgh";
        int k=3;
        combk(s,k);
    }
}

stale element reference: element is not attached to the page document

use this code to wait till the element is attached:

boolean breakIt = true;
        while (true) {
        breakIt = true;
        try {
            // write your code here
        } catch (Exception e) {
            if (e.getMessage().contains("element is not attached")) {
                breakIt = false;
            }
        }
        if (breakIt) {
            break;
        }

    }

Find the server name for an Oracle database

The query below demonstrates use of the package and some of the information you can get.

select sys_context ( 'USERENV', 'DB_NAME' ) db_name,
sys_context ( 'USERENV', 'SESSION_USER' ) user_name,
sys_context ( 'USERENV', 'SERVER_HOST' ) db_host,
sys_context ( 'USERENV', 'HOST' ) user_host
from dual

NOTE: The parameter ‘SERVER_HOST’ is available in 10G only.

Any Oracle User that can connect to the database can run a query against “dual”. No special permissions are required and SYS_CONTEXT provides a greater range of application-specific information than “sys.v$instance”.

ListBox vs. ListView - how to choose for data binding

A ListView is a specialized ListBox (that is, it inherits from ListBox). It allows you to specify different views rather than a straight list. You can either roll your own view, or use GridView (think explorer-like "details view"). It's basically the multi-column listbox, the cousin of windows form's listview.

If you don't need the additional capabilities of ListView, you can certainly use ListBox if you're simply showing a list of items (Even if the template is complex).

Where can I read the Console output in Visual Studio 2015

You can run your program by: Debug -> Start Without Debugging. It will keep a console opened after the program will be finished.

enter image description here

ASP.NET MVC Razor: How to render a Razor Partial View's HTML inside the controller action

Although adequate answers have already been given, I'd like to propose a less verbose solution, that can be used without the helper methods available in an MVC controller class. Using a third party library called "RazorEngine" you can use .Net file IO to get the contents of the razor file and call

string html = Razor.Parse(razorViewContentString, modelObject);

Get the third party library here.

What is the correct target for the JAVA_HOME environment variable for a Linux OpenJDK Debian-based distribution?

As far as I remember, I used the update-java-alternatives script instead of the update-alternatives. And it did set the JAVA_HOME for me correctly.

How to get Linux console window width in Python

Not sure why it is in the module shutil, but it landed there in Python 3.3, Querying the size of the output terminal:

>>> import shutil
>>> shutil.get_terminal_size((80, 20))  # pass fallback
os.terminal_size(columns=87, lines=23)  # returns a named-tuple

A low-level implementation is in the os module. Also works in Windows.

A backport is now available for Python 3.2 and below:

How can I set a dynamic model name in AngularJS?

You can use something like this scopeValue[field], but if your field is in another object you will need another solution.

To solve all kind of situations, you can use this directive:

this.app.directive('dynamicModel', ['$compile', '$parse', function ($compile, $parse) {
    return {
        restrict: 'A',
        terminal: true,
        priority: 100000,
        link: function (scope, elem) {
            var name = $parse(elem.attr('dynamic-model'))(scope);
            elem.removeAttr('dynamic-model');
            elem.attr('ng-model', name);
            $compile(elem)(scope);
        }
    };
}]);

Html example:

<input dynamic-model="'scopeValue.' + field" type="text">

How do I validate a date string format in python?

from datetime import datetime

datetime.strptime(date_string, "%Y-%m-%d")

..this raises a ValueError if it receives an incompatible format.

..if you're dealing with dates and times a lot (in the sense of datetime objects, as opposed to unix timestamp floats), it's a good idea to look into the pytz module, and for storage/db, store everything in UTC.

How to read a text file from server using JavaScript?

I really think your going about this in the wrong manner. Trying to download and parse a +3Mb text file is complete insanity. Why not parse the file on the server side, storing the results viva an ORM to a database(your choice, SQL is good but it also depends on the content key-value data works better on something like CouchDB) then use ajax to parse data on the client end.

Plus, an even better idea would to skip the text file entirely for even better performance if at all possible.

Add padding to HTML text input field

<input class="form-control search-query input_style" placeholder="Search…"  name="" title="Search for:" type="text">


.input_style
{
    padding-left:20px;
}

How to get cookie's expire time

When you create a cookie via PHP die Default Value is 0, from the manual:

If set to 0, or omitted, the cookie will expire at the end of the session (when the browser closes)

Otherwise you can set the cookies lifetime in seconds as the third parameter:

http://www.php.net/manual/en/function.setcookie.php

But if you mean to get the remaining lifetime of an already existing cookie, i fear that, is not possible (at least not in a direct way).

Running code after Spring Boot starts

I really like the suggestion for usage of the EventListener annotation by @cahen (https://stackoverflow.com/a/44923402/9122660) since it is very clean. Unfortunately I could not get this to work in a Spring + Kotlin setup. What does work for Kotlin is adding the class as a method parameter:

@EventListener 
fun doSomethingAfterStartup(event: ApplicationReadyEvent) {
    System.out.println("hello world, I have just started up");
}