Programs & Examples On #Dynamically loaded xap

Iterate through DataSet

foreach (DataTable table in dataSet.Tables)
{
    foreach (DataRow row in table.Rows)
    {
        foreach (object item in row.ItemArray)
        {
            // read item
        }
    }
}

Or, if you need the column info:

foreach (DataTable table in dataSet.Tables)
{
    foreach (DataRow row in table.Rows)
    {
        foreach (DataColumn column in table.Columns)
        {
            object item = row[column];
            // read column and item
        }
    }
}

How does Python return multiple values from a function?

Here It is actually returning tuple.

If you execute this code in Python 3:

def get():
    a = 3
    b = 5
    return a,b
number = get()
print(type(number))
print(number)

Output :

<class 'tuple'>
(3, 5)

But if you change the code line return [a,b] instead of return a,b and execute :

def get():
    a = 3
    b = 5
    return [a,b]
number = get()
print(type(number))
print(number)

Output :

<class 'list'>
[3, 5]

It is only returning single object which contains multiple values.

There is another alternative to return statement for returning multiple values, use yield( to check in details see this What does the "yield" keyword do in Python?)

Sample Example :

def get():
    for i in range(5):
        yield i
number = get()
print(type(number))
print(number)
for i in number:
    print(i)

Output :

<class 'generator'>
<generator object get at 0x7fbe5a1698b8>
0
1
2
3
4

How to print a dictionary's key?

If you want to get the key of a single value, the following would help:

def get_key(b): # the value is passed to the function
    for k, v in mydic.items():
        if v.lower() == b.lower():
            return k

In pythonic way:

c = next((x for x, y in mydic.items() if y.lower() == b.lower()), \
     "Enter a valid 'Value'")
print(c)

How to enable local network users to access my WAMP sites?

Because I just went through this - I wanted to give my solution even though this is a bit old.

I have several computers on a home router and I have been working on some projects for myself. Well, I wanted to see what it looked like on my mobil devices. But WAMP was set so I could only get on from the development system. So I began looking around and found this article as well as some others. The problem is - none of them worked for me. So I was left to figure this out on my own.

My solution:

First, in the HTTPD.CONF file you need to add one line to the end of the list of what devices are allowed to access your WAMP server. So instead of:

#    Require all granted
#   onlineoffline tag - don't remove
     Order Deny,Allow
     Deny from all
     Allow from 127.0.0.1
     Allow from ::1
     Allow from localhost

make it:

#    Require all granted
#   onlineoffline tag - don't remove
     Order Deny,Allow
     Deny from all
     Allow from 127.0.0.1
     Allow from ::1
     Allow from localhost
     Allow from 192.168.78

The above says that any device that is on your router (the '78' is just an arbitrary number picked for this solution. It should be whatever your router is set up for. So it might be 192.168.1 or 192.168.0 or even 192.168.254 - you have to look it up on your router.) can now access your server.

The above did NOT do anything for me - at first. There is more you need to do. But first - what you do NOT need to do. You do NOT need to change the WAMP setting from Offline to Online. FOR ME - changing that setting doesn't do anything. Unknown why - it just doesn't. So change it if you want - but I don't think it needs to be changed.

So what else DOES need to be changed? You have to go all the way back to the beginning of the httpd.conf file for this next change and it is really simple. You have to add a new line after the

Listen Localhost:80

add

Listen 192.168.78.###:80

Where the "###" is what IP your server is on. So let's say your server is on IP number 234. Then the above command would become

Listen localhost:80
Listen 192.168.78.234:80

Again - the '78' is just an arbitrary number I picked. To get your real IP number you have to open a command window and type in

ipconfig/all

command. Look for what your TCP/IPv4 number is and set it to that number or TCP/IPv6 if that is all you have (although on internal router sets you usually have an IPv4 number).

Note: In case you do not know how to bring up a command window - you click on Start, select the "Run" option, and type "cmd.exe" in to the dialog box without the quotes. On newer systems (since they keep changing everything) it might be the white windows icon or the circle or Bill Gates jumping up and down. Whatever it is - click on it.

Once you have done the above - restart all services and everything should come up just fine.

Finally - why? Why do you have to change the Listen command? It has to do with localhost. 'localhost' is set to 127.0.0.1 and NOT your IP address by default. This can be found in your host file which is usually found in the system32 folder under Windows but probably has been moved by Microsoft to somewhere else. Look it up online for where it is and go look at it. If you see a lot of sex, porn, etc sites in your localhost host file - you need to get rid of them (unless that is your thing). I suggest RogueKiller (at AdLice.com) be used to take a look at your system because it can reset your host file for you.

If your host file is normal though - it should contain just one entry and that entry is to set localhost to 127.0.0.1. That is why using localhost in the httpd.conf file makes it so you only can work on everything and see everything from your server computer.

So if you feel adventurous - change your host file and leave the Listen command alone OR just change the Listen command to listen to port 80 on your server.

NEW (I forgot to put in this part)

You MAY have to change your TCP/IP address. (Mine is already set up so I didn't need to do this.) You will need to look up for your OS how to get to where your TCP/IP address is defined. Under Windows XP this was Control Panel->Network Connections. This has changed in later OSs so you have to look up how to get there. Anyway, once there you will see your Wireless Network Connection or Local Area Connection (Windows). Basically WIFI or Ethernet cable. Select the one that is active and in use. Under Windows you then right-click and select Properties. A dialog should pop-up and you should see a list of checkboxes with what they are to the side. Look for the one that is for TCP/IP. There should be one that says TCP/IP v4. Select it. (If there isn't one - you should proceed with caution.) Click the Properties button and you should get another dialog box. This one shows either "Obtain an IP address automatically" or "Use the following IP address" selected. If it is the first one then you have to change it to the second one. BUT BEFORE YOU DO THAT - bring up a command window and type in the ipcongfig/all command so you have, right there in front of you, what your default gateway is. Then change it from "Obtain..." to "Use...". Where it says "IP address" put in the IP address you want to always use. This is the IP address you put in on the Listen command above. The second line (Subnet mask) usually is 255.255.255.0 meaning only the last number (ie: 0) changes. Then, looking back at the command window put in your default gateway. Last, but not least, when you changed from "Obtain..." to "Use..." the DNS settings may have changed. If the section which deals with DNS settings has changed to "Use..." and it is blank - the answer is simple. Just look at that ipconfig/all output, find the DNS setting(s) there and put them in to the fields provided. Once done click the OK button and then click the second OK button. Once the dialog closes you may have to reboot your system for the changes to take effect. Try it out by going to Google or Stack Overflow. If you can still go places - then no reboot is required. Otherwise, reboot. Remember! If you can't get on the internet afterwards all you do is go back and reset everything to the "Obtain..." option. The most likely reason, after making the changes, that you can no longer get on the internet is because the TCP/IP address you chose to use is already in use by the router. The saying "There can be only one" goes for TCP/IP addresses too. This is why I always pick a high one-hundreds number or a low two-hundreds number. Because most DHCP set ups use numbers less than fifty. So in this way you don't collide with someone else's TCP/IP number.

This is how I fixed my problem.

How to find which views are using a certain table in SQL Server (2008)?

I find this works better:

SELECT type, *
FROM sys.objects
WHERE OBJECT_DEFINITION(object_id) LIKE '%' + @ObjectName + '%'
AND type IN ('V')
ORDER BY name

Filtering VIEW_DEFINTION inside INFORMATION_SCHEMA.VIEWS is giving me quite a few false positives.

Escape sequence \f - form feed - what exactly is it?

It skips to the start of the next page. (Applies mostly to terminals where the output device is a printer rather than a VDU.)

DNS problem, nslookup works, ping doesn't

I have the same issue with IIS running on my home server, on the client machine a command like ipconfig /flushdns usually solves the problem.

How To Show And Hide Input Fields Based On Radio Button Selection

You'll need to also set the height of the element to 0 when it's hidden. I ran into this problem while using jQuery, my solution was to set the height and opacity to 0 when it's hidden, then change height to auto and opacity to 1 when it's un-hidden.

I'd recommend looking at jQuery. It's pretty easy to pick up and will allow you to do things like this a lot more easily.

$('#yesCheck').click(function() {
    $('#ifYes').slideDown();
});
$('#noCheck').click(function() {
    $('#ifYes').slideUp();
});

It's slightly better for performance to change the CSS with jQuery and use CSS3 animations to do the dropdown, but that's also more complex. The example above should work, but I haven't tested it.

How to run specific test cases in GoogleTest

Summarising @Rasmi Ranjan Nayak and @nogard answers and adding another option:

On the console

You should use the flag --gtest_filter, like

--gtest_filter=Test_Cases1*

(You can also do this in Properties|Configuration Properties|Debugging|Command Arguments)

On the environment

You should set the variable GTEST_FILTER like

export GTEST_FILTER = "Test_Cases1*"

On the code

You should set a flag filter, like

::testing::GTEST_FLAG(filter) = "Test_Cases1*";

such that your main function becomes something like

int main(int argc, char **argv) {
    ::testing::InitGoogleTest(&argc, argv);
    ::testing::GTEST_FLAG(filter) = "Test_Cases1*";
    return RUN_ALL_TESTS();
}

See section Running a Subset of the Tests for more info on the syntax of the string you can use.

VueJS conditionally add an attribute for an element

You can add colon before attribute (also can use conditions) like

<div :class="current? 'active': '' " > 
<button :disabled="InvalidForm? true : false " >

If you want to set a dynamic value like props then you also can use colon before attribute name like :

<Child :data="userList" />

How to convert string to XML using C#

string test = "<body><head>test header</head></body>";

XmlDocument xmltest = new XmlDocument();
xmltest.LoadXml(test);

XmlNodeList elemlist = xmltest.GetElementsByTagName("head");

string result = elemlist[0].InnerXml; 

//result -> "test header"

anchor jumping by using javascript

I have a button for a prompt that on click it opens the display dialogue and then I can write what I want to search and it goes to that location on the page. It uses javascript to answer the header.

On the .html file I have:

<button onclick="myFunction()">Load Prompt</button>
<span id="test100"><h4>Hello</h4></span>

On the .js file I have

function myFunction() {
    var input = prompt("list or new or quit");

    while(input !== "quit") {
        if(input ==="test100") {
            window.location.hash = 'test100';
            return;
// else if(input.indexOf("test100") >= 0) {
//   window.location.hash = 'test100';
//   return;
// }
        }
    }
}

When I write test100 into the prompt, then it will go to where I have placed span id="test100" in the html file.

I use Google Chrome.

Note: This idea comes from linking on the same page using

<a href="#test100">Test link</a>

which on click will send to the anchor. For it to work multiple times, from experience need to reload the page.

Credit to the people at stackoverflow (and possibly stackexchange, too) can't remember how I gathered all the bits and pieces. ?

What are CN, OU, DC in an LDAP search?

What are CN, OU, DC?

From RFC2253 (UTF-8 String Representation of Distinguished Names):

String  X.500 AttributeType
------------------------------
CN      commonName
L       localityName
ST      stateOrProvinceName
O       organizationName
OU      organizationalUnitName
C       countryName
STREET  streetAddress
DC      domainComponent
UID     userid


What does the string from that query mean?

The string ("CN=Dev-India,OU=Distribution Groups,DC=gp,DC=gl,DC=google,DC=com") is a path from an hierarchical structure (DIT = Directory Information Tree) and should be read from right (root) to left (leaf).

It is a DN (Distinguished Name) (a series of comma-separated key/value pairs used to identify entries uniquely in the directory hierarchy). The DN is actually the entry's fully qualified name.

Here you can see an example where I added some more possible entries.
The actual path is represented using green.

LDAP tree

The following paths represent DNs (and their value depends on what you want to get after the query is run):

  • "DC=gp,DC=gl,DC=google,DC=com"
  • "OU=Distribution Groups,DC=gp,DC=gl,DC=google,DC=com"
  • "OU=People,DC=gp,DC=gl,DC=google,DC=com"
  • "OU=Groups,DC=gp,DC=gl,DC=google,DC=com"
  • "CN=QA-Romania,OU=Distribution Groups,DC=gp,DC=gl,DC=google,DC=com"
  • "CN=Dev-India,OU=Distribution Groups,DC=gp,DC=gl,DC=google,DC=com"
  • "CN=Diana Anton,OU=People,DC=gp,DC=gl,DC=google,DC=com"

How to convert an Array to a Set in Java

In Eclipse Collections, the following will work:

Set<Integer> set1 = Sets.mutable.of(1, 2, 3, 4, 5);
Set<Integer> set2 = Sets.mutable.of(new Integer[]{1, 2, 3, 4, 5});
MutableSet<Integer> mutableSet = Sets.mutable.of(1, 2, 3, 4, 5);
ImmutableSet<Integer> immutableSet = Sets.immutable.of(1, 2, 3, 4, 5);

Set<Integer> unmodifiableSet = Sets.mutable.of(1, 2, 3, 4, 5).asUnmodifiable();
Set<Integer> synchronizedSet = Sets.mutable.of(1, 2, 3, 4, 5).asSynchronized();
ImmutableSet<Integer> immutableSet = Sets.mutable.of(1, 2, 3, 4, 5).toImmutable();

Note: I am a committer for Eclipse Collections

Reading data from a website using C#

The WebClient class should be more than capable of handling the functionality you describe, for example:

System.Net.WebClient wc = new System.Net.WebClient();
byte[] raw = wc.DownloadData("http://www.yoursite.com/resource/file.htm");

string webData = System.Text.Encoding.UTF8.GetString(raw);

or (further to suggestion from Fredrick in comments)

System.Net.WebClient wc = new System.Net.WebClient();
string webData = wc.DownloadString("http://www.yoursite.com/resource/file.htm");

When you say it took 30 seconds, can you expand on that a little more? There are many reasons as to why that could have happened. Slow servers, internet connections, dodgy implementation etc etc.

You could go a level lower and implement something like this:

HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create("http://www.yoursite.com/resource/file.htm");

using (StreamWriter streamWriter = new StreamWriter(webRequest.GetRequestStream(), Encoding.UTF8))
{
    streamWriter.Write(requestData);
}

string responseData = string.Empty;
HttpWebResponse httpResponse = (HttpWebResponse)webRequest.GetResponse();
using (StreamReader responseReader = new StreamReader(httpResponse.GetResponseStream()))
{
    responseData = responseReader.ReadToEnd();
}

However, at the end of the day the WebClient class wraps up this functionality for you. So I would suggest that you use WebClient and investigate the causes of the 30 second delay.

Best way to format integer as string with leading zeros?

For Python 3 and beyond: str.zfill() is still the most readable option

But it is a good idea to look into the new and powerful str.format(), what if you want to pad something that is not 0?

    # if we want to pad 22 with zeros in front, to be 5 digits in length:
    str_output = '{:0>5}'.format(22)
    print(str_output)
    # >>> 00022
    # {:0>5} meaning: ":0" means: pad with 0, ">" means move 22 to right most, "5" means the total length is 5

    # another example for comparision
    str_output = '{:#<4}'.format(11)
    print(str_output)
    # >>> 11##

    # to put it in a less hard-coded format:
    int_inputArg = 22
    int_desiredLength = 5
    str_output = '{str_0:0>{str_1}}'.format(str_0=int_inputArg, str_1=int_desiredLength)
    print(str_output)
    # >>> 00022

Laravel - Model Class not found

In your router.php file, you should use the model class like this

 use App\Post;

and use the model class like this.

Route::get('/posts', function() {

        $results = Post::all();
        return $results; });

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

One corner case to keep in mind, which surprised me when I first found out about it: Windows allows leading space characters in file names! For example, the following are all legal, and distinct, file names on Windows (minus the quotes):

"file.txt"
" file.txt"
"  file.txt"

One takeaway from this: Use caution when writing code that trims leading/trailing whitespace from a filename string.

Shortcut to comment out a block of code with sublime text

The shortcut to comment out or uncomment the selected text or current line:

  • Windows: Ctrl+/
  • Mac: Command ?+/
  • Linux: Ctrl+Shift+/

Alternatively, use the menu: Edit > Comment

For the block comment you may want to use:

  • Windows: Ctrl+Shift+/
  • Mac: Command ?+Option/Alt+/

Changing color of Twitter bootstrap Nav-Pills

The following code worked for me:-

.nav-pills .nav-link.active, .nav-pills .show>.nav-link {
    color: #fff;
    background-color: rgba(0,123,255,.5);
}

Note:- This worked for me using Bootstrap 4

Change image in HTML page every few seconds

Best way to swap images with javascript with left vertical clickable thumbnails

SCRIPT FILE: function swapImages() {

    window.onload = function () {
        var img = document.getElementById("img_wrap");
        var imgall = img.getElementsByTagName("img");
        var firstimg = imgall[0]; //first image
        for (var a = 0; a <= imgall.length; a++) {
            setInterval(function () {
                var rand = Math.floor(Math.random() * imgall.length);
                firstimg.src = imgall[rand].src;
            }, 3000);



            imgall[1].onmouseover = function () {
                 //alert("what");
                clearInterval();
                firstimg.src = imgall[1].src;


            }
            imgall[2].onmouseover = function () {
                clearInterval();
                firstimg.src = imgall[2].src;
            }
            imgall[3].onmouseover = function () {
                clearInterval();
                firstimg.src = imgall[3].src;
            }
            imgall[4].onmouseover = function () {
                clearInterval();
                firstimg.src = imgall[4].src;
            }
            imgall[5].onmouseover = function () {
                clearInterval();
                firstimg.src = imgall[5].src;
            }
        }

    }


}

Using margin:auto to vertically-align a div

I know the question is from 2012, but I found the easiest way ever, and I wanted to share.

HTML:

<div id="parent">
     <div id="child">Content here</div>
</div>

and CSS:

#parent{
     height: 100%;
     display: table;
}    
#child {
     display: table-cell;
     vertical-align: middle; 
}

How can I format date by locale in Java?

I agree with Laura and the SimpleDateFormat which is the best way to manage Dates in java. You can set the pattern and the locale. Plus you can have a look at this wikipedia article about Date in the world -there are not so many different ways to use it; typically USA / China / rest of the world -

dll missing in JDBC

Alright guys, I found it out! I didn't really need to change the java.library.path but the "Native library location" of sqljdbc.jar

This is the best answer I could find: https://stackoverflow.com/a/958074/2000342

It works now, thanks for the support!

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

An XML declaration is not required in all XML documents; however XHTML document authors are strongly encouraged to use XML declarations in all their documents. Such a declaration is required when the character encoding of the document is other than the default UTF-8 or UTF-16 and no encoding was determined by a higher-level protocol. Here is an example of an XHTML document. In this example, the XML declaration is included.

<?xml version="1.0" encoding="UTF-8"?>
 <!DOCTYPE html 
 PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
 <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
  <head>
    <title>Virtual Library</title>
  </head>
  <body>
    <p>Moved to <a href="http://example.org/">example.org</a>.</p>
 </body>
</html>

Please refer to the W3 standards for XML.

Remove characters from C# string

Simple:

String.Join("", "My name @is ,Wan.;'; Wan".Split('@', ',' ,'.' ,';', '\''));

MySQL JOIN ON vs USING?

For those experimenting with this in phpMyAdmin, just a word:

phpMyAdmin appears to have a few problems with USING. For the record this is phpMyAdmin run on Linux Mint, version: "4.5.4.1deb2ubuntu2", Database server: "10.2.14-MariaDB-10.2.14+maria~xenial - mariadb.org binary distribution".

I have run SELECT commands using JOIN and USING in both phpMyAdmin and in Terminal (command line), and the ones in phpMyAdmin produce some baffling responses:

1) a LIMIT clause at the end appears to be ignored.
2) the supposed number of rows as reported at the top of the page with the results is sometimes wrong: for example 4 are returned, but at the top it says "Showing rows 0 - 24 (2503 total, Query took 0.0018 seconds.)"

Logging on to mysql normally and running the same queries does not produce these errors. Nor do these errors occur when running the same query in phpMyAdmin using JOIN ... ON .... Presumably a phpMyAdmin bug.

How to include clean target in Makefile?

In makefile language $@ means "name of the target", so rm -f $@ translates to rm -f clean.

You need to specify to rm what exactly you want to delete, like rm -f *.o code1 code2

Multi-dimensional arraylist or list in C#?

If you want to modify this I'd go with either of the following:

List<string[]> results;

-- or --

List<List<string>> results;

depending on your needs...

How to make HTML Text unselectable

I altered the jQuery plugin posted above so it would work on live elements.

(function ($) {
$.fn.disableSelection = function () {
    return this.each(function () {
        if (typeof this.onselectstart != 'undefined') {
            this.onselectstart = function() { return false; };
        } else if (typeof this.style.MozUserSelect != 'undefined') {
            this.style.MozUserSelect = 'none';
        } else {
            this.onmousedown = function() { return false; };
        }
    });
};
})(jQuery);

Then you could so something like:

$(document).ready(function() {
    $('label').disableSelection();

    // Or to make everything unselectable
    $('*').disableSelection();
});

How to use executables from a package installed locally in node_modules?

Use npm-run.

From the readme:

npm-run

Find & run local executables from node_modules

Any executable available to an npm lifecycle script is available to npm-run.

Usage

$ npm install mocha # mocha installed in ./node_modules
$ npm-run mocha test/* # uses locally installed mocha executable 

Installation

$ npm install -g npm-run

How do I pass JavaScript values to Scriptlet in JSP?

This is for other people landing here. First of all you need a servlet. I used a @POST request. Now in your jsp file you have two ways to do this:

  1. The complicated way with AJAX, in case you are new to jsp: You need to do a post with the javascript var that you want to use in you java class and use JSP to call your java function from inside your request:

    $(document).ready(function() {
        var sendVar = "hello";
        $('#domId').click(function (e)
        {                               
            $.ajax({
                type: "post",
                url: "/", //or whatever your url is
                data: "var=" + sendVar ,
                success: function(){      
                        console.log("success: " + sendVar );                            
                      <% 
                          String received= request.getParameter("var");
    
                          if(received == null || received.isEmpty()){
                              received = "some default value";
                          }
                          MyJavaClass.processJSvar(received); 
                      %>;                            
    
                }
            });
        });
    
    });
    
  2. The easy way just with JSP:

    <form id="myform" method="post" action="http://localhost:port/index.jsp">
         <input type="hidden" name="inputName" value=""/>
                   <% 
                          String pg = request.getParameter("inputName");
    
                          if(pg == null || pg.isEmpty()){
                              pg = "some default value";
                          }
                          DatasyncMain.changeToPage(pg); 
                      %>;     
    </form>
    

Of course in this case you still have to load the input value from JS (so far I haven't figured out another way to load it).

UTF-8 problems while reading CSV file with fgetcsv

Try putting this into the top of your file (before any other output):

<?php

header('Content-Type: text/html; charset=UTF-8');

?>

Jquery DatePicker Set default date

Today date:

$( ".selector" ).datepicker( "setDate", new Date());
// Or on the init
$( ".selector" ).datepicker({ defaultDate: new Date() });

15 days from today:

$( ".selector" ).datepicker( "setDate", 15);
// Or on the init
$( ".selector" ).datepicker({ defaultDate: 15 });

jQuery ui docs

Set equal width of columns in table layout in Android

Change android:stretchColumns value to *.

Value 0 means stretch the first column. Value 1 means stretch the second column and so on.

Value * means stretch all the columns.

How to programmatically disable page scrolling with jQuery

This will completely disable scrolling:

$('html, body').css({
    overflow: 'hidden',
    height: '100%'
});

To restore:

$('html, body').css({
    overflow: 'auto',
    height: 'auto'
});

Tested it on Firefox and Chrome.

java.net.URL read stream to byte[]

There's no guarantee that the content length you're provided is actually correct. Try something akin to the following:

ByteArrayOutputStream baos = new ByteArrayOutputStream();
InputStream is = null;
try {
  is = url.openStream ();
  byte[] byteChunk = new byte[4096]; // Or whatever size you want to read in at a time.
  int n;

  while ( (n = is.read(byteChunk)) > 0 ) {
    baos.write(byteChunk, 0, n);
  }
}
catch (IOException e) {
  System.err.printf ("Failed while reading bytes from %s: %s", url.toExternalForm(), e.getMessage());
  e.printStackTrace ();
  // Perform any other exception handling that's appropriate.
}
finally {
  if (is != null) { is.close(); }
}

You'll then have the image data in baos, from which you can get a byte array by calling baos.toByteArray().

This code is untested (I just wrote it in the answer box), but it's a reasonably close approximation to what I think you're after.

How to format a floating number to fixed width in Python

I needed something similar for arrays. That helped me

some_array_rounded=np.around(some_array, 5)

Host binding and Host listening

This is the simple example to use both of them:

import {
  Directive, HostListener, HostBinding
}
from '@angular/core';

@Directive({
  selector: '[Highlight]'
})
export class HighlightDirective {
  @HostListener('mouseenter') mouseover() {
    this.backgroundColor = 'green';
  };

  @HostListener('mouseleave') mouseleave() {
    this.backgroundColor = 'white';
  }

  @HostBinding('style.backgroundColor') get setColor() {
     return this.backgroundColor;
  };

  private backgroundColor = 'white';
  constructor() {}

}

Introduction:

  1. HostListener can bind an event to the element.

  2. HostBinding can bind a style to the element.

  3. this is directive, so we can use it for

    Some Text
  4. So according to the debug, we can find that this div has been binded style = "background-color:white"

    Some Text
  5. we also can find that EventListener of this div has two event: mouseenter and mouseleave. So when we move the mouse into the div, the colour will become green, mouse leave, the colour will become white.

Should I use Python 32bit or Python 64bit

Machine learning packages like tensorflow 2.x are designed to work only on 64 bit Python as they are memory intensive.

There can be only one auto column

CREATE TABLE book (
   id INT AUTO_INCREMENT primary key NOT NULL,
   accepted_terms BIT(1) NOT NULL,
   accepted_privacy BIT(1) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1

Javascript : natural sort of alphanumerical strings

So you need a natural sort ?

If so, than maybe this script by Brian Huisman based on David koelle's work would be what you need.

It seems like Brian Huisman's solution is now directly hosted on David Koelle's blog:

Dynamically change bootstrap progress bar value when checkboxes checked

Try this maybe :

Bootply : http://www.bootply.com/106527

Js :

$('input').on('click', function(){
  var valeur = 0;
  $('input:checked').each(function(){
       if ( $(this).attr('value') > valeur )
       {
           valeur =  $(this).attr('value');
       }
  });
  $('.progress-bar').css('width', valeur+'%').attr('aria-valuenow', valeur);    
});

HTML :

 <div class="progress progress-striped active">
        <div class="progress-bar" role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100">
        </div>
    </div>
<div class="row tasks">
        <div class="col-md-6">
          <p><span>Identify your campaign audience.</span>Who are we talking to here? Understand your buyer persona before launching into a campaign, so you can target them correctly.</p>
        </div>
        <div class="col-md-2">
          <label>2014-01-29</label>
        </div>
        <div class="col-md-2">
          <input name="progress" class="progress" type="checkbox" value="10">
        </div>
        <div class="col-md-2">
          <input name="done" class="done" type="checkbox" value="20">
        </div>
      </div><!-- tasks -->

<div class="row tasks">
        <div class="col-md-6">
          <p><span>Set your goals + benchmarks</span>Having SMART goals can help you be
sure that you’ll have tangible results to share with the world (or your
boss) at the end of your campaign.</p>
        </div>
        <div class="col-md-2">
          <label>2014-01-25</label>
        </div>
        <div class="col-md-2">
          <input name="progress" class="progress" type="checkbox" value="30">
        </div>
        <div class="col-md-2">
          <input name="done" class="done" type="checkbox" value="40">
        </div>
      </div><!-- tasks -->

Css

.tasks{
    background-color: #F6F8F8;
    padding: 10px;
    border-radius: 5px;
    margin-top: 10px;
}
.tasks span{
    font-weight: bold;
}
.tasks input{
    display: block;
    margin: 0 auto;
    margin-top: 10px;
}
.tasks a{
    color: #000;
    text-decoration: none;
    border:none;
}
.tasks a:hover{
    border-bottom: dashed 1px #0088cc;
}
.tasks label{
    display: block;
    text-align: center;
}

_x000D_
_x000D_
$(function(){_x000D_
$('input').on('click', function(){_x000D_
  var valeur = 0;_x000D_
  $('input:checked').each(function(){_x000D_
       if ( $(this).attr('value') > valeur )_x000D_
       {_x000D_
           valeur =  $(this).attr('value');_x000D_
       }_x000D_
  });_x000D_
  $('.progress-bar').css('width', valeur+'%').attr('aria-valuenow', valeur);    _x000D_
});_x000D_
_x000D_
});
_x000D_
.tasks{_x000D_
 background-color: #F6F8F8;_x000D_
 padding: 10px;_x000D_
 border-radius: 5px;_x000D_
 margin-top: 10px;_x000D_
}_x000D_
.tasks span{_x000D_
 font-weight: bold;_x000D_
}_x000D_
.tasks input{_x000D_
 display: block;_x000D_
 margin: 0 auto;_x000D_
 margin-top: 10px;_x000D_
}_x000D_
.tasks a{_x000D_
 color: #000;_x000D_
 text-decoration: none;_x000D_
 border:none;_x000D_
}_x000D_
.tasks a:hover{_x000D_
 border-bottom: dashed 1px #0088cc;_x000D_
}_x000D_
.tasks label{_x000D_
 display: block;_x000D_
 text-align: center;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
_x000D_
 <div class="progress progress-striped active">_x000D_
        <div class="progress-bar" role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100">_x000D_
        </div>_x000D_
    </div>_x000D_
<div class="row tasks">_x000D_
        <div class="col-md-6">_x000D_
          <p><span>Identify your campaign audience.</span>Who are we talking to here? Understand your buyer persona before launching into a campaign, so you can target them correctly.</p>_x000D_
        </div>_x000D_
        <div class="col-md-2">_x000D_
          <label>2014-01-29</label>_x000D_
        </div>_x000D_
        <div class="col-md-2">_x000D_
          <input name="progress" class="progress" type="checkbox" value="10">_x000D_
        </div>_x000D_
        <div class="col-md-2">_x000D_
          <input name="done" class="done" type="checkbox" value="20">_x000D_
        </div>_x000D_
      </div><!-- tasks -->_x000D_
_x000D_
<div class="row tasks">_x000D_
        <div class="col-md-6">_x000D_
          <p><span>Set your goals + benchmarks</span>Having SMART goals can help you be_x000D_
sure that you’ll have tangible results to share with the world (or your_x000D_
boss) at the end of your campaign.</p>_x000D_
        </div>_x000D_
        <div class="col-md-2">_x000D_
          <label>2014-01-25</label>_x000D_
        </div>_x000D_
        <div class="col-md-2">_x000D_
          <input name="progress" class="progress" type="checkbox" value="30">_x000D_
        </div>_x000D_
        <div class="col-md-2">_x000D_
          <input name="done" class="done" type="checkbox" value="40">_x000D_
        </div>_x000D_
      </div><!-- tasks -->
_x000D_
_x000D_
_x000D_

Javascript "Uncaught TypeError: object is not a function" associativity question

I was getting this same error and spent a day and a half trying to find a solution. Naomi's answer lead me to the solution I needed.

My input (type=button) had an attribute name that was identical to a function name that was being called by the onClick event. Once I changed the attribute name everything worked.

<input type="button" name="clearEmployer" onClick="clearEmployer();">

changed to:

<input type="button" name="clearEmployerBtn" onClick="clearEmployer();">

Best Practice to Organize Javascript Library & CSS Folder Structure

 root/
   assets/
      lib/-------------------------libraries--------------------
          bootstrap/--------------Libraries can have js/css/images------------
              css/
              js/
              images/  
          jquery/
              js/
          font-awesome/
              css/
              images/
     common/--------------------common section will have application level resources             
          css/
          js/
          img/

 index.html

This is how I organized my application's static resources.

Creating runnable JAR with Gradle

Least effort solution for me was to make use of the gradle-shadow-plugin

Besides applying the plugin all that needs to be done is:

Configure the jar task to put your Main class into manifest

jar {
  manifest {
   attributes 'Main-Class': 'com.my.app.Main'
  }
}

Run the gradle task

./gradlew shadowJar

Take the app-version-all.jar from build/libs/

And finally execute it via:

java -jar app-version-all.jar

Best place to insert the Google Analytics code

Yes, it is recommended to put the GA code in the footer anyway, as the page shouldnt count as a page visit until its read all the markup.

wait() or sleep() function in jquery?

You can use the .delay() function.
This is what you're after:

.addClass("load").delay(2000).addClass("done");

Image vs zImage vs uImage

What is the difference between them?

Image: the generic Linux kernel binary image file.

zImage: a compressed version of the Linux kernel image that is self-extracting.

uImage: an image file that has a U-Boot wrapper (installed by the mkimage utility) that includes the OS type and loader information.
A very common practice (e.g. the typical Linux kernel Makefile) is to use a zImage file. Since a zImage file is self-extracting (i.e. needs no external decompressors), the wrapper would indicate that this kernel is "not compressed" even though it actually is.


Note that the author/maintainer of U-Boot considers the (widespread) use of using a zImage inside a uImage questionable:

Actually it's pretty stupid to use a zImage inside an uImage. It is much better to use normal (uncompressed) kernel image, compress it using just gzip, and use this as poayload for mkimage. This way U-Boot does the uncompresiong instead of including yet another uncompressor with each kernel image.

(quoted from https://lists.yoctoproject.org/pipermail/yocto/2013-October/016778.html)


Which type of kernel image do I have to use?

You could choose whatever you want to program for.
For economy of storage, you should probably chose a compressed image over the uncompressed one.
Beware that executing the kernel (presumably the Linux kernel) involves more than just loading the kernel image into memory. Depending on the architecture (e.g. ARM) and the Linux kernel version (e.g. with or without DTB), there are registers and memory buffers that may have to be prepared for the kernel. In one instance there was also hardware initialization that U-Boot performed that had to be replicated.

ADDENDUM

I know that u-boot needs a kernel in uImage format.

That is accurate for all versions of U-Boot which only have the bootm command.
But more recent versions of U-Boot could also have the bootz command that can boot a zImage.

How to increase Neo4j's maximum file open limit (ulimit) in Ubuntu?

Try run this command it will create a *_limits.conf file under /etc/security/limits.d

echo "* soft nofile 102400" > /etc/security/limits.d/*_limits.conf && echo "* hard nofile 102400" >> /etc/security/limits.d/*_limits.conf

Just exit from terminal and login again and verify by ulimit -n it will set for * users

How to start an Intent by passing some parameters to it?

In order to pass the parameters you create new intent and put a parameter map:

Intent myIntent = new Intent(this, NewActivityClassName.class);
myIntent.putExtra("firstKeyName","FirstKeyValue");
myIntent.putExtra("secondKeyName","SecondKeyValue");
startActivity(myIntent);

In order to get the parameters values inside the started activity, you must call the get[type]Extra() on the same intent:

// getIntent() is a method from the started activity
Intent myIntent = getIntent(); // gets the previously created intent
String firstKeyName = myIntent.getStringExtra("firstKeyName"); // will return "FirstKeyValue"
String secondKeyName= myIntent.getStringExtra("secondKeyName"); // will return "SecondKeyValue"

If your parameters are ints you would use getIntExtra() instead etc. Now you can use your parameters like you normally would.

Logging in Scala

I use SLF4J + Logback classic and apply it like this:

trait Logging {
  lazy val logger = LoggerFactory.getLogger(getClass)

  implicit def logging2Logger(anything: Logging): Logger = anything.logger
}

Then you can use it whichever fits your style better:

class X with Logging {
    logger.debug("foo")
    debug("bar")
}

but this approach of course uses a logger instance per class instance.

How to run a method every X seconds

Here I used a thread in onCreate() an Activity repeatly, timer does not allow everything in some cases Thread is the solution

     Thread t = new Thread() {
        @Override
        public void run() {
            while (!isInterrupted()) {
                try {
                    Thread.sleep(10000);  //1000ms = 1 sec
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {

                            SharedPreferences mPrefs = getSharedPreferences("sam", MODE_PRIVATE);
                            Gson gson = new Gson();
                            String json = mPrefs.getString("chat_list", "");
                            GelenMesajlar model = gson.fromJson(json, GelenMesajlar.class);
                            String sam = "";

                            ChatAdapter adapter = new ChatAdapter(Chat.this, model.getData());
                            listview.setAdapter(adapter);
                           // listview.setStackFromBottom(true);
                          //  Util.showMessage(Chat.this,"Merhabalar");
                        }
                    });

                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    };

    t.start();

In case it needed it can be stoped by

@Override
protected void onDestroy() {
    super.onDestroy();
    Thread.interrupted();
    //t.interrupted();
}

"Connection for controluser as defined in your configuration failed" with phpMyAdmin in XAMPP

On Ubunbtu.

Ben's message is close but it's not the root password that is the problem, the problem I found was I had created a password for the phpmyadmin database when I installed it. This password is not carried into the installation on ubuntu so the variable $dbpass=''; in the database settings file is empty and not the password you set.

  1. To check you have the right password at the command line login to mysql using the following command: mysql -u phpmyadmin -p try a blank password I found I got access denied, enter the command again using the password you set during installation. If it logs in you now know what the password is.
  2. Edit /etc/phpadmin/config-db.php and change $dbpass=''; to $dbpass='Your Password'; and save the file.
  3. Edit /etc/dbconfig-common/phpmyadmin.conf change dbc_dbpass=''; to dbc_dbpass='Your Password'; and save the file. Close your browser and reload you will now find the message has gone way.

How do I convert ticks to minutes?

TimeSpan.FromTicks(28000000000).TotalMinutes;

How to make the corners of a button round?

Is there an easy way to achieve this in Android?

Yes, today there is, and it is very simple.
Just use the MaterialButton in the Material Components library with the app:cornerRadius attribute.

Something like:

    <com.google.android.material.button.MaterialButton
        android:text="BUTTON"
        app:cornerRadius="8dp"
        ../>

enter image description here

It is enough to obtain a Button with rounded corners.

You can use one of Material button styles. For example:

<com.google.android.material.button.MaterialButton
    style="@style/Widget.MaterialComponents.Button.OutlinedButton"
    .../>

enter image description here

Also starting from the version 1.1.0 you can also change the shape of your button. Just use the shapeAppearanceOverlay attribute in the button style:

  <style name="MyButtonStyle" parent="Widget.MaterialComponents.Button">
    <item name="shapeAppearanceOverlay">@style/ShapeAppearanceOverlay.MyApp.Button.Rounded</item>
  </style>

  <style name="ShapeAppearanceOverlay.MyApp.Button.Rounded" parent="">
    <item name="cornerFamily">rounded</item>
    <item name="cornerSize">16dp</item>
  </style>

Then just use:

<com.google.android.material.button.MaterialButton
   style="@style/MyButtonStyle"
   .../>

You can also apply the shapeAppearanceOverlay in the xml layout:

<com.google.android.material.button.MaterialButton
   app:shapeAppearanceOverlay="@style/ShapeAppearanceOverlay.MyApp.Button.Rounded"
   .../>

The shapeAppearance allows also to have different shape and dimension for each corner:

<style name="ShapeAppearanceOverlay.MyApp.Button.Rounded" parent="">
    <item name="cornerFamily">rounded</item>
    <item name="cornerFamilyTopRight">cut</item>
    <item name="cornerFamilyBottomRight">cut</item>
    <item name="cornerSizeTopLeft">32dp</item>
    <item name="cornerSizeBottomLeft">32dp</item>
</style>

enter image description here

Enabling error display in PHP via htaccess only

This works for me (reference):

# PHP error handling for production servers
# Disable display of startup errors
php_flag display_startup_errors off

# Disable display of all other errors
php_flag display_errors off

# Disable HTML markup of errors
php_flag html_errors off

# Enable logging of errors
php_flag log_errors on

# Disable ignoring of repeat errors
php_flag ignore_repeated_errors off

# Disable ignoring of unique source errors
php_flag ignore_repeated_source off

# Enable logging of PHP memory leaks
php_flag report_memleaks on

# Preserve most recent error via php_errormsg
php_flag track_errors on

# Disable formatting of error reference links
php_value docref_root 0

# Disable formatting of error reference links
php_value docref_ext 0

# Specify path to PHP error log
php_value error_log /home/path/public_html/domain/PHP_errors.log

# Specify recording of all PHP errors
# [see footnote 3] # php_value error_reporting 999999999
php_value error_reporting -1

# Disable max error string length
php_value log_errors_max_len 0

# Protect error log by preventing public access
<Files PHP_errors.log>
 Order allow,deny
 Deny from all
 Satisfy All
</Files>

Is there a way to delete created variables, functions, etc from the memory of the interpreter?

This worked for me.

You need to run it twice once for globals followed by locals

for name in dir():
    if not name.startswith('_'):
        del globals()[name]

for name in dir():
    if not name.startswith('_'):
        del locals()[name]

How do you check "if not null" with Eloquent?

We can use

Model::whereNotNull('sent_at');

Or

Model::whereRaw('sent_at is not null');

jquery append external html file into my page

i'm not sure what you're expecting this to refer to in your example.. here's an alternative method:

<html>
    <head>
        <script src="http://code.jquery.com/jquery-1.6.4.min.js" type="text/javascript"></script>
        <script type="text/javascript">
            $(function () {
                $.get("banner.html", function (data) {
                    $("#appendToThis").append(data);
                });
            });
        </script>
    </head>
    <body>
        <div id="appendToThis"></div>
    </body>
</html>

How do I revert to a previous package in Anaconda?

For the case that you wish to revert a recently installed package that made several changes to dependencies (such as tensorflow), you can "roll back" to an earlier installation state via the following method:

conda list --revisions
conda install --revision [revision number]

The first command shows previous installation revisions (with dependencies) and the second reverts to whichever revision number you specify.

Note that if you wish to (re)install a later revision, you may have to sequentially reinstall all intermediate versions. If you had been at revision 23, reinstalled revision 20 and wish to return, you may have to run each:

conda install --revision 21
conda install --revision 22
conda install --revision 23

How to remove non-alphanumeric characters?

[\W_]+

 

$string = preg_replace("/[\W_]+/u", '', $string);

It select all not A-Z, a-z, 0-9 and delete it.

See example here: https://regexr.com/3h1rj

Converting integer to binary in python

('0' * 7 + bin(6)[2:])[-8:]

or

right_side = bin(6)[2:]
'0' * ( 8 - len( right_side )) + right_side

How do I change the default library path for R packages

Windows 7/10: If your C:\Program Files (or wherever R is installed) is blocked for writing, as mine is, then you'll get frustrated editing RProfile.site (as I did). As specified above, I updated R_LIBS_USER and it worked. However, even after reading the fine manual several times and extensive searching, it took me several hours to do this. In the spirit of saving someone else time...

Let's assume you want your packages to reside in C:\R\Library:

  1. Create the folder C:\R\Library
  2. Click Start --> Control Panel --> User Accounts --> Change my environmental variables
  3. The Environmental Variables window pops up. If you see R_LIBS_USER, highlight it and click Edit. Otherwise click New. Both actions open a window with fields for Variable and Value.
  4. In my case, R_LIBS_USER was already there, and the value was a path to my desktop. I added to the path the folder that I created, separated by semicolon as mentioned above. C:\R\Library;C:\Users\Eric.Krantz\Desktop\R stuff\Packages. NOTE: I could have removed the path to the Desktop location and simply left C:\R\Library.

Adding Image to xCode by dragging it from File

You can't add image from desktop to UIimageView, you only can add image (dragging) into project folders and then select the name image into UIimageView properties (inspector).

Tutorial on how to do that: http://conecode.com/news/2011/06/ios-tutorial-creating-an-image-view-uiimageview/

How to show math equations in general github's markdown(not github's blog)

It ’s 2020 now, let me summarize the progress of the mathematical formula rendering support of source code repository hosts.

GitHub & Bitbucket

GitHub and Bitbucket still do not support the rendering of mathematical formulas, whether it is the default delimiters or other.

Bitbucket Cloud / BCLOUD-11192 -- Add LaTeX Support in MarkDown Documents (BB-12552)

GitHub / markup -- Rendering math equations

GitHub / markup -- Support latex

GitHub Community Forum -- [FEATURE REQUEST] LaTeX Math in Markdown

talk.commonmark.org -- Can math formula added to the markdown

GitHub has hardly made any substantial progress in recent years.

GitLab

GitLab is already supported, but not the most common way. It uses its own delimiter.

This math is inline $`a^2+b^2=c^2`$.

This is on a separate line

```math
a^2+b^2=c^2
```

GitLab Flavored Markdown -- Math

Who supports the universal delimiters?

A Markdown parser used by Hugo

Other ways to render

The entity type <type> is not part of the model for the current context

My issue was resolved by updating the metadata part of the connection string. Apparently it was pointing at the wrong .csdl / .ssdl / .msl reference.

Set language for syntax highlighting in Visual Studio Code

Another reason why people might struggle to get Syntax Highlighting working is because they don't have the appropriate syntax package installed. While some default syntax packages come pre-installed (like Swift, C, JS, CSS), others may not be available.

To solve this you can Cmd + Shift + P ? "install Extensions" and look for the language you want to add, say "Scala".

enter image description here

Find the suitable Syntax package, install it and reload. This will pick up the correct syntax for your files with the predefined extension, i.e. .scala in this case.

On top of that you might want VS Code to treat all files with certain custom extensions as your preferred language of choice. Let's say you want to highlight all *.es files as JavaScript, then just open "User Settings" (Cmd + Shift + P ? "User Settings") and configure your custom files association like so:

  "files.associations": {
    "*.es": "javascript"
  },

C# equivalent to Java's charAt()?

please try to make it as a character

string str = "Tigger";
//then str[0] will return 'T' not "T"

Mysql - delete from multiple tables with one query

The documentation for DELETE tells you the multi-table syntax.

DELETE [LOW_PRIORITY] [QUICK] [IGNORE]
    tbl_name[.*] [, tbl_name[.*]] ...
    FROM table_references
    [WHERE where_condition]

Or:

DELETE [LOW_PRIORITY] [QUICK] [IGNORE]
    FROM tbl_name[.*] [, tbl_name[.*]] ...
    USING table_references
    [WHERE where_condition]

Global Git ignore

To create global gitignore from scratch:

$ cd ~
$ touch .gitignore_global
$ git config --global core.excludesfile ~/.gitignore_global
  1. First line changes directory to C:/Users/User
  2. After that you create an empty file with .gitignore_global extension
  3. And finally setting global ignore to that file.
  4. Then you should open it with some kind of notepad and add the needed ignore rules.

How do you add CSS with Javascript?

Here's a slightly updated version of Chris Herring's solution, taking into account that you can use innerHTML as well instead of a creating a new text node:

function insertCss( code ) {
    var style = document.createElement('style');
    style.type = 'text/css';

    if (style.styleSheet) {
        // IE
        style.styleSheet.cssText = code;
    } else {
        // Other browsers
        style.innerHTML = code;
    }

    document.getElementsByTagName("head")[0].appendChild( style );
}

Why can I not switch branches?

you can reset your branch with HEAD

git reset --hard branch_name

then fetch branches and delete branches which are not on remote from local,

git fetch -p 

Return Result from Select Query in stored procedure to a List

// GET: api/GetStudent

public Response Get() {
    return StoredProcedure.GetStudent();
}

public static Response GetStudent() {
    using (var db = new dal()) {
        var student = db.Database.SqlQuery<GetStudentVm>("GetStudent").ToList();
        return new Response {
            Sucess = true,
            Message = student.Count() + " Student found",
            Data = student
        };
    }
}

How can I add new keys to a dictionary?

This popular question addresses functional methods of merging dictionaries a and b.

Here are some of the more straightforward methods (tested in Python 3)...

c = dict( a, **b ) ## see also https://stackoverflow.com/q/2255878
c = dict( list(a.items()) + list(b.items()) )
c = dict( i for d in [a,b] for i in d.items() )

Note: The first method above only works if the keys in b are strings.

To add or modify a single element, the b dictionary would contain only that one element...

c = dict( a, **{'d':'dog'} ) ## returns a dictionary based on 'a'

This is equivalent to...

def functional_dict_add( dictionary, key, value ):
   temp = dictionary.copy()
   temp[key] = value
   return temp

c = functional_dict_add( a, 'd', 'dog' )

Securing a password in a properties file

What about providing a custom N-Factor authentication mechanism?

Before combining available methods, let's assume we can perform the following:

1) Hard-code inside the Java program

2) Store in a .properties file

3) Ask user to type password from command line

4) Ask user to type password from a form

5) Ask user to load a password-file from command line or a form

6) Provide the password through network

7) many alternatives (eg Draw A Secret, Fingerprint, IP-specific, bla bla bla)

1st option: We could make things more complicated for an attacker by using obfuscation, but this is not considered a good countermeasure. A good coder can easily understand how it works if he/she can access the file. We could even export a per-user binary (or just the obfuscation part or key-part), so an attacker must have access to this user-specific file, not another distro. Again, we should find a way to change passwords, eg by recompiling or using reflection to on-the-fly change class behavior.

2nd option: We can store the password in the .properties file in an encrypted format, so it's not directly visible from an attacker (just like jasypt does). If we need a password manager we'll need a master password too which again should be stored somewhere - inside a .class file, the keystore, kernel, another file or even in memory - all have their pros and cons.
But, now users will just edit the .properties file for password change.

3rd option: type the password when running from command line e.g. java -jar /myprogram.jar -p sdflhjkiweHIUHIU8976hyd.

This doesn't require the password to be stored and will stay in memory. However, history commands and OS logs, may be your worst enemy here. To change passwords on-the-fly, you will need to implement some methods (eg listen for console inputs, RMI, sockets, REST bla bla bla), but the password will always stay in memory.

One can even temporarily decrypt it only when required -> then delete the decrypted, but always keep the encrypted password in memory. Unfortunately, the aforementioned method does not increase security against unauthorized in-memory access, because the person who achieves that, will probably have access to the algorithm, salt and any other secrets being used.

4th option: provide the password from a custom form, rather than the command line. This will circumvent the problem of logging exposure.

5th option: provide a file as a password stored previously on a another medium -> then hard delete file. This will again circumvent the problem of logging exposure, plus no typing is required that could be shoulder-surfing stolen. When a change is required, provide another file, then delete again.

6th option: again to avoid shoulder-surfing, one can implement an RMI method call, to provide the password (through an encrypted channel) from another device, eg via a mobile phone. However, you now need to protect your network channel and access to the other device.

I would choose a combination of the above methods to achieve maximum security so one would have to access the .class files, the property file, logs, network channel, shoulder surfing, man in the middle, other files bla bla bla. This can be easily implemented using a XOR operation between all sub_passwords to produce the actual password.

We can't be protected from unauthorized in-memory access though, this can only be achieved by using some access-restricted hardware (eg smartcards, HSMs, SGX), where everything is computed into them, without anyone, even the legitimate owner being able to access decryption keys or algorithms. Again, one can steal this hardware too, there are reported side-channel attacks that may help attackers in key extraction and in some cases you need to trust another party (eg with SGX you trust Intel). Of course, situation may worsen when secure-enclave cloning (de-assembling) will be possible, but I guess this will take some years to be practical.

Also, one may consider a key sharing solution where the full key is split between different servers. However, upon reconstruction, the full key can be stolen. The only way to mitigate the aforementioned issue is by secure multiparty computation.

We should always keep in mind that whatever the input method, we need to ensure we are not vulnerable from network sniffing (MITM attacks) and/or key-loggers.

How to disable Google Chrome auto update?

Just add the object yourself using regedit:

Under HKEY_LOCAL_MACHINE\SOFTWARE\Policies,

  • Create new Key, "Google"
  • In "Google", create new Key, "Update"
  • In "Update" go to that key and create Dword, "AutoUpdateCheckPeriodMinutes" which automatically value set to 0, just double check and change if needed.

All done!

Restart might be needed.

Calling a PHP function from an HTML form in the same file

Here is a full php script to do what you're describing, though pointless. You need to read up on server-side vs. client-side. PHP can't run on the client-side, you have to use javascript to interact with the server, or put up with a page refresh. If you can't understand that, there is no way you'll be able to use my code (or anyone else's) to your benefit.

The following code performs AJAX call without jQuery, and calls the same script to stream XML to the AJAX. It then inserts your username and a <br/> in a div below the user box.

Please go back to learning the basics before trying to pursue something as advanced as AJAX. You'll only be confusing yourself in the end and potentially wasting other people's money.

<?php
    function test() {
        header("Content-Type: text/xml");
        echo "<?xml version=\"1.0\" standalone=\"yes\"?><user>".$_GET["user"]."</user>"; //output an xml document.
    }
    if(isset($_GET["user"])){
        test();
    } else {
?><html>
    <head>
        <title>Test</title>
        <script type="text/javascript">
            function do_ajax() {
                if(window.XMLHttpRequest){
                    xmlhttp=new XMLHttpRequest();
                } else {
                    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
                }
                xmlhttp.onreadystatechange = function(){
                    if (xmlhttp.readyState==4 && xmlhttp.status==200)
                    {
                        var xmlDoc = xmlhttp.responseXML;
                        data=xmlDoc.getElementsByTagName("user")[0].childNodes[0].nodeValue;
                        mydiv = document.getElementById("Test");
                        mydiv.appendChild(document.createTextNode(data));
                        mydiv.appendChild(document.createElement("br"));
                    }
                }
                xmlhttp.open("GET","<?php echo $_SERVER["PHP_SELF"]; ?>?user="+document.getElementById('username').value,true);
                xmlhttp.send();
            }
        </script>
    </head>
    <body>
        <form action="test.php" method="post">
            <input type="text" name="user" placeholder="enter a text" id="username"/>
            <input type="button" value="submit" onclick="do_ajax()" />
        </form>
        <div id="Test"></div>
    </body>
</html><?php } ?>

The container 'Maven Dependencies' references non existing library - STS

I finally found my maven repo mirror is down. I changed to another one, problem solved.

android : Error converting byte to dex

After I upgraded to Android Studio 2.1, the next time I rebooted, I was asked to upgrade to JDK 1.8. After I upgraded to JDK 1.8, that's when my AS project had trouble compiling. I followed all of the suggestions in this page, but to no avail. Finally, I decided to check the version of JDK that my project was using, and to my surprise, it somehow was pointing to JDK 1.8!

Moral of the story: If compileSdkVersion<=23, double check that your project is using JDK1.7 as follows:

  • Right Mouse on top level module
  • Project STructure => JDK Location

UTL_FILE.FOPEN() procedure not accepting path for directory?

Since Oracle 9i there are two ways or declaring a directory for use with UTL_FILE.

The older way is to set the INIT.ORA parameter UTL_FILE_DIR. We have to restart the database for a change to take affect. The value can like any other PATH variable; it accepts wildcards. Using this approach means passing the directory path...

UTL_FILE.FOPEN('c:\temp', 'vineet.txt', 'W');

The alternative approach is to declare a directory object.

create or replace directory temp_dir as 'C:\temp'
/

grant read, write on directory temp_dir to vineet
/

Directory objects require the exact file path, and don't accept wildcards. In this approach we pass the directory object name...

UTL_FILE.FOPEN('TEMP_DIR', 'vineet.txt', 'W');

The UTL_FILE_DIR is deprecated because it is inherently insecure - all users have access to all the OS directories specified in the path, whereas read and write privileges can de granted discretely to individual users. Also, with Directory objects we can be add, remove or change directories without bouncing the database.

In either case, the oracle OS user must have read and/or write privileges on the OS directory. In case it isn't obvious, this means the directory must be visible from the database server. So we cannot use either approach to expose a directory on our local PC to a process running on a remote database server. Files must be uploaded to the database server, or a shared network drive.


If the oracle OS user does not have the appropriate privileges on the OS directory, or if the path specified in the database does not match to an actual path, the program will hurl this exception:

ORA-29283: invalid file operation
ORA-06512: at "SYS.UTL_FILE", line 536
ORA-29283: invalid file operation
ORA-06512: at line 7

The OERR text for this error is pretty clear:

29283 -  "invalid file operation"
*Cause:    An attempt was made to read from a file or directory that does
           not exist, or file or directory access was denied by the
           operating system.
*Action:   Verify file and directory access privileges on the file system,
           and if reading, verify that the file exists.

php multidimensional array get values

For people who searched for php multidimensional array get values and actually want to solve problem comes from getting one column value from a 2 dimensinal array (like me!), here's a much elegant way than using foreach, which is array_column

For example, if I only want to get hotel_name from the below array, and form to another array:

$hotels = [
    [
        'hotel_name' => 'Hotel A',
        'info' => 'Hotel A Info',
    ],
    [
        'hotel_name' => 'Hotel B',
        'info' => 'Hotel B Info',
    ]
];

I can do this using array_column:

$hotel_name = array_column($hotels, 'hotel_name');

print_r($hotel_name); // Which will give me ['Hotel A', 'Hotel B']

For the actual answer for this question, it can also be beautified by array_column and call_user_func_array('array_merge', $twoDimensionalArray);

Let's make the data in PHP:

$hotels = [
    [
        'hotel_name' => 'Hotel A',
        'info' => 'Hotel A Info',
        'rooms' => [
            [
                'room_name' => 'Luxury Room',
                'bed' => 2,
                'boards' => [
                    'board_id' => 1,
                    'price' => 200
                ]
            ],
            [
                'room_name' => 'Non Luxy Room',
                'bed' => 4,
                'boards' => [
                    'board_id' => 2,
                    'price' => 150
                ]
            ],
        ]
    ],
    [
        'hotel_name' => 'Hotel B',
        'info' => 'Hotel B Info',
        'rooms' => [
            [
                'room_name' => 'Luxury Room',
                'bed' => 2,
                'boards' => [
                    'board_id' => 3,
                    'price' => 900
                ]
            ],
            [
                'room_name' => 'Non Luxy Room',
                'bed' => 4,
                'boards' => [
                    'board_id' => 4,
                    'price' => 300
                ]
            ],
        ]
    ]
];

And here's the calculation:

$rooms = array_column($hotels, 'rooms');
$rooms = call_user_func_array('array_merge', $rooms);
$boards = array_column($rooms, 'boards');

foreach($boards as $board){
    $board_id = $board['board_id'];
    $price = $board['price'];
    echo "Board ID is: ".$board_id." and price is: ".$price . "<br/>";
}

Which will give you the following result:

Board ID is: 1 and price is: 200
Board ID is: 2 and price is: 150
Board ID is: 3 and price is: 900
Board ID is: 4 and price is: 300

Exit a while loop in VBS/VBA

VBScript's While loops don't support early exit. Use the Do loop for that:

num = 0
do while (num < 10)
  if (status = "Fail") then exit do
  num = num + 1
loop

facebook: permanent Page Access Token?

I made a PHP script to make it easier. Create an app. In the Graph API Explorer select your App and get a user token with manage_pages and publish_pages permission. Find your page's ID at the bottom of its About page. Fill in the config vars and run the script.

<?php
$args=[
    'usertoken'=>'',
    'appid'=>'',
    'appsecret'=>'',
    'pageid'=>''
];

echo generate_token($args);

function generate_token($args){
    $r=json_decode(file_get_contents("https://graph.facebook.com/v2.8/oauth/access_token?grant_type=fb_exchange_token&client_id={$args['appid']}&client_secret={$args['appsecret']}&fb_exchange_token={$args['usertoken']}")); // get long-lived token
    $longtoken=$r->access_token;
    $r=json_decode(file_get_contents("https://graph.facebook.com/v2.8/me?access_token={$longtoken}")); // get user id
    $userid=$r->id;
    $r=json_decode(file_get_contents("https://graph.facebook.com/v2.8/{$userid}/accounts?access_token={$longtoken}")); // get permanent token
    foreach($r->data as $d) if($d->id==$args['pageid']) return $d->access_token;
}

Detect changed input text box

I think you can use keydown too:

$('#fieldID').on('keydown', function (e) {
  //console.log(e.which);
  if (e.which === 8) {
    //do something when pressing delete
    return true;
  } else {
    //do something else
    return false;
  }
});

Does Spring Data JPA have any way to count entites using method name resolving?

Working example

@Repository
public interface TenantRepository extends JpaRepository< Tenant, Long > {
    List<Tenant>findByTenantName(String tenantName,Pageable pageRequest);
    long countByTenantName(String tenantName);
}

Calling from DAO layer

@Override
public long countByTenantName(String tenantName) {
    return repository.countByTenantName(tenantName);
}

How to retrieve raw post data from HttpServletRequest in java

The request body is available as byte stream by HttpServletRequest#getInputStream():

InputStream body = request.getInputStream();
// ...

Or as character stream by HttpServletRequest#getReader():

Reader body = request.getReader();
// ...

Note that you can read it only once. The client ain't going to resend the same request multiple times. Calling getParameter() and so on will implicitly also read it. If you need to break down parameters later on, you've got to store the body somewhere and process yourself.

How to grep for two words existing on the same line?

Why do you pass -c? That will just show the number of matches. Similarly, there is no reason to use -r. I suggest you read man grep.

To grep for 2 words existing on the same line, simply do:

grep "word1" FILE | grep "word2"

grep "word1" FILE will print all lines that have word1 in them from FILE, and then grep "word2" will print the lines that have word2 in them. Hence, if you combine these using a pipe, it will show lines containing both word1 and word2.

If you just want a count of how many lines had the 2 words on the same line, do:

grep "word1" FILE | grep -c "word2"

Also, to address your question why does it get stuck : in grep -c "word1", you did not specify a file. Therefore, grep expects input from stdin, which is why it seems to hang. You can press Ctrl+D to send an EOF (end-of-file) so that it quits.

Clearing UIWebview cache

After various attempt, only this works well for me (under ios 8):

NSURLCache *cache = [[NSURLCache alloc] initWithMemoryCapacity:1 diskCapacity:1 diskPath:nil];
[NSURLCache setSharedURLCache:cache];

How to get access to raw resources that I put in res folder?

InputStream in = getResources().openRawResource(resourceName);

This will work correctly. Before that you have to create the xml file / text file in raw resource. Then it will be accessible.

Edit
Some times com.andriod.R will be imported if there is any error in layout file or image names. So You have to import package correctly, then only the raw file will be accessible.

Deleting elements from std::set while iterating

You misunderstand what "undefined behavior" means. Undefined behavior does not mean "if you do this, your program will crash or produce unexpected results." It means "if you do this, your program could crash or produce unexpected results", or do anything else, depending on your compiler, your operating system, the phase of the moon, etc.

If something executes without crashing and behaves as you expect it to, that is not proof that it is not undefined behavior. All it proves is that its behavior happened to be as observed for that particular run after compiling with that particular compiler on that particular operating system.

Erasing an element from a set invalidates the iterator to the erased element. Using an invalidated iterator is undefined behavior. It just so happened that the observed behavior was what you intended in this particular instance; it does not mean that the code is correct.

conflicting types error when compiling c program using gcc

To answer a more generic case, this error is noticed when you pick a function name which is already used in some built in library. For e.g., select.

A simple method to know about it is while compiling the file, the compiler will indicate the previous declaration.

How do I check if the mouse is over an element in jQuery?

I combined ideas from this topic and came up with this, which is useful for showing/hiding a submenu:

$("#menu_item_a").mouseenter(function(){
   clearTimeout($(this).data('timeoutId'));
   $("#submenu_a").fadeIn("fast");
}).mouseleave(function(){
   var menu_item = $(this);

   var timeoutId = setTimeout(function(){
      if($('#submenu_a').is(':hover'))
      {
        clearTimeout(menu_item.data('timeoutId'));
      }
      else
      {
        $("#submenu_a").fadeOut("fast");
      }
   }, 650);

    menu_item.data('timeoutId', timeoutId); 
});

 $("#submenu_a").mouseleave(function(){
   $(this).fadeOut("fast");
 });

Seems to work for me. Hope this helps someone.

EDIT: Now realizing this approach is not working correctly in IE.

undefined reference to WinMain@16 (codeblocks)

Open the project you want to add it.

Right click on the name. Then select, add in the active project. Then the cpp file will get its link to cbp.

In Visual Basic how do you create a block comment

Not in VB.NET, you have to select all lines at then Edit, Advanced, Comment Selection menu, or a keyboard shortcut for that menu.

http://bytes.com/topic/visual-basic-net/answers/376760-how-block-comment

http://forums.asp.net/t/1011404.aspx/1

How to use data-binding with Fragment

Very helpful blog about Databinding : https://link.medium.com/HQY2VizKO1

class FragmentBinding<out T : ViewDataBinding>(
    @LayoutRes private val resId: Int
) : ReadOnlyProperty<Fragment, T> {

    private var binding: T? = null

    override operator fun getValue(
        thisRef: Fragment,
        property: KProperty<*>
    ): T = binding ?: createBinding(thisRef).also { binding = it }

    private fun createBinding(
        activity: Fragment
    ): T = DataBindingUtil.inflate(LayoutInflater.from(activity.context),resId,null,true)
}

Declare binding val like this in Fragment :

private val binding by FragmentBinding<FragmentLoginBinding>(R.layout.fragment_login)

Don't forget to write this in fragment

override fun onCreateView(
    inflater: LayoutInflater,
    container: ViewGroup?,
    savedInstanceState: Bundle?
): View? {
    return binding.root
}

Split string with multiple delimiters in Python

In response to Jonathan's answer above, this only seems to work for certain delimiters. For example:

>>> a='Beautiful, is; better*than\nugly'
>>> import re
>>> re.split('; |, |\*|\n',a)
['Beautiful', 'is', 'better', 'than', 'ugly']

>>> b='1999-05-03 10:37:00'
>>> re.split('- :', b)
['1999-05-03 10:37:00']

By putting the delimiters in square brackets it seems to work more effectively.

>>> re.split('[- :]', b)
['1999', '05', '03', '10', '37', '00']

Postgresql -bash: psql: command not found

If you are using the Postgres Mac app (by Heroku) and Bundler, you can add the pg_config directly inside the app, to your bundle.

bundle config build.pg --with-pg-config=/Applications/Postgres.app/Contents/Versions/9.4/bin/pg_config

...then run bundle again.

Note: check the version first using the following.

ls /Applications/Postgres.app/Contents/Versions/

Error: could not find function ... in R

This error can occur even if the name of the function is valid if some mandatory arguments are missing (i.e you did not provide enough arguments).
I got this in an Rcpp context, where I wrote a C++ function with optionnal arguments, and did not provided those arguments in R. It appeared that optionnal arguments from the C++ were seen as mandatory by R. As a result, R could not find a matching function for the correct name but an incorrect number of arguments.

Rcpp Function : SEXP RcppFunction(arg1, arg2=0) {}
R Calls :
RcppFunction(0) raises the error
RcppFunction(0, 0) does not

Is it possible to define more than one function per file in MATLAB, and access them from outside that file?

Along the same lines as SCFrench's answer, but with a more C# style spin..

I would (and often do) make a class containing multiple static methods. For example:

classdef Statistics

    methods(Static)
        function val = MyMean(data)
            val = mean(data);
        end

        function val = MyStd(data)
            val = std(data);
        end
    end

end

As the methods are static you don't need to instansiate the class. You call the functions as follows:

data = 1:10;

mean = Statistics.MyMean(data);
std = Statistics.MyStd(data);     

The remote certificate is invalid according to the validation procedure

You must check the certificate hash code.

ServicePointManager.ServerCertificateValidationCallback = (sender, certificate, chain,
    errors) =>
        {
            var hashString = certificate.GetCertHashString();
            if (hashString != null)
            {
                var certHashString = hashString.ToLower();
                return certHashString == "dec2b525ddeemma8ccfaa8df174455d6e38248c5";
            }
            return false;
        };

How do I do a not equal in Django queryset filtering?

results = Model.objects.filter(a = True).exclude(x = 5)
Generetes this sql:
select * from tablex where a != 0 and x !=5
The sql depends on how your True/False field is represented, and the database engine. The django code is all you need though.

How to identify object types in java

You can compare class tokens to each other, so you could use value.getClass() == Integer.class. However, the simpler and more canonical way is to use instanceof :

    if (value instanceof Integer) {
        System.out.println("This is an Integer");
    } else if(value instanceof String) {
        System.out.println("This is a String");
    } else if(value instanceof Float) {
        System.out.println("This is a Float");
    }

Notes:

  • the only difference between the two is that comparing class tokens detects exact matches only, while instanceof C matches for subclasses of C too. However, in this case all the classes listed are final, so they have no subclasses. Thus instanceof is probably fine here.
  • as JB Nizet stated, such checks are not OO design. You may be able to solve this problem in a more OO way, e.g.

    System.out.println("This is a(n) " + value.getClass().getSimpleName());
    

jQuery UI Sortable Position

Use update instead of stop

http://api.jqueryui.com/sortable/

update( event, ui )

Type: sortupdate

This event is triggered when the user stopped sorting and the DOM position has changed.

.

stop( event, ui )

Type: sortstop

This event is triggered when sorting has stopped. event Type: Event

Piece of code:

http://jsfiddle.net/7a1836ce/

<script type="text/javascript">

var sortable    = new Object();
sortable.s1     = new Array(1, 2, 3, 4, 5);
sortable.s2     = new Array(1, 2, 3, 4, 5);
sortable.s3     = new Array(1, 2, 3, 4, 5);
sortable.s4     = new Array(1, 2, 3, 4, 5);
sortable.s5     = new Array(1, 2, 3, 4, 5);

sortingExample();

function sortingExample()
{
    // Init vars

    var tDiv    = $('<div></div>');
    var tSel    = '';

    // ul
    for (var tName in sortable)
    {

        // Creating ul list
        tDiv.append(createUl(sortable[tName], tName));
        // Add selector id
        tSel += '#' + tName + ',';

    }

    $('body').append('<div id="divArrayInfo"></div>');
    $('body').append(tDiv);

    // ul sortable params

    $(tSel).sortable({connectWith:tSel,
       start: function(event, ui) 
       {
            ui.item.startPos = ui.item.index();
       },
        update: function(event, ui)
        {
            var a   = ui.item.startPos;
            var b   = ui.item.index();
            var id = this.id;

            // If element moved to another Ul then 'update' will be called twice
            // 1st from sender list
            // 2nd from receiver list
            // Skip call from sender. Just check is element removed or not

            if($('#' + id + ' li').length < sortable[id].length)
            {
                return;
            }

            if(ui.sender === null)
            {
                sortArray(a, b, this.id, this.id);
            }
            else
            {
                sortArray(a, b, $(ui.sender).attr('id'), this.id);
            }

            printArrayInfo();

        }
    }).disableSelection();;

// Add styles

    $('<style>')
    .attr('type', 'text/css')
    .html(' body {background:black; color:white; padding:50px;} .sortableClass { clear:both; display: block; overflow: hidden; list-style-type: none; } .sortableClass li { border: 1px solid grey; float:left; clear:none; padding:20px; }')
    .appendTo('head');


    printArrayInfo();

}

function printArrayInfo()
{

    var tStr = '';

    for ( tName in sortable)
    {

        tStr += tName + ': ';

        for(var i=0; i < sortable[tName].length; i++)
        {

            // console.log(sortable[tName][i]);
            tStr += sortable[tName][i] + ', ';

        }

        tStr += '<br>';

    }

    $('#divArrayInfo').html(tStr);

}


function createUl(tArray, tId)
{

    var tUl = $('<ul>', {id:tId, class:'sortableClass'})

    for(var i=0; i < tArray.length; i++)
    {

        // Create Li element
        var tLi = $('<li>' + tArray[i] + '</li>');
        tUl.append(tLi);

    }

    return tUl;
}

function sortArray(a, b, idA, idB)
{
    var c;

    c = sortable[idA].splice(a, 1);
    sortable[idB].splice(b, 0, c);      

}
</script>

regex match any single character (one character only)

Simple answer

If you want to match single character, put it inside those brackets [ ]

Examples

  • match + ...... [+] or +
  • match a ...... a
  • match & ...... &

...and so on. You can check your regular expresion online on this site: https://regex101.com/

(updated based on comment)

Pandas get the most frequent values of a column

You could use .apply and pd.value_counts to get a count the occurrence of all the names in the name column.

dataframe['name'].apply(pd.value_counts)

Triggering a checkbox value changed event in DataGridView

I found a simple solution.

Just change the cell focus after click on cell.

private void DGV_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
    if (e.ColumnIndex == "Here checkbox column id or name") {
        DGV.Item(e.ColumnIndex, e.RowIndex + 1).Selected = true;
        //Here your code

    }
}

Don't forget to check if the column of your (ckeckbox + 1) index exist.

python JSON only get keys in first level

A good way to check whether a python object is an instance of a type is to use isinstance() which is Python's 'built-in' function. For Python 3.6:

dct = {
       "1": "a", 
       "3": "b", 
       "8": {
            "12": "c", 
            "25": "d"
           }
      }

for key in dct.keys():
    if isinstance(dct[key], dict)== False:
       print(key, dct[key])
#shows:
# 1 a
# 3 b

Error:Conflict with dependency 'com.google.code.findbugs:jsr305'

i was trying to use airbnb deeplink dispatch and got this error. i had to also exlude the findbugs group from the annotationProcessor.

//airBnb
    compile ('com.airbnb:deeplinkdispatch:3.1.1'){
        exclude group:'com.google.code.findbugs'
    }
    annotationProcessor ('com.airbnb:deeplinkdispatch-processor:3.1.1'){
        exclude group:'com.google.code.findbugs'
    }

CSS to set A4 paper size

I looked into this a bit more and the actual problem seems to be with assigning initial to page width under the print media rule. It seems like in Chrome width: initial on the .page element results in scaling of the page content if no specific length value is defined for width on any of the parent elements (width: initial in this case resolves to width: auto ... but actually any value smaller than the size defined under the @page rule causes the same issue).

So not only the content is now too long for the page (by about 2cm), but also the page padding will be slightly more than the initial 2cm and so on (it seems to render the contents under width: auto to the width of ~196mm and then scale the whole content up to the width of 210mm ~ but strangely exactly the same scaling factor is applied to contents with any width smaller than 210mm).

To fix this problem you can simply in the print media rule assign the A4 paper width and hight to html, body or directly to .page and in this case avoid the initial keyword.

DEMO

@page {
  size: A4;
  margin: 0;
}
@media print {
  html, body {
    width: 210mm;
    height: 297mm;
  }
  /* ... the rest of the rules ... */
}

This seems to keep everything else the way it is in your original CSS and fix the problem in Chrome (tested in different versions of Chrome under Windows, OS X and Ubuntu).

How to check if current thread is not main thread

You can check

if(Looper.myLooper() == Looper.getMainLooper()) {
   // You are on mainThread 
}else{
// you are on non-ui thread
}

How to concatenate two strings to build a complete path

The POSIX standard mandates that multiple / are treated as a single / in a file name. Thus //dir///subdir////file is the same as /dir/subdir/file.

As such concatenating a two strings to build a complete path is a simple as:

full_path="$part1/$part2"

Check if date is in the past Javascript

_x000D_
_x000D_
$('#datepicker').datepicker().change(evt => {_x000D_
  var selectedDate = $('#datepicker').datepicker('getDate');_x000D_
  var now = new Date();_x000D_
  now.setHours(0,0,0,0);_x000D_
  if (selectedDate < now) {_x000D_
    console.log("Selected date is in the past");_x000D_
  } else {_x000D_
    console.log("Selected date is NOT in the past");_x000D_
  }_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js"></script>_x000D_
<input type="text" id="datepicker" name="event_date" class="datepicker">
_x000D_
_x000D_
_x000D_

CertificateException: No name matching ssl.someUrl.de found

I created a method fixUntrustCertificate(), so when I am dealing with a domain that is not in trusted CAs you can invoke the method before the request. This code will gonna work after java1.4. This method applies for all hosts:

public void fixUntrustCertificate() throws KeyManagementException, NoSuchAlgorithmException{


        TrustManager[] trustAllCerts = new TrustManager[]{
            new X509TrustManager() {
                public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                    return null;
                }

                public void checkClientTrusted(X509Certificate[] certs, String authType) {
                }

                public void checkServerTrusted(X509Certificate[] certs, String authType) {
                }

            }
        };

        SSLContext sc = SSLContext.getInstance("SSL");
        sc.init(null, trustAllCerts, new java.security.SecureRandom());
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());

        HostnameVerifier allHostsValid = new HostnameVerifier() {
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        };

        // set the  allTrusting verifier
        HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);
}

how to convert an RGB image to numpy array?

Using Keras:

from keras.preprocessing import image
  
img = image.load_img('path_to_image', target_size=(300, 300))
x = image.img_to_array(img)
x = np.expand_dims(x, axis=0)
images = np.vstack([x])

How to filter by IP address in Wireshark?

Try

ip.dst == 172.16.3.255

How do I get the unix timestamp in C as an int?

An important point is to consider if you perform tasks based on difference between 2 timestamps because you will get odd behavior if you generate it with gettimeofday(), and even clock_gettime(CLOCK_REALTIME,..) at the moment where you will set the time of your system.

To prevent such problem, use clock_gettime(CLOCK_MONOTONIC_RAW, &tms) instead.

How can I start an interactive console for Perl?

I use the command line as a console:

$ perl -e 'print "JAPH\n"'

Then I can use my bash history to get back old commands. This does not preserve state, however.

This form is most useful when you want to test "one little thing" (like when answering Perl questions). Often, I find these commands get scraped verbatim into a shell script or makefile.

How to insert data using wpdb

global $wpdb;
$insert = $wpdb->query("INSERT INTO `front-post`(`id`, `content`) VALUES ('$id', '$content')");

JavaFX FXML controller - constructor vs initialize method

In a few words: The constructor is called first, then any @FXML annotated fields are populated, then initialize() is called.

This means the constructor does not have access to @FXML fields referring to components defined in the .fxml file, while initialize() does have access to them.

Quoting from the Introduction to FXML:

[...] the controller can define an initialize() method, which will be called once on an implementing controller when the contents of its associated document have been completely loaded [...] This allows the implementing class to perform any necessary post-processing on the content.

How to compare two java objects

You need to Override equals and hashCode.
equals will compare the objects for equality according to the properties you need and hashCode is mandatory in order for your objects to be used correctly in Collections and Maps

Declare multiple module.exports in Node.js

There are multiple ways to do this, one way is mentioned below. Just assume you have .js file like this.

let add = function (a, b) {
   console.log(a + b);
};

let sub = function (a, b) {
   console.log(a - b);
};

You can export these functions using the following code snippet,

 module.exports.add = add;
 module.exports.sub = sub;

And you can use the exported functions using this code snippet,

var add = require('./counter').add;
var sub = require('./counter').sub;

add(1,2);
sub(1,2);

I know this is a late reply, but hope this helps!

Add a default value to a column through a migration

**Rails 4.X +**

As of Rails 4 you can't generate a migration to add a column to a table with a default value, The following steps add a new column to an existing table with default value true or false.

1. Run the migration from command line to add the new column

$ rails generate migration add_columnname_to_tablename columnname:boolean

The above command will add a new column in your table.

2. Set the new column value to TRUE/FALSE by editing the new migration file created.

class AddColumnnameToTablename < ActiveRecord::Migration
  def change
    add_column :table_name, :column_name, :boolean, default: false
  end
end

**3. To make the changes into your application database table, run the following command in terminal**

$ rake db:migrate

Code for Greatest Common Divisor in Python

in python with recursion:

def gcd(a, b):
    if a%b == 0:
        return b
    return gcd(b, a%b)

How can I drop all the tables in a PostgreSQL database?

If you want to nuke all tables anyway, you can dispense with niceties such as CASCADE by putting all tables into a single statement. This also makes execution quicker.

SELECT 'TRUNCATE TABLE ' || string_agg('"' || tablename || '"', ', ') || ';' 
FROM pg_tables WHERE schemaname = 'public';

Executing it directly:

DO $$
DECLARE tablenames text;
BEGIN    
    tablenames := string_agg('"' || tablename || '"', ', ') 
        FROM pg_tables WHERE schemaname = 'public';
    EXECUTE 'TRUNCATE TABLE ' || tablenames;
END; $$

Replace TRUNCATE with DROP as applicable.

How can one see content of stack with GDB?

Use:

  • bt - backtrace: show stack functions and args
  • info frame - show stack start/end/args/locals pointers
  • x/100x $sp - show stack memory
(gdb) bt
#0  zzz () at zzz.c:96
#1  0xf7d39cba in yyy (arg=arg@entry=0x0) at yyy.c:542
#2  0xf7d3a4f6 in yyyinit () at yyy.c:590
#3  0x0804ac0c in gnninit () at gnn.c:374
#4  main (argc=1, argv=0xffffd5e4) at gnn.c:389

(gdb) info frame
Stack level 0, frame at 0xffeac770:
 eip = 0x8049047 in main (goo.c:291); saved eip 0xf7f1fea1
 source language c.
 Arglist at 0xffeac768, args: argc=1, argv=0xffffd5e4
 Locals at 0xffeac768, Previous frame's sp is 0xffeac770
 Saved registers:
  ebx at 0xffeac75c, ebp at 0xffeac768, esi at 0xffeac760, edi at 0xffeac764, eip at 0xffeac76c

(gdb) x/10x $sp
0xffeac63c: 0xf7d39cba  0xf7d3c0d8  0xf7d3c21b  0x00000001
0xffeac64c: 0xf78d133f  0xffeac6f4  0xf7a14450  0xffeac678
0xffeac65c: 0x00000000  0xf7d3790e

How to print to console in pytest?

By default, py.test captures the result of standard out so that it can control how it prints it out. If it didn't do this, it would spew out a lot of text without the context of what test printed that text.

However, if a test fails, it will include a section in the resulting report that shows what was printed to standard out in that particular test.

For example,

def test_good():
    for i in range(1000):
        print(i)

def test_bad():
    print('this should fail!')
    assert False

Results in the following output:

>>> py.test tmp.py
============================= test session starts ==============================
platform darwin -- Python 2.7.6 -- py-1.4.20 -- pytest-2.5.2
plugins: cache, cov, pep8, xdist
collected 2 items

tmp.py .F

=================================== FAILURES ===================================
___________________________________ test_bad ___________________________________

    def test_bad():
        print('this should fail!')
>       assert False
E       assert False

tmp.py:7: AssertionError
------------------------------- Captured stdout --------------------------------
this should fail!
====================== 1 failed, 1 passed in 0.04 seconds ======================

Note the Captured stdout section.

If you would like to see print statements as they are executed, you can pass the -s flag to py.test. However, note that this can sometimes be difficult to parse.

>>> py.test tmp.py -s
============================= test session starts ==============================
platform darwin -- Python 2.7.6 -- py-1.4.20 -- pytest-2.5.2
plugins: cache, cov, pep8, xdist
collected 2 items

tmp.py 0
1
2
3
... and so on ...
997
998
999
.this should fail!
F

=================================== FAILURES ===================================
___________________________________ test_bad ___________________________________

    def test_bad():
        print('this should fail!')
>       assert False
E       assert False

tmp.py:7: AssertionError
====================== 1 failed, 1 passed in 0.02 seconds ======================

How to allow user to pick the image with Swift?

I know this is question is a year old, but here's some pretty simple code (mostly from this tutorial) that's working well for me:

import UIKit

class ViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {

@IBOutlet weak var imageView: UIImageView!

var imagePicker = UIImagePickerController()

override func viewDidLoad() {
    super.viewDidLoad()

    self.imagePicker.delegate = self
}

@IBAction func loadImageButtonTapped(sender: AnyObject) {
    print("hey!")
    self.imagePicker.allowsEditing = false
    self.imagePicker.sourceType = .SavedPhotosAlbum

    self.presentViewController(imagePicker, animated: true, completion: nil)
}

func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [NSObject : AnyObject]) {
    if let pickedImage = info[UIImagePickerControllerOriginalImage] as? UIImage {
        self.imageView.contentMode = .ScaleAspectFit
        self.imageView.image = pickedImage
    }

    dismissViewControllerAnimated(true, completion: nil)

}

func imagePickerControllerDidCancel(picker: UIImagePickerController) {
    self.imagePicker = UIImagePickerController()
    dismissViewControllerAnimated(true, completion: nil)
}

How to check if field is null or empty in MySQL?

Alternatively you can also use CASE for the same:

SELECT CASE WHEN field1 IS NULL OR field1 = '' 
       THEN 'empty' 
       ELSE field1 END AS field1
FROM tablename.

DLL load failed error when importing cv2

Please Remember if you want to install python package/libraries for windows,

you should always consider Python unofficial Binaries

Step 1:

Search for your package, download dependent version 2.7 or 3.6 you can find it under Downloads/your_package_version.whl its called python wheel

Step 2:

Now install using pip,

pip install ~/Downloads/your_packae_ver.whl

this will install without any error.

ng-repeat: access key and value for each object in array of objects

A repeater inside a repeater

<div ng-repeat="step in steps">
    <div ng-repeat="(key, value) in step">
        {{key}} : {{value}}
    </div>
</div>

Turning error reporting off php

Tried this yet?

error_reporting(0);
@ini_set('display_errors', 0);

How comment a JSP expression?

your <%= //map.size() %> doesnt simply work because it should have been

<% //= map.size() %>

Object array initialization without default constructor

No, there isn't. New-expression only allows default initialization or no initialization at all.

The workaround would be to allocate raw memory buffer using operator new[] and then construct objects in that buffer using placement-new with non-default constructor.

Dependent DLL is not getting copied to the build output folder in Visual Studio

It looks slick when you make it an assembly attribute

[AttributeUsage(AttributeTargets.Assembly)]
public class ForceAssemblyReference: Attribute
{        
    public ForceAssemblyReference(Type forcedType)
    {
        //not sure if these two lines are required since 
        //the type is passed to constructor as parameter, 
        //thus effectively being used
        Action<Type> noop = _ => { };
        noop(forcedType);
    }
}

The usage will be:

[assembly: ForceAssemblyReference(typeof(AbcDll.AnyClass))]

PHP replacing special characters like à->a, è->e

As of PHP >= 5.4.0

$translatedString = transliterator_transliterate('Any-Latin; Latin-ASCII; [\u0080-\u7fff] remove', $string);

"E: Unable to locate package python-pip" on Ubuntu 18.04

Try following command sequence on Ubuntu terminal:

sudo apt-get install software-properties-common
sudo apt-add-repository universe
sudo apt-get update
sudo apt-get install python-pip

Convert month name to month number in SQL Server

select  Convert(datetime, '01 ' +  Replace('OCT-12', '-', ' '),6)

Apache and IIS side by side (both listening to port 80) on windows2003

You need at least mod_proxy and mod_proxy_http which both are part of the distribution (yet not everytime built automatically). Then you can look here: http://httpd.apache.org/docs/2.2/mod/mod_proxy.html

Simplest config in a virtualhost context is:

ProxyPass         /winapp http://127.0.0.1:8080/somedir/

ProxyPassReverse  /winapp http://127.0.0.1:8080/somedir/

(Depending on your webapp, the actual config might become more sophisticated. ) That transparently redirects every request on the path winapp/ to the windows server and transfers the resulting output back to the client.

Attention: Take care of the links in the delivered pages: they aren't rewritten, so you can save yourself lotsa hassle if you generally use relative links in your app, like

<a href=../pics/mypic.jpg">

instead of the usual integration nightmare of every link being absolute:

<a href="http://myinternalhostname/somedir/crappydesign.jpg">

THE LATTER IS BAD ALMOST EVERY SINGLE TIME!

For rewriting links in pages there's mod_proxy_html (not to confuse with mod_proxy_http!) but that's another story and a cruel one as well.

Difference between Fact table and Dimension table?

Dimension table Dimension table is a table which contain attributes of measurements stored in fact tables. This table consists of hierarchies, categories and logic that can be used to traverse in nodes.

Fact table contains the measurement of business processes, and it contains foreign keys for the dimension tables.

Example – If the business process is manufacturing of bricks

Average number of bricks produced by one person/machine – measure of the business process

Webclient / HttpWebRequest with Basic Authentication returns 404 not found for valid URL

This part of code worked fine for me:

        WebRequest request = WebRequest.Create(url);
        request.Method = WebRequestMethods.Http.Get;
        NetworkCredential networkCredential = new NetworkCredential(logon, password); // logon in format "domain\username"
        CredentialCache myCredentialCache = new CredentialCache {{new Uri(url), "Basic", networkCredential}};
        request.PreAuthenticate = true;
        request.Credentials = myCredentialCache;
        using (WebResponse response = request.GetResponse())
        {
            Console.WriteLine(((HttpWebResponse)response).StatusDescription);

            using (Stream dataStream = response.GetResponseStream())
            {
                using (StreamReader reader = new StreamReader(dataStream))
                {
                    string responseFromServer = reader.ReadToEnd();
                    Console.WriteLine(responseFromServer);
                }
            }
        }

How to populate options of h:selectOneMenu from database?

Based on your question history, you're using JSF 2.x. So, here's a JSF 2.x targeted answer. In JSF 1.x you would be forced to wrap item values/labels in ugly SelectItem instances. This is fortunately not needed anymore in JSF 2.x.


Basic example

To answer your question directly, just use <f:selectItems> whose value points to a List<T> property which you preserve from the DB during bean's (post)construction. Here's a basic kickoff example assuming that T actually represents a String.

<h:selectOneMenu value="#{bean.name}">
    <f:selectItems value="#{bean.names}" />
</h:selectOneMenu>

with

@ManagedBean
@RequestScoped
public class Bean {

    private String name;
    private List<String> names; 

    @EJB
    private NameService nameService;

    @PostConstruct
    public void init() {
        names = nameService.list();
    }

    // ... (getters, setters, etc)
}

Simple as that. Actually, the T's toString() will be used to represent both the dropdown item label and value. So, when you're instead of List<String> using a list of complex objects like List<SomeEntity> and you haven't overridden the class' toString() method, then you would see com.example.SomeEntity@hashcode as item values. See next section how to solve it properly.

Also note that the bean for <f:selectItems> value does not necessarily need to be the same bean as the bean for <h:selectOneMenu> value. This is useful whenever the values are actually applicationwide constants which you just have to load only once during application's startup. You could then just make it a property of an application scoped bean.

<h:selectOneMenu value="#{bean.name}">
    <f:selectItems value="#{data.names}" />
</h:selectOneMenu>

Complex objects as available items

Whenever T concerns a complex object (a javabean), such as User which has a String property of name, then you could use the var attribute to get hold of the iteration variable which you in turn can use in itemValue and/or itemLabel attribtues (if you omit the itemLabel, then the label becomes the same as the value).

Example #1:

<h:selectOneMenu value="#{bean.userName}">
    <f:selectItems value="#{bean.users}" var="user" itemValue="#{user.name}" />
</h:selectOneMenu>

with

private String userName;
private List<User> users;

@EJB
private UserService userService;

@PostConstruct
public void init() {
    users = userService.list();
}

// ... (getters, setters, etc)

Or when it has a Long property id which you would rather like to set as item value:

Example #2:

<h:selectOneMenu value="#{bean.userId}">
    <f:selectItems value="#{bean.users}" var="user" itemValue="#{user.id}" itemLabel="#{user.name}" />
</h:selectOneMenu>

with

private Long userId;
private List<User> users;

// ... (the same as in previous bean example)

Complex object as selected item

Whenever you would like to set it to a T property in the bean as well and T represents an User, then you would need to bake a custom Converter which converts between User and an unique string representation (which can be the id property). Do note that the itemValue must represent the complex object itself, exactly the type which needs to be set as selection component's value.

<h:selectOneMenu value="#{bean.user}" converter="#{userConverter}">
    <f:selectItems value="#{bean.users}" var="user" itemValue="#{user}" itemLabel="#{user.name}" />
</h:selectOneMenu>

with

private User user;
private List<User> users;

// ... (the same as in previous bean example)

and

@ManagedBean
@RequestScoped
public class UserConverter implements Converter {

    @EJB
    private UserService userService;

    @Override
    public Object getAsObject(FacesContext context, UIComponent component, String submittedValue) {
        if (submittedValue == null || submittedValue.isEmpty()) {
            return null;
        }

        try {
            return userService.find(Long.valueOf(submittedValue));
        } catch (NumberFormatException e) {
            throw new ConverterException(new FacesMessage(String.format("%s is not a valid User ID", submittedValue)), e);
        }
    }

    @Override
    public String getAsString(FacesContext context, UIComponent component, Object modelValue) {
        if (modelValue == null) {
            return "";
        }

        if (modelValue instanceof User) {
            return String.valueOf(((User) modelValue).getId());
        } else {
            throw new ConverterException(new FacesMessage(String.format("%s is not a valid User", modelValue)), e);
        }
    }

}

(please note that the Converter is a bit hacky in order to be able to inject an @EJB in a JSF converter; normally one would have annotated it as @FacesConverter(forClass=User.class), but that unfortunately doesn't allow @EJB injections)

Don't forget to make sure that the complex object class has equals() and hashCode() properly implemented, otherwise JSF will during render fail to show preselected item(s), and you'll on submit face Validation Error: Value is not valid.

public class User {

    private Long id;

    @Override
    public boolean equals(Object other) {
        return (other != null && getClass() == other.getClass() && id != null)
            ? id.equals(((User) other).id)
            : (other == this);
    }

    @Override
    public int hashCode() {
        return (id != null) 
            ? (getClass().hashCode() + id.hashCode())
            : super.hashCode();
    }

}

Complex objects with a generic converter

Head to this answer: Implement converters for entities with Java Generics.


Complex objects without a custom converter

The JSF utility library OmniFaces offers a special converter out the box which allows you to use complex objects in <h:selectOneMenu> without the need to create a custom converter. The SelectItemsConverter will simply do the conversion based on readily available items in <f:selectItem(s)>.

<h:selectOneMenu value="#{bean.user}" converter="omnifaces.SelectItemsConverter">
    <f:selectItems value="#{bean.users}" var="user" itemValue="#{user}" itemLabel="#{user.name}" />
</h:selectOneMenu>

See also:

Double array initialization in Java

You can initialize an array by writing actual values it holds in curly braces on the right hand side like:

String[] strArr = { "one", "two", "three"};
int[] numArr = { 1, 2, 3};

In the same manner two-dimensional array or array-of-arrays holds an array as a value, so:

String strArrayOfArrays = { {"a", "b", "c"}, {"one", "two", "three"} };

Your example shows exactly that

double m[][] = {
    {0*0,1*0,2*0,3*0},
    {0*1,1*1,2*1,3*1},
    {0*2,1*2,2*2,3*2},
    {0*3,1*3,2*3,3*3}
};

But also the multiplication of number will also be performed and its the same as:

double m[][] = { {0, 0, 0, 0}, {0, 1, 2, 3}, {0, 2, 4, 6}, {0, 3, 6, 9} };

what's the easiest way to put space between 2 side-by-side buttons in asp.net

Try putting the following class on your second button

.div-button
{
    margin-left: 20px;
}

Edit:

If you want your first button to be spaced from the div as well as from the second button, then apply this class to your first button also.

Delete multiple rows by selecting checkboxes using PHP

Something that sometimes crops up you may/maynot be aware of

Won't always be picked up by by $_POST['delete'] when using IE. Firefox and chrome should work fine though. I use a seperate isntead which solves the problem for IE

As for your not deleting in your code above you appear to be echoing out 2x sets of check boxes both pulling the same data? Is this just a copy + paste mistake or is this actually how your code is?

If its how your code is that'll be the problem as the user could be ticking one checkbox array item but the other one will be unchecked so the php code for delete is getting confused. Either rename the 2nd check box or delete that block of html surely you don't need to display the same list twice ?

Using new line(\n) in string and rendering the same in HTML

Use <br /> for new line in html:

display_txt = display_txt.replace(/\n/g, "<br />");

What is the difference between MacVim and regular Vim?

unfortunately, with "mvim -v", ALT plus arrow windows still does not work. I have not found any way to enable it :-(

How do I create an Android Spinner as a popup?

Here is an Spinner subclass which overrides performClick() to show a dialog instead of a dropdown. No XML required. Give it a try, let me know if it works for you.

public class DialogSpinner extends Spinner {
    public DialogSpinner(Context context) {
        super(context);
    }

    @Override 
    public boolean performClick() {
        new AlertDialog.Builder(getContext()).setAdapter((ListAdapter) getAdapter(), 
            new DialogInterface.OnClickListener() {
                @Override public void onClick(DialogInterface dialog, int which) {
                    setSelection(which);
                    dialog.dismiss();
                }
            }).create().show();
        return true;
    }
}

For more information read this article: How To Make Android Spinner Options Popup In A Dialog

Get LatLng from Zip Code - Google Maps API

Here is the most reliable way to get the lat/long from zip code (i.e. postal code):

https://maps.googleapis.com/maps/api/geocode/json?key=YOUR_API_KEY&components=postal_code:97403

How to remove square brackets from list in Python?

Yes, there are several ways to do it. For instance, you can convert the list to a string and then remove the first and last characters:

l = ['a', 2, 'c']
print str(l)[1:-1]
'a', 2, 'c'

If your list contains only strings and you want remove the quotes too then you can use the join method as has already been said.

How do I upgrade PHP in Mac OS X?

Saving on keystrokes, this worked on MacOS Sierra:

$ brew install homebrew/php/php71

$ /usr/local/opt/php71/bin/php -v
PHP 7.1.4 (cli) (built: Apr 14 2017 15:02:16) ( NTS )
Copyright (c) 1997-2017 The PHP Group
Zend Engine v3.1.0, Copyright (c) 1998-2017 Zend Technologies

Centering a button vertically in table cell, using Twitter Bootstrap

A little update for Bootstrap 3.

Bootstrap now has the following style for table cells:

.table tbody>tr>td
{
    vertical-align: top;
}

The way to go is to add a your own class, with the same selector:

.table tbody>tr>td.vert-align
{
    vertical-align: middle;
}

And then add it to your tds

<td class="vert-align"></td>

Does PHP have threading?

I know this is a way old question, but you could look at http://phpthreadlib.sourceforge.net/

Bi-directional communication, support for Win32, and no extensions required.

How to prevent scrollbar from repositioning web page?

html {
  overflow-x: hidden;
  margin-right: calc(-1 * (100vw - 100%));
}

Example. Click "change min-height" button.

With calc(100vw - 100%) we can calculate the width of the scrollbar (and if it is not displayed, it will be 0). Idea: using negative margin-right, we can increase the width of <html> to this width. You will see a horizontal scroll bar — it should be hidden using overflow-x: hidden.

When is a language considered a scripting language?

I would say scripting language is the one heavily manipulating entities it doesn't itself define. For instance, JavaScript manipulates DOM objects provided by the browser, PHP operates enormous library of C-based functions, and so on. Of course not a precise definition, more a way to think if it.

JQuery Ajax Post results in 500 Internal Server Error

Your code contains dataType: json.

In this case jQuery evaluates the response as JSON and returns a JavaScript object. The JSON data is parsed in a strict manner. Any malformed JSON is rejected and a parse error is thrown. An empty response is also rejected.

The server should return a response of null or {} instead.

How to change the height of a <br>?

<span style="line-height:40px;"><br></span> 

You'd have to do this inline and on each
element but it should work on most browsers Fiddle with the line height to get the desired effect. If you make it inline on each element, it should work across most browsers and e-mail(but this is too complex to discuss here).

How to set the custom border color of UIView programmatically?

swift 3

func borderColor(){

    self.viewMenuItems.layer.cornerRadius = 13
    self.viewMenuItems.layer.borderWidth = 1
    self.viewMenuItems.layer.borderColor = UIColor.white.cgColor
}

Business logic in MVC

Business rules go in the model.

Say you were displaying emails for a mailing list. The user clicks the "delete" button next to one of the emails, the controller notifies the model to delete entry N, then notifies the view the model has changed.

Perhaps the admin's email should never be removed from the list. That's a business rule, that knowledge belongs in the model. The view may ultimately represent this rule somehow -- perhaps the model exposes an "IsDeletable" property which is a function of the business rule, so that the delete button in the view is disabled for certain entries - but the rule itself isn't contained in the view.

The model is ultimately gatekeeper for your data. You should be able to test your business logic without touching the UI at all.

J2ME/Android/BlackBerry - driving directions, route between two locations

J2ME Map Route Provider

maps.google.com has a navigation service which can provide you route information in KML format.

To get kml file we need to form url with start and destination locations:

public static String getUrl(double fromLat, double fromLon,
                            double toLat, double toLon) {// connect to map web service
    StringBuffer urlString = new StringBuffer();
    urlString.append("http://maps.google.com/maps?f=d&hl=en");
    urlString.append("&saddr=");// from
    urlString.append(Double.toString(fromLat));
    urlString.append(",");
    urlString.append(Double.toString(fromLon));
    urlString.append("&daddr=");// to
    urlString.append(Double.toString(toLat));
    urlString.append(",");
    urlString.append(Double.toString(toLon));
    urlString.append("&ie=UTF8&0&om=0&output=kml");
    return urlString.toString();
}

Next you will need to parse xml (implemented with SAXParser) and fill data structures:

public class Point {
    String mName;
    String mDescription;
    String mIconUrl;
    double mLatitude;
    double mLongitude;
}

public class Road {
    public String mName;
    public String mDescription;
    public int mColor;
    public int mWidth;
    public double[][] mRoute = new double[][] {};
    public Point[] mPoints = new Point[] {};
}

Network connection is implemented in different ways on Android and Blackberry, so you will have to first form url:

 public static String getUrl(double fromLat, double fromLon,
     double toLat, double toLon)

then create connection with this url and get InputStream.
Then pass this InputStream and get parsed data structure:

 public static Road getRoute(InputStream is) 

Full source code RoadProvider.java

BlackBerry

class MapPathScreen extends MainScreen {
    MapControl map;
    Road mRoad = new Road();
    public MapPathScreen() {
        double fromLat = 49.85, fromLon = 24.016667;
        double toLat = 50.45, toLon = 30.523333;
        String url = RoadProvider.getUrl(fromLat, fromLon, toLat, toLon);
        InputStream is = getConnection(url);
        mRoad = RoadProvider.getRoute(is);
        map = new MapControl();
        add(new LabelField(mRoad.mName));
        add(new LabelField(mRoad.mDescription));
        add(map);
    }
    protected void onUiEngineAttached(boolean attached) {
        super.onUiEngineAttached(attached);
        if (attached) {
            map.drawPath(mRoad);
        }
    }
    private InputStream getConnection(String url) {
        HttpConnection urlConnection = null;
        InputStream is = null;
        try {
            urlConnection = (HttpConnection) Connector.open(url);
            urlConnection.setRequestMethod("GET");
            is = urlConnection.openInputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return is;
    }
}

See full code on J2MEMapRouteBlackBerryEx on Google Code

Android

Android G1 screenshot

public class MapRouteActivity extends MapActivity {
    LinearLayout linearLayout;
    MapView mapView;
    private Road mRoad;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        mapView = (MapView) findViewById(R.id.mapview);
        mapView.setBuiltInZoomControls(true);
        new Thread() {
            @Override
            public void run() {
                double fromLat = 49.85, fromLon = 24.016667;
                double toLat = 50.45, toLon = 30.523333;
                String url = RoadProvider
                        .getUrl(fromLat, fromLon, toLat, toLon);
                InputStream is = getConnection(url);
                mRoad = RoadProvider.getRoute(is);
                mHandler.sendEmptyMessage(0);
            }
        }.start();
    }

    Handler mHandler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            TextView textView = (TextView) findViewById(R.id.description);
            textView.setText(mRoad.mName + " " + mRoad.mDescription);
            MapOverlay mapOverlay = new MapOverlay(mRoad, mapView);
            List<Overlay> listOfOverlays = mapView.getOverlays();
            listOfOverlays.clear();
            listOfOverlays.add(mapOverlay);
            mapView.invalidate();
        };
    };

    private InputStream getConnection(String url) {
        InputStream is = null;
        try {
            URLConnection conn = new URL(url).openConnection();
            is = conn.getInputStream();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return is;
    }
    @Override
    protected boolean isRouteDisplayed() {
        return false;
    }
}

See full code on J2MEMapRouteAndroidEx on Google Code

CSS background-size: cover replacement for Mobile Safari

html body {
  background: url(/assets/images/header-bg.jpg) no-repeat top center fixed;
  width: 100%;
  height: 100%;
  min-width: 100%;
  min-height: 100%;

  -webkit-background-size: auto auto;
  -moz-background-size: auto auto;
  -o-background-size: auto auto;
  background-size: auto auto;
}

Cast object to interface in TypeScript

There's no casting in javascript, so you cannot throw if "casting fails".
Typescript supports casting but that's only for compilation time, and you can do it like this:

const toDo = <IToDoDto> req.body;
// or
const toDo = req.body as IToDoDto;

You can check at runtime if the value is valid and if not throw an error, i.e.:

function isToDoDto(obj: any): obj is IToDoDto {
    return typeof obj.description === "string" && typeof obj.status === "boolean";
}

@Post()
addToDo(@Response() res, @Request() req) {
    if (!isToDoDto(req.body)) {
        throw new Error("invalid request");
    }

    const toDo = req.body as IToDoDto;
    this.toDoService.addToDo(toDo);
    return res.status(HttpStatus.CREATED).end();
}

Edit

As @huyz pointed out, there's no need for the type assertion because isToDoDto is a type guard, so this should be enough:

if (!isToDoDto(req.body)) {
    throw new Error("invalid request");
}

this.toDoService.addToDo(req.body);

Get the correct week number of a given date

The question is: How do you define if a week is in 2012 or in 2013? Your supposition, I guess, is that since 6 days of the week are in 2013, this week should be marked as the first week of 2013.

Not sure if this is the right way to go. That week started on 2012 (On monday 31th Dec), so it should be marked as the last week of 2012, therefore it should be the 53rd of 2012. The first week of 2013 should start on monday the 7th.

Now, you can handle the particular case of edge weeks (first and last week of the year) using the day of week information. It all depends on your logic.

Make xargs execute the command once for each line of input

If you want to run the command for every line (i.e. result) coming from find, then what do you need the xargs for?

Try:

find path -type f -exec your-command {} \;

where the literal {} gets substituted by the filename and the literal \; is needed for find to know that the custom command ends there.

EDIT:

(after the edit of your question clarifying that you know about -exec)

From man xargs:

-L max-lines
Use at most max-lines nonblank input lines per command line. Trailing blanks cause an input line to be logically continued on the next input line. Implies -x.

Note that filenames ending in blanks would cause you trouble if you use xargs:

$ mkdir /tmp/bax; cd /tmp/bax
$ touch a\  b c\  c
$ find . -type f -print | xargs -L1 wc -l
0 ./c
0 ./c
0 total
0 ./b
wc: ./a: No such file or directory

So if you don't care about the -exec option, you better use -print0 and -0:

$ find . -type f -print0 | xargs -0L1 wc -l
0 ./c
0 ./c
0 ./b
0 ./a

How to close the command line window after running a batch file?

Used this to start Xming, placed the bat file in the Start->Startup directory and now I have xming running on start up.

start "" "C:\Program Files (x86)\Xming\Xming.exe" -screen 0 -clipboard -multiwindow

How can I send an email by Java application using GMail, Yahoo, or Hotmail?

The posted code solutions may cause problems when you need to set up multiple SMTP sessions anywhere within the same JVM.

The JavaMail FAQ recommends using

Session.getInstance(properties);

instead of

Session.getDefaultInstance(properties);

because the getDefault will only use the properties given the first time it is invoked. All later uses of the default instance will ignore property changes.

See http://www.oracle.com/technetwork/java/faq-135477.html#getdefaultinstance

AngularJS disable partial caching on dev machine

As others have said, defeating caching completely for dev purposes can be done easily without changing code: use a browser setting or a plugin. Outside of dev, to defeat Angular template caching of route-based templates, remove the template URL from the cache during $routeChangeStart (or $stateChangeStart, for UI Router) as Shayan showed. However, that does NOT affect the caching of templates loaded by ng-include, because those templates are not loaded through the router.

I wanted to be able to hotfix any template, including those loaded by ng-include, in production and have users receive the hotfix in their browser quickly, without having to reload the entire page. I'm also not concerned about defeating HTTP caching for templates. The solution is to intercept every HTTP request that the app makes, ignore those that are not for my app's .html templates, then add a param to the template's URL that changes every minute. Note that the path-checking is specific to the path of your app's templates. To get a different interval, change the math for the param, or remove the % completely to get no caching.

// this defeats Angular's $templateCache on a 1-minute interval
// as a side-effect it also defeats HTTP (browser) caching
angular.module('myApp').config(function($httpProvider, ...) {
    $httpProvider.interceptors.push(function() {
        return {
            'request': function(config) {
                config.url = getTimeVersionedUrl(config.url);
                return config;
            }
        };
    });

    function getTimeVersionedUrl(url) {
        // only do for html templates of this app
        // NOTE: the path to test for is app dependent!
        if (!url || url.indexOf('a/app/') < 0 || url.indexOf('.html') < 0) return url;
        // create a URL param that changes every minute
        // and add it intelligently to the template's previous url
        var param = 'v=' + ~~(Date.now() / 60000) % 10000; // 4 unique digits every minute
        if (url.indexOf('?') > 0) {
            if (url.indexOf('v=') > 0) return url.replace(/v=[0-9](4)/, param);
            return url + '&' + param;
        }
        return url + '?' + param;
    }

String.format() to format double in java

There are many way you can do this. Those are given bellow:

Suppose your original number is given bellow: double number = 2354548.235;

Using NumberFormat and Rounding mode

NumberFormat nf = DecimalFormat.getInstance(Locale.ENGLISH);
    DecimalFormat decimalFormatter = (DecimalFormat) nf;
    decimalFormatter.applyPattern("#,###,###.##");
    decimalFormatter.setRoundingMode(RoundingMode.CEILING);

    String fString = decimalFormatter.format(number);
    System.out.println(fString);

Using String formatter

System.out.println(String.format("%1$,.2f", number));

In all cases the output will be: 2354548.24

Note:

During rounding you can add RoundingMode in your formatter. Here are some Rounding mode given bellow:

    decimalFormat.setRoundingMode(RoundingMode.CEILING);
    decimalFormat.setRoundingMode(RoundingMode.FLOOR);
    decimalFormat.setRoundingMode(RoundingMode.HALF_DOWN);
    decimalFormat.setRoundingMode(RoundingMode.HALF_UP);
    decimalFormat.setRoundingMode(RoundingMode.UP);

Here are the imports:

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.Locale;

How to Detect Browser Window /Tab Close Event?

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<script type="text/javascript">
var validNavigation = false;

function wireUpEvents() {
var dont_confirm_leave = 0; //set dont_confirm_leave to 1 when you want the    user to be able to leave withou confirmation
 var leave_message = 'ServerThemes.Net Recommend BEST WEB HOSTING at new tab  window. Good things will come to you'
 function goodbye(e) {
if (!validNavigation) {
window.open("http://serverthemes.net/best-web-hosting-services","_blank");
return leave_message;

}
}
window.onbeforeunload=goodbye;

// Attach the event keypress to exclude the F5 refresh
$(document).bind('keypress', function(e) {
if (e.keyCode == 116){
  validNavigation = true;
 }
 });

// Attach the event click for all links in the page
$("a").bind("click", function() {
validNavigation = true;
});
  // Attach the event submit for all forms in the page
 $("form").bind("submit", function() {
 validNavigation = true;
});

 // Attach the event click for all inputs in the page
  $("input[type=submit]").bind("click", function() {
 validNavigation = true;
 });

 }

  // Wire up the events as soon as the DOM tree is ready
   $(document).ready(function() {
   wireUpEvents();
   });
   </script>

I did answer at Can you use JavaScript to detect whether a user has closed a browser tab? closed a browser? or has left a browser?

How to avoid the "Windows Defender SmartScreen prevented an unrecognized app from starting warning"

If you have a standard code signing certificate, some time will be needed for your application to build trust. Microsoft affirms that an Extended Validation (EV) Code Signing Certificate allows us to skip this period of trust-building. According to Microsoft, extended validation certificates allow the developer to immediately establish a reputation with SmartScreen. Otherwise, the users will see a warning like "Windows Defender SmartScreen prevented an unrecognized app from starting. Running this app might put your PC at risk.", with the two buttons: "Run anyway" and "Don't run".

Another Microsoft resource states the following (quote): "Although not required, programs signed by an EV code signing certificate can immediately establish a reputation with SmartScreen reputation services even if no prior reputation exists for that file or publisher. EV code signing certificates also have a unique identifier which makes it easier to maintain reputation across certificate renewals."

My experience is as follows. Since 2005, we have been using regular (non-EV) code signing certificates to sign .MSI, .EXE and .DLL files with time stamps, and there has never been a problem with SmartScreen until 2018, when there was just one case when it took 3 days for a beta version of our application to build trust since we have released it to beta testers, and it was in the middle of certificate validity period. I don't know what SmartScreen might not like in that specific version of our application, but there have been no SmartScreen complaints since then. Therefore, if your certificate is a non-EV, it is a signed application (such as an .MSI file) that will build trust over time, not a certificate. For example, a certificate can be issued a few months ago and used to sign many files, but for each signed file you publish, it may take a few days for SmartScreen to stop complaining about the file after publishing, as was in our case in 2018.

As a conclusion, to avoid the warning completely, i.e. prevent it from happening even suddenly, you need an Extended Validation (EV) code signing certificate.

Python IndentationError unindent does not match any outer indentation level

You have mixed indentation formatting (spaces and tabs)

On Notepad++

Change Tab Settings to 4 spaces

Go to Settings -> Preferences -> Tab Settings -> Replace by spaces

Fix the current file mixed indentations

Select everything CTRL+A

Click TAB once, to add an indentation everywhere

Run SHIFT + TAB to remove the extra indentation, it will replace all TAB characters to 4 spaces.

How to fix: "HAX is not working and emulator runs in emulation mode"

For Windows.

In Android Studio:

Tools > Android > AVD Manager > Your Device > Pencil Icon> Show Advanced Settings > Memory and Storage > RAM > Set RAM to your preferred size.

In Control Panel:

Programs and Features > Intel Hardware Accelerated Execution Manager > Change > Set manually > Set RAM to your preferred size.

It is better for RAM sizes set in both places to be the same.

How do I calculate a point on a circle’s circumference?

Implemented in JavaScript (ES6):

/**
    * Calculate x and y in circle's circumference
    * @param {Object} input - The input parameters
    * @param {number} input.radius - The circle's radius
    * @param {number} input.angle - The angle in degrees
    * @param {number} input.cx - The circle's origin x
    * @param {number} input.cy - The circle's origin y
    * @returns {Array[number,number]} The calculated x and y
*/
function pointsOnCircle({ radius, angle, cx, cy }){

    angle = angle * ( Math.PI / 180 ); // Convert from Degrees to Radians
    const x = cx + radius * Math.sin(angle);
    const y = cy + radius * Math.cos(angle);
    return [ x, y ];

}

Usage:

const [ x, y ] = pointsOnCircle({ radius: 100, angle: 180, cx: 150, cy: 150 });
console.log( x, y );

Codepen

_x000D_
_x000D_
/**
 * Calculate x and y in circle's circumference
 * @param {Object} input - The input parameters
 * @param {number} input.radius - The circle's radius
 * @param {number} input.angle - The angle in degrees
 * @param {number} input.cx - The circle's origin x
 * @param {number} input.cy - The circle's origin y
 * @returns {Array[number,number]} The calculated x and y
 */
function pointsOnCircle({ radius, angle, cx, cy }){
  angle = angle * ( Math.PI / 180 ); // Convert from Degrees to Radians
  const x = cx + radius * Math.sin(angle);
  const y = cy + radius * Math.cos(angle);
  return [ x, y ];
}

const canvas = document.querySelector("canvas");
const ctx = canvas.getContext("2d");

function draw( x, y ){

  ctx.clearRect( 0, 0, canvas.width, canvas.height );
  ctx.beginPath();
  ctx.strokeStyle = "orange";
  ctx.arc( 100, 100, 80, 0, 2 * Math.PI);
  ctx.lineWidth = 3;
  ctx.stroke();
  ctx.closePath();

  ctx.beginPath();
  ctx.fillStyle = "indigo";
  ctx.arc( x, y, 6, 0, 2 * Math.PI);
  ctx.fill();
  ctx.closePath();
  
}

let angle = 0;  // In degrees
setInterval(function(){

  const [ x, y ] = pointsOnCircle({ radius: 80, angle: angle++, cx: 100, cy: 100 });
  console.log( x, y );
  draw( x, y );
  document.querySelector("#degrees").innerHTML = angle + "&deg;";
  document.querySelector("#points").textContent = x.toFixed() + "," + y.toFixed();

}, 100 );
_x000D_
<p>Degrees: <span id="degrees">0</span></p>
<p>Points on Circle (x,y): <span id="points">0,0</span></p>
<canvas width="200" height="200" style="border: 1px solid"></canvas>
_x000D_
_x000D_
_x000D_

Change a Django form field to a hidden field

If you have a custom template and view you may exclude the field and use {{ modelform.instance.field }} to get the value.

also you may prefer to use in the view:

form.fields['field_name'].widget = forms.HiddenInput()

but I'm not sure it will protect save method on post.

Hope it helps.

When should an Excel VBA variable be killed or set to Nothing?

VBA uses a garbage collector which is implemented by reference counting.

There can be multiple references to a given object (for example, Dim aw = ActiveWorkbook creates a new reference to Active Workbook), so the garbage collector only cleans up an object when it is clear that there are no other references. Setting to Nothing is an explicit way of decrementing the reference count. The count is implicitly decremented when you exit scope.

Strictly speaking, in modern Excel versions (2010+) setting to Nothing isn't necessary, but there were issues with older versions of Excel (for which the workaround was to explicitly set)

Python regex findall

you can replace your pattern with

regex = ur"\[P\]([\w\s]+)\[\/P\]"

Use cell's color as condition in if statement (function)

You cannot use VBA (Interior.ColorIndex) in a formula which is why you receive the error.

It is not possible to do this without VBA.

Function YellowIt(rng As Range) As Boolean
    If rng.Interior.ColorIndex = 6 Then
        YellowIt = True
    Else
        YellowIt = False
    End If
End Function

However, I do not recommend this: it is not how user-defined VBA functions (UDFs) are intended to be used. They should reflect the behaviour of Excel functions, which cannot read the colour-formatting of a cell. (This function may not work in a future version of Excel.)

It is far better that you base a formula on the original condition (decision) that makes the cell yellow in the first place. Or, alternatively, run a Sub procedure to fill in the True or False values (although, of course, these values will no longer be linked to the original cell's formatting).

How to get multiline input from user

input(prompt) is basically equivalent to

def input(prompt):
    print(prompt, end='', file=sys.stderr)
    return sys.stdin.readline()

You can read directly from sys.stdin if you like.

lines = sys.stdin.readlines()

lines = [line for line in sys.stdin]

five_lines = list(itertools.islice(sys.stdin, 5))

The first two require that the input end somehow, either by reaching the end of a file or by the user typing Control-D (or Control-Z in Windows) to signal the end. The last one will return after five lines have been read, whether from a file or from the terminal/keyboard.

Flutter - Wrap text on overflow, like insert ellipsis or fade

First, wrap your Row or Column in Expanded widget

Then

Text(
    'your long text here',
    overflow: TextOverflow.fade,
    maxLines: 1,
    softWrap: false,
    style: Theme.of(context).textTheme.body1,
)

How to prevent multiple definitions in C?

You actually compile the source code of test.c twice:

  • The first time when compiling test.c itself,
  • The second time when compiling main.c which includes all the test.c source.

What you need in your main.c in order to use the test() function is a simple declaration, not its definition. This is achieved by including a test.h header file which contains something like:

void test(void);

This informs the compiler that such a function with input parameters and return type exists. What this function does ( everything inside { and } ) is left in your test.c file.

In main.c, replace #include "test.c" by #include "test.h".

A last point: with your programs being more complex, you will be faced to situations when header files may be included several times. To prevent this, header sources are sometimes enclosed by specific macro definitions, like:

#ifndef TEST_H_INCLUDED
#define TEST_H_INCLUDED

void test(void);

#endif

rawQuery(query, selectionArgs)

see below code it may help you.

String q = "SELECT * FROM customer";
Cursor mCursor = mDb.rawQuery(q, null);

or

String q = "SELECT * FROM customer WHERE _id = " + customerDbId  ;
Cursor mCursor = mDb.rawQuery(q, null);

If statement with String comparison fails

If you code in C++ as well as Java, it is better to remember that in C++, the string class has the == operator overloaded. But not so in Java. you need to use equals() or equalsIgnoreCase() for that.

What does "xmlns" in XML mean?

xmlns - xml namespace. It's just a method to avoid element name conflicts. For example:

<config xmlns:rnc="URI1" xmlns:bsc="URI2">
  <rnc:node>
      <rnc:rncId>5</rnc:rncId>
  </rnc:node>

  <bsc:node>
      <bsc:cId>5</bsc:cId>
  </bsc:node>
</config>

Two different node elements in one xml file. Without namespaces this file would not be valid.

use mysql SUM() in a WHERE clause

Not tested, but I think this will be close?

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

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

Adding a column to a dataframe in R

Even if that's a 7 years old question, people new to R should consider using the data.table, package.

A data.table is a data.frame so all you can do for/to a data.frame you can also do. But many think are ORDERS of magnitude faster with data.table.

vec <- 1:10
library(data.table)
DT <- data.table(start=c(1,3,5,7), end=c(2,6,7,9))
DT[,new:=apply(DT,1,function(row) mean(vec[ row[1] : row[2] ] ))]

How to solve SyntaxError on autogenerated manage.py?

just you describe your python version

=> python3.5 manage.py runserver

(my python version=3.5)

Checking if jquery is loaded using Javascript

if ('undefined' == typeof window.jQuery) {
    // jQuery not present
} else {
    // jQuery present
}

Get month name from date in Oracle

Try this

select to_char(SYSDATE,'Month') from dual;

for full name and try this

select to_char(SYSDATE,'Mon') from dual;

for abbreviation

you can find more option here:

https://www.techonthenet.com/oracle/functions/to_char.php

UTF-8 all the way through

in connection.php: mysqli_set_charset($con,“utf8”); and in sql collation utf=8

How do you performance test JavaScript code?

You could use https://github.com/anywhichway/benchtest which wraps existing Mocha unit tests with performance tests.

What is (functional) reactive programming?

Paul Hudak's book, The Haskell School of Expression, is not only a fine introduction to Haskell, but it also spends a fair amount of time on FRP. If you're a beginner with FRP, I highly recommend it to give you a sense of how FRP works.

There is also what looks like a new rewrite of this book (released 2011, updated 2014), The Haskell School of Music.

Formatting floats in a numpy array

In order to make numpy display float arrays in an arbitrary format, you can define a custom function that takes a float value as its input and returns a formatted string:

In [1]: float_formatter = "{:.2f}".format

The f here means fixed-point format (not 'scientific'), and the .2 means two decimal places (you can read more about string formatting here).

Let's test it out with a float value:

In [2]: float_formatter(1.234567E3)
Out[2]: '1234.57'

To make numpy print all float arrays this way, you can pass the formatter= argument to np.set_printoptions:

In [3]: np.set_printoptions(formatter={'float_kind':float_formatter})

Now numpy will print all float arrays this way:

In [4]: np.random.randn(5) * 10
Out[4]: array([5.25, 3.91, 0.04, -1.53, 6.68]

Note that this only affects numpy arrays, not scalars:

In [5]: np.pi
Out[5]: 3.141592653589793

It also won't affect non-floats, complex floats etc - you will need to define separate formatters for other scalar types.

You should also be aware that this only affects how numpy displays float values - the actual values that will be used in computations will retain their original precision.

For example:

In [6]: a = np.array([1E-9])

In [7]: a
Out[7]: array([0.00])

In [8]: a == 0
Out[8]: array([False], dtype=bool)

numpy prints a as if it were equal to 0, but it is not - it still equals 1E-9.

If you actually want to round the values in your array in a way that affects how they will be used in calculations, you should use np.round, as others have already pointed out.

Iterating through struct fieldnames in MATLAB

You have to use curly braces ({}) to access fields, since the fieldnames function returns a cell array of strings:

for i = 1:numel(fields)
  teststruct.(fields{i})
end

Using parentheses to access data in your cell array will just return another cell array, which is displayed differently from a character array:

>> fields(1)  % Get the first cell of the cell array

ans = 

    'a'       % This is how the 1-element cell array is displayed

>> fields{1}  % Get the contents of the first cell of the cell array

ans =

a             % This is how the single character is displayed

Error reading JObject from JsonReader. Current JsonReader item is not an object: StartArray. Path

The first part of your question is a duplicate of Why do I get a JsonReaderException with this code?, but the most relevant part from that (my) answer is this:

[A] JObject isn't the elementary base type of everything in JSON.net, but JToken is. So even though you could say,

object i = new int[0];

in C#, you can't say,

JObject i = JObject.Parse("[0, 0, 0]");

in JSON.net.

What you want is JArray.Parse, which will accept the array you're passing it (denoted by the opening [ in your API response). This is what the "StartArray" in the error message is telling you.

As for what happened when you used JArray, you're using arr instead of obj:

var rcvdData = JsonConvert.DeserializeObject<LocationData>(arr /* <-- Here */.ToString(), settings);

Swap that, and I believe it should work.

Although I'd be tempted to deserialize arr directly as an IEnumerable<LocationData>, which would save some code and effort of looping through the array. If you aren't going to use the parsed version separately, it's best to avoid it.

Validation of radio button group using jQuery validation plugin

I had the same problem. Wound up just writing a custom highlight and unhighlight function for the validator. Adding this to the validaton options should add the error class to the element and its respective label:

        'highlight': function (element, errorClass, validClass) {
            if($(element).attr('type') == 'radio'){
                $(element.form).find("input[type=radio]").each(function(which){
                    $(element.form).find("label[for=" + this.id + "]").addClass(errorClass);
                    $(this).addClass(errorClass);
                });
            } else {
                $(element.form).find("label[for=" + element.id + "]").addClass(errorClass);
                $(element).addClass(errorClass);
            }
        },
        'unhighlight': function (element, errorClass, validClass) {
            if($(element).attr('type') == 'radio'){
                $(element.form).find("input[type=radio]").each(function(which){
                    $(element.form).find("label[for=" + this.id + "]").removeClass(errorClass);
                    $(this).removeClass(errorClass);
                });
            }else {
                $(element.form).find("label[for=" + element.id + "]").removeClass(errorClass);
                $(element).removeClass(errorClass);
            }
        },

What's the difference between Docker Compose vs. Dockerfile

Dockerfile is a file that contains text commands to assemble an image.

Docker compose is used to run a multi-container environment.

In your specific scenario, if you have multiple services for each technology you mentioned (service 1 using reddis, service 2 using rabbit mq etc), then you can have a Dockerfile for each of the services and a common docker-compose.yml to run all the "Dockerfile" as containers.

If you want them all in a single service, docker-compose will be a viable option.