Programs & Examples On #Standard error

Plot mean and standard deviation

plt.errorbar can be used to plot x, y, error data (as opposed to the usual plt.plot)

import matplotlib.pyplot as plt
import numpy as np

x = np.array([1, 2, 3, 4, 5])
y = np.power(x, 2) # Effectively y = x**2
e = np.array([1.5, 2.6, 3.7, 4.6, 5.5])

plt.errorbar(x, y, e, linestyle='None', marker='^')

plt.show()

plt.errorbar accepts the same arguments as plt.plot with additional yerr and xerr which default to None (i.e. if you leave them blank it will act as plt.plot).

Example plot

Truncate/round whole number in JavaScript?

If you have a string, parse it as an integer:

var num = '20.536';
var result = parseInt(num, 10);  // 20

If you have a number, ECMAScript 6 offers Math.trunc for completely consistent truncation, already available in Firefox 24+ and Edge:

var num = -2147483649.536;
var result = Math.trunc(num);  // -2147483649

If you can’t rely on that and will always have a positive number, you can of course just use Math.floor:

var num = 20.536;
var result = Math.floor(num);  // 20

And finally, if you have a number in [−2147483648, 2147483647], you can truncate to 32 bits using any bitwise operator. | 0 is common, and >>> 0 can be used to obtain an unsigned 32-bit integer:

var num = -20.536;
var result = num | 0;  // -20

How to list physical disks?

The answer is far simpler than all the above answers. The physical drive list is actually stored in a Registry key which also gives the device mapping.

HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\disk\Enum

Count is the number of PhysicalDrive# and each numbered Registry Value is the corresponding physical drive.

For example, Registry Value "0" is PhysicalDrive0. The value is the actual device PhysicalDrive0 is mapped to. The value contained here can be passed into CM_Locate_DevNode within parameter pDeviceID to use the plug and play services. This will allow you to gather a wealth of information on the device. Such as the properties from Device Manager like "Friendly Display Name" if you need a name for the drive, serial numbers and more.

There is no need for WMI services which may not be running on the system or other hackery and this functionality has been present in Windows since at least 2000 and continues to be the case in Windows 10.

The right way of setting <a href=""> when it's a local file

../htmlfilename with .html User can do this This will solve your problem of redirection to anypage for local files.

What does FETCH_HEAD in Git mean?

git pull is combination of a fetch followed by a merge. When git fetch happens it notes the head commit of what it fetched in FETCH_HEAD (just a file by that name in .git) And these commits are then merged into your working directory.

Entity Framework: "Store update, insert, or delete statement affected an unexpected number of rows (0)."

For those of you using AutoMapper If you are updating an entity that has foreign keys to another entity(or entities), make sure all of the foreign entities have their primary key set to database generated (or auto-incremented for MySQL).

For example:

public class BuyerEntity
{
    [Key]
    public int BuyerId{ get; set; }

    public int Cash { get; set; }

    public List<VehicleEntity> Vehicles { get; set; }

    public List<PropertyEntity> Properties { get; set; }

}

Vehicles and Properties are stored in other tables than Buyers. When you add a new buyer, AutoMapper and EF will automatically update the Vehicles and Properties tables so if you don't have auto-increment set up on either of those tables (like I didn't), then you will see the error from the OP's question.

How do I force make/GCC to show me the commands?

Library makefiles, which are generated by autotools (the ./configure you have to issue) often have a verbose option, so basically, using make VERBOSE=1 or make V=1 should give you the full commands.

But this depends on how the makefile was generated.

The -d option might help, but it will give you an extremely long output.

How to create exe of a console application

The following steps are necessary to create .exe i.e. executable files which are as 1) Open visual studio framework 2) Then, create a new project or application 3) Build or execute your application by pressing F5

PHP 7 simpleXML

Had the same problem on AWS Linux 2, phpinfo() shows SimpleXML installed but not working, below cmd solved my issue

sudo yum install php-xml

How to place div side by side

There are many ways to do what you're asking for:

  1. Using CSS float property:

_x000D_
_x000D_
 <div style="width: 100%; overflow: hidden;">
     <div style="width: 600px; float: left;"> Left </div>
     <div style="margin-left: 620px;"> Right </div>
</div>
_x000D_
_x000D_
_x000D_

  1. Using CSS display property - which can be used to make divs act like a table:

_x000D_
_x000D_
<div style="width: 100%; display: table;">
    <div style="display: table-row">
        <div style="width: 600px; display: table-cell;"> Left </div>
        <div style="display: table-cell;"> Right </div>
    </div>
</div>
_x000D_
_x000D_
_x000D_

There are more methods, but those two are the most popular.

How to insert Records in Database using C# language?

Use a parameterized query to prevent Sql injections (secutity problem)

Use the using statement so the connection will be closed and resources will be disposed.

using(var connection = new SqlConnection("connectionString"))
{
    connection.Open();
    var sql = "INSERT INTO Main(FirstName, SecondName) VALUES(@FirstName, @SecondName)";
    using(var cmd = new SqlCommand(sql, connection))
    {
        cmd.Parameters.AddWithValue("@FirstName", txFirstName.Text);
        cmd.Parameters.AddWithValue("@SecondName", txSecondName.Text);

        cmd.ExecuteNonQuery();
    }
}

Android check null or empty string in Android

All you can do is to call equals() method on empty String literal and pass the object you are testing as shown below :

 String nullString = null;
 String empty = new String();
 boolean test = "".equals(empty); // true 
 System.out.println(test); 
 boolean check = "".equals(nullString); // false 
 System.out.println(check);

Likelihood of collision using most significant bits of a UUID in Java

You are better off just generating a random long value, then all the bits are random. In Java 6, new Random() uses the System.nanoTime() plus a counter as a seed.

There are different levels of uniqueness.

If you need uniqueness across many machines, you could have a central database table for allocating unique ids, or even batches of unique ids.

If you just need to have uniqueness in one app you can just have a counter (or a counter which starts from the currentTimeMillis()*1000 or nanoTime() depending on your requirements)

How to center links in HTML

Since you have a list of links, you should be marking them up as a list (and not as paragraphs).

Listamatic has a bunch of examples of how you can style lists of links, including a number that are vertical lists with each link being centred (which is what you appear to be after). It also has a tutorial which explains the principles.

That part of the styling essentially boils down to "Set text-align: center on an element that is displaying as a block which contains the link text" (that could be the anchor itself (if you make it display as a block) or the list item containing it.

How to access the content of an iframe with jQuery?

You have to use the contents() method:

$("#myiframe").contents().find("#myContent")

Source: http://simple.procoding.net/2008/03/21/how-to-access-iframe-in-jquery/

API Doc: https://api.jquery.com/contents/

Github Windows 'Failed to sync this branch'

I had the same problem when I tried from inside Visual Studio and "git status" in shell showed no problem. But I managed to push the local changes with "git push" via shell.

Add two textbox values and display the sum in a third textbox automatically

In below code i have done operation of sum and subtraction: because of using JavaScript if you want to call function, then you have to put your below code outside of document.ready(function{ }); and outside the script end tag.

I have taken one another script tag for this operation.And put below code between script starting tag // your code // script ending tag.

 function operation() 

 {

   var txtFirstNumberValue = parseInt(document.getElementById('basic').value);
   var txtSecondNumberValue =parseInt(document.getElementById('hra').value);
   var txtThirdNumberValue =parseInt(document.getElementById('transport').value);
   var txtFourthNumberValue =parseInt(document.getElementById('pt').value);
   var txtFiveNumberValue = parseInt(document.getElementById('pf').value);

   if (txtFirstNumberValue == "")
       txtFirstNumberValue = 0;
   if (txtSecondNumberValue == "")
       txtSecondNumberValue = 0;
   if (txtThirdNumberValue == "")
       txtThirdNumberValue = 0;
   if (txtFourthNumberValue == "")
       txtFourthNumberValue = 0;
   if (txtFiveNumberValue == "")
       txtFiveNumberValue = 0;



   var result = ((txtFirstNumberValue + txtSecondNumberValue + 
  txtThirdNumberValue) - (txtFourthNumberValue + txtFiveNumberValue));
   if (!isNaN(result)) {
       document.getElementById('total').value = result;
   }
 }

And put onkeyup="operation();" inside all 5 textboxes in your html form. This code running in both Firefox and Chrome.

How do I call a specific Java method on a click/submit event of a specific button in JSP?

Just give the individual button elements a unique name. When pressed, the button's name is available as a request parameter the usual way like as with input elements.

You only need to make sure that the button inputs have type="submit" as in <input type="submit"> and <button type="submit"> and not type="button", which only renders a "dead" button purely for onclick stuff and all.

E.g.

<form action="${pageContext.request.contextPath}/myservlet" method="post">
    <input type="submit" name="button1" value="Button 1" />
    <input type="submit" name="button2" value="Button 2" />
    <input type="submit" name="button3" value="Button 3" />
</form>

with

@WebServlet("/myservlet")
public class MyServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        MyClass myClass = new MyClass();

        if (request.getParameter("button1") != null) {
            myClass.method1();
        } else if (request.getParameter("button2") != null) {
            myClass.method2();
        } else if (request.getParameter("button3") != null) {
            myClass.method3();
        } else {
            // ???
        }

        request.getRequestDispatcher("/WEB-INF/some-result.jsp").forward(request, response);
    }

}

Alternatively, use <button type="submit"> instead of <input type="submit">, then you can give them all the same name, but an unique value. The value of the <button> won't be used as label, you can just specify that yourself as child.

E.g.

<form action="${pageContext.request.contextPath}/myservlet" method="post">
    <button type="submit" name="button" value="button1">Button 1</button>
    <button type="submit" name="button" value="button2">Button 2</button>
    <button type="submit" name="button" value="button3">Button 3</button>
</form>

with

@WebServlet("/myservlet")
public class MyServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        MyClass myClass = new MyClass();
        String button = request.getParameter("button");

        if ("button1".equals(button)) {
            myClass.method1();
        } else if ("button2".equals(button)) {
            myClass.method2();
        } else if ("button3".equals(button)) {
            myClass.method3();
        } else {
            // ???
        }

        request.getRequestDispatcher("/WEB-INF/some-result.jsp").forward(request, response);
    }

}

See also:

How we can bold only the name in table td tag not the value

Surround what you want to be bold with:

<span style="font-weight:bold">Your bold text</span>

This would go inside your <td> tag.

Video auto play is not working in Safari and Chrome desktop browser

Google just changed their policy for autoplay videos, it has to be muted

You can check here

so just add muted

<video height="256" loop="true" autoplay="autoplay" controls="controls" id="vid" muted>
         <source type="video/mp4" src="video_file.mp4"></source>
         <source type="video/ogg" src="video_file.ogg"></source>
</video>

Content-Disposition:What are the differences between "inline" and "attachment"?

It might also be worth mentioning that inline will try to open Office Documents (xls, doc etc) directly from the server, which might lead to a User Credentials Prompt.

see this link:

http://forums.asp.net/t/1885657.aspx/1?Access+the+SSRS+Report+in+excel+format+on+server

somebody tried to deliver an Excel Report from SSRS via ASP.Net -> the user always got prompted to enter the credentials. After clicking cancel on the prompt it would be opened anyway...

If the Content Disposition is marked as Attachment it will automatically be saved to the temp folder after clicking open and then opened in Excel from the local copy.

Hibernate, @SequenceGenerator and allocationSize

After digging into hibernate source code and Below configuration goes to Oracle db for the next value after 50 inserts. So make your INST_PK_SEQ increment 50 each time it is called.

Hibernate 5 is used for below strategy

Check also below http://docs.jboss.org/hibernate/orm/5.1/userguide/html_single/Hibernate_User_Guide.html#identifiers-generators-sequence

@Id
@Column(name = "ID")
@GenericGenerator(name = "INST_PK_SEQ", 
strategy = "org.hibernate.id.enhanced.SequenceStyleGenerator",
parameters = {
        @org.hibernate.annotations.Parameter(
                name = "optimizer", value = "pooled-lo"),
        @org.hibernate.annotations.Parameter(
                name = "initial_value", value = "1"),
        @org.hibernate.annotations.Parameter(
                name = "increment_size", value = "50"),
        @org.hibernate.annotations.Parameter(
                name = SequenceStyleGenerator.SEQUENCE_PARAM, value = "INST_PK_SEQ"),
    }
)
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "INST_PK_SEQ")
private Long id;

Switch on Enum in Java

First, you can switch on an enum in Java. I'm guessing you intended to say you can’t, but you can. chars have a set range of values, so it's easy to compare. Strings can be anything.

A switch statement is usually implemented as a jump table (branch table) in the underlying compilation, which is only possible with a finite set of values. C# can switch on strings, but it causes a performance decrease because a jump table cannot be used.

Java 7 and later supports String switches with the same characteristics.

Regex - Should hyphens be escaped?

Correct on all fronts. Outside of a character class (that's what the "square brackets" are called) the hyphen has no special meaning, and within a character class, you can place a hyphen as the first or last character in the range (e.g. [-a-z] or [0-9-]), OR escape it (e.g. [a-z\-0-9]) in order to add "hyphen" to your class.

It's more common to find a hyphen placed first or last within a character class, but by no means will you be lynched by hordes of furious neckbeards for choosing to escape it instead.

(Actually... my experience has been that a lot of regex is employed by folks who don't fully grok the syntax. In these cases, you'll typically see everything escaped (e.g. [a-z\%\$\#\@\!\-\_]) simply because the engineer doesn't know what's "special" and what's not... so they "play it safe" and obfuscate the expression with loads of excessive backslashes. You'll be doing yourself, your contemporaries, and your posterity a huge favor by taking the time to really understand regex syntax before using it.)

Great question!

How to call a stored procedure from Java and JPA

You can use @Query(value = "{call PROC_TEST()}", nativeQuery = true) in your repository. This worked for me.

Attention: use '{' and '}' or else it will not work.

Navigation Controller Push View Controller

Let's Say If you want to go from ViewController A --> B then

  1. Make sure your ViewControllerA is embedded in Navigation Controller

  2. In ViewControllerA's Button click you should have code like this.

@IBAction func goToViewController(_ sender: Any) {

    if let viewControllerB = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "ViewControllerB") as? ViewControllerB {

        if let navigator = navigationController {
            navigator.pushViewController(viewControllerB, animated: true)
        }
    }
}
  1. Please double check your storyboard name, and ViewControllerB's Identifier mentioned in storyboard for ViewControllerB's View

Look at StoryboardID = ViewControllerB

enter image description here

How do I find the absolute position of an element using jQuery?

Note that $(element).offset() tells you the position of an element relative to the document. This works great in most circumstances, but in the case of position:fixed you can get unexpected results.

If your document is longer than the viewport and you have scrolled vertically toward the bottom of the document, then your position:fixed element's offset() value will be greater than the expected value by the amount you have scrolled.

If you are looking for a value relative to the viewport (window), rather than the document on a position:fixed element, you can subtract the document's scrollTop() value from the fixed element's offset().top value. Example: $("#el").offset().top - $(document).scrollTop()

If the position:fixed element's offset parent is the document, you want to read parseInt($.css('top')) instead.

How to write to file in Ruby?

You can use the short version:

File.write('/path/to/file', 'Some glorious content')

It returns the length written; see ::write for more details and options.

To append to the file, if it already exists, use:

File.write('/path/to/file', 'Some glorious content', mode: 'a')

How to get milliseconds from LocalDateTime in Java 8

You can use java.sql.Timestamp also to get milliseconds.

LocalDateTime now = LocalDateTime.now();
long milliSeconds = Timestamp.valueOf(now).getTime();
System.out.println("MilliSeconds: "+milliSeconds);

In C++ check if std::vector<string> contains a certain value

it's in <algorithm> and called std::find.

What does it mean when an HTTP request returns status code 0?

In my case, the error occurred in a page requested with HTTP protocol, with a Javascript inside it trying to make an HTTPS request. And vice-versa.

After page loading, press F12 (or Ctrl + U) and take a look at the HTML code of your page. If you see something like that in your code:

<!-- javascript request inside the page -->
<script>
var ajaxurl = "https://example.com/wp-admin/admin-ajax.php";
(...)
</script>

And your page was requested this way:

http://example.com/example-page/2019/09/13/my-post/#elf_l1_Lw

You certainly will face this error.

To fix it, set the protocol of the Javascript request equal to the protocol of page request.

This situation involving different protocols, for page and js requests, was mentioned before in the answer of Brad Parks but, I guess the diagnostic technique presented here is easier, for the majority of users.

How to deep merge instead of shallow merge?

Here is an immutable (does not modify the inputs) version of @Salakar's answer. Useful if you're doing functional programming type stuff.

export function isObject(item) {
  return (item && typeof item === 'object' && !Array.isArray(item));
}

export default function mergeDeep(target, source) {
  let output = Object.assign({}, target);
  if (isObject(target) && isObject(source)) {
    Object.keys(source).forEach(key => {
      if (isObject(source[key])) {
        if (!(key in target))
          Object.assign(output, { [key]: source[key] });
        else
          output[key] = mergeDeep(target[key], source[key]);
      } else {
        Object.assign(output, { [key]: source[key] });
      }
    });
  }
  return output;
}

Android Studio - Device is connected but 'offline'

Change the USB cable !!!! I can't explain this technically, however after a lot of trial and error, this what have worked for me.

comparing 2 strings alphabetically for sorting purposes

Lets say that we have an array of objects:

{ name : String }

then we can sort our array as follows:

array.sort(function(a, b) {
    var orderBool = a.name > b.name;
    return orderBool ? 1 : -1;
});

Note: Be careful for upper letters, you may need to cast your string to lower case due to your purpose.

In MySQL, can I copy one row to insert into the same table?

I updated @LeonardChallis's solution as it didn't work for me as none of the others. I removed the WHERE clauses and SET primaryKey = 0 in the temp table so MySQL auto-increments itself the primaryKey

CREATE TEMPORARY TABLE tmptable SELECT * FROM myTable;
UPDATE tmptable SET primaryKey = 0;
INSERT INTO myTable SELECT * FROM tmptable;

This is of course to duplicate all the rows in the table.

How can I return an empty IEnumerable?

As for me, most elegant way is yield break

Java Delegates?

It doesn't have an explicit delegate keyword as C#, but you can achieve similar in Java 8 by using a functional interface (i.e. any interface with exactly one method) and lambda:

private interface SingleFunc {
    void printMe();
}

public static void main(String[] args) {
    SingleFunc sf = () -> {
        System.out.println("Hello, I am a simple single func.");
    };
    SingleFunc sfComplex = () -> {
        System.out.println("Hello, I am a COMPLEX single func.");
    };
    delegate(sf);
    delegate(sfComplex);
}

private static void delegate(SingleFunc f) {
    f.printMe();
}

Every new object of type SingleFunc must implement printMe(), so it is safe to pass it to another method (e.g. delegate(SingleFunc)) to call the printMe() method.

How to make asynchronous HTTP requests in PHP

Here is a working example, just run it and open storage.txt afterwards, to check the magical result

<?php
    function curlGet($target){
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $target);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $result = curl_exec ($ch);
        curl_close ($ch);
        return $result;
    }

    // Its the next 3 lines that do the magic
    ignore_user_abort(true);
    header("Connection: close"); header("Content-Length: 0");
    echo str_repeat("s", 100000); flush();

    $i = $_GET['i'];
    if(!is_numeric($i)) $i = 1;
    if($i > 4) exit;
    if($i == 1) file_put_contents('storage.txt', '');

    file_put_contents('storage.txt', file_get_contents('storage.txt') . time() . "\n");

    sleep(5);
    curlGet($_SERVER['HTTP_HOST'] . $_SERVER['SCRIPT_NAME'] . '?i=' . ($i + 1));
    curlGet($_SERVER['HTTP_HOST'] . $_SERVER['SCRIPT_NAME'] . '?i=' . ($i + 1));

"static const" vs "#define" vs "enum"

In C #define is much more popular. You can use those values for declaring array sizes for example:

#define MAXLEN 5

void foo(void) {
   int bar[MAXLEN];
}

ANSI C doesn't allow you to use static consts in this context as far as I know. In C++ you should avoid macros in these cases. You can write

const int maxlen = 5;

void foo() {
   int bar[maxlen];
}

and even leave out static because internal linkage is implied by const already [in C++ only].

Only allow Numbers in input Tag without Javascript

Though it's probably suggested to get some heavier validation via JS or on the server, HTML5 does support this via the pattern attribute.

<input type= "text" name= "name" pattern= "[0-9]"  title= "Title"/>

How to pass a list from Python, by Jinja2 to JavaScript

Make some invisible HTML tags like <label>, <p>, <input> etc. and name its id, and the class name is a pattern so that you can retrieve it later.

Let you have two lists maintenance_next[] and maintenance_block_time[] of the same length, and you want to pass these two list's data to javascript using the flask. So you take some invisible label tag and set its tag name is a pattern of list's index and set its class name as value at index.

_x000D_
_x000D_
{% for i in range(maintenance_next|length): %}_x000D_
<label id="maintenance_next_{{i}}" name="{{maintenance_next[i]}}" style="display: none;"></label>_x000D_
<label id="maintenance_block_time_{{i}}" name="{{maintenance_block_time[i]}}" style="display: none;"></label>_x000D_
{% endfor%}
_x000D_
_x000D_
_x000D_

Now you can retrieve the data in javascript using some javascript operation like below -

_x000D_
_x000D_
<script>_x000D_
var total_len = {{ total_len }};_x000D_
 _x000D_
for (var i = 0; i < total_len; i++) {_x000D_
    var tm1 = document.getElementById("maintenance_next_" + i).getAttribute("name");_x000D_
    var tm2 = document.getElementById("maintenance_block_time_" + i).getAttribute("name");_x000D_
    _x000D_
    //Do what you need to do with tm1 and tm2._x000D_
    _x000D_
    console.log(tm1);_x000D_
    console.log(tm2);_x000D_
}_x000D_
</script>
_x000D_
_x000D_
_x000D_

Change Schema Name Of Table In SQL

Be very very careful renaming objects in sql. You can cause dependencies to fail if you are not fully away with what you are doing. Having said that this works easily(too much so) for renaming things provided you have access proper on the environment:

exec sp_rename 'Nameofobject', 'ReNameofobject'

How to pass a querystring or route parameter to AWS Lambda from Amazon API Gateway

The following parameter-mapping example passes all parameters, including path, querystring and header, through to the integration endpoint via a JSON payload

#set($allParams = $input.params())
{
  "params" : {
    #foreach($type in $allParams.keySet())
    #set($params = $allParams.get($type))
    "$type" : {
      #foreach($paramName in $params.keySet())
      "$paramName" : "$util.escapeJavaScript($params.get($paramName))"
      #if($foreach.hasNext),#end
      #end
    }
    #if($foreach.hasNext),#end
    #end
  }
}

In effect, this mapping template outputs all the request parameters in the payload as outlined as follows:

{
  "parameters" : {
     "path" : {    
       "path_name" : "path_value", 
       ...
     }
     "header" : {  
       "header_name" : "header_value",
       ...
     }
     'querystring" : {
       "querystring_name" : "querystring_value",
       ...
     }
   }
}

Copied from the Amazon API Gateway Developer Guide

What is the use of adding a null key or value to a HashMap in Java?

One example of usage for null values is when using a HashMap as a cache for results of an expensive operation (such as a call to an external web service) which may return null.

Putting a null value in the map then allows you to distinguish between the case where the operation has not been performed for a given key (cache.containsKey(someKey) returns false), and where the operation has been performed but returned a null value (cache.containsKey(someKey) returns true, cache.get(someKey) returns null).

Without null values, you would have to either put some special value in the cache to indicate a null response, or simply not cache that response at all and perform the operation every time.

hardcoded string "row three", should use @string resource

It is not good practice to hard code strings into your layout files/ code. You should add them to a string resource file and then reference them from your layout.

  1. This allows you to update every occurrence of the same word in all
    layouts at the same time by just editing your strings.xml file.
  2. It is also extremely useful for supporting multiple languages as a separate strings.xml file can be used for each supported language
  3. the actual point of having the @string system please read over the localization documentation. It allows you to easily locate text in your app and later have it translated.
  4. Strings can be internationalized easily, allowing your application to support multiple languages with a single application package file (APK).

Benefits

  • Lets say you used same string in 10 different locations in the code. What if you decide to alter it? Instead of searching for where all it has been used in the project you just change it once and changes are reflected everywhere in the project.
  • Strings don’t clutter up your application code, leaving it clear and easy to maintain.

java.lang.IllegalArgumentException: No converter found for return value of type

In my case i'm using spring boot , and i have encountered a similar error :

No converter for [class java.util.ArrayList] with preset Content-Type 'null'

turns out that i have a controller with

@GetMapping(produces = { "application/xml", "application/json" })

and shamefully i wasn't adding the Accept header to my requests

How to replace values at specific indexes of a python list?

You can use operator.setitem.

from operator import setitem
a = [5, 4, 3, 2, 1, 0]
ell = [0, 1, 3, 5]
m = [0, 0, 0, 0]
for b, c in zip(ell, m):
    setitem(a, b, c)
>>> a
[0, 0, 3, 0, 1, 0]

Is it any more readable or efficient than your solution? I am not sure!

How to pass boolean parameter value in pipeline to downstream jobs?

build job: 'downstream_job_name', parameters: [
    booleanParam(name: 'parameter_name', value: false)
]

(cf. https://www.jenkins.io/doc/pipeline/steps/pipeline-build-step/#-build-%20build%20a%20job)

Parsing arguments to a Java command line program

You could just do it manually.

NB: might be better to use a HashMap instead of an inner class for the opts.

/** convenient "-flag opt" combination */
private class Option {
     String flag, opt;
     public Option(String flag, String opt) { this.flag = flag; this.opt = opt; }
}

static public void main(String[] args) {
    List<String> argsList = new ArrayList<String>();  
    List<Option> optsList = new ArrayList<Option>();
    List<String> doubleOptsList = new ArrayList<String>();

    for (int i = 0; i < args.length; i++) {
        switch (args[i].charAt(0)) {
        case '-':
            if (args[i].length < 2)
                throw new IllegalArgumentException("Not a valid argument: "+args[i]);
            if (args[i].charAt(1) == '-') {
                if (args[i].length < 3)
                    throw new IllegalArgumentException("Not a valid argument: "+args[i]);
                // --opt
                doubleOptsList.add(args[i].substring(2, args[i].length));
            } else {
                if (args.length-1 == i)
                    throw new IllegalArgumentException("Expected arg after: "+args[i]);
                // -opt
                optsList.add(new Option(args[i], args[i+1]));
                i++;
            }
            break;
        default:
            // arg
            argsList.add(args[i]);
            break;
        }
    }
    // etc
}

Loading context in Spring using web.xml

You can also specify context location relatively to current classpath, which may be preferable

<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath*:applicationContext*.xml</param-value>
</context-param>

<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

java collections - keyset() vs entrySet() in map

Every time you call itr2.next() you are getting a distinct value. Not the same value. You should only call this once in the loop.

Iterator<String> itr2 = keys.iterator();
    while(itr2.hasNext()){
        String v = itr2.next();
        System.out.println("Key: "+v+" ,value: "+m.get(v));
    }

How to get enum value by string or int

Simply try this

It's another way

public enum CaseOriginCode
{
    Web = 0,
    Email = 1,
    Telefoon = 2
}

public void setCaseOriginCode(string CaseOriginCode)
{
    int caseOriginCode = (int)(CaseOriginCode)Enum.Parse(typeof(CaseOriginCode), CaseOriginCode);
}

Converting Hexadecimal String to Decimal Integer

void htod(String hexadecimal)
{
    int h = hexadecimal.length() - 1;
    int d = 0;
    int n = 0;

    for(int i = 0; i<hexadecimal.length(); i++)
    {
        char ch = hexadecimal.charAt(i);
        boolean flag = false;
        switch(ch)
        {
            case '1': n = 1; break;
            case '2': n = 2; break;
            case '3': n = 3; break;
            case '4': n = 4; break;
            case '5': n = 5; break;
            case '6': n = 6; break;
            case '7': n = 7; break;
            case '8': n = 8; break;
            case '9': n = 9; break;
            case 'A': n = 10; break;
            case 'B': n = 11; break;
            case 'C': n = 12; break;
            case 'D': n = 13; break;
            case 'E': n = 14; break;
            case 'F': n = 15; break;
            default : flag = true;
        }
        if(flag)
        {
            System.out.println("Wrong Entry"); 
            break;
        }
        d = (int)(n*(Math.pow(16,h))) + (int)d;
        h--;
    }
    System.out.println("The decimal form of hexadecimal number "+hexadecimal+" is " + d);
}

JQuery Bootstrap Multiselect plugin - Set a value as selected in the multiselect dropdown

//Do it simple

var data="1,2,3,4";

//Make an array

var dataarray=data.split(",");

// Set the value

$("#multiselectbox").val(dataarray);

// Then refresh

$("#multiselectbox").multiselect("refresh");

Android Support Design TabLayout: Gravity Center and Mode Scrollable

Look at android-tablayouthelper

Automatically switch TabLayout.MODE_FIXED and TabLayout.MODE_SCROLLABLE depends on total tab width.

Substring in excel

Another way you can do this is by using the substitute function. Substitute "(", ")" and "," with spaces. e.g.

 =SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(A1, "(", " "), ")", " "), ",", " ")

Auto-Submit Form using JavaScript

A simple solution for a delayed auto submit:

<body onload="setTimeout(function() { document.frm1.submit() }, 5000)">
   <form action="https://www.google.com" name="frm1">
      <input type="hidden" name="q" value="Hello world" />
   </form>
</body>

Google map V3 Set Center to specific Marker

may be this will help:

map.setCenter(window.markersArray[2].getPosition());

all the markers info are in markersArray array and it is global. So you can access it from anywhere using window.variablename. Each marker has a unique id and you can put that id in the key of array. so you create marker like this:

window.markersArray[2] = new google.maps.Marker({
            position: new google.maps.LatLng(23.81927, 90.362349),          
            map: map,
            title: 'your info '  
        });

Hope this will help.

What's the environment variable for the path to the desktop?

@Dave Webb's answer is probably the way to go. The only other thing I can think of are the CSIDLs:

CSIDL_DESKTOPDIRECTORY

The file system directory used to physically store file objects on the desktop (which should not be confused with the desktop folder itself). A typical path is C:\Documents and Settings\username\Desktop.

I have no idea how to get hold of those from the command line, though.

How to display a gif fullscreen for a webpage background?

if you're happy using it as a background image and CSS3 then background-size: cover; would do the trick

When to use "ON UPDATE CASCADE"

A few days ago I've had an issue with triggers, and I've figured out that ON UPDATE CASCADE can be useful. Take a look at this example (PostgreSQL):

CREATE TABLE club
(
    key SERIAL PRIMARY KEY,
    name TEXT UNIQUE
);

CREATE TABLE band
(
    key SERIAL PRIMARY KEY,
    name TEXT UNIQUE
);

CREATE TABLE concert
(
    key SERIAL PRIMARY KEY,
    club_name TEXT REFERENCES club(name) ON UPDATE CASCADE,
    band_name TEXT REFERENCES band(name) ON UPDATE CASCADE,
    concert_date DATE
);

In my issue, I had to define some additional operations (trigger) for updating the concert's table. Those operations had to modify club_name and band_name. I was unable to do it, because of reference. I couldn't modify concert and then deal with club and band tables. I couldn't also do it the other way. ON UPDATE CASCADE was the key to solve the problem.

Null pointer Exception on .setOnClickListener

I too got similar error when i misplaced the code

text=(TextView)findViewById(R.id.text);// this line has to be below setcontentview
setContentView(R.layout.activity_my_otype);
//this is the correct place
text.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            }
    });

I got it working on placing the code in right order as shown below

setContentView(R.layout.activity_my_otype);
text=(TextView)findViewById(R.id.text);
 text.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            }
    });

How can I get the last 7 characters of a PHP string?

Safer results for working with multibyte character codes, allways use mb_substr instead substr. Example for utf-8:

$str = 'Ne zaman seni düsünsem';
echo substr( $str, -7 ) . ' <strong>is not equal to</strong> ' .
  mb_substr( $str, -7, null, 'UTF-8') ;

CMAKE_MAKE_PROGRAM not found

Well, if it is useful, I have had several problems with cmake, including this one. They all disappeared when I fix the global variable (in my case the MinGW Codeblocks) PATH in the system. When the codeblocks install is not in default, and for some unknow reason, this global variable does not point to the right place. Check if the path of Codeblocks or MinGW are correct:

Right click on "My Computer"> Properties> Advanced Properties or Advanced> Environment Variables> to Change the PATH variable

It worked for me;)

Replace new line/return with space using regex

Your regex is good altough I would replace it with the empty string

String resultString = subjectString.replaceAll("[\t\n\r]", "");

You expect a space between "text." and "And" right?

I get that space when I try the regex by copying your sample

"This is my text. "

So all is well here. Maybe if you just replace it with the empty string it will work. I don't know why you replace it with \s. And the alternation | is not necessary in a character class.

Setting Elastic search limit to "unlimited"

From the docs, "Note that from + size can not be more than the index.max_result_window index setting which defaults to 10,000". So my admittedly very ad-hoc solution is to just pass size: 10000 or 10,000 minus from if I use the from argument.

Note that following Matt's comment below, the proper way to do this if you have a larger amount of documents is to use the scroll api. I have used this successfully, but only with the python interface.

How to configure postgresql for the first time?

You probably need to update your pg_hba.conf file. This file controls what users can log in from what IP addresses. I think that the postgres user is pretty locked-down by default.

execute function after complete page load

you can try like this without using jquery

_x000D_
_x000D_
window.addEventListener("load", afterLoaded,false);
function afterLoaded(){
alert("after load")
}
_x000D_
_x000D_
_x000D_

BarCode Image Generator in Java

I use barbeque , it's great, and supports a very wide range of different barcode formats.
See if you like its API .

Sample API:

public static Barcode createCode128(java.lang.String data)
                             throws BarcodeException

Creates a Code 128 barcode that dynamically switches between character sets to give the smallest possible encoding. This will encode all numeric characters, upper and lower case alpha characters and control characters from the standard ASCII character set. The size of the barcode created will be the smallest possible for the given data, and use of this "optimal" encoding will generally give smaller barcodes than any of the other 3 "vanilla" encodings.

How to set the value for Radio Buttons When edit?

just add 'checked="checked"' in the correct radio button that you would like it to be default on. As example you could use php quick if notation to add that in:

<input type="radio" name="sex" value="Male" size="17" <?php echo($isMale?'checked="checked"':''); ?>>Male
<input type="radio" name="sex" value="Female" size="17" <?php echo($isFemale?'checked="checked"':''); ?>>Female

in this example $isMale & $isFemale is boolean values that you assign based on the value from your database.

ActionController::InvalidAuthenticityToken

If you have done a rake rails:update or otherwise recently changed your config/initializers/session_store.rb, this may be a symptom of old cookies in the browser. Hopefully this is done in dev/test (it was for me), and you can just clear all browser cookies related to the domain in question.

If this is in production, and you changed key, consider changing it back to use the old cookies (<- just speculation).

How to create PDF files in Python

fpdf works well for me. Much simpler than ReportLab and really free. Works with UTF-8.

Comparing arrays for equality in C++

Right. In most, if not all implementations of C, the array identifier can be implicitly casted to a pointer to the first element (i.e. the first element's address). What you're doing here is comparing those addresses, which is obviously wrong.

Instead, you need to iterate over both arrays, checking each element against each other. If you get to the end of both without a failure, they're equal.

PowerShell array initialization

The original example returns an error because the array is created empty, then you try to access the nth element to assign it a value.

The are a number of creative answers here, many I didn't know before reading this post. All are fine for a small array, but as n0rd points out, there are significant differences in performance.

Here I use Measure-Command to find out how long each initialization takes. As you might guess, any approach that uses an explicit PowerShell loop is slower than those that use .Net constructors or PowerShell operators (which would be compiled in IL or native code).

Summary

  • New-Object and @(somevalue)*n are fast (around 20k ticks for 100k elements).
  • Creating an array with the range operator n..m is 10x slower (200k ticks).
  • Using an ArrayList with the Add() method is 1000x slower than the baseline (20M ticks), as is looping through an already-sized array using for() or ForEach-Object (a.k.a. foreach,%).
  • Appending with += is the worst (2M ticks for just 1000 elements).

Overall, I'd say array*n is "best" because:

  • It's fast.
  • You can use any value, not just the default for the type.
  • You can create repeating values (to illustrate, type this at the powershell prompt: (1..10)*10 -join " " or ('one',2,3)*3)
  • Terse syntax.

The only drawback:

  • Non-obvious. If you haven't seen this construct before, it's not apparent what it does.

But keep in mind that for many cases where you would want to initialize the array elements to some value, then a strongly-typed array is exactly what you need. If you're initializing everything to $false, then is the array ever going to hold anything other than $false or $true? If not, then New-Object type[] n is the "best" approach.

Testing

Create and size a default array, then assign values:

PS> Measure-Command -Expression {$a = new-object object[] 100000} | Format-List -Property "Ticks"
Ticks : 20039

PS> Measure-Command -Expression {for($i=0; $i -lt $a.Length;$i++) {$a[$i] = $false}} | Format-List -Property "Ticks"
Ticks : 28866028

Creating an array of Boolean is bit little slower than and array of Object:

PS> Measure-Command -Expression {$a = New-Object bool[] 100000} | Format-List -Property "Ticks"
Ticks : 130968

It's not obvious what this does, the documentation for New-Object just says that the second parameter is an argument list which is passed to the .Net object constructor. In the case of arrays, the parameter evidently is the desired size.

Appending with +=

PS> $a=@()
PS> Measure-Command -Expression { for ($i=0; $i -lt 100000; $i++) {$a+=$false} } | Format-List -Property "Ticks"

I got tired of waiting for that to complete, so ctrl+c then:

PS> $a=@()
PS> Measure-Command -Expression { for ($i=0; $i -lt    100; $i++) {$a+=$false} } | Format-List -Property "Ticks"
Ticks : 147663
PS> $a=@()
PS> Measure-Command -Expression { for ($i=0; $i -lt   1000; $i++) {$a+=$false} } | Format-List -Property "Ticks"
Ticks : 2194398

Just as (6 * 3) is conceptually similar to (6 + 6 + 6), so ($somearray * 3) ought to give the same result as ($somearray + $somearray + $somearray). But with arrays, + is concatenation rather than addition.

If $array+=$element is slow, you might expect $array*$n to also be slow, but it's not:

PS> Measure-Command -Expression { $a = @($false) * 100000 } | Format-List -Property "Ticks"
Ticks : 20131

Just like Java has a StringBuilder class to avoid creating multiple objects when appending, so it seems PowerShell has an ArrayList.

PS> $al = New-Object System.Collections.ArrayList
PS> Measure-Command -Expression { for($i=0; $i -lt 1000; $i++) {$al.Add($false)} } | Format-List -Property "Ticks"
Ticks : 447133
PS> $al = New-Object System.Collections.ArrayList
PS> Measure-Command -Expression { for($i=0; $i -lt 10000; $i++) {$al.Add($false)} } | Format-List -Property "Ticks"
Ticks : 2097498
PS> $al = New-Object System.Collections.ArrayList
PS> Measure-Command -Expression { for($i=0; $i -lt 100000; $i++) {$al.Add($false)} } | Format-List -Property "Ticks"
Ticks : 19866894

Range operator, and Where-Object loop:

PS> Measure-Command -Expression { $a = 1..100000 } | Format-List -Property "Ticks"
Ticks : 239863
Measure-Command -Expression { $a | % {$false} } | Format-List -Property "Ticks"
Ticks : 102298091

Notes:

  • I nulled the variable between each run ($a=$null).
  • Testing was on a tablet with Atom processor; you would probably see faster speeds on other machines. [edit: About twice as fast on a desktop machine.]
  • There was a fair bit of variation when I tried multiple runs. Look for the orders of magnitude rather than exact numbers.
  • Testing was with PowerShell 3.0 in Windows 8.

Acknowledgements

Thanks to @halr9000 for array*n, @Scott Saad and Lee Desmond for New-Object, and @EBGreen for ArrayList.

Thanks to @n0rd for getting me to think about performance.

What's the difference between integer class and numeric class in R

There are multiple classes that are grouped together as "numeric" classes, the 2 most common of which are double (for double precision floating point numbers) and integer. R will automatically convert between the numeric classes when needed, so for the most part it does not matter to the casual user whether the number 3 is currently stored as an integer or as a double. Most math is done using double precision, so that is often the default storage.

Sometimes you may want to specifically store a vector as integers if you know that they will never be converted to doubles (used as ID values or indexing) since integers require less storage space. But if they are going to be used in any math that will convert them to double, then it will probably be quickest to just store them as doubles to begin with.

Working copy XXX locked and cleanup failed in SVN

In my case I solved it by manually deleting a record in the SQLite ".svn\wc" file lock record in the WC_LOCK table.

I opened the "WC" file with SQLite editor and executed

delete from WC_LOCK

screenshot showing all entries purged from WC_LOCK

Following eakkas's comment, you might need to delete all the entries from WORK_QUEUE table as well.

HTML5 Number Input - Always show 2 decimal places

My preferred approach, which uses data attributes to hold the state of the number:

<input type='number' step='0.01'/>

// react to stepping in UI
el.addEventListener('onchange', ev => ev.target.dataset.val = ev.target.value * 100)

// react to keys
el.addEventListener('onkeyup', ev => {

    // user cleared field
    if (!ev.target.value) ev.target.dataset.val = ''

    // non num input
    if (isNaN(ev.key)) {

        // deleting
        if (ev.keyCode == 8)

            ev.target.dataset.val = ev.target.dataset.val.slice(0, -1)

    // num input
    } else ev.target.dataset.val += ev.key

    ev.target.value = parseFloat(ev.target.dataset.val) / 100

})

Java: how to represent graphs?

I'd recommend graphviz highly when you get to the point where you want to render your graphs.

And its companions: take a look at Laszlo Szathmary's GraphViz class, along with notugly.xls.

Debugging PHP Mail() and/or PHPMailer

It looks like the class.phpmailer.php file is corrupt. I would download the latest version and try again.

I've always used phpMailer's SMTP feature:

$mail->IsSMTP();
$mail->Host = "localhost";

And if you need debug info:

$mail->SMTPDebug  = 2; // enables SMTP debug information (for testing)
                       // 1 = errors and messages
                       // 2 = messages only

Center icon in a div - horizontally and vertically

Horizontal centering is as easy as:

text-align: center

Vertical centering when the container is a known height:

height: 100px;
line-height: 100px;
vertical-align: middle

Vertical centering when the container isn't a known height AND you can set the image in the background:

background: url(someimage) no-repeat center center;

How to set margin of ImageView using code, not xml

In Kotlin you can write it in more pleasant way

myView.layoutParams = LinearLayout.LayoutParams(
                RadioGroup.LayoutParams.MATCH_PARENT, RadioGroup.LayoutParams.WRAP_CONTENT
            ).apply {
                setMargins(12, 12, 12, 12)
            }

Change remote repository credentials (authentication) on Intellij IDEA 14

IN Android Studio 2.3

  1. Open Setting (CTRL+ALT+S)
  2. Select Other Settings (at the end)
  3. select Bitbucket

Here you can change your new Password or User

How to pass table value parameters to stored procedure from .net code

The cleanest way to work with it. Assuming your table is a list of integers called "dbo.tvp_Int" (Customize for your own table type)

Create this extension method...

public static void AddWithValue_Tvp_Int(this SqlParameterCollection paramCollection, string parameterName, List<int> data)
{
   if(paramCollection != null)
   {
       var p = paramCollection.Add(parameterName, SqlDbType.Structured);
       p.TypeName = "dbo.tvp_Int";
       DataTable _dt = new DataTable() {Columns = {"Value"}};
       data.ForEach(value => _dt.Rows.Add(value));
       p.Value = _dt;
   }
}

Now you can add a table valued parameter in one line anywhere simply by doing this:

cmd.Parameters.AddWithValueFor_Tvp_Int("@IDValues", listOfIds);

How to display image from database using php

For example if you use this code , you can load image from db (mysql) and display it in php5 ;)

<?php
   $con =mysql_connect("localhost", "root" , "");
   $sdb= mysql_select_db("my_database",$con);
   $sql = "SELECT * FROM `news` WHERE 1";
   $mq = mysql_query($sql) or die ("not working query");
   $row = mysql_fetch_array($mq) or die("line 44 not working");
   $s=$row['photo'];
   echo $row['photo'];

   echo '<img src="'.$s.'" alt="HTML5 Icon" style="width:128px;height:128px">';
   ?>

Disable resizing of a Windows Forms form

There is far more efficient answer: just put the following instructions in the Form_Load:

Me.MinimumSize = New Size(Width, Height)
Me.MaximumSize = Me.MinimumSize

How to install XCODE in windows 7 platform?

X-code is primarily made for OS-X or iPhone development on Mac systems. Versions for Windows are not available. However this might help!

There is no way to get Xcode on Windows; however you can use a different SDK like Corona instead although it will not use Objective-C (I believe it uses Lua). I have however heard that it is horrible to use.

Source: classroomm.com

adb remount permission denied, but able to access super user in shell -- android

In case anyone has the same problem in the future:

$ adb shell
$ su
# mount -o rw,remount /system

Both adb remount and adb root don't work on a production build without altering ro.secure, but you can still remount /system by opening a shell, asking for root permissions and typing the mount command.

How to handle the modal closing event in Twitter Bootstrap?

Bootstrap Modal Events:

  1. hide.bs.modal => Occurs when the modal is about to be hidden.
  2. hidden.bs.modal => Occurs when the modal is fully hidden (after CSS transitions have completed).
<script type="text/javascript">
    $("#salesitems_modal").on('hide.bs.modal', function () {
        //actions you want to perform after modal is closed.
    });
</script>

I hope this will Help.

Comparing strings, c++

Regarding the question,

can someone explain why the compare() function exists if a comparison can be made using simple operands?

Relative to < and ==, the compare function is conceptually simpler and in practice it can be more efficient since it avoids two comparisons per item for ordinary ordering of items.


As an example of simplicity, for small integer values you can write a compare function like this:

auto compare( int a, int b ) -> int { return a - b; }

which is highly efficient.

Now for a structure

struct Foo
{
    int a;
    int b;
    int c;
};

auto compare( Foo const& x, Foo const& y )
    -> int
{
    if( int const r = compare( x.a, y.a ) ) { return r; }
    if( int const r = compare( x.b, y.b ) ) { return r; }
    return compare( x.c, y.c );
}

Trying to express this lexicographic compare directly in terms of < you wind up with horrendous complexity and inefficiency, relatively speaking.


With C++11, for the simplicity alone ordinary less-than comparison based lexicographic compare can be very simply implemented in terms of tuple comparison.

How to use bitmask?

Bit masking is "useful" to use when you want to store (and subsequently extract) different data within a single data value.

An example application I've used before is imagine you were storing colour RGB values in a 16 bit value. So something that looks like this:

RRRR RGGG GGGB BBBB

You could then use bit masking to retrieve the colour components as follows:

  const unsigned short redMask   = 0xF800;
  const unsigned short greenMask = 0x07E0;
  const unsigned short blueMask  = 0x001F;

  unsigned short lightGray = 0x7BEF;

  unsigned short redComponent   = (lightGray & redMask) >> 11;
  unsigned short greenComponent = (lightGray & greenMask) >> 5;
  unsigned short blueComponent =  (lightGray & blueMask);

How to set full calendar to a specific start date when it's initialized for the 1st time?

For v5 please use initialDate instead of defaultDate. Simply renamed option

eg

var calendarEl = document.getElementById('calendar');
var calendar = new FullCalendar.Calendar(calendarEl, {
     ...
     initialDate: '2020-09-02',
     ...
});

Swing JLabel text change on the running application

import java.awt.*;
import javax.swing.*;
import javax.swing.border.*;
import java.awt.event.*;
public class Test extends JFrame implements ActionListener
{
    private JLabel label;
    private JTextField field;
    public Test()
    {
        super("The title");
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setPreferredSize(new Dimension(400, 90));
        ((JPanel) getContentPane()).setBorder(new EmptyBorder(13, 13, 13, 13) );
        setLayout(new FlowLayout());
        JButton btn = new JButton("Change");
        btn.setActionCommand("myButton");
        btn.addActionListener(this);
        label = new JLabel("flag");
        field = new JTextField(5);
        add(field);
        add(btn);
        add(label);
        pack();
        setLocationRelativeTo(null);
        setVisible(true);
        setResizable(false);
    }
    public void actionPerformed(ActionEvent e)
    {
        if(e.getActionCommand().equals("myButton"))
        {
            label.setText(field.getText());
        }
    }
    public static void main(String[] args)
    {
        new Test();
    }
}

Matplotlib - Move X-Axis label downwards, but not X-Axis Ticks

If the variable ax.xaxis._autolabelpos = True, matplotlib sets the label position in function _update_label_position in axis.py according to (some excerpts):

    bboxes, bboxes2 = self._get_tick_bboxes(ticks_to_draw, renderer)
    bbox = mtransforms.Bbox.union(bboxes)
    bottom = bbox.y0
    x, y = self.label.get_position()
    self.label.set_position((x, bottom - self.labelpad * self.figure.dpi / 72.0))

You can set the label position independently of the ticks by using:

    ax.xaxis.set_label_coords(x0, y0)

that sets _autolabelpos to False or as mentioned above by changing the labelpad parameter.

command to remove row from a data frame

eldNew <- eld[-14,]

See ?"[" for a start ...

For ‘[’-indexing only: ‘i’, ‘j’, ‘...’ can be logical vectors, indicating elements/slices to select. Such vectors are recycled if necessary to match the corresponding extent. ‘i’, ‘j’, ‘...’ can also be negative integers, indicating elements/slices to leave out of the selection.

(emphasis added)

edit: looking around I notice How to delete the first row of a dataframe in R? , which has the answer ... seems like the title should have popped to your attention if you were looking for answers on SO?

edit 2: I also found How do I delete rows in a data frame? , searching SO for delete row data frame ...

Also http://rwiki.sciviews.org/doku.php?id=tips:data-frames:remove_rows_data_frame

pip install failing with: OSError: [Errno 13] Permission denied on directory

Option a) Create a virtualenv, activate it and install:

virtualenv .venv
source .venv/bin/activate
pip install -r requirements.txt

Option b) Install in your homedir:

pip install --user -r requirements.txt

My recommendation use safe (a) option, so that requirements of this project do not interfere with other projects requirements.

How do I Merge two Arrays in VBA?

Unfortunately there is no way to append / merge / insert / delete elements in arrays using VBA without doing it element by element, different from many modern languages, like Java or Javascript.

It's possible using split and join to do it, like a previous answer has showed, but it is a slow method and it is not generic.

For my personal use, I've implemented a splice functions for 1D arrays, similar to Javascript or Java. splice get an array and optionally delete some elements from a given position and also optionally insert an array in that position

'*************************************************************
'*                      Fill(N1,N2)
'* Create 1 dimension array with values from N1 to N2 step 1
'*************************************************************
Function Fill(N1 As Long, N2 As Long) As Variant
Dim Arr As Variant
If N2 < N1 Then
  Fill = False
  Exit Function
End If
Fill = WorksheetFunction.Transpose(
          Evaluate("Row(" & N1 & ":" & N2 & ")"))
End Function
'**********************************************************************
'*                        Slice(AArray, [N1,N2])
'* Slice an array between indices N1 to N2
'***********************************************************************
Function Slice(VArray As Variant, Optional N1 As Long = 1, 
               Optional N2 As Long = 0) As Variant
Dim Indices As Variant
If N2 = 0 Then N2 = UBound(VArray)
If N1 = LBound(VArray) And N2 = UBound(VArray) Then
   Slice = VArray
Else
  Indices = Fill(N1, N2)
  Slice = WorksheetFunction.Index(VArray, 1, Indices)
End If
End Function
'************************************************
'*                 AddArr(V1,V2, [V3])
'* Concatena 2 ou 3 vetores
'**************************************************
Function AddArr(V1 As Variant, V2 As Variant, 
  Optional V3 As Variant = 0, Optional Sep = "#") As Variant
Dim Arr As Variant
Dim Ini As Integer
Dim N As Long, K As Long, I As Integer
  Arr = V1
  Ini = UBound(Arr)
  N = UBound(V1) - LBound(V1) + 1 + UBound(V2) - LBound(V2) + 1
  ReDim Preserve Arr(N)
  K = 0
  For I = LBound(V2) To UBound(V2)
    K = K + 1
    Arr(Ini + K) = V2(I)
  Next I
If IsArray(V3) Then
  Ini = UBound(Arr)
  N = UBound(Arr) - LBound(Arr) + 1 + UBound(V3) - LBound(V3) + 1
  ReDim Preserve Arr(N)
  K = 0
  For I = LBound(V3) To UBound(V3)
    K = K + 1
    Arr(Ini + K) = V3(I)
  Next I
End If
AddArr = Arr
End Function

'**********************************************************************
'*                        Slice(AArray,Ind, [ NElme, Vet] )
'* Delete NELEM (default 0) element from position IND in VARRAY
'* and optionally insert an array VET in that postion
'***********************************************************************
Function Splice(VArray As Variant, Ind As Long, 
  Optional NElem As Long = 0, Optional Vet As Variant = 0) As Variant
Dim V1, V2
If Ind < LBound(VArray) Or Ind > UBound(VArray) Or NElem < 0 Then
  Splice = False
  Exit Function
End If
V2 = Slice(VArray, Ind + NElem, UBound(VArray))
If Ind > LBound(VArray) Then
  V1 = Slice(VArray, LBound(VArray), Ind - 1)
  If IsArray(Vet) Then
     Splice = AddArr(V1, Vet, V2)
  Else
     Splice = AddArr(V1, V2)
  End If
Else
  If IsArray(Vet) Then
     Splice = AddArr(Vet, V2)
  Else
     Splice = V2
  End If
End If

End Function

For testing

Sub TestSplice()
Dim V, Res
Dim J As Integer
V = Fill(100, 109)
Res = Splice(V, 2, 2, Array(201, 202))
PrintArr (Res)
End Sub

'************************************************
'*                 PrintArr(VArr)
'* Print the array VARR
'**************************************************
Function PrintArr(VArray As Variant)
Dim S As String
S = Join(VArray, ", ")
MsgBox (S)
End Function

Results in

100,201,202,103,104,105,106,107,108,109

matplotlib: Group boxplots

Just to add to the conversation, I have found a more elegant way to change the color of the box plot by iterating over the dictionary of the object itself

import numpy as np
import matplotlib.pyplot as plt

def color_box(bp, color):

    # Define the elements to color. You can also add medians, fliers and means
    elements = ['boxes','caps','whiskers']

    # Iterate over each of the elements changing the color
    for elem in elements:
        [plt.setp(bp[elem][idx], color=color) for idx in xrange(len(bp[elem]))]
    return

a = np.random.uniform(0,10,[100,5])    

bp = plt.boxplot(a)
color_box(bp, 'red')

Original box plot

Modified box plot

Cheers!

jquery variable syntax

The dollarsign as a prefix in the var name is a usage from the concept of the hungarian notation.

Setting font on NSAttributedString on UITextView disregards line spacing

I found your question because I was also fighting with NSAttributedString. For me, the beginEditing and endEditing methods did the trick, like stated in Changing an Attributed String. Apart from that, the lineSpacing is set with setLineSpacing on the paragraphStyle.

So you might want to try changing your code to:

NSString *string = @" Hello \n world";
attrString = [[NSMutableAttributedString alloc] initWithString:string];
NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle defaultParagraphStyle] mutableCopy];

[paragraphStyle setLineSpacing:20]  // Or whatever (positive) value you like...    
[attrSting beginEditing];

[attrString addAttribute:NSFontAttributeName value:[UIFont boldSystemFontOfSize:20] range:NSMakeRange(0, string.length)];
[attrString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, string.length)];

[attrString endEditing];

mainTextView.attributedText = attrString;

Didn't test this exact code though, btw, but mine looks nearly the same.

EDIT:

Meanwhile, I've tested it, and, correct me if I'm wrong, the - beginEditing and - endEditing calls seem to be of quite an importance.

no operator "<<" matches these operands

If you want to use std::string reliably, you must #include <string>.

NSDictionary - Need to check whether dictionary contains key-value pair or not

With literal syntax you can check as follows

static const NSString* kKeyToCheck = @"yourKey"
if (xyz[kKeyToCheck])
  NSLog(@"Key: %@, has Value: %@", kKeyToCheck, xyz[kKeyToCheck]);
else
 NSLog(@"Key pair do not exits for key: %@", kKeyToCheck); 

Clicking a checkbox with ng-click does not update the model

Why dont you use

$watch('todo',function(.....

Or another solution would be to set the todo.done inside the ng-click callback and only use ng-click

<div ng-app="myApp" ng-controller="Ctrl">
<li  ng-repeat="todo in todos">
<input type='checkbox' ng-click='onCompleteTodo(todo)'>
    {{todo.text}} {{todo.done}}

and

$scope.onCompleteTodo = function(todo) {
        todo.done = !todo.done; //toggle value
        console.log("onCompleteTodo -done: " + todo.done + " : " + todo.text);
        $scope.current = todo;
}

How to convert an integer (time) to HH:MM:SS::00 in SQL Server 2008?

declare @T int

set @T = 10455836
--set @T = 421151

select (@T / 1000000) % 100 as hour,
       (@T / 10000) % 100 as minute,
       (@T / 100) % 100 as second,
       (@T % 100) * 10 as millisecond

select dateadd(hour, (@T / 1000000) % 100,
       dateadd(minute, (@T / 10000) % 100,
       dateadd(second, (@T / 100) % 100,
       dateadd(millisecond, (@T % 100) * 10, cast('00:00:00' as time(2))))))  

Result:

hour        minute      second      millisecond
----------- ----------- ----------- -----------
10          45          58          360

(1 row(s) affected)


----------------
10:45:58.36

(1 row(s) affected)

Can't create handler inside thread that has not called Looper.prepare() inside AsyncTask for ProgressDialog

I had a hard time making this work too, the solution for me was to use both hyui and konstantin answers,

class ExampleTask extends AsyncTask<String, String, String> {

// Your onPreExecute method.

@Override
protected String doInBackground(String... params) {
    // Your code.
    if (condition_is_true) {
        this.publishProgress("Show the dialog");
    }
    return "Result";
}

@Override
protected void onProgressUpdate(String... values) {

    super.onProgressUpdate(values);
    YourActivity.this.runOnUiThread(new Runnable() {
       public void run() {
           alertDialog.show();
       }
     });
 }

}

How to convert string to integer in C#

int i;
string whatever;

//Best since no exception raised
int.TryParse(whatever, out i);

//Better use try catch on this one
i = Convert.ToInt32(whatever);

Types in Objective-C on iOS

Update for the new 64bit arch

Ranges:
CHAR_MIN:   -128
CHAR_MAX:   127
SHRT_MIN:   -32768
SHRT_MAX:   32767
INT_MIN:    -2147483648
INT_MAX:    2147483647
LONG_MIN:   -9223372036854775808
LONG_MAX:   9223372036854775807
ULONG_MAX:  18446744073709551615
LLONG_MIN:  -9223372036854775808
LLONG_MAX:  9223372036854775807
ULLONG_MAX: 18446744073709551615

PHP - Debugging Curl

Another (crude) option is to utilize netcat for dumping the full request:

nc -l -p 8000 -w 3 | tee curldbg.txt

And of course sending the failing request to it:

curl_setup(CURLOPT_URL, "http://localhost/testytest");

Notably that will always hang+fail, since netcat won't ever construct a valid HTTP response. It's really just for inspecting what really got sent. The better option, of course, is using a http request debugging service.

is python capable of running on multiple cores?

Threads share a process and a process runs on a core, but you can use python's multiprocessing module to call your functions in separate processes and use other cores, or you can use the subprocess module, which can run your code and non-python code too.

java.io.FileNotFoundException: class path resource cannot be opened because it does not exist

What you put directly under src/main/java is in the default package, at the root of the classpath. It's the same for resources put under src/main/resources: they end up at the root of the classpath.

So the path of the resource is app-context.xml, not main/resources/app-context.xml.

How to get last inserted row ID from WordPress database?

Straight after the $wpdb->insert() that does the insert, do this:

$lastid = $wpdb->insert_id;

More information about how to do things the WordPress way can be found in the WordPress codex. The details above were found here on the wpdb class page

How to set username and password for SmtpClient object in .NET?

SmtpClient MyMail = new SmtpClient();
MailMessage MyMsg = new MailMessage();
MyMail.Host = "mail.eraygan.com";
MyMsg.Priority = MailPriority.High;
MyMsg.To.Add(new MailAddress(Mail));
MyMsg.Subject = Subject;
MyMsg.SubjectEncoding = Encoding.UTF8;
MyMsg.IsBodyHtml = true;
MyMsg.From = new MailAddress("username", "displayname");
MyMsg.BodyEncoding = Encoding.UTF8;
MyMsg.Body = Body;
MyMail.UseDefaultCredentials = false;
NetworkCredential MyCredentials = new NetworkCredential("username", "password");
MyMail.Credentials = MyCredentials;
MyMail.Send(MyMsg);

Android Studio does not show layout preview

I used the Debug "app" button enter image description here
and my problem was solved

Convert an integer to a float number

Type Conversions T() where T is the desired datatype of the result are quite simple in GoLang.

In my program, I scan an integer i from the user input, perform a type conversion on it and store it in the variable f. The output prints the float64 equivalent of the int input. float32 datatype is also available in GoLang

Code:

package main
import "fmt"
func main() {
    var i int
    fmt.Println("Enter an Integer input: ")
    fmt.Scanf("%d", &i)
    f := float64(i)
    fmt.Printf("The float64 representation of %d is %f\n", i, f)
}

Solution:

>>> Enter an Integer input:
>>> 232332
>>> The float64 representation of 232332 is 232332.000000

Performance differences between ArrayList and LinkedList

ArrayList: The ArrayList class extends AbstractList and implements the List interface and RandomAccess (marker interface). ArrayList supports dynamic arrays that can grow as needed. It gives us first iteration over elements.

LinkedList: A LinkedList is ordered by index position, like ArrayList, except that the elements are doubly-linked to one another. This linkage gives you new methods (beyond what you get from the List interface) for adding and removing from the beginning or end, which makes it an easy choice for implementing a stack or queue. Keep in mind that a LinkedList may iterate more slowly than an ArrayList, but it's a good choice when you need fast insertion and deletion. As of Java 5, the LinkedList class has been enhanced to implement the java.util.Queue interface. As such, it now supports the common queue methods: peek (), poll (), and offer ().

Each GROUP BY expression must contain at least one column that is not an outer reference

When you're using GROUP BY, you need to also use aggregate functions for the columns not inside your group by clause.

I don't know exactly what you're trying to do, but I guess this would work:

select 
    LEFT(SUBSTRING(batchinfo.datapath, PATINDEX('%[0-9][0-9][0-9]%', batchinfo.datapath), 8000),
    PATINDEX('%[^0-9]%', SUBSTRING(batchinfo.datapath, PATINDEX('%[0-9][0-9][0-9]%', batchinfo.datapath), 8000))-1),
    qvalues.name,
    qvalues.compound,
    MAX(qvalues.rid)
from
    batchinfo join qvalues on batchinfo.rowid=qvalues.rowid
where
    LEN(datapath)>4
group by
    LEFT(SUBSTRING(batchinfo.datapath, PATINDEX('%[0-9][0-9][0-9]%', batchinfo.datapath), 8000),
    PATINDEX('%[^0-9]%', SUBSTRING(batchinfo.datapath, PATINDEX('%[0-9][0-9][0-9]%', batchinfo.datapath), 8000))-1),
    qvalues.name,
    qvalues.compound
having
    rid!=MAX(rid)

Edit: What I'm trying to do here is a group by with all fields but rid. If that's not what you want, what you need to do in order to have a valid SQL statement is adding an aggregate function call for each removed group by field...

Error:java: javacTask: source release 8 requires target release 1.8

I just re-import maven button, then the error disappeared.

enter image description here

Filling a List with all enum values in Java

private ComboBox gender;
private enum Selgender{Male,Famle};
ObservableList<Object> observableList  =FXCollections.observableArrayList(Selgender.values());

How to convert a Bitmap to Drawable in android?

I used with context

//Convert bitmap to drawable
Drawable drawable = new BitmapDrawable(context.getResources(), bitmap);

Declare variable in table valued function

There are two flavors of table valued functions. One that is just a select statement and one that can have more rows than just a select statement.

This can not have a variable:

create function Func() returns table
as
return
select 10 as ColName

You have to do like this instead:

create function Func()
returns @T table(ColName int)
as
begin
  declare @Var int
  set @Var = 10
  insert into @T(ColName) values (@Var)
  return
end

How to change maven java home

If you are in Linux, set JAVA_HOME using syntax export JAVA_HOME=<path-to-java>. Actually it is not only for Maven.

Importing large sql file to MySql via command line

+1 to @MartinNuc, you can run the mysql client in batch mode and then you won't see the long stream of "OK" lines.

The amount of time it takes to import a given SQL file depends on a lot of things. Not only the size of the file, but the type of statements in it, how powerful your server server is, and how many other things are running at the same time.

@MartinNuc says he can load 4GB of SQL in 4-5 minutes, but I have run 0.5 GB SQL files and had it take 45 minutes on a smaller server.

We can't really guess how long it will take to run your SQL script on your server.


Re your comment,

@MartinNuc is correct you can choose to make the mysql client print every statement. Or you could open a second session and run mysql> SHOW PROCESSLIST to see what's running. But you probably are more interested in a "percentage done" figure or an estimate for how long it will take to complete the remaining statements.

Sorry, there is no such feature. The mysql client doesn't know how long it will take to run later statements, or even how many there are. So it can't give a meaningful estimate for how much time it will take to complete.

Convert any object to a byte[]

How about something simple like this?

return ((object[])value).Cast<byte>().ToArray(); 

How to get values from selected row in DataGrid for Windows Form Application?

Description

Assuming i understand your question.

You can get the selected row using the DataGridView.SelectedRows Collection. If your DataGridView allows only one selected, have a look at my sample.

DataGridView.SelectedRows Gets the collection of rows selected by the user.

Sample

if (dataGridView1.SelectedRows.Count != 0)
{
    DataGridViewRow row = this.dataGridView1.SelectedRows[0];
    row.Cells["ColumnName"].Value
}

More Information

Plotting using a CSV file

You can also plot to a png file using gnuplot (which is free):

terminal commands

gnuplot> set title '<title>'
gnuplot> set ylabel '<yLabel>'
gnuplot> set xlabel '<xLabel>'
gnuplot> set grid
gnuplot> set term png
gnuplot> set output '<Output file name>.png'
gnuplot> plot '<fromfile.csv>'

note: you always need to give the right extension (.png here) at set output

Then it is also possible that the ouput is not lines, because your data is not continues. To fix this simply change the 'plot' line to:

plot '<Fromfile.csv>' with line lt -1 lw 2

More line editing options (dashes and line color ect.) at: http://gnuplot.sourceforge.net/demo_canvas/dashcolor.html

  • gnuplot is available in most linux distros via the package manager (e.g. on an apt based distro, run apt-get install gnuplot)
  • gnuplot is available in windows via Cygwin
  • gnuplot is available on macOS via homebrew (run brew install gnuplot)

How to stop VMware port error of 443 on XAMPP Control Panel v3.2.1

It's easier to change the port in VMware Workstation:

  1. Edit > Preferences;
  2. Shared VMs tab;
  3. Disable;
  4. Change port;
  5. Enable.

enter image description here

enter image description here

enter image description here

Done.

How do you add a timer to a C# console application

Or using Rx, short and sweet:

static void Main()
{
Observable.Interval(TimeSpan.FromSeconds(10)).Subscribe(t => Console.WriteLine("I am called... {0}", t));

for (; ; ) { }
}

List all tables in postgresql information_schema

1.get all tables and views from information_schema.tables, include those of information_schema and pg_catalog.

select * from information_schema.tables

2.get tables and views belong certain schema

select * from information_schema.tables
    where table_schema not in ('information_schema', 'pg_catalog')

3.get tables only(almost \dt)

select * from information_schema.tables
    where table_schema not in ('information_schema', 'pg_catalog') and
    table_type = 'BASE TABLE'

How to get date and time from server

For enable PHP Extension intl , follow the Steps..

  1. Open the xampp/php/php.ini file in any editor.
  2. Search ";extension=php_intl.dll"
  3. kindly remove the starting semicolon ( ; ) Like : ;extension=php_intl.dll. to. extension=php_intl.dll.
  4. Save the xampp/php/php.ini file.
  5. Restart your xampp/wamp.

Get lengths of a list in a jinja2 template

Alex' comment looks good but I was still confused with using range. The following worked for me while working on a for condition using length within range.

{% for i in range(0,(nums['list_users_response']['list_users_result']['users'])| length) %}
<li>    {{ nums['list_users_response']['list_users_result']['users'][i]['user_name'] }} </li>
{% endfor %}

PHP function ssh2_connect is not working

I have solved this on ubuntu 16.4 PHP 7.0.27-0+deb9u and nginx

sudo apt install php-ssh2 

Java: how can I split an ArrayList in multiple small ArrayLists?

You can use subList(int fromIndex, int toIndex) to get a view of a portion of the original list.

From the API:

Returns a view of the portion of this list between the specified fromIndex, inclusive, and toIndex, exclusive. (If fromIndex and toIndex are equal, the returned list is empty.) The returned list is backed by this list, so non-structural changes in the returned list are reflected in this list, and vice-versa. The returned list supports all of the optional list operations supported by this list.

Example:

List<Integer> numbers = new ArrayList<Integer>(
    Arrays.asList(5,3,1,2,9,5,0,7)
);

List<Integer> head = numbers.subList(0, 4);
List<Integer> tail = numbers.subList(4, 8);
System.out.println(head); // prints "[5, 3, 1, 2]"
System.out.println(tail); // prints "[9, 5, 0, 7]"

Collections.sort(head);
System.out.println(numbers); // prints "[1, 2, 3, 5, 9, 5, 0, 7]"

tail.add(-1);
System.out.println(numbers); // prints "[1, 2, 3, 5, 9, 5, 0, 7, -1]"

If you need these chopped lists to be NOT a view, then simply create a new List from the subList. Here's an example of putting a few of these things together:

// chops a list into non-view sublists of length L
static <T> List<List<T>> chopped(List<T> list, final int L) {
    List<List<T>> parts = new ArrayList<List<T>>();
    final int N = list.size();
    for (int i = 0; i < N; i += L) {
        parts.add(new ArrayList<T>(
            list.subList(i, Math.min(N, i + L)))
        );
    }
    return parts;
}


List<Integer> numbers = Collections.unmodifiableList(
    Arrays.asList(5,3,1,2,9,5,0,7)
);
List<List<Integer>> parts = chopped(numbers, 3);
System.out.println(parts); // prints "[[5, 3, 1], [2, 9, 5], [0, 7]]"
parts.get(0).add(-1);
System.out.println(parts); // prints "[[5, 3, 1, -1], [2, 9, 5], [0, 7]]"
System.out.println(numbers); // prints "[5, 3, 1, 2, 9, 5, 0, 7]" (unmodified!)

Download Excel file via AJAX MVC

using ClosedXML.Excel;

   public ActionResult Downloadexcel()
    {   
        var Emplist = JsonConvert.SerializeObject(dbcontext.Employees.ToList());
        DataTable dt11 = (DataTable)JsonConvert.DeserializeObject(Emplist, (typeof(DataTable)));
        dt11.TableName = "Emptbl";
        FileContentResult robj;
        using (XLWorkbook wb = new XLWorkbook())
        {
            wb.Worksheets.Add(dt11);
            using (MemoryStream stream = new MemoryStream())
            {
                wb.SaveAs(stream);
                var bytesdata = File(stream.ToArray(), "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "myFileName.xlsx");
                robj = bytesdata;
            }
        }


        return Json(robj, JsonRequestBehavior.AllowGet);
    }

change html input type by JS?

_x000D_
_x000D_
$(".show-pass").click(function (e) {_x000D_
    e.preventDefault();_x000D_
    var type = $("#signupform-password").attr('type');_x000D_
    switch (type) {_x000D_
        case 'password':_x000D_
        {_x000D_
            $("#signupform-password").attr('type', 'text');_x000D_
            return;_x000D_
        }_x000D_
        case 'text':_x000D_
        {_x000D_
            $("#signupform-password").attr('type', 'password');_x000D_
            return;_x000D_
        }_x000D_
    }_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<input type="text" name="password" class="show-pass">
_x000D_
_x000D_
_x000D_

Difference between chr(13) and chr(10)

Chr(10) is the Line Feed character and Chr(13) is the Carriage Return character.

You probably won't notice a difference if you use only one or the other, but you might find yourself in a situation where the output doesn't show properly with only one or the other. So it's safer to include both.


Historically, Line Feed would move down a line but not return to column 1:

This  
    is  
        a  
            test.

Similarly Carriage Return would return to column 1 but not move down a line:

This  
is  
a  
test.

Paste this into a text editor and then choose to "show all characters", and you'll see both characters present at the end of each line. Better safe than sorry.

Download File to server from URL

Use a simple method in php copy()

copy($source_url, $local_path_with_file_name);

Note: if the destination file already exists, it will be overwritten

PHP copy() Function

Note: You need to set permission 777 for the destination folder. Use this method when you are downloading to your local machine.

Special Note: 777 is a permission in Unix based system with full read/write/execute permission to owner, group and everyone. In general we give this permission to assets which are not much needed to be hidden from public on a web server. Example: images folder.

How to run Linux commands in Java?

You can also write a shell script file and invoke that file from the java code. as shown below

{
   Process proc = Runtime.getRuntime().exec("./your_script.sh");                        
   proc.waitFor();
}

Write the linux commands in the script file, once the execution is over you can read the diff file in Java.

The advantage with this approach is you can change the commands with out changing java code.

Using ng-if as a switch inside ng-repeat?

This one is noteworthy as well

<div ng-repeat="post in posts" ng-if="post.type=='article'">
  <h1>{{post.title}}</h1>
</div>

Visual Studio 2017 does not have Business Intelligence Integration Services/Projects

Information on this will probably get outdated fast because Microsoft is running to complete its work on this, but as today, June 9th 2017, support to create SQL Server Integration Services (SSIS) projects on Visual Studio 2017 is not available. So, you can't see this option because so far it doesn't exist yet.

Beyond that, even installing what is being called SSDT (SQL Server Data Tools) in VS 2017 installer (what seems very confusing from Microsoft's part, using a known name for a different thing, breaking the behavior we expect as users), you won't see SQL Server Analysis Services (SSAS) and SQL Server Reporting Services (SSRS) project templates as well.

Actually, the Business Intelligence group under the Installed templates on the New Project dialog won't be present at all.

You need to go to this page (https://docs.microsoft.com/en-us/sql/ssdt/download-sql-server-data-tools-ssdt) and install two separate installers, one for SSAS and one for SSRS.

Once you install at least one of these components, the Business Intelligence group will be created and the correspondent template(s) will be available. But as today, there is no installer for SSIS, so if you need to work with SSIS projects, you need to keep using SSDT 2015, for now.

Anaconda Navigator won't launch (windows 10)

You need to run the cmd prompt from the Scripts directory of Anaconda where ever you have the Anaconda parent folder installed. I happen to have in the root directory of the C drive on my Windows machine. If you are not familiar there are two ways to do that:

A) Use the key combination Win-key + R then type cmd and hit return to launch the terminal window and then type: cd C:\Anaconda\Scripts (or whatever directory path yours is).

B) Navigate using windows explorer to that Scripts directory then type cmd in the address bar of that window and hit return (that will launch the terminal already set to that directory).

Next type the follow commands waiting in between for each to complete:

activate root
conda update -n root conda
conda update --all

When complete type the following and Navigator hopefully should launch:

anaconda-navigator

How to automatically indent source code?

In 2010 it is Ctrl+k, Ctrl+d. See image below.

enter image description here

how to run vibrate continuously in iphone?

The above answers are good and you can do it in a simple way also.

You can use the recursive method calls.

func vibrateTheDeviceContinuously() throws {
        
        // Added concurrent queue for next & Vibrate device
        DispatchQueue.global(qos: .utility).async {
            
            //Vibrate the device
            AudioServicesPlaySystemSound(kSystemSoundID_Vibrate)

            self.incrementalCount += 1
            usleep(800000) // if you don't want, remove this line.

            do {
                if let isKeepBuzzing = self.iShouldKeepBuzzing , isKeepBuzzing == true {
                    try self.vibrateTheDeviceContinuously()
                }
                 else {
                    return 
                 }
                
            } catch  {
                //Exception handle
               print("exception")
            }
            
        }
    }

To stop the device vibration use the following line.

self.iShouldKeepBuzzing = false

How to study design patterns?

My two cents for such and old question

Some people already mentioned, practice and refactoring. I believe the right order to learn about patterns is this:

  1. Learn Test Driven Development (TDD)
  2. Learn refactoring
  3. Learn patterns

Most people ignore 1, many believe they can do 2, and almost everybody goes straight for 3.

For me the key to improve my software skills was learning TDD. It might be a long time of painful and slow coding, but writing your tests first certainly makes you think a lot about your code. If a class needs too much boilerplate or breaks easily you start noticing bad smells quite fast

The main benefit of TDD is that you lose your fear of refactoring your code and force you to write classes that are highly independent and cohesive. Without a good set of tests, it is just too painful to touch something that is not broken. With safety net you will really adventure into drastic changes to your code. That is the moment when you can really start learning from practice.

Now comes the point where you must read books about patterns, and to my opinion, it is a complete waste of time trying too hard. I only understood patterns really well after noticing I did something similar, or I could apply that to existing code. Without the safety tests, or habits of refactoring, I would have waited until a new project. The problem of using patterns in a fresh project is that you do not see how they impact or change a working code. I only understood a software pattern once I refactored my code into one of them, never when I introduced one fresh in my code.

package javax.servlet.http does not exist

This error occurs when you compile a java program using classes that support the Servlet API. The compiler searches for the library (included in a .jar file) by using the CLASSPATH. You can specify this when you compile using -classpath or -cp options as noted in other responses, but you should set up your environment to define the classpath as needed.

Set the CLASSPATH environment variable to reference the location of servlet-api.jar, which depends on your setup (OS, how you installed, etc.)

Assuming you're using Tomcat and have installed it in one of 20 possible ways, the APIs used by servlets will be installed on your system, relative to wherever Tomcat is installed. For historical reasons, Tomcat is also known as "Catalina", so you can use the command "catalina" to run certain commands, and alone, it will report, amongst other things the CATALINA_BASE. For example on my Mac using Tomcat installed using homebrew it's

Using CATALINA_BASE:   /usr/local/Cellar/tomcat/8.5.9/libexec

The location of the Tomcat servlet libraries is under this in the lib directory. Set CATALINA_BASE, then set CLASSPATH using the base as a start, for example for Linux or OSX you might set this in .profile, or .bash_profile like so:

export CATALINA_BASE=/usr/local/Cellar/tomcat/8.5.9/libexec
export CLASSPATH=$CATALINA_BASE/lib/servlet-api.jar:$CLASSPATH

Exit the terminal/shell and come back in to run the profile. You should be able to see that the variable is set by using the echo command, e.g.

echo $CLASSPATH

or in Windows

echo %CLASSPATH%

If it displays the full path to the jar `javac WebTest.java' compile your class.

Other answers are correct -- set up your IDE (Eclipse, IntelliJ) to know about Tomcat or build with Maven and you'll save pain.

How to fill OpenCV image with one solid color?

Use numpy.full. Here's a Python that creates a gray, blue, green and red image and shows in a 2x2 grid.

import cv2
import numpy as np

gray_img = np.full((100, 100, 3), 127, np.uint8)

blue_img = np.full((100, 100, 3), 0, np.uint8)
green_img = np.full((100, 100, 3), 0, np.uint8)
red_img = np.full((100, 100, 3), 0, np.uint8)

full_layer = np.full((100, 100), 255, np.uint8)

# OpenCV goes in blue, green, red order
blue_img[:, :, 0] = full_layer
green_img[:, :, 1] = full_layer
red_img[:, :, 2] = full_layer

cv2.imshow('2x2_grid', np.vstack([
    np.hstack([gray_img, blue_img]), 
    np.hstack([green_img, red_img])
]))
cv2.waitKey(0)
cv2.destroyWindow('2x2_grid')

How does the Spring @ResponseBody annotation work?

Further to this, the return type is determined by

  1. What the HTTP Request says it wants - in its Accept header. Try looking at the initial request as see what Accept is set to.

  2. What HttpMessageConverters Spring sets up. Spring MVC will setup converters for XML (using JAXB) and JSON if Jackson libraries are on he classpath.

If there is a choice it picks one - in this example, it happens to be JSON.

This is covered in the course notes. Look for the notes on Message Convertors and Content Negotiation.

Is it possible to pull just one file in Git?

You can fetch and then check out only one file in this way:

git fetch
git checkout -m <revision> <yourfilepath>
git add <yourfilepath>
git commit

Regarding the git checkout command:

  • <revision> -- a branch name, i.e. origin/master
  • <yourfilepath> does not include the repository name (that you can get from clicking copy path button on a file page on GitHub), i.e. README.md

jQuery Cross Domain Ajax

When using "jsonp", you would basically be returning data wrapped in a function call, something like

jsonpCallback([{"id":1,"value":"testing"},{"id":2,"value":"test again"}])
where the function/callback name is 'jsonpCallback'.

If you have access to the server, please first verify that the response is in the correct "jsonp" format

For such a response coming from the server, you would need to specify something in the ajax call as well, something like

jsonpCallback: "jsonpCallback",  in your ajax call

Please note that the name of the callback does not need to be "jsonpCallback" its just a name picked as an example but it needs to match the name(wrapping) done on the server side.

My first guess to your problem is that the response from the server is not what it should be.

What is the difference between XAMPP or WAMP Server & IIS?

WAMP [ Windows, Apache, Mysql, Php]

XAMPP [X-os, Apache, Mysql, Php , Perl ] (x-os : it can be used on any OS )

Both can be used to easily run and test websites and web applications locally. WAMP cannot be run parallel with XAMPP because with default installation XAMPP gets priority and it takes up ports.

WAMP easy to setup configuration in. WAMPServer has a graphical user interface to switch on or off individual component softwares while it is running. WAMPServer provide an option to switch among many versions of Apache, many versions of PHP and many versions of MySQL all installed which provide more flexibility towards developing while XAMPPServer doesn't have such an option. If you want to use Perl with WAMP you can configure Perl with WAMPServer http://phpflow.com/perl/how-to-configure-perl-on-wamp/ but it is better to go with XAMPP.

XAMPP is easy to use than WAMP. XAMPP is more powerful. XAMPP has a control panel from that you can start and stop individual components (such as MySQL,Apache etc.). XAMPP is more resource consuming than WAMP because of heavy amount of internal component softwares like Tomcat , FileZilla FTP server, Webalizer, Mercury Mail etc.So if you donot need high features better to go with WAMP. XAMPP also has SSL feature which WAMP doesn't.(Secure Sockets Layer (SSL) is a networking protocol that manages server authentication, client authentication and encrypted communication between servers and clients. )

IIS acronym for Internet Information Server also an extensible web server initiated as a research project for for Microsoft NT.IIS can be used for making Web applications, search engines, and Web-based applications that access databases such as SQL Server within Microsoft OSs. . IIS supports HTTP, HTTPS, FTP, FTPS, SMTP and NNTP.

How to get position of a certain element in strings vector, to use it as an index in ints vector?

I am a beginner so here is a beginners answer. The if in the for loop gives i which can then be used however needed such as Numbers[i] in another vector. Most is fluff for examples sake, the for/if really says it all.

int main(){
vector<string>names{"Sara", "Harold", "Frank", "Taylor", "Sasha", "Seymore"};
string req_name;
cout<<"Enter search name: "<<'\n';
cin>>req_name;
    for(int i=0; i<=names.size()-1; ++i) {
        if(names[i]==req_name){
            cout<<"The index number for "<<req_name<<" is "<<i<<'\n';
            return 0;
        }
        else if(names[i]!=req_name && i==names.size()-1) {
            cout<<"That name is not an element in this vector"<<'\n';
        } else {
            continue;
        }
    }

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

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

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

E.g.

How big is the "docker" project?

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

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

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

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

Best practice for partial updates in a RESTful service

Regarding your Update.

The concept of CRUD I believe has caused some confusion regarding API design. CRUD is a general low level concept for basic operations to perform on data, and HTTP verbs are just request methods (created 21 years ago) that may or may not map to a CRUD operation. In fact, try to find the presence of the CRUD acronym in the HTTP 1.0/1.1 specification.

A very well explained guide that applies a pragmatic convention can be found in the Google cloud platform API documentation. It describes the concepts behind the creation of a resource based API, one that emphasizes a big amount of resources over operations, and includes the use cases that you are describing. Although is a just a convention design for their product, I think it makes a lot of sense.

The base concept here (and one that produces a lot of confusion) is the mapping between "methods" and HTTP verbs. One thing is to define what "operations" (methods) your API will do over which types of resources (for example, get a list of customers, or send an email), and another are the HTTP verbs. There must be a definition of both, the methods and the verbs that you plan to use and a mapping between them.

It also says that, when an operation does not map exactly with a standard method (List, Get, Create, Update, Delete in this case), one may use "Custom methods", like BatchGet, which retrieves several objects based on several object id input, or SendEmail.

ImportError: No module named win32com.client

Try both pip install pywin32 and pip install pypiwin32.

It works.

How do I fix a merge conflict due to removal of a file in a branch?

The conflict message:

CONFLICT (delete/modify): res/layout/dialog_item.xml deleted in dialog and modified in HEAD

means that res/layout/dialog_item.xml was deleted in the 'dialog' branch you are merging, but was modified in HEAD (in the branch you are merging to).

So you have to decide whether

  • remove file using "git rm res/layout/dialog_item.xml"

or

  • accept version from HEAD (perhaps after editing it) with "git add res/layout/dialog_item.xml"

Then you finalize merge with "git commit".

Note that git will warn you that you are creating a merge commit, in the (rare) case where it is something you don't want. Probably remains from the days where said case was less rare.

How to deserialize a list using GSON or another JSON library in Java?

Be careful using the answer provide by @DevNG. Arrays.asList() returns internal implementation of ArrayList that doesn't implement some useful methods like add(), delete(), etc. If you call them an UnsupportedOperationException will be thrown. In order to get real ArrayList instance you need to write something like this:

List<Video> = new ArrayList<>(Arrays.asList(videoArray));

while EOF in JAVA?

Each call to nextLine() moves onto the next line, so when you are actually at the last readable line and the while check passes inspection, the next call to nextLine() will return EOF.


Perhaps you could do one of the following instead:

If fileReader is of type Scanner:

while ((line = fileReader.hasNextLine()) != null) {
    String line = fileReader.nextLine(); 
    System.out.println(line);
}

If fileReader is of type BufferedReader:

String line;
while ((line = fileReader.readLine()) != null) {
    System.out.println(line);
}

So you're reading the current line in the while condition and saving the line in a string for later use.

How to use paths in tsconfig.json?

You can use combination of baseUrl and paths docs.

Assuming root is on the topmost src dir(and I read your image properly) use

// tsconfig.json
{
  "compilerOptions": {
    ...
    "baseUrl": ".",
    "paths": {
      "lib/*": [
        "src/org/global/lib/*"
      ]
    }
  }
}

For webpack you might also need to add module resolution. For webpack2 this could look like

// webpack.config.js
module.exports = {
    resolve: {
        ...
        modules: [
            ...
            './src/org/global'
        ]
    }
}

Why does viewWillAppear not get called when an app comes back from the background?

Swift

Short answer

Use a NotificationCenter observer rather than viewWillAppear.

override func viewDidLoad() {
    super.viewDidLoad()

    // set observer for UIApplication.willEnterForegroundNotification
    NotificationCenter.default.addObserver(self, selector: #selector(willEnterForeground), name: UIApplication.willEnterForegroundNotification, object: nil)

}

// my selector that was defined above
@objc func willEnterForeground() {
    // do stuff
}

Long answer

To find out when an app comes back from the background, use a NotificationCenter observer rather than viewWillAppear. Here is a sample project that shows which events happen when. (This is an adaptation of this Objective-C answer.)

import UIKit
class ViewController: UIViewController {

    // MARK: - Overrides

    override func viewDidLoad() {
        super.viewDidLoad()
        print("view did load")

        // add notification observers
        NotificationCenter.default.addObserver(self, selector: #selector(didBecomeActive), name: UIApplication.didBecomeActiveNotification, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(willEnterForeground), name: UIApplication.willEnterForegroundNotification, object: nil)

    }

    override func viewWillAppear(_ animated: Bool) {
        print("view will appear")
    }

    override func viewDidAppear(_ animated: Bool) {
        print("view did appear")
    }

    // MARK: - Notification oberserver methods

    @objc func didBecomeActive() {
        print("did become active")
    }

    @objc func willEnterForeground() {
        print("will enter foreground")
    }

}

On first starting the app, the output order is:

view did load
view will appear
did become active
view did appear

After pushing the home button and then bringing the app back to the foreground, the output order is:

will enter foreground
did become active 

So if you were originally trying to use viewWillAppear then UIApplication.willEnterForegroundNotification is probably what you want.

Note

As of iOS 9 and later, you don't need to remove the observer. The documentation states:

If your app targets iOS 9.0 and later or macOS 10.11 and later, you don't need to unregister an observer in its dealloc method.

When should iteritems() be used instead of items()?

In Python 2.x - .items() returned a list of (key, value) pairs. In Python 3.x, .items() is now an itemview object, which behaves different - so it has to be iterated over, or materialised... So, list(dict.items()) is required for what was dict.items() in Python 2.x.

Python 2.7 also has a bit of a back-port for key handling, in that you have viewkeys, viewitems and viewvalues methods, the most useful being viewkeys which behaves more like a set (which you'd expect from a dict).

Simple example:

common_keys = list(dict_a.viewkeys() & dict_b.viewkeys())

Will give you a list of the common keys, but again, in Python 3.x - just use .keys() instead.

Python 3.x has generally been made to be more "lazy" - i.e. map is now effectively itertools.imap, zip is itertools.izip, etc.

Get free disk space

Check this out (this is a working solution for me)

public long AvailableFreeSpace()
{
    long longAvailableFreeSpace = 0;
    try{
        DriveInfo[] arrayOfDrives = DriveInfo.GetDrives();
        foreach (var d in arrayOfDrives)
        {
            Console.WriteLine("Drive {0}", d.Name);
            Console.WriteLine("  Drive type: {0}", d.DriveType);
            if (d.IsReady == true && d.Name == "/data")
            {
                Console.WriteLine("Volume label: {0}", d.VolumeLabel);
                Console.WriteLine("File system: {0}", d.DriveFormat);
                Console.WriteLine("AvailableFreeSpace for current user:{0, 15} bytes",d.AvailableFreeSpace);
                Console.WriteLine("TotalFreeSpace {0, 15} bytes",d.TotalFreeSpace);
                Console.WriteLine("Total size of drive: {0, 15} bytes \n",d.TotalSize);
                }
                longAvailableFreeSpaceInMB = d.TotalFreeSpace;
        }
    }
    catch(Exception ex){
        ServiceLocator.GetInsightsProvider()?.LogError(ex);
    }
    return longAvailableFreeSpace;
}

How to enter quotes in a Java string?

Not sure what language you're using (you didn't specify), but you should be able to "escape" the quotation mark character with a backslash: "\"ROM\""

Unable to find valid certification path to requested target - error even after cert imported

In my case I was facing the problem because in my tomcat process specific keystore was given using

-Djavax.net.ssl.trustStore=/pathtosomeselfsignedstore/truststore.jks

Wheras I was importing the certificate to the cacert of JRE/lib/security and the changes were not reflecting. Then I did below command where /tmp/cert1.test contains the certificate of the target server

keytool -import -trustcacerts -keystore /pathtosomeselfsignedstore/truststore.jks -storepass password123 -noprompt -alias rapidssl-myserver -file /tmp/cert1.test

We can double check if the certificate import is successful

keytool -list -v -keystore /pathtosomeselfsignedstore/truststore.jks

and see if your taget server is found against alias rapidssl-myserver

HTML5 Dynamically create Canvas

Alternative

Use element .innerHTML= which is quite fast in modern browsers

_x000D_
_x000D_
document.body.innerHTML = "<canvas width=500 height=150 id='CursorLayer'>";


// TEST

var ctx = CursorLayer.getContext("2d");
ctx.fillStyle = "red";
ctx.fillRect(100, 100, 50, 50);
_x000D_
canvas { border: 1px solid black }
_x000D_
_x000D_
_x000D_

Add padding on view programmatically

Context contect=MainActivity.this;
TextView tview=new TextView(context);
tview.setPaddingRelative(10,0,0,0);

How to strip all whitespace from string

TL/DR

This solution was tested using Python 3.6

To strip all spaces from a string in Python3 you can use the following function:

def remove_spaces(in_string: str):
    return in_string.translate(str.maketrans({' ': ''})

To remove any whitespace characters (' \t\n\r\x0b\x0c') you can use the following function:

import string
def remove_whitespace(in_string: str):
    return in_string.translate(str.maketrans(dict.fromkeys(string.whitespace)))

Explanation

Python's str.translate method is a built-in class method of str, it takes a table and returns a copy of the string with each character mapped through the passed translation table. Full documentation for str.translate

To create the translation table str.maketrans is used. This method is another built-in class method of str. Here we use it with only one parameter, in this case a dictionary, where the keys are the characters to be replaced mapped to values with the characters replacement value. It returns a translation table for use with str.translate. Full documentation for str.maketrans

The string module in python contains some common string operations and constants. string.whitespace is a constant which returns a string containing all ASCII characters that are considered whitespace. This includes the characters space, tab, linefeed, return, formfeed, and vertical tab.Full documentation for string

In the second function dict.fromkeys is used to create a dictionary where the keys are the characters in the string returned by string.whitespace each with value None. Full documentation for dict.fromkeys

Properties file with a list as the value for an individual key

There's probably a another way or better. But this is how I do this in Spring Boot.

My property file contains the following lines. "," is the delimiter in each line.

mml.pots=STDEP:DETY=LI3;,STDEP:DETY=LIMA;
mml.isdn.grunntengingar=STDEP:DETY=LIBAE;,STDEP:DETY=LIBAMA;
mml.isdn.stofntengingar=STDEP:DETY=LIPRAE;,STDEP:DETY=LIPRAM;,STDEP:DETY=LIPRAGS;,STDEP:DETY=LIPRVGS;

My server config

@Configuration
public class ServerConfig {

    @Inject
    private Environment env;

    @Bean
    public MMLProperties mmlProperties() {
        MMLProperties properties = new MMLProperties();
        properties.setMmmlPots(env.getProperty("mml.pots"));
        properties.setMmmlPots(env.getProperty("mml.isdn.grunntengingar"));
        properties.setMmmlPots(env.getProperty("mml.isdn.stofntengingar"));
        return properties;
    }
}

MMLProperties class.

public class MMLProperties {
    private String mmlPots;
    private String mmlIsdnGrunntengingar;
    private String mmlIsdnStofntengingar;

    public MMLProperties() {
        super();
    }

    public void setMmmlPots(String mmlPots) {
        this.mmlPots = mmlPots;
    }

    public void setMmlIsdnGrunntengingar(String mmlIsdnGrunntengingar) {
        this.mmlIsdnGrunntengingar = mmlIsdnGrunntengingar;
    }

    public void setMmlIsdnStofntengingar(String mmlIsdnStofntengingar) {
        this.mmlIsdnStofntengingar = mmlIsdnStofntengingar;
    }

    // These three public getXXX functions then take care of spliting the properties into List
    public List<String> getMmmlCommandForPotsAsList() {
        return getPropertieAsList(mmlPots);
    }

    public List<String> getMmlCommandsForIsdnGrunntengingarAsList() {
        return getPropertieAsList(mmlIsdnGrunntengingar);
    }

    public List<String> getMmlCommandsForIsdnStofntengingarAsList() {
        return getPropertieAsList(mmlIsdnStofntengingar);
    }

    private List<String> getPropertieAsList(String propertie) {
        return ((propertie != null) || (propertie.length() > 0))
        ? Arrays.asList(propertie.split("\\s*,\\s*"))
        : Collections.emptyList();
    }
}

Then in my Runner class I Autowire MMLProperties

@Component
public class Runner implements CommandLineRunner {

    @Autowired
    MMLProperties mmlProperties;

    @Override
    public void run(String... arg0) throws Exception {
        // Now I can call my getXXX function to retrieve the properties as List
        for (String command : mmlProperties.getMmmlCommandForPotsAsList()) {
            System.out.println(command);
        }
    }
}

Hope this helps

How to find whether a number belongs to a particular range in Python?

print 'yes' if 0 < x < 0.5 else 'no'

range() is for generating arrays of consecutive integers

How to take complete backup of mysql database using mysqldump command line utility

On MySQL 5.7 its work for me, I'm using CentOS7.

For taking Dump.

Command :

mysqldump -u user_name -p database_name -R -E > file_name.sql

Exemple :

mysqldump -u root -p mr_sbc_clean -R -E > mr_sbc_clean_dump.sql

For deploying Dump.

Command :

mysql -u user_name -p database_name < file_name.sql

Exemple :

mysql -u root -p mr_sbc_clean_new < mr_sbc_clean_dump.sql

Read Variable from Web.Config

I would suggest you to don't modify web.config from your, because every time when change, it will restart your application.

However you can read web.config using System.Configuration.ConfigurationManager.AppSettings

Dynamically Dimensioning A VBA Array?

You can use a dynamic array when you don't know the number of values it will contain until run-time:

Dim Zombies() As Integer
ReDim Zombies(NumberOfZombies)

Or you could do everything with one statement if you're creating an array that's local to a procedure:

ReDim Zombies(NumberOfZombies) As Integer

Fixed-size arrays require the number of elements contained to be known at compile-time. This is why you can't use a variable to set the size of the array—by definition, the values of a variable are variable and only known at run-time.

You could use a constant if you knew the value of the variable was not going to change:

Const NumberOfZombies = 2000

but there's no way to cast between constants and variables. They have distinctly different meanings.

How do I create a table based on another table

There is no such syntax in SQL Server, though CREATE TABLE AS ... SELECT does exist in PDW. In SQL Server you can use this query to create an empty table:

SELECT * INTO schema.newtable FROM schema.oldtable WHERE 1 = 0;

(If you want to make a copy of the table including all of the data, then leave out the WHERE clause.)

Note that this creates the same column structure (including an IDENTITY column if one exists) but it does not copy any indexes, constraints, triggers, etc.

MySQL TEXT vs BLOB vs CLOB

It's worth to mention that CLOB / BLOB data types and their sizes are supported by MySQL 5.0+, so you can choose the proper data type for your need.

http://dev.mysql.com/doc/refman/5.7/en/storage-requirements.html

Data Type   Date Type   Storage Required
(CLOB)      (BLOB)

TINYTEXT    TINYBLOB    L + 1 bytes, where L < 2**8  (255)
TEXT        BLOB        L + 2 bytes, where L < 2**16 (64 K)
MEDIUMTEXT  MEDIUMBLOB  L + 3 bytes, where L < 2**24 (16 MB)
LONGTEXT    LONGBLOB    L + 4 bytes, where L < 2**32 (4 GB)

where L stands for the byte length of a string

How to center HTML5 Videos?

I will not prefer to center just using video tag as @user142019 says. I will prefer doing it like this:

_x000D_
_x000D_
.videoDiv_x000D_
{_x000D_
    width: 70%; /*or whatever % you prefer*/_x000D_
    margin: 0 auto;_x000D_
    display: block;_x000D_
}
_x000D_
<div class="videoDiv">_x000D_
  <video width="100%" controls>_x000D_
    <source src="https://www.w3schools.com/html/mov_bbb.mp4" type="video/mp4">_x000D_
    <source src="https://www.w3schools.com/html/mov_bbb.ogg" type="video/ogg">_x000D_
  Your browser does not support the video tag._x000D_
  </video>_x000D_
</div>
_x000D_
_x000D_
_x000D_

This will make your video responsive at the same time the panel for controls will have the same size as the video rectangle (I tried what @user142019 says and the video was centered, but it looked ugly in Google Chrome).

In Maven how to exclude resources from the generated jar?

When I create an executable jar with dependencies (using this guide), all properties files are packaged into that jar too. How to stop it from happening? Thanks.

Properties files from where? Your main jar? Dependencies?

In the former case, putting resources under src/test/resources as suggested is probably the most straight forward and simplest option.

In the later case, you'll have to create a custom assembly descriptor with special excludes/exclude in the unpackOptions.

Could not load file or assembly 'System.Web.WebPages.Razor, Version=3.0.0.0

Update using NuGet Package Manager Console in your Visual Studio

Update-Package -reinstall Microsoft.AspNet.Mvc

How to insert new row to database with AUTO_INCREMENT column without specifying column names?

For some databases, you can just explicitly insert a NULL into the auto_increment column:

INSERT INTO table_name VALUES (NULL, 'my name', 'my group')

File loading by getClass().getResource()

The best way to access files from resource folder inside a jar is it to use the InputStream via getResourceAsStream. If you still need a the resource as a file instance you can copy the resource as a stream into a temporary file (the temp file will be deleted when the JVM exits):

public static File getResourceAsFile(String resourcePath) {
    try {
        InputStream in = ClassLoader.getSystemClassLoader().getResourceAsStream(resourcePath);
        if (in == null) {
            return null;
        }

        File tempFile = File.createTempFile(String.valueOf(in.hashCode()), ".tmp");
        tempFile.deleteOnExit();

        try (FileOutputStream out = new FileOutputStream(tempFile)) {
            //copy stream
            byte[] buffer = new byte[1024];
            int bytesRead;
            while ((bytesRead = in.read(buffer)) != -1) {
                out.write(buffer, 0, bytesRead);
            }
        }
        return tempFile;
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }
}

Reporting (free || open source) Alternatives to Crystal Reports in Winforms

Free to try with a nagging banner... DevExpress XtraReports and XRCharts. Very nice dev tool, great support, speaking from experience.

Retrieving a List from a java.util.stream.Stream in Java 8

I like to use a util method that returns a collector for ArrayList when that is what I want.

I think the solution using Collectors.toCollection(ArrayList::new) is a little too noisy for such a common operation.

Example:

ArrayList<Long> result = sourceLongList.stream()
    .filter(l -> l > 100)
    .collect(toArrayList());

public static <T> Collector<T, ?, ArrayList<T>> toArrayList() {
    return Collectors.toCollection(ArrayList::new);
}

With this answer I also want to demonstrate how simple it is to create and use custom collectors, which is very useful generally.

How to add/update an attribute to an HTML element using JavaScript?

What do you want to do with the attribute? Is it an html attribute or something of your own?

Most of the time you can simply address it as a property: want to set a title on an element? element.title = "foo" will do it.

For your own custom JS attributes the DOM is naturally extensible (aka expando=true), the simple upshot of which is that you can do element.myCustomFlag = foo and subsequently read it without issue.

Differences Between vbLf, vbCrLf & vbCr Constants

The three constants have similar functions nowadays, but different historical origins, and very occasionally you may be required to use one or the other.

You need to think back to the days of old manual typewriters to get the origins of this. There are two distinct actions needed to start a new line of text:

  1. move the typing head back to the left. In practice in a typewriter this is done by moving the roll which carries the paper (the "carriage") all the way back to the right -- the typing head is fixed. This is a carriage return.
  2. move the paper up by the width of one line. This is a line feed.

In computers, these two actions are represented by two different characters - carriage return is CR, ASCII character 13, vbCr; line feed is LF, ASCII character 10, vbLf. In the old days of teletypes and line printers, the printer needed to be sent these two characters -- traditionally in the sequence CRLF -- to start a new line, and so the CRLF combination -- vbCrLf -- became a traditional line ending sequence, in some computing environments.

The problem was, of course, that it made just as much sense to only use one character to mark the line ending, and have the terminal or printer perform both the carriage return and line feed actions automatically. And so before you knew it, we had 3 different valid line endings: LF alone (used in Unix and Macintoshes), CR alone (apparently used in older Mac OSes) and the CRLF combination (used in DOS, and hence in Windows). This in turn led to the complications of DOS / Windows programs having the option of opening files in text mode, where any CRLF pair read from the file was converted to a single CR (and vice versa when writing).

So - to cut a (much too) long story short - there are historical reasons for the existence of the three separate line separators, which are now often irrelevant: and perhaps the best course of action in .NET is to use Environment.NewLine which means someone else has decided for you which to use, and future portability issues should be reduced.

Finding version of Microsoft C++ compiler from command-line (for makefiles)

Try:

cl /v

Actually, any time I give cl an argument, it prints out the version number on the first line.

You could just feed it a garbage argument and then parse the first line of the output, which contains the verison number.

Is it possible to use std::string in a constexpr?

Since the problem is the non-trivial destructor so if the destructor is removed from the std::string, it's possible to define a constexpr instance of that type. Like this

struct constexpr_str {
    char const* str;
    std::size_t size;

    // can only construct from a char[] literal
    template <std::size_t N>
    constexpr constexpr_str(char const (&s)[N])
        : str(s)
        , size(N - 1) // not count the trailing nul
    {}
};

int main()
{
    constexpr constexpr_str s("constString");

    // its .size is a constexpr
    std::array<int, s.size> a;
    return 0;
}

How can I switch language in google play?

Answer below the dotted line below is the original that's now outdated.

Here is the latest information ( Thank you @deadfish ):

add &hl=<language> like &hl=pl or &hl=en

example: https://play.google.com/store/apps/details?id=com.example.xxx&hl=en or https://play.google.com/store/apps/details?id=com.example.xxx&hl=pl

All available languages and abbreviations can be looked up here: https://support.google.com/googleplay/android-developer/table/4419860?hl=en

......................................................................

To change the actual local market:

Basically the market is determined automatically based on your IP. You can change some local country settings from your Gmail account settings but still IP of the country you're browsing from is more important. To go around it you'd have to Proxy-cheat. Check out some ways/sites: http://www.affilorama.com/forum/market-research/how-to-change-country-search-settings-in-google-t4160.html

To do it from an Android phone you'd need to find an app. I don't have my Droid anymore but give this a try: http://forum.xda-developers.com/showthread.php?t=694720

jQuery UI DatePicker - Change Date Format

Try to use the

$( ".selector" ).datepicker({ dateFormat: 'dd/mm/yy' });  

and there is lots of option available For the datepicker you can find it Here

http://api.jqueryui.com/datepicker/

This is the way we call the datepicker with the parameter

$(function() {
      $('.selector').datepicker({
            dateFormat: 'dd/mm/yy',
            changeMonth: true,
            numberOfMonths: 1,
            buttonImage: 'contact/calendar/calendar.gif',
            buttonImageOnly: true,
            onSelect: function(selectedDate) {
                 // we can write code here 
             }
      });
});

What does yield mean in PHP?

With yield you can easily describe the breakpoints between multiple tasks in a single function. That's all, there is nothing special about it.

$closure = function ($injected1, $injected2, ...){
    $returned = array();
    //task1 on $injected1
    $returned[] = $returned1;
//I need a breakpoint here!!!!!!!!!!!!!!!!!!!!!!!!!
    //task2 on $injected2
    $returned[] = $returned2;
    //...
    return $returned;
};
$returned = $closure($injected1, $injected2, ...);

If task1 and task2 are highly related, but you need a breakpoint between them to do something else:

  • free memory between processing database rows
  • run other tasks which provide dependency to the next task, but which are unrelated by understanding the current code
  • doing async calls and wait for the results
  • and so on ...

then generators are the best solution, because you don't have to split up your code into many closures or mix it with other code, or use callbacks, etc... You just use yield to add a breakpoint, and you can continue from that breakpoint if you are ready.

Add breakpoint without generators:

$closure1 = function ($injected1){
    //task1 on $injected1
    return $returned1;
};
$closure2 = function ($injected2){
    //task2 on $injected2
    return $returned1;
};
//...
$returned1 = $closure1($injected1);
//breakpoint between task1 and task2
$returned2 = $closure2($injected2);
//...

Add breakpoint with generators

$closure = function (){
    $injected1 = yield;
    //task1 on $injected1
    $injected2 = (yield($returned1));
    //task2 on $injected2
    $injected3 = (yield($returned2));
    //...
    yield($returnedN);
};
$generator = $closure();
$returned1 = $generator->send($injected1);
//breakpoint between task1 and task2
$returned2 = $generator->send($injected2);
//...
$returnedN = $generator->send($injectedN);

note: It is easy to make mistake with generators, so always write unit tests before you implement them! note2: Using generators in an infinite loop is like writing a closure which has infinite length...

Explanation of "ClassCastException" in Java

Do you understand the concept of casting? Casting is the process of type conversion, which is in Java very common because its a statically typed language. Some examples:

Cast the String "1" to an int -> no problem

Cast the String "abc" to an int -> raises a ClassCastException

Or think of a class diagram with Animal.class, Dog.class and Cat.class

Animal a = new Dog();
Dog d = (Dog) a; // No problem, the type animal can be casted to a dog, because its a dog.
Cat c = (Dog) a; // Raises class cast exception; you can't cast a dog to a cat.

Adding elements to a C# array

What's abaut this one:

List<int> tmpList = intArry.ToList(); tmpList.Add(anyInt); intArry = tmpList.ToArray();

Find intersection of two nested lists?

You don't need to define intersection. It's already a first-class part of set.

>>> b1 = [1,2,3,4,5,9,11,15]
>>> b2 = [4,5,6,7,8]
>>> set(b1).intersection(b2)
set([4, 5])

I need to round a float to two decimal places in Java

You can make use of DecimalFormat to give you the style you wish.

DecimalFormat df = new DecimalFormat("0.00E0");
double number = 1.2975118E7;
System.out.println(df.format(number));  // prints 1.30E7

Since it's in scientific notation, you won't be able to get the number any smaller than 107 without losing that many orders of magnitude of accuracy.

How do I convert a decimal to an int in C#?

System.Decimal implements the IConvertable interface, which has a ToInt32() member.

Does calling System.Decimal.ToInt32() work for you?

Capture key press without placing an input element on the page?

Detect key press, including key combinations:

window.addEventListener('keydown', function (e) {
  if (e.ctrlKey && e.keyCode == 90) {
    // Ctrl + z pressed
  }
});

Benefit here is that you are not overwriting any global properties, but instead merely introducing a side effect. Not good, but definitely a whole lot less nefarious than other suggestions on here.

How to fill the whole canvas with specific color?

_x000D_
_x000D_
let canvas = document.getElementById('canvas');_x000D_
canvas.setAttribute('width', window.innerWidth);_x000D_
canvas.setAttribute('height', window.innerHeight);_x000D_
let ctx = canvas.getContext('2d');_x000D_
_x000D_
//Draw Canvas Fill mode_x000D_
ctx.fillStyle = 'blue';_x000D_
ctx.fillRect(0,0,canvas.width, canvas.height);
_x000D_
* { margin: 0; padding: 0; box-sizing: border-box; }_x000D_
body { overflow: hidden; }
_x000D_
<canvas id='canvas'></canvas>
_x000D_
_x000D_
_x000D_

How to Get a Sublist in C#

With LINQ:

List<string> l = new List<string> { "1", "2", "3" ,"4","5"};
List<string> l2 = l.Skip(1).Take(2).ToList();

If you need foreach, then no need for ToList:

foreach (string s in l.Skip(1).Take(2)){}

Advantage of LINQ is that if you want to just skip some leading element,you can :

List<string> l2 = l.Skip(1).ToList();
foreach (string s in l.Skip(1)){}

i.e. no need to take care of count/length, etc.

When to use references vs. pointers

There is problem with "use references wherever possible" rule and it arises if you want to keep reference for further use. To illustrate this with example, imagine you have following classes.

class SimCard
{
    public:
        explicit SimCard(int id):
            m_id(id)
        {
        }

        int getId() const
        {
            return m_id;
        }

    private:
        int m_id;
};

class RefPhone
{
    public:
        explicit RefPhone(const SimCard & card):
            m_card(card)
        {
        }

        int getSimId()
        {
            return m_card.getId();
        }

    private:
        const SimCard & m_card;
};

At first it may seem to be a good idea to have parameter in RefPhone(const SimCard & card) constructor passed by a reference, because it prevents passing wrong/null pointers to the constructor. It somehow encourages allocation of variables on stack and taking benefits from RAII.

PtrPhone nullPhone(0);  //this will not happen that easily
SimCard * cardPtr = new SimCard(666);  //evil pointer
delete cardPtr;  //muahaha
PtrPhone uninitPhone(cardPtr);  //this will not happen that easily

But then temporaries come to destroy your happy world.

RefPhone tempPhone(SimCard(666));   //evil temporary
//function referring to destroyed object
tempPhone.getSimId();    //this can happen

So if you blindly stick to references you trade off possibility of passing invalid pointers for the possibility of storing references to destroyed objects, which has basically same effect.

edit: Note that I sticked to the rule "Use reference wherever you can, pointers wherever you must. Avoid pointers until you can't." from the most upvoted and accepted answer (other answers also suggest so). Though it should be obvious, example is not to show that references as such are bad. They can be misused however, just like pointers and they can bring their own threats to the code.


There are following differences between pointers and references.

  1. When it comes to passing variables, pass by reference looks like pass by value, but has pointer semantics (acts like pointer).
  2. Reference can not be directly initialized to 0 (null).
  3. Reference (reference, not referenced object) can not be modified (equivalent to "* const" pointer).
  4. const reference can accept temporary parameter.
  5. Local const references prolong the lifetime of temporary objects

Taking those into account my current rules are as follows.

  • Use references for parameters that will be used locally within a function scope.
  • Use pointers when 0 (null) is acceptable parameter value or you need to store parameter for further use. If 0 (null) is acceptable I am adding "_n" suffix to parameter, use guarded pointer (like QPointer in Qt) or just document it. You can also use smart pointers. You have to be even more careful with shared pointers than with normal pointers (otherwise you can end up with by design memory leaks and responsibility mess).

scale fit mobile web content using viewport meta tag

ok, here is my final solution with 100% native javascript:

<meta id="viewport" name="viewport">

<script type="text/javascript">
//mobile viewport hack
(function(){

  function apply_viewport(){
    if( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent)   ) {

      var ww = window.screen.width;
      var mw = 800; // min width of site
      var ratio =  ww / mw; //calculate ratio
      var viewport_meta_tag = document.getElementById('viewport');
      if( ww < mw){ //smaller than minimum size
        viewport_meta_tag.setAttribute('content', 'initial-scale=' + ratio + ', maximum-scale=' + ratio + ', minimum-scale=' + ratio + ', user-scalable=no, width=' + mw);
      }
      else { //regular size
        viewport_meta_tag.setAttribute('content', 'initial-scale=1.0, maximum-scale=1, minimum-scale=1.0, user-scalable=yes, width=' + ww);
      }
    }
  }

  //ok, i need to update viewport scale if screen dimentions changed
  window.addEventListener('resize', function(){
    apply_viewport();
  });

  apply_viewport();

}());
</script>

Print an integer in binary format in Java

System.out.println(Integer.toBinaryString(343));

PHP validation/regex for URL

Just in case you want to know if the url really exists:

function url_exist($url){//se passar a URL existe
    $c=curl_init();
    curl_setopt($c,CURLOPT_URL,$url);
    curl_setopt($c,CURLOPT_HEADER,1);//get the header
    curl_setopt($c,CURLOPT_NOBODY,1);//and *only* get the header
    curl_setopt($c,CURLOPT_RETURNTRANSFER,1);//get the response as a string from curl_exec(), rather than echoing it
    curl_setopt($c,CURLOPT_FRESH_CONNECT,1);//don't use a cached version of the url
    if(!curl_exec($c)){
        //echo $url.' inexists';
        return false;
    }else{
        //echo $url.' exists';
        return true;
    }
    //$httpcode=curl_getinfo($c,CURLINFO_HTTP_CODE);
    //return ($httpcode<400);
}