Programs & Examples On #C++builder

Embarcadero C++Builder is a RAD C++ environment (compiler system & IDE) and component framework for Windows, OS X, iOS and Android.

'cannot find or open the pdb file' Visual Studio C++ 2013

Working with VS 2013. Try the following

Tools -> Options -> Debugging -> Output Window -> Module Load Messages -> Off

It will disable the display of modules loaded.

Git SSH error: "Connect to host: Bad file number"

You can also try to:

telnet example.com 22

to see if you have connectivity to the server. I saw this message and it ended up being the VPN I was on was blocking access. Disconnected from the VPN and I was good to go.

Undo a merge by pull request?

There is a better answer to this problem, though I could just break this down step-by-step.

You will need to fetch and checkout the latest upstream changes like so, e.g.:

git fetch upstream
git checkout upstream/master -b revert/john/foo_and_bar

Taking a look at the commit log, you should find something similar to this:

commit b76a5f1f5d3b323679e466a1a1d5f93c8828b269
Merge: 9271e6e a507888
Author: Tim Tom <[email protected]>
Date:   Mon Apr 29 06:12:38 2013 -0700

    Merge pull request #123 from john/foo_and_bar

    Add foo and bar

commit a507888e9fcc9e08b658c0b25414d1aeb1eef45e
Author: John Doe <[email protected]>
Date:   Mon Apr 29 12:13:29 2013 +0000

    Add bar

commit 470ee0f407198057d5cb1d6427bb8371eab6157e
Author: John Doe <[email protected]>
Date:   Mon Apr 29 10:29:10 2013 +0000

    Add foo

Now you want to revert the entire pull request with the ability to unrevert later. To do so, you will need to take the ID of the merge commit.

In the above example the merge commit is the top one where it says "Merged pull request #123...".

Do this to revert the both changes ("Add bar" and "Add foo") and you will end up with in one commit reverting the entire pull request which you can unrevert later on and keep the history of changes clean:

git revert -m 1 b76a5f1f5d3b323679e466a1a1d5f93c8828b269

Get my phone number in android

If the function you called returns null, it means your phone number is not registered in your contact list.

If instead of the phone number you just need an unique number, you may use the sim card's serial number:

    TelephonyManager telemamanger = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
    String getSimSerialNumber = telemamanger.getSimSerialNumber();  

Android emulator-5554 offline

1 . Simply "Wipe data" to fix this issue.

enter image description here

2 . If it doesn't work, go to emulated device and enable developer options > enable usb debugging

jQuery Find and List all LI elements within a UL within a specific DIV

$('li[rel=7]').siblings().andSelf();

// or:

$('li[rel=7]').parent().children();

Now that you added that comment explaining that you want to "form an array of rels per column", you should do this:

var rels = [];

$('ul').each(function() {
    var localRels = [];

    $(this).find('li').each(function(){
        localRels.push( $(this).attr('rel') );
    });

    rels.push(localRels);
});

How to put a component inside another component in Angular2?

If you remove directives attribute it should work.

@Component({
    selector: 'parent',
    template: `
            <h1>Parent Component</h1>
            <child></child>
        `
    })
    export class ParentComponent{}


@Component({
    selector: 'child',    
    template: `
            <h4>Child Component</h4>
        `
    })
    export class ChildComponent{}

Directives are like components but they are used in attributes. They also have a declarator @Directive. You can read more about directives Structural Directives and Attribute Directives.

There are two other kinds of Angular directives, described extensively elsewhere: (1) components and (2) attribute directives.

A component manages a region of HTML in the manner of a native HTML element. Technically it's a directive with a template.


Also if you are open the glossary you can find that components are also directives.

Directives fall into one of the following categories:

  • Components combine application logic with an HTML template to render application views. Components are usually represented as HTML elements. They are the building blocks of an Angular application.

  • Attribute directives can listen to and modify the behavior of other HTML elements, attributes, properties, and components. They are usually represented as HTML attributes, hence the name.

  • Structural directives are responsible for shaping or reshaping HTML layout, typically by adding, removing, or manipulating elements and their children.


The difference that components have a template. See Angular Architecture overview.

A directive is a class with a @Directive decorator. A component is a directive-with-a-template; a @Component decorator is actually a @Directive decorator extended with template-oriented features.


The @Component metadata doesn't have directives attribute. See Component decorator.

Remove Null Value from String array in java

If you want to avoid fencepost errors and avoid moving and deleting items in an array, here is a somewhat verbose solution that uses List:

import java.util.ArrayList;
import java.util.List;

public class RemoveNullValue {
  public static void main( String args[] ) {
    String[] firstArray = {"test1", "", "test2", "test4", "", null};

    List<String> list = new ArrayList<String>();

    for(String s : firstArray) {
       if(s != null && s.length() > 0) {
          list.add(s);
       }
    }

    firstArray = list.toArray(new String[list.size()]);
  }
}

Added null to show the difference between an empty String instance ("") and null.

Since this answer is around 4.5 years old, I'm adding a Java 8 example:

import java.util.Arrays;
import java.util.stream.Collectors;

public class RemoveNullValue {
    public static void main( String args[] ) {
        String[] firstArray = {"test1", "", "test2", "test4", "", null};

        firstArray = Arrays.stream(firstArray)
                     .filter(s -> (s != null && s.length() > 0))
                     .toArray(String[]::new);    

    }
}

How to iterate through a list of objects in C++

It is also worth to mention, that if you DO NOT intent to modify the values of the list, it is possible (and better) to use the const_iterator, as follows:

for (std::list<Student>::const_iterator it = data.begin(); it != data.end(); ++it){
    // do whatever you wish but don't modify the list elements
    std::cout << it->name;
}

Convert PDF to image with high resolution

In ImageMagick, you can do "supersampling". You specify a large density and then resize down as much as desired for the final output size. For example with your image:

convert -density 600 test.pdf -background white -flatten -resize 25% test.png


enter image description here

Download the image to view at full resolution for comparison..

I do not recommend saving to JPG if you are expecting to do further processing.

If you want the output to be the same size as the input, then resize to the inverse of the ratio of your density to 72. For example, -density 288 and -resize 25%. 288=4*72 and 25%=1/4

The larger the density the better the resulting quality, but it will take longer to process.

Traverse a list in reverse order in Python

A simple way :

n = int(input())
arr = list(map(int, input().split()))

for i in reversed(range(0, n)):
    print("%d %d" %(i, arr[i]))

How do I test a single file using Jest?

Jest will use what you pass as a regular expression pattern. That it will match for.

If you want to run a specific test file, then the best way to do it is to use the precise full path to it. (You can too specify a certain relative path like (src/XFolder/index.spec.ts)).

The easiest way to provide the full path being in the directory and in Linux is:

jest $PWD/index.spec.ts

Note the use of the variable $PWD.

Enter image description here

For Windows! (to be updated)

Command not found when using sudo

You can also create a soft link to your script in one of the directories (/usr/local/bin for example) in the super user PATH. It'll then be available to the sudo.

chmod +x foo.sh
sudo ln -s path-to-foo.sh /usr/local/bin/foo

Have a look at this answer to have an idea of which directory to put soft link in.

Is it possible to start a shell session in a running container (without ssh)

Maybe you were mislead like myself into thinking in terms of VMs when developing containers. My advice: Try not to.

Containers are just like any other process. Indeed you might want to "attach" to them for debugging purposes (think of /proc//env or strace -p ) but that's a very special case.

Normally you just "run" the process, so if you want to modify the configuration or read the logs, just create a new container and make sure you write the logs outside of it by sharing directories, writing to stdout (so docker logs works) or something like that.

For debugging purposes you might want to start a shell, then your code, then press CTRL-p + CTRL-q to leave the shell intact. This way you can reattach using:

docker attach <container_id>

If you want to debug the container because it's doing something you haven't expect it to do, try to debug it: https://serverfault.com/questions/596994/how-can-i-debug-a-docker-container-initialization

Read String line by line

You can try the following regular expression:

\r?\n

Code:

String input = "\nab\n\n    \n\ncd\nef\n\n\n\n\n";
String[] lines = input.split("\\r?\\n", -1);
int n = 1;
for(String line : lines) {
    System.out.printf("\tLine %02d \"%s\"%n", n++, line);
}

Output:

Line 01 ""
Line 02 "ab"
Line 03 ""
Line 04 "    "
Line 05 ""
Line 06 "cd"
Line 07 "ef"
Line 08 ""
Line 09 ""
Line 10 ""
Line 11 ""
Line 12 ""

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

The principal is the Random Class constructed with the same seed will generate the same pattern of numbers every time.

[Vue warn]: Cannot find element

I think the problem is your script is executed before the target dom element is loaded in the dom... one reason could be that you have placed your script in the head of the page or in a script tag that is placed before the div element #main. So when the script is executed it won't be able to find the target element thus the error.

One solution is to place your script in the load event handler like

window.onload = function () {
    var main = new Vue({
        el: '#main',
        data: {
            currentActivity: 'home'
        }
    });
}

Another syntax

window.addEventListener('load', function () {
    //your script
})

How to use MD5 in javascript to transmit a password

if you're using php jquery, this might help:

   $.ajax({
        url:'phpmd5file.php',
        data:{'mypassword',mypassword},
        dataType:"json",
        method:"POST",
        success:function(mymd5password){
            alert(mymd5password);
        }
    });

on your phpmd5.php file:

echo json_encode($_POST["mypassword"]);

no jsplugins needed. just use ajax and let php md5() do the job.

Excel VBA Run-time error '13' Type mismatch

Thank you guys for all your help! Finally I was able to make it work perfectly thanks to a friend and also you! Here is the final code so you can also see how we solve it.

Thanks again!

Option Explicit

Sub k()

Dim x As Integer, i As Integer, a As Integer
Dim name As String
'name = InputBox("Please insert the name of the sheet")
i = 1
name = "Reserva"
Sheets(name).Cells(4, 57) = Sheets(name).Cells(4, 56)

On Error GoTo fim
x = Sheets(name).Cells(4, 56).Value
Application.Calculation = xlCalculationManual
Do While Not IsEmpty(Sheets(name).Cells(i + 4, 56))
    a = 0
    If Sheets(name).Cells(4 + i, 56) <> x Then
        If Sheets(name).Cells(4 + i, 56) <> 0 Then
            If Sheets(name).Cells(4 + i, 56) = 3 Then
                a = x
                Sheets(name).Cells(4 + i, 57) = Sheets(name).Cells(4 + i, 56) - x
                x = Cells(4 + i, 56) - x
            End If
            Sheets(name).Cells(4 + i, 57) = Sheets(name).Cells(4 + i, 56) - a
            x = Sheets(name).Cells(4 + i, 56) - a
        Else
        Cells(4 + i, 57) = ""
        End If
    Else
    Cells(4 + i, 57) = ""
    End If

i = i + 1
Loop
Application.Calculation = xlCalculationAutomatic
Exit Sub
fim:
MsgBox Err.Description
Application.Calculation = xlCalculationAutomatic
End Sub

Git - How to fix "corrupted" interactive rebase?

On Windows, if you are unwilling or unable to restart the machine see below.

Install Process Explorer: https://technet.microsoft.com/en-us/sysinternals/bb896653.aspx

In Process Explorer, Find > File Handle or DLL ...

Type in the file name mentioned in the error (for my error it was 'git-rebase-todo' but in the question above, 'done').

Process Explorer will highlight the process holding a lock on the file (for me it was 'grep').

Kill the process and you will be able to abort the git action in the standard way.

What causes this error? "Runtime error 380: Invalid property value"

I presume your application uses a masked edit box? This is a relatively well known problem, documented by Microsoft here:

http://support.microsoft.com/kb/177088

The article refers to VB4 and 5, but I am pretty sure the same is true for VB6.

EDIT

On further research, I am finding references to this problem with other controls as well. Recompiling your application on Windows XP for users that are running XP will probably produce them a working version, though it's not an ideal solution...

IE 8: background-size fix

Also i have found another useful link. It is a background hack used like this

.selector { background-size: cover; -ms-behavior: url(/backgroundsize.min.htc); }

https://github.com/louisremi/background-size-polyfill

How to get database structure in MySQL via query

Take a look at the INFORMATION_SCHEMA.TABLES table. It contains metadata about all your tables.

Example:

SELECT * FROM `INFORMATION_SCHEMA`.`TABLES`
WHERE TABLE_NAME LIKE 'table1'

The advantage of this over other methods is that you can easily use queries like the one above as subqueries in your other queries.

Initialization of all elements of an array to one default value in C++?

For the case of an array of single-byte elements, you can use memset to set all elements to the same value.

There's an example here.

Centering a div block without the width

This is one way to center anything within a div not know the inner width of the elements.

#product_15{
    position: relative;
    margin: 0 auto;
    display: table;
}
.price, img{
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
}

No found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations:

I added @Service before impl class and the error is gone.

@Service
public class FCSPAnalysisImpl implements FCSPAnalysis
{}

Making sure at least one checkbox is checked

< script type = "text/javascript" src = "js/jquery-1.6.4.min.js" >  <  / script >
     < script type = "text/javascript" >

function checkSelectedAtleastOne(clsName) {
    if (selectedValue == "select")
        return false;

    var i = 0;
    $("." + clsName).each(function () {

        if ($(this).is(':checked')) {
            i = 1;
        }

    });

    if (i == 0) {
        alert("Please select atleast one users");
        return false;
    } else if (i == 1) {
        return true;
    }

    return true;

}

$(document).ready(function () {
    $('#chkSearchAll').click(function () {

        var checked = $(this).is(':checked');
        $('.clsChkSearch').each(function () {
            var checkBox = $(this);
            if (checked) {
                checkBox.prop('checked', true);
            } else {
                checkBox.prop('checked', false);
            }
        });

    });

    //for select and deselect 'select all' check box when clicking individual check boxes
    $(".clsChkSearch").click(function () {

        var i = 0;
        $(".clsChkSearch").each(function () {

            if ($(this).is(':checked')) {}
            else {

                i = 1; //unchecked
            }

        });

        if (i == 0) {
            $("#chkSearchAll").attr("checked", true)
        } else if (i == 1) {

            $("#chkSearchAll").attr("checked", false)
        }

    });

});

<  / script >

How do I do base64 encoding on iOS?

in iOS 7

        NSData *data=[[NSData alloc]init];
        [data base64Encoding];

How to manually reload Google Map with JavaScript

Yes, you can 'refresh' a Google Map like this:

google.maps.event.trigger(map, 'resize');

This basically sends a signal to your map to redraw it.

Hope that helps!

Please help me convert this script to a simple image slider

Problems only surface when I am I trying to give the first loaded content an active state

Does this mean that you want to add a class to the first button?

$('.o-links').click(function(e) {   // ... }).first().addClass('O_Nav_Current'); 

instead of using IDs for the slider's items and resetting html contents you can use classes and indexes:

CSS:

.image-area {     width: 100%;     height: auto;     display: none; }  .image-area:first-of-type {     display: block; } 

JavaScript:

var $slides = $('.image-area'),     $btns = $('a.o-links');  $btns.on('click', function (e) {     var i = $btns.removeClass('O_Nav_Current').index(this);     $(this).addClass('O_Nav_Current');      $slides.filter(':visible').fadeOut(1000, function () {         $slides.eq(i).fadeIn(1000);     });      e.preventDefault();  }).first().addClass('O_Nav_Current'); 

http://jsfiddle.net/RmF57/

How to define Typescript Map of key value pair. where key is a number and value is an array of objects

The most simple way is to use Record type Record<number, productDetails >

interface productDetails {
   productId : number , 
   price : number , 
   discount : number
};

const myVar : Record<number, productDetails> = {
   1: {
       productId : number , 
       price : number , 
       discount : number
   }
}

How to remove all callbacks from a Handler?

In my experience calling this worked great!

handler.removeCallbacksAndMessages(null);

In the docs for removeCallbacksAndMessages it says...

Remove any pending posts of callbacks and sent messages whose obj is token. If token is null, all callbacks and messages will be removed.

Codeigniter - multiple database connections

It works fine for me...

This is default database :

$db['default'] = array(
    'dsn'   => '',
    'hostname' => 'localhost',
    'username' => 'root',
    'password' => '',
    'database' => 'mydatabase',
    'dbdriver' => 'mysqli',
    'dbprefix' => '',
    'pconnect' => TRUE,
    'db_debug' => (ENVIRONMENT !== 'production'),
    'cache_on' => FALSE,
    'cachedir' => '',
    'char_set' => 'utf8',
    'dbcollat' => 'utf8_general_ci',
    'swap_pre' => '',
    'encrypt' => FALSE,
    'compress' => FALSE,
    'stricton' => FALSE,
    'failover' => array(),
    'save_queries' => TRUE
);

Add another database at the bottom of database.php file

$db['second'] = array(
    'dsn'   => '',
    'hostname' => 'localhost',
    'username' => 'root',
    'password' => '',
    'database' => 'mysecond',
    'dbdriver' => 'mysqli',
    'dbprefix' => '',
    'pconnect' => TRUE,
    'db_debug' => (ENVIRONMENT !== 'production'),
    'cache_on' => FALSE,
    'cachedir' => '',
    'char_set' => 'utf8',
    'dbcollat' => 'utf8_general_ci',
    'swap_pre' => '',
    'encrypt' => FALSE,
    'compress' => FALSE,
    'stricton' => FALSE,
    'failover' => array(),
    'save_queries' => TRUE
);

In autoload.php config file

$autoload['libraries'] = array('database', 'email', 'session');

The default database is worked fine by autoload the database library but second database load and connect by using constructor in model and controller...

<?php
    class Seconddb_model extends CI_Model {
        function __construct(){
            parent::__construct();
            //load our second db and put in $db2
            $this->db2 = $this->load->database('second', TRUE);
        }

        public function getsecondUsers(){
            $query = $this->db2->get('members');
            return $query->result(); 
        }

    }
?>

How to copy file from host to container using Dockerfile

If you want to copy the current dir's contents, you can run:

docker build  -t <imagename:tag> -f- ./ < Dockerfile

Get length of array?

Function

Public Function ArrayLen(arr As Variant) As Integer
    ArrayLen = UBound(arr) - LBound(arr) + 1
End Function

Usage

Dim arr(1 To 3) As String  ' Array starting at 1 instead of 0: nightmare fuel
Debug.Print ArrayLen(arr)  ' Prints 3.  Everything's going to be ok.

Get folder up one level

The parent directory of an included file would be

dirname(getcwd())

e.g. the file is /var/www/html/folder/inc/file.inc.php which is included in /var/www/html/folder/index.php

then by calling /file/index.php

getcwd() is /var/www/html/folder  
__DIR__ is /var/www/html/folder/inc  
so dirname(__DIR__) is /var/www/html/folder

but what we want is /var/www/html which is dirname(getcwd())

Sending emails through SMTP with PHPMailer

As far as I can see everything is right with your code. Your error is:

SMTP Error: Could not authenticate.

Which means that the credentials you've sending are rejected by the SMTP server. Make sure the host, port, username and password are good.

If you want to use STARTTLS, try adding:

$mail->SMTPSecure = 'tls';

If you want to use SMTPS (SSL), try adding:

$mail->SMTPSecure = 'ssl';

Keep in mind that:

  • Some SMTP servers can forbid connections from "outsiders".
  • Some SMTP servers don't support SSL (or TLS) connections.

Maybe this example can help (GMail secure SMTP).

[Source]

How to test if a list contains another list?

Dave answer is good. But I suggest this implementation which is more efficient and doesn't use nested loops.

def contains(small_list, big_list):
    """
    Returns index of start of small_list in big_list if big_list
    contains small_list, otherwise -1.
    """
    loop = True
    i, curr_id_small= 0, 0
    while loop and i<len(big_list):
        if big_list[i]==small_list[curr_id_small]:
            if curr_id_small==len(small_list)-1:
                loop = False
            else:
                curr_id_small += 1
        else:
            curr_id_small = 0
        i=i+1
    if not loop:
        return i-len(small_list)
    else:
        return -1

What is the correct "-moz-appearance" value to hide dropdown arrow of a <select> element

Try putting opacity:0; your select element will be invisible but the options will be visible when you click on it.

Linker Command failed with exit code 1 (use -v to see invocation), Xcode 8, Swift 3

Make sure the Find Implicit Dependencies checkbox is checked.

(Product -> Scheme -> Edit Scheme -> Build -> Find Implicit Dependencies)

Get value of a merged cell of an excel from its cell address in vba

Even if it is really discouraged to use merge cells in Excel (use Center Across Selection for instance if needed), the cell that "contains" the value is the one on the top left (at least, that's a way to express it).

Hence, you can get the value of merged cells in range B4:B11 in several ways:

  • Range("B4").Value
  • Range("B4:B11").Cells(1).Value
  • Range("B4:B11").Cells(1,1).Value

You can also note that all the other cells have no value in them. While debugging, you can see that the value is empty.

Also note that Range("B4:B11").Value won't work (raises an execution error number 13 if you try to Debug.Print it) because it returns an array.

bitwise XOR of hex numbers in python

If the two hex strings are the same length and you want a hex string output then you might try this.

def hexxor(a, b):    # xor two hex strings of the same length
    return "".join(["%x" % (int(x,16) ^ int(y,16)) for (x, y) in zip(a, b)])

How would I run an async Task<T> method synchronously?

Surprised no one mentioned this:

public Task<int> BlahAsync()
{
    // ...
}

int result = BlahAsync().GetAwaiter().GetResult();

Not as pretty as some of the other methods here, but it has the following benefits:

  • it doesn't swallow exceptions (like Wait)
  • it won't wrap any exceptions thrown in an AggregateException (like Result)
  • works for both Task and Task<T> (try it out yourself!)

Also, since GetAwaiter is duck-typed, this should work for any object that is returned from an async method (like ConfiguredAwaitable or YieldAwaitable), not just Tasks.


edit: Please note that it's possible for this approach (or using .Result) to deadlock, unless you make sure to add .ConfigureAwait(false) every time you await, for all async methods that can possibly be reached from BlahAsync() (not just ones it calls directly). Explanation.

// In BlahAsync() body
await FooAsync(); // BAD!
await FooAsync().ConfigureAwait(false); // Good... but make sure FooAsync() and
                                        // all its descendants use ConfigureAwait(false)
                                        // too. Then you can be sure that
                                        // BlahAsync().GetAwaiter().GetResult()
                                        // won't deadlock.

If you're too lazy to add .ConfigureAwait(false) everywhere, and you don't care about performance you can alternatively do

Task.Run(() => BlahAsync()).GetAwaiter().GetResult()

php foreach with multidimensional array

With arrays in php, the foreach loop is always a pretty solution.
In this case it could be for example:

foreach($my_array as $number => $number_array)
    {
    foreach($number_array as $data = > $user_data)
        {
            print "Array number: $number, contains $data with $user_data.  <br>";
        }
    }

How to make a flex item not fill the height of the flex container?

When you create a flex container various default flex rules come into play.

Two of these default rules are flex-direction: row and align-items: stretch. This means that flex items will automatically align in a single row, and each item will fill the height of the container.

If you don't want flex items to stretch – i.e., like you wrote:

make its height the minimum required for holding its content

... then simply override the default with align-items: flex-start.

_x000D_
_x000D_
#a {_x000D_
  display: flex;_x000D_
  align-items: flex-start; /* NEW */_x000D_
}_x000D_
#a > div {_x000D_
  background-color: red;_x000D_
  padding: 5px;_x000D_
  margin: 2px;_x000D_
}_x000D_
#b {_x000D_
  height: auto;_x000D_
}
_x000D_
<div id="a">_x000D_
  <div id="b">left</div>_x000D_
  <div>_x000D_
    right<br>right<br>right<br>right<br>right<br>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Here's an illustration from the flexbox spec that highlights the five values for align-items and how they position flex items within the container. As mentioned before, stretch is the default value.

enter image description here Source: W3C

mysqld: Can't change dir to data. Server doesn't start

Since you used the Windows installer, everything is set up for you to run MySQL 5.7 as a Windows service, which is a great option in most cases.

Instead of running mysqld.exe from the command line,

  1. Win + R
  2. Run services.msc
  3. Right-click on MySQL57
  4. Start the service.

Does IE9 support console.log, and is it a real function?

A simple solution to this console.log problem is to define the following at the beginning of your JS code:

if (!window.console) window.console = {};
if (!window.console.log) window.console.log = function () { };

This works for me in all browsers. This creates a dummy function for console.log when the debugger is not active. When the debugger is active, the method console.log is defined and executes normally.

Why do I always get the same sequence of random numbers with rand()?

None of you guys are answering his question.

with this code i get the same sequance everytime the code but it generates random sequences if i add srand(/somevalue/) before the for loop . can someone explain why ?

From what my professor has told me, it is used if you want to make sure your code is running properly and to see if there is something wrong or if you can change something.

How to preserve insertion order in HashMap?

LinkedHashMap is precisely what you're looking for.

It is exactly like HashMap, except that when you iterate over it, it presents the items in the insertion order.

How can I change property names when serializing with Json.net?

You could decorate the property you wish controlling its name with the [JsonProperty] attribute which allows you to specify a different name:

using Newtonsoft.Json;
// ...

[JsonProperty(PropertyName = "FooBar")]
public string Foo { get; set; }

Documentation: Serialization Attributes

Is there an equivalent to the SUBSTRING function in MS Access SQL?

I think there is MID() and maybe LEFT() and RIGHT() in Access.

When doing a MERGE in Oracle SQL, how can I update rows that aren't matched in the SOURCE?

You can do it with a separate UPDATE statement

UPDATE report.TEST target
SET    is Deleted = 'Y'
WHERE  NOT EXISTS (SELECT 1
                   FROM   main.TEST source
                   WHERE  source.ID = target.ID);

I don't know of any way to integrate this into your MERGE statement.

Read tab-separated file line into array

If you really want to split every word (bash meaning) into a different array index completely changing the array in every while loop iteration, @ruakh's answer is the correct approach. But you can use the read property to split every read word into different variables column1, column2, column3 like in this code snippet

while IFS=$'\t' read -r column1 column2 column3 ; do
  printf "%b\n" "column1<${column1}>"
  printf "%b\n" "column2<${column2}>"
  printf "%b\n" "column3<${column3}>"
done < "myfile"

to reach a similar result avoiding array index access and improving your code readability by using meaningful variable names (of course using columnN is not a good idea to do so).

Error "The input device is not a TTY"

Remove the -it from your cli to make it non interactive and remove the TTY. If you don't need either, e.g. running your command inside of a Jenkins or cron script, you should do this.

Or you can change it to -i if you have input piped into the docker command that doesn't come from a TTY. If you have something like xyz | docker ... or docker ... <input in your command line, do this.

Or you can change it to -t if you want TTY support but don't have it available on the input device. Do this for apps that check for a TTY to enable color formatting of the output in your logs, or for when you later attach to the container with a proper terminal.

Or if you need an interactive terminal and aren't running in a terminal on Linux or MacOS, use a different command line interface. PowerShell is reported to include this support on Windows.


What is a TTY? It's a terminal interface that supports escape sequences, moving the cursor around, etc, that comes from the old days of dumb terminals attached to mainframes. Today it is provided by the Linux command terminals and ssh interfaces. See the wikipedia article for more details.

To see the difference of running a container with and without a TTY, run a container without one: docker run --rm -i ubuntu bash. From inside that container, install vim with apt-get update; apt-get install vim. Note the lack of a prompt. When running vim against a file, try to move the cursor around within the file.

How to change line width in ggplot?

Line width in ggplot2 can be changed with argument size= in geom_line().

#sample data
df<-data.frame(x=rnorm(100),y=rnorm(100))
ggplot(df,aes(x=x,y=y))+geom_line(size=2)

enter image description here

Using DISTINCT inner join in SQL

SELECT DISTINCT C.valueC 
FROM C 
  LEFT JOIN B ON C.id = B.lookupC
  LEFT JOIN A ON B.id = A.lookupB
WHERE C.id IS NOT NULL

I don't see a good reason why you want to limit the result sets of A and B because what you want to have is a list of all C's that are referenced by A. I did a distinct on C.valueC because i guessed you wanted a unique list of C's.


EDIT: I agree with your argument. Even if your solution looks a bit nested it seems to be the best and fastest way to use your knowledge of the data and reduce the result sets.

There is no distinct join construct you could use so just stay with what you already have :)

Node.js Error: Cannot find module express

create one folder in your harddisk e.g sample1 and go to command prompt type :cd and gives the path of sample1 folder and then install all modules...

npm install express

npm install jade

npm install socket.io

and then whatever you are creating application save in sample1 folder

try it...

Select Tag Helper in ASP.NET Core MVC

You can use below code for multiple select:

<select asp-for="EmployeeId"  multiple="multiple" asp-items="@ViewBag.Employees">
    <option>Please select</option>
</select>

You can also use:

<select id="EmployeeId" name="EmployeeId"  multiple="multiple" asp-items="@ViewBag.Employees">
    <option>Please select</option>
</select>

How to get VM arguments from inside of Java application?

At startup pass this -Dname=value

and then in your code you should use

value=System.getProperty("name");

to get that value

C# Ignore certificate errors?

If you are using sockets directly and are authenticating as the client, then the Service Point Manager callback method won't work. Here's what did work for me. PLEASE USE FOR TESTING PURPOSES ONLY.

var activeStream = new SslStream(networkStream, false, (a, b, c, d) => { return true; });
await activeStream.AuthenticateAsClientAsync("computer.local");

The key here, is to provide the remote certificate validation callback right in the constructor of the SSL stream.

addEventListener not working in IE8

Try:

if (_checkbox.addEventListener) {
    _checkbox.addEventListener("click", setCheckedValues, false);
}
else {
    _checkbox.attachEvent("onclick", setCheckedValues);
}

Update:: For Internet Explorer versions prior to IE9, attachEvent method should be used to register the specified listener to the EventTarget it is called on, for others addEventListener should be used.

Database Diagram Support Objects cannot be Installed ... no valid owner

You should consider SQL authentication account for database ownership; then you don't have to worry about accounts coming and going, databases or instances moving to different servers, and your next PC name change. I have several systems where we use:

ALTER AUTHORIZATION ON DATABASE::Ariha TO [sa];

Or if you want to change the owner to that local Administrator account, then it should be:

ALTER AUTHORIZATION ON DATABASE::Ariha TO [DevPC\Administrator];

Because renaming the machine to DevPC has eliminated the local account that used to be named WIN-ND...\Administrator and this has also invalidated the current owner of the database.

If SELECT @@SERVERNAME; is not accurate (it should say DevPC), then in order to ensure that your server rename has taken hold within SQL Server, you may also want to issue the following:

EXEC sys.sp_dropserver @server = N'old server name';
GO
EXEC sys.sp_addserver @server = N'DevPC', @local = N'local';
GO

How to remove CocoaPods from a project?

$ sudo gem install cocoapods-deintegrate cocoapods-clean
$ pod deintegrate
$ pod clean
$ rm Podfile

Split string into individual words Java

StringTokenizer separate = new StringTokenizer(s, " ");
String word = separate.nextToken();
System.out.println(word);

Create a zip file and download it

$zip = new ZipArchive;
$tmp_file = 'assets/myzip.zip';
    if ($zip->open($tmp_file,  ZipArchive::CREATE)) {
        $zip->addFile('folder/bootstrap.js', 'bootstrap.js');
        $zip->addFile('folder/bootstrap.min.js', 'bootstrap.min.js');
        $zip->close();
        echo 'Archive created!';
        header('Content-disposition: attachment; filename=files.zip');
        header('Content-type: application/zip');
        readfile($tmp_file);
   } else {
       echo 'Failed!';
   }

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

You might have python 3 pip installed already. Instead of pip install you can use pip3 install.

Where does forever store console.log output?

Forever, by default, will put logs into a random file in ~/.forever/ folder.

You should run forever list to see the running processes and their corresponding log file.

Sample output

>>> forever list
info:    Forever processes running
data:        uid  command       script forever pid  logfile                         uptime
data:    [0] 6n71 /usr/bin/node app.js 2233    2239 /home/vagrant/.forever/6n71.log 0:0:0:1.590

However, it's probably best to specify with -l as mentioned by bryanmac.

Appending an element to the end of a list in Scala

This is similar to one of the answers but in different way :

scala> val x = List(1,2,3)
x: List[Int] = List(1, 2, 3)

scala> val y = x ::: 4 :: Nil
y: List[Int] = List(1, 2, 3, 4)

How to parse XML using vba

Update

The procedure presented below gives an example of parsing XML with VBA using the XML DOM objects. Code is based on a beginners guide of the XML DOM.

Public Sub LoadDocument()
    Dim xDoc As MSXML.DOMDocument
    Set xDoc = New MSXML.DOMDocument
    xDoc.validateOnParse = False
    If xDoc.Load("C:\My Documents\sample.xml") Then
        ' The document loaded successfully.
        ' Now do something intersting.
        DisplayNode xDoc.childNodes, 0
    Else
        ' The document failed to load.
        ' See the previous listing for error information.
    End If
End Sub

Public Sub DisplayNode(ByRef Nodes As MSXML.IXMLDOMNodeList, _
   ByVal Indent As Integer)

   Dim xNode As MSXML.IXMLDOMNode
   Indent = Indent + 2

   For Each xNode In Nodes
      If xNode.nodeType = NODE_TEXT Then
         Debug.Print Space$(Indent) & xNode.parentNode.nodeName & _
            ":" & xNode.nodeValue
      End If

      If xNode.hasChildNodes Then
         DisplayNode xNode.childNodes, Indent
      End If
   Next xNode
End Sub

Nota Bene - This initial answer shows the simplest possible thing I could imagine (at the time I was working on a very specific issue) . Naturally using the XML facilities built into the VBA XML Dom would be much better. See the updates above.

Original Response

I know this is a very old post but I wanted to share my simple solution to this complicated question. Primarily I've used basic string functions to access the xml data.

This assumes you have some xml data (in the temp variable) that has been returned within a VBA function. Interestingly enough one can also see how I am linking to an xml web service to retrieve the value. The function shown in the image also takes a lookup value because this Excel VBA function can be accessed from within a cell using = FunctionName(value1, value2) to return values via the web service into a spreadsheet.

sample function


openTag = ""
closeTag = "" 

' Locate the position of the enclosing tags startPos = InStr(1, temp, openTag) endPos = InStr(1, temp, closeTag) startTagPos = InStr(startPos, temp, ">") + 1 ' Parse xml for returned value Data = Mid(temp, startTagPos, endPos - startTagPos)

CSS Input field text color of inputted text

To add color to an input, Use the following css code:

input{
     color: black;
}

How to find the Git commit that introduced a string in any branch?

Messing around with the same answers:

$ git config --global alias.find '!git log --color -p -S '
  • ! is needed because other way, git do not pass argument correctly to -S. See this response
  • --color and -p helps to show exactly "whatchanged"

Now you can do

$ git find <whatever>

or

$ git find <whatever> --all
$ git find <whatever> master develop

How to delete last character in a string in C#?

Add a StringBuilder extension method.

public static StringBuilder RemoveLast(this StringBuilder sb, string value)
{
    if(sb.Length < 1) return sb;
    sb.Remove(sb.ToString().LastIndexOf(value), value.Length);
    return sb;
}

then use:

yourStringBuilder.RemoveLast(",");

How can I cast int to enum?

I think to get a complete answer, people have to know how enums work internally in .NET.

How stuff works

An enum in .NET is a structure that maps a set of values (fields) to a basic type (the default is int). However, you can actually choose the integral type that your enum maps to:

public enum Foo : short

In this case the enum is mapped to the short data type, which means it will be stored in memory as a short and will behave as a short when you cast and use it.

If you look at it from a IL point of view, a (normal, int) enum looks like this:

.class public auto ansi serializable sealed BarFlag extends System.Enum
{
    .custom instance void System.FlagsAttribute::.ctor()
    .custom instance void ComVisibleAttribute::.ctor(bool) = { bool(true) }

    .field public static literal valuetype BarFlag AllFlags = int32(0x3fff)
    .field public static literal valuetype BarFlag Foo1 = int32(1)
    .field public static literal valuetype BarFlag Foo2 = int32(0x2000)

    // and so on for all flags or enum values

    .field public specialname rtspecialname int32 value__
}

What should get your attention here is that the value__ is stored separately from the enum values. In the case of the enum Foo above, the type of value__ is int16. This basically means that you can store whatever you want in an enum, as long as the types match.

At this point I'd like to point out that System.Enum is a value type, which basically means that BarFlag will take up 4 bytes in memory and Foo will take up 2 -- e.g. the size of the underlying type (it's actually more complicated than that, but hey...).

The answer

So, if you have an integer that you want to map to an enum, the runtime only has to do 2 things: copy the 4 bytes and name it something else (the name of the enum). Copying is implicit because the data is stored as value type - this basically means that if you use unmanaged code, you can simply interchange enums and integers without copying data.

To make it safe, I think it's a best practice to know that the underlying types are the same or implicitly convertible and to ensure the enum values exist (they aren't checked by default!).

To see how this works, try the following code:

public enum MyEnum : int
{
    Foo = 1,
    Bar = 2,
    Mek = 5
}

static void Main(string[] args)
{
    var e1 = (MyEnum)5;
    var e2 = (MyEnum)6;

    Console.WriteLine("{0} {1}", e1, e2);
    Console.ReadLine();
}

Note that casting to e2 also works! From the compiler perspective above this makes sense: the value__ field is simply filled with either 5 or 6 and when Console.WriteLine calls ToString(), the name of e1 is resolved while the name of e2 is not.

If that's not what you intended, use Enum.IsDefined(typeof(MyEnum), 6) to check if the value you are casting maps to a defined enum.

Also note that I'm explicit about the underlying type of the enum, even though the compiler actually checks this. I'm doing this to ensure I don't run into any surprises down the road. To see these surprises in action, you can use the following code (actually I've seen this happen a lot in database code):

public enum MyEnum : short
{
    Mek = 5
}

static void Main(string[] args)
{
    var e1 = (MyEnum)32769; // will not compile, out of bounds for a short

    object o = 5;
    var e2 = (MyEnum)o;     // will throw at runtime, because o is of type int

    Console.WriteLine("{0} {1}", e1, e2);
    Console.ReadLine();
}

changing the owner of folder in linux

Use chown to change ownership and chmod to change rights.

use the -R option to apply the rights for all files inside of a directory too.

Note that both these commands just work for directories too. The -R option makes them also change the permissions for all files and directories inside of the directory.

For example

sudo chown -R username:group directory

will change ownership (both user and group) of all files and directories inside of directory and directory itself.

sudo chown username:group directory

will only change the permission of the folder directory but will leave the files and folders inside the directory alone.

you need to use sudo to change the ownership from root to yourself.

Edit:

Note that if you use chown user: file (Note the left-out group), it will use the default group for that user.

Also You can change the group ownership of a file or directory with the command:

chgrp group_name file/directory_name

You must be a member of the group to which you are changing ownership to.

You can find group of file as follows

# ls -l file
-rw-r--r-- 1 root family 0 2012-05-22 20:03 file

# chown sujit:friends file

User 500 is just a normal user. Typically user 500 was the first user on the system, recent changes (to /etc/login.defs) has altered the minimum user id to 1000 in many distributions, so typically 1000 is now the first (non root) user.

What you may be seeing is a system which has been upgraded from the old state to the new state and still has some processes knocking about on uid 500. You can likely change it by first checking if your distro should indeed now use 1000, and if so alter the login.defs file yourself, the renumber the user account in /etc/passwd and chown/chgrp all their files, usually in /home/, then reboot.

But in answer to your question, no, you should not really be worried about this in all likelihood. It'll be showing as "500" instead of a username because o user in /etc/passwd has a uid set of 500, that's all.

Also you can show your current numbers using id i'm willing to bet it comes back as 1000 for you.

How do I match any character across multiple lines in a regular expression?

I had the same problem and solved it in probably not the best way but it works. I replaced all line breaks before I did my real match:

mystring= Regex.Replace(mystring, "\r\n", "")

I am manipulating HTML so line breaks don't really matter to me in this case.

I tried all of the suggestions above with no luck, I am using .Net 3.5 FYI

There is no ViewData item of type 'IEnumerable<SelectListItem>' that has the key country

If you were using DropDownListFor like this:

@Html.DropDownListFor(m => m.SelectedItemId, Model.MySelectList)

where MySelectList in the model was a property of type SelectList, this error could be thrown if the property was null.

Avoid this by simple initializing it in constructor, like this:

public MyModel()
{
    MySelectList = new SelectList(new List<string>()); // empty list of anything...
}

I know it's not the OP's case, but this might help someone like me which had the same error due to this.

Replace all double quotes within String

String info = "Hello \"world\"!";
info = info.replace("\"", "\\\"");

String info1 = "Hello "world!";
info1 = info1.replace('"', '\"').replace("\"", "\\\"");

For the 2nd field info1, 1st replace double quotes with an escape character.

ArrayList vs List<> in C#

Another difference to add is with respect to Thread Synchronization.

ArrayList provides some thread-safety through the Synchronized property, which returns a thread-safe wrapper around the collection. The wrapper works by locking the entire collection on every add or remove operation. Therefore, each thread that is attempting to access the collection must wait for its turn to take the one lock. This is not scalable and can cause significant performance degradation for large collections.

List<T> does not provide any thread synchronization; user code must provide all synchronization when items are added or removed on multiple threads concurrently.

More info here Thread Synchronization in the .Net Framework

putting datepicker() on dynamically created elements - JQuery/JQueryUI

None of the other solutions worked for me. In my app, I'm adding the date range elements to the document using jquery and then applying datepicker to them. So none of the event solutions worked for some reason.

This is what finally worked:

$(document).on('changeDate',"#elementid", function(){
    alert('event fired');
});

Hope this helps someone because this set me back a bit.

How to resize html canvas element?

This worked for me just now:

<canvas id="c" height="100" width="100" style="border:1px solid red"></canvas>
<script>
var c = document.getElementById('c');
alert(c.height + ' ' + c.width);
c.height = 200;
c.width = 200;
alert(c.height + ' ' + c.width);
</script>

this.getClass().getClassLoader().getResource("...") and NullPointerException

When eclipse runs the test case it will look for the file in target/classes not src/test/resources. When the resource is saved eclipse should copy it from src/test/resources to target/classes if it has changed but if for some reason this has not happened then you will get this error. Check that the file exists in target/classes to see if this is the problem.

iOS 10 - Changes in asking permissions of Camera, microphone and Photo Library causing application to crash

[UPDATED privacy keys list to iOS 13 - see below]

There is a list of all Cocoa Keys that you can specify in your Info.plist file:

https://developer.apple.com/library/content/documentation/General/Reference/InfoPlistKeyReference/Articles/CocoaKeys.html

(Xcode: Target -> Info -> Custom iOS Target Properties)

iOS already required permissions to access microphone, camera, and media library earlier (iOS 6, iOS 7), but since iOS 10 app will crash if you don't provide the description why you are asking for the permission (it can't be empty).

Privacy keys with example description: cheatsheet

Source

Alternatively, you can open Info.plist as source code: source code

Source

And add privacy keys like this:

<key>NSLocationAlwaysUsageDescription</key>
<string>${PRODUCT_NAME} always location use</string>

List of all privacy keys: [UPDATED to iOS 13]

NFCReaderUsageDescription
NSAppleMusicUsageDescription
NSBluetoothAlwaysUsageDescription
NSBluetoothPeripheralUsageDescription
NSCalendarsUsageDescription
NSCameraUsageDescription
NSContactsUsageDescription
NSFaceIDUsageDescription
NSHealthShareUsageDescription
NSHealthUpdateUsageDescription
NSHomeKitUsageDescription
NSLocationAlwaysUsageDescription
NSLocationUsageDescription
NSLocationWhenInUseUsageDescription
NSMicrophoneUsageDescription
NSMotionUsageDescription
NSPhotoLibraryAddUsageDescription
NSPhotoLibraryUsageDescription
NSRemindersUsageDescription
NSSiriUsageDescription
NSSpeechRecognitionUsageDescription
NSVideoSubscriberAccountUsageDescription

Update 2019:

In the last months, two of my apps were rejected during the review because the camera usage description wasn't specifying what I do with taken photos.

I had to change the description from ${PRODUCT_NAME} need access to the camera to take a photo to ${PRODUCT_NAME} need access to the camera to update your avatar even though the app context was obvious (user tapped on the avatar).

It seems that Apple is now paying even more attention to the privacy usage descriptions, and we should explain in details why we are asking for permission.

How to check if a string contains an element from a list in Python

Check if it matches this regex:

'(\.pdf$|\.doc$|\.xls$)'

Note: if you extensions are not at the end of the url, remove the $ characters, but it does weaken it slightly

Undefined symbols for architecture i386

well i found a solution to this problem for who want to work with xCode 4. All what you have to do is importing frameworks from the SimulatorSDK folder /Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator4.3.sdk/System/Library/Frameworks

i don't know if it works when you try to test your app on a real iDevice, but i'm sure that it works on simulator.

ENJOY

Ruby: How to iterate over a range, but in set increments?

Here's another, perhaps more familiar-looking way to do it:

for i in (0..10).step(2) do
    puts i
end

Python: can't assign to literal

The left hand side of the = operator needs to be a variable. What you're doing here is telling python: "You know the number one? Set it to the inputted string.". 1 is a literal number, not a variable. 1 is always 1, you can't "set" it to something else.

A variable is like a box in which you can store a value. 1 is a value that can be stored in the variable. The input call returns a string, another value that can be stored in a variable.

Instead, use lists:

import random

namelist = []
namelist.append(input("Please enter name 1:"))  #Stored in namelist[0]
namelist.append(input('Please enter name 2:'))  #Stored in namelist[1]
namelist.append(input('Please enter name 3:'))  #Stored in namelist[2]
namelist.append(input('Please enter name 4:'))  #Stored in namelist[3]
namelist.append(input('Please enter name 5:'))  #Stored in namelist[4]

nameindex = random.randint(0, 5)
print('Well done {}. You are the winner!'.format(namelist[nameindex]))

Using a for loop, you can cut down even more:

import random

namecount = 5
namelist=[]
for i in range(0, namecount):
  namelist.append(input("Please enter name %s:" % (i+1))) #Stored in namelist[i]

nameindex = random.randint(0, namecount)
print('Well done {}. You are the winner!'.format(namelist[nameindex]))

convert json ipython notebook(.ipynb) to .py file

Jupytext allows for such a conversion on the command line, and importantly you can go back again from the script to a notebook (even an executed notebook). See here.

How to move the cursor word by word in the OS X Terminal

Hold down the Option key and click where you'd like the cursor to move

Is there a combination of "LIKE" and "IN" in SQL?

do this

WHERE something + '%' in ('bla', 'foo', 'batz')
OR '%' + something + '%' in ('tra', 'la', 'la')

or

WHERE something + '%' in (select col from table where ....)

Get the first element of each tuple in a list in Python

res_list = [x[0] for x in rows]

c.f. http://docs.python.org/3/tutorial/datastructures.html#list-comprehensions

For a discussion on why to prefer comprehensions over higher-order functions such as map, go to http://www.artima.com/weblogs/viewpost.jsp?thread=98196.

Why es6 react component works only with "export default"?

Add { } while importing and exporting: export { ... }; | import { ... } from './Template';

exportimport { ... } from './Template'

export defaultimport ... from './Template'


Here is a working example:

// ExportExample.js
import React from "react";

function DefaultExport() {
  return "This is the default export";
}

function Export1() {
  return "Export without default 1";
}

function Export2() {
  return "Export without default 2";
}

export default DefaultExport;
export { Export1, Export2 };

// App.js
import React from "react";
import DefaultExport, { Export1, Export2 } from "./ExportExample";

export default function App() {
  return (
    <>
      <strong>
        <DefaultExport />
      </strong>
      <br />
      <Export1 />
      <br />
      <Export2 />
    </>
  );
}

??Working sandbox to play around: https://codesandbox.io/s/export-import-example-react-jl839?fontsize=14&hidenavigation=1&theme=dark

PDF Blob - Pop up window not showing content

I have been struggling for days finally the solution which worked for me is given below. I had to make the window.print() for PDF in new window needs to work.

 var xhr = new XMLHttpRequest();
      xhr.open('GET', pdfUrl, true);
      xhr.responseType = 'blob';

      xhr.onload = function(e) {
        if (this['status'] == 200) {          
          var blob = new Blob([this['response']], {type: 'application/pdf'});
          var url = URL.createObjectURL(blob);
          var printWindow = window.open(url, '', 'width=800,height=500');
          printWindow.print()
        }
      };

      xhr.send();

Some notes on loading PDF & printing in a new window.

  • Loading pdf in a new window via an iframe will work, but the print will not work if url is an external url.
  • Browser pop ups must be allowed, then only it will work.
  • If you try to load iframe from external url and try window.print() you will get empty print or elements which excludes iframe. But you can trigger print manually, which will work.

Failed to resolve: com.android.support:cardview-v7:26.0.0 android

Clean your gradle from terminal

./gradlew clean

then use this code in your build.gradle section

allprojects {
    repositories {
        jcenter()
        maven {
            url "https://maven.google.com"
        }
    }
}

Make sure, your included library version is available. For your checking, you can use this link

How to manually deploy artifacts in Nexus Repository Manager OSS 3

This is implemented in Nexus since Version 3.9.0.

  • Login
  • Select Upload

enter image description here

  • Fill out form and upload Artifact

enter image description here

Maven skip tests

I had some inter-dependency with the tests in order to build the package.

The following command manage to override the need for the test artifact in order to complete the goal:

mvn -DskipTests=true  package

How to add a hook to the application context initialization event?

Since Spring 4.2 you can use @EventListener (documentation)

@Component
class MyClassWithEventListeners {

    @EventListener({ContextRefreshedEvent.class})
    void contextRefreshedEvent() {
        System.out.println("a context refreshed event happened");
    }
}

Connect multiple devices to one device via Bluetooth

This is the class where the connection is established and messages are recieved. Make sure to pair the devices before you run the application. If you want to have a slave/master connection, where each slave can only send messages to the master , and the master can broadcast messages to all slaves. You should only pair the master with each slave , but you shouldn't pair the slaves together.

    package com.example.gaby.coordinatorv1;
    import java.io.DataInputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.OutputStream;
    import java.util.ArrayList;
    import java.util.HashMap;
    import java.util.Set;
    import java.util.UUID;
    import android.bluetooth.BluetoothAdapter;
    import android.bluetooth.BluetoothDevice;
    import android.bluetooth.BluetoothServerSocket;
    import android.bluetooth.BluetoothSocket;
    import android.content.Context;
    import android.os.Bundle;
    import android.os.Handler;
    import android.os.Message;
    import android.util.Log;
    import android.widget.Toast;

    public class Piconet {


        private final static String TAG = Piconet.class.getSimpleName();

        // Name for the SDP record when creating server socket
        private static final String PICONET = "ANDROID_PICONET_BLUETOOTH";

        private final BluetoothAdapter mBluetoothAdapter;

        // String: device address
        // BluetoothSocket: socket that represent a bluetooth connection
        private HashMap<String, BluetoothSocket> mBtSockets;

        // String: device address
        // Thread: thread for connection
        private HashMap<String, Thread> mBtConnectionThreads;

        private ArrayList<UUID> mUuidList;

        private ArrayList<String> mBtDeviceAddresses;

        private Context context;


        private Handler handler = new Handler() {
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case 1:
                        Toast.makeText(context, msg.getData().getString("msg"), Toast.LENGTH_SHORT).show();
                        break;
                    default:
                        break;
                }
            };
        };

        public Piconet(Context context) {
            this.context = context;

            mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

            mBtSockets = new HashMap<String, BluetoothSocket>();
            mBtConnectionThreads = new HashMap<String, Thread>();
            mUuidList = new ArrayList<UUID>();
            mBtDeviceAddresses = new ArrayList<String>();

            // Allow up to 7 devices to connect to the server
            mUuidList.add(UUID.fromString("a60f35f0-b93a-11de-8a39-08002009c666"));
            mUuidList.add(UUID.fromString("54d1cc90-1169-11e2-892e-0800200c9a66"));
            mUuidList.add(UUID.fromString("6acffcb0-1169-11e2-892e-0800200c9a66"));
            mUuidList.add(UUID.fromString("7b977d20-1169-11e2-892e-0800200c9a66"));
            mUuidList.add(UUID.fromString("815473d0-1169-11e2-892e-0800200c9a66"));
            mUuidList.add(UUID.fromString("503c7434-bc23-11de-8a39-0800200c9a66"));
            mUuidList.add(UUID.fromString("503c7435-bc23-11de-8a39-0800200c9a66"));

            Thread connectionProvider = new Thread(new ConnectionProvider());
            connectionProvider.start();

        }



        public void startPiconet() {
            Log.d(TAG, " -- Looking devices -- ");
            // The devices must be already paired
            Set<BluetoothDevice> pairedDevices = mBluetoothAdapter
                    .getBondedDevices();
            if (pairedDevices.size() > 0) {
                for (BluetoothDevice device : pairedDevices) {
                    // X , Y and Z are the Bluetooth name (ID) for each device you want to connect to
                    if (device != null && (device.getName().equalsIgnoreCase("X") || device.getName().equalsIgnoreCase("Y")
                            || device.getName().equalsIgnoreCase("Z") || device.getName().equalsIgnoreCase("M"))) {
                        Log.d(TAG, " -- Device " + device.getName() + " found --");
                        BluetoothDevice remoteDevice = mBluetoothAdapter
                                .getRemoteDevice(device.getAddress());
                        connect(remoteDevice);
                    }
                }
            } else {
                Toast.makeText(context, "No paired devices", Toast.LENGTH_SHORT).show();
            }
        }

        private class ConnectionProvider implements Runnable {
            @Override
            public void run() {
                try {
                    for (int i=0; i<mUuidList.size(); i++) {
                        BluetoothServerSocket myServerSocket = mBluetoothAdapter
                                .listenUsingRfcommWithServiceRecord(PICONET, mUuidList.get(i));
                        Log.d(TAG, " ** Opened connection for uuid " + i + " ** ");

                        // This is a blocking call and will only return on a
                        // successful connection or an exception
                        Log.d(TAG, " ** Waiting connection for socket " + i + " ** ");
                        BluetoothSocket myBTsocket = myServerSocket.accept();
                        Log.d(TAG, " ** Socket accept for uuid " + i + " ** ");
                        try {
                            // Close the socket now that the
                            // connection has been made.
                            myServerSocket.close();
                        } catch (IOException e) {
                            Log.e(TAG, " ** IOException when trying to close serverSocket ** ");
                        }

                        if (myBTsocket != null) {
                            String address = myBTsocket.getRemoteDevice().getAddress();

                            mBtSockets.put(address, myBTsocket);
                            mBtDeviceAddresses.add(address);

                            Thread mBtConnectionThread = new Thread(new BluetoohConnection(myBTsocket));
                            mBtConnectionThread.start();

                            Log.i(TAG," ** Adding " + address + " in mBtDeviceAddresses ** ");
                            mBtConnectionThreads.put(address, mBtConnectionThread);
                        } else {
                            Log.e(TAG, " ** Can't establish connection ** ");
                        }
                    }
                } catch (IOException e) {
                    Log.e(TAG, " ** IOException in ConnectionService:ConnectionProvider ** ", e);
                }
            }
        }

        private class BluetoohConnection implements Runnable {
            private String address;

            private final InputStream mmInStream;

            public BluetoohConnection(BluetoothSocket btSocket) {

                InputStream tmpIn = null;

                try {
                    tmpIn = new DataInputStream(btSocket.getInputStream());
                } catch (IOException e) {
                    Log.e(TAG, " ** IOException on create InputStream object ** ", e);
                }
                mmInStream = tmpIn;
            }
            @Override
            public void run() {
                byte[] buffer = new byte[1];
                String message = "";
                while (true) {

                    try {
                        int readByte = mmInStream.read();
                        if (readByte == -1) {
                            Log.e(TAG, "Discarting message: " + message);
                            message = "";
                            continue;
                        }
                        buffer[0] = (byte) readByte;

                        if (readByte == 0) { // see terminateFlag on write method
                            onReceive(message);
                            message = "";
                        } else { // a message has been recieved
                            message += new String(buffer, 0, 1);
                        }
                    } catch (IOException e) {
                        Log.e(TAG, " ** disconnected ** ", e);
                    }

                    mBtDeviceAddresses.remove(address);
                    mBtSockets.remove(address);
                    mBtConnectionThreads.remove(address);
                }
            }
        }

        /**
         * @param receiveMessage
         */
        private void onReceive(String receiveMessage) {
            if (receiveMessage != null && receiveMessage.length() > 0) {
                Log.i(TAG, " $$$$ " + receiveMessage + " $$$$ ");
                Bundle bundle = new Bundle();
                bundle.putString("msg", receiveMessage);
                Message message = new Message();
                message.what = 1;
                message.setData(bundle);
                handler.sendMessage(message);
            }
        }

        /**
         * @param device
         * @param uuidToTry
         * @return
         */
        private BluetoothSocket getConnectedSocket(BluetoothDevice device, UUID uuidToTry) {
            BluetoothSocket myBtSocket;
            try {
                myBtSocket = device.createRfcommSocketToServiceRecord(uuidToTry);
                myBtSocket.connect();
                return myBtSocket;
            } catch (IOException e) {
                Log.e(TAG, "IOException in getConnectedSocket", e);
            }
            return null;
        }

        private void connect(BluetoothDevice device) {
            BluetoothSocket myBtSocket = null;
            String address = device.getAddress();
            BluetoothDevice remoteDevice = mBluetoothAdapter.getRemoteDevice(address);
            // Try to get connection through all uuids available
            for (int i = 0; i < mUuidList.size() && myBtSocket == null; i++) {
                // Try to get the socket 2 times for each uuid of the list
                for (int j = 0; j < 2 && myBtSocket == null; j++) {
                    Log.d(TAG, " ** Trying connection..." + j + " with " + device.getName() + ", uuid " + i + "...** ");
                    myBtSocket = getConnectedSocket(remoteDevice, mUuidList.get(i));
                    if (myBtSocket == null) {
                        try {
                            Thread.sleep(200);
                        } catch (InterruptedException e) {
                            Log.e(TAG, "InterruptedException in connect", e);
                        }
                    }
                }
            }
            if (myBtSocket == null) {
                Log.e(TAG, " ** Could not connect ** ");
                return;
            }
            Log.d(TAG, " ** Connection established with " + device.getName() +"! ** ");
            mBtSockets.put(address, myBtSocket);
            mBtDeviceAddresses.add(address);
            Thread mBluetoohConnectionThread = new Thread(new BluetoohConnection(myBtSocket));
            mBluetoohConnectionThread.start();
            mBtConnectionThreads.put(address, mBluetoohConnectionThread);

        }

        public void bluetoothBroadcastMessage(String message) {
            //send message to all except Id
            for (int i = 0; i < mBtDeviceAddresses.size(); i++) {
                sendMessage(mBtDeviceAddresses.get(i), message);
            }
        }

        private void sendMessage(String destination, String message) {
            BluetoothSocket myBsock = mBtSockets.get(destination);
            if (myBsock != null) {
                try {
                    OutputStream outStream = myBsock.getOutputStream();
                    final int pieceSize = 16;
                    for (int i = 0; i < message.length(); i += pieceSize) {
                        byte[] send = message.substring(i,
                                Math.min(message.length(), i + pieceSize)).getBytes();
                        outStream.write(send);
                    }
                    // we put at the end of message a character to sinalize that message
                    // was finished
                    byte[] terminateFlag = new byte[1];
                    terminateFlag[0] = 0; // ascii table value NULL (code 0)
                    outStream.write(new byte[1]);
                } catch (IOException e) {
                    Log.d(TAG, "line 278", e);
                }
            }
        }

    }

Your main activity should be as follow :

package com.example.gaby.coordinatorv1;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class MainActivity extends Activity {

    private Button discoveryButton;
    private Button messageButton;

    private Piconet piconet;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        piconet = new Piconet(getApplicationContext());

        messageButton = (Button) findViewById(R.id.messageButton);
        messageButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                piconet.bluetoothBroadcastMessage("Hello World---*Gaby Bou Tayeh*");
            }
        });

        discoveryButton = (Button) findViewById(R.id.discoveryButton);
        discoveryButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                piconet.startPiconet();
            }
        });

    }

}

And here's the XML Layout :

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >

<Button
    android:id="@+id/discoveryButton"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Discover"
    />

<Button
    android:id="@+id/messageButton"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Send message"
    />

Do not forget to add the following permissions to your Manifest File :

    <uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />

Solve error javax.mail.AuthenticationFailedException

By default Gmail account is highly secured. When we use gmail smtp from non gmail tool, email is blocked. To test in our local environment, make your gmail account less secure as

  1. Login to Gmail.
  2. Access the URL as https://www.google.com/settings/security/lesssecureapps
  3. Select "Turn on"

How to detect page zoom level in all modern browsers?

This may or may not help anyone, but I had a page I could not get to center correctly no matter what Css tricks I tried so I wrote a JQuery file call Center Page:

The problem occurred with zoom level of the browser, the page would shift based upon if you were 100%, 125%, 150%, etc.

The code below is in a JQuery file called centerpage.js.

From my page I had to link to JQuery and this file to get it work, even though my master page already had a link to JQuery.

<title>Home Page.</title>
<script src="Scripts/jquery-1.7.1.min.js"></script>
<script src="Scripts/centerpage.js"></script>

centerpage.js:

// centering page element
function centerPage() {
    // get body element
    var body = document.body;

    // if the body element exists
    if (body != null) {
        // get the clientWidth
        var clientWidth = body.clientWidth;

        // request data for centering
        var windowWidth = document.documentElement.clientWidth;
        var left = (windowWidth - bodyWidth) / 2;

        // this is a hack, but it works for me a better method is to determine the 
        // scale but for now it works for my needs
        if (left > 84) {
            // the zoom level is most likely around 150 or higher
            $('#MainBody').removeClass('body').addClass('body150');
        } else if (left < 100) {
            // the zoom level is most likely around 110 - 140
            $('#MainBody').removeClass('body').addClass('body125');
        }
    }
}


// CONTROLLING EVENTS IN jQuery
$(document).ready(function() {
    // center the page
    centerPage();
});

Also if you want to center a panel:

// centering panel
function centerPanel($panelControl) {
    // if the panel control exists
    if ($panelControl && $panelControl.length) {
        // request data for centering
        var windowWidth = document.documentElement.clientWidth;
        var windowHeight = document.documentElement.clientHeight;
        var panelHeight = $panelControl.height();
        var panelWidth = $panelControl.width();

        // centering
        $panelControl.css({
            'position': 'absolute',
            'top': (windowHeight - panelHeight) / 2,
            'left': (windowWidth - panelWidth) / 2
        });

        // only need force for IE6
        $('#backgroundPanel').css('height', windowHeight);
    }
}

What is the purpose of a plus symbol before a variable?

As explained in other answers it converts the variable to a number. Specially useful when d can be either a number or a string that evaluates to a number.

Example (using the addMonths function in the question):

addMonths(34,1,true);
addMonths("34",1,true);

then the +d will evaluate to a number in all cases. Thus avoiding the need to check for the type and take different code paths depending on whether d is a number, a function or a string that can be converted to a number.

Writing files in Node.js

fs.createWriteStream(path[,options])

options may also include a start option to allow writing data at some position past the beginning of the file. Modifying a file rather than replacing it may require a flags mode of r+ rather than the default mode w. The encoding can be any one of those accepted by Buffer.

If autoClose is set to true (default behavior) on 'error' or 'finish' the file descriptor will be closed automatically. If autoClose is false, then the file descriptor won't be closed, even if there's an error. It is the application's responsibility to close it and make sure there's no file descriptor leak.

Like ReadStream, if fd is specified, WriteStream will ignore the path argument and will use the specified file descriptor. This means that no 'open' event will be emitted. fd should be blocking; non-blocking fds should be passed to net.Socket.

If options is a string, then it specifies the encoding.

After, reading this long article. You should understand how it works. So, here's an example of createWriteStream().

/* The fs.createWriteStream() returns an (WritableStream {aka} internal.Writeable) and we want the encoding as 'utf'-8 */
/* The WriteableStream has the method write() */
fs.createWriteStream('out.txt', 'utf-8')
.write('hello world');

append option to select menu?

$(document).ready(function(){

    $('#mySelect').append("<option>BMW</option>")

})

Can "list_display" in a Django ModelAdmin display attributes of ForeignKey fields?

You can show whatever you want in list display by using a callable. It would look like this:


def book_author(object):
  return object.book.author

class PersonAdmin(admin.ModelAdmin):
  list_display = [book_author,]

MySQL show current connection info

You can use the status command in MySQL client.

mysql> status;
--------------
mysql  Ver 14.14 Distrib 5.5.8, for Win32 (x86)

Connection id:          1
Current database:       test
Current user:           ODBC@localhost
SSL:                    Not in use
Using delimiter:        ;
Server version:         5.5.8 MySQL Community Server (GPL)
Protocol version:       10
Connection:             localhost via TCP/IP
Server characterset:    latin1
Db     characterset:    latin1
Client characterset:    gbk
Conn.  characterset:    gbk
TCP port:               3306
Uptime:                 7 min 16 sec

Threads: 1  Questions: 21  Slow queries: 0  Opens: 33  Flush tables: 1  Open tables: 26  Queries per second avg: 0.48
--------------

mysql>

CSS technique for a horizontal line with words in the middle

Horizontal and Vertical line with words in the middle

_x000D_
_x000D_
.box{_x000D_
    background-image: url("https://i.stack.imgur.com/N39wV.jpg");_x000D_
    width: 350px;_x000D_
    padding: 10px;_x000D_
}_x000D_
_x000D_
/*begin first box*/_x000D_
.first{_x000D_
    width: 300px;_x000D_
    height: 100px;_x000D_
    margin: 10px;_x000D_
    border-width: 0 2px 0 2px;_x000D_
    border-color: red;_x000D_
    border-style: solid;_x000D_
    position: relative;_x000D_
}_x000D_
_x000D_
.first span {_x000D_
    position: absolute;_x000D_
    display: flex;_x000D_
    right: 0;_x000D_
    left: 0;_x000D_
    align-items: center;_x000D_
}_x000D_
.first .foo{_x000D_
    top: -8px;_x000D_
}_x000D_
.first .bar{_x000D_
    bottom: -8.5px;_x000D_
}_x000D_
.first span:before{_x000D_
    margin-right: 15px;_x000D_
}_x000D_
.first span:after {_x000D_
    margin-left: 15px;_x000D_
}_x000D_
.first span:before , .first span:after {_x000D_
    content: ' ';_x000D_
    height: 2px;_x000D_
    background: red;_x000D_
    display: block;_x000D_
    width: 50%;_x000D_
}_x000D_
_x000D_
_x000D_
/*begin second box*/_x000D_
.second{_x000D_
    width: 300px;_x000D_
    height: 100px;_x000D_
    margin: 10px;_x000D_
    border-width: 2px 0 2px 0;_x000D_
    border-color: red;_x000D_
    border-style: solid;_x000D_
    position: relative;_x000D_
}_x000D_
_x000D_
.second span {_x000D_
    position: absolute;_x000D_
    top: 0;_x000D_
    bottom: 0;_x000D_
    display: flex;_x000D_
    flex-direction: column;_x000D_
    align-items: center;_x000D_
}_x000D_
.second .foo{_x000D_
    left: -15px;_x000D_
}_x000D_
.second .bar{_x000D_
    right: -15.5px;_x000D_
}_x000D_
.second span:before{_x000D_
    margin-bottom: 15px;_x000D_
}_x000D_
.second span:after {_x000D_
    margin-top: 15px;_x000D_
}_x000D_
.second span:before , .second span:after {_x000D_
    content: ' ';_x000D_
    width: 2px;_x000D_
    background: red;_x000D_
    display: block;_x000D_
    height: 50%;_x000D_
}
_x000D_
<div class="box">_x000D_
    <div class="first">_x000D_
        <span class="foo">FOO</span>_x000D_
        <span class="bar">BAR</span>_x000D_
    </div>_x000D_
_x000D_
   <br>_x000D_
_x000D_
    <div class="second">_x000D_
        <span class="foo">FOO</span>_x000D_
        <span class="bar">BAR</span>_x000D_
    </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

This is also answered in https://stackoverflow.com/a/57279326/6569224

Grouping functions (tapply, by, aggregate) and the *apply family

There are lots of great answers which discuss differences in the use cases for each function. None of the answer discuss the differences in performance. That is reasonable cause various functions expects various input and produces various output, yet most of them have a general common objective to evaluate by series/groups. My answer is going to focus on performance. Due to above the input creation from the vectors is included in the timing, also the apply function is not measured.

I have tested two different functions sum and length at once. Volume tested is 50M on input and 50K on output. I have also included two currently popular packages which were not widely used at the time when question was asked, data.table and dplyr. Both are definitely worth to look if you are aiming for good performance.

library(dplyr)
library(data.table)
set.seed(123)
n = 5e7
k = 5e5
x = runif(n)
grp = sample(k, n, TRUE)

timing = list()

# sapply
timing[["sapply"]] = system.time({
    lt = split(x, grp)
    r.sapply = sapply(lt, function(x) list(sum(x), length(x)), simplify = FALSE)
})

# lapply
timing[["lapply"]] = system.time({
    lt = split(x, grp)
    r.lapply = lapply(lt, function(x) list(sum(x), length(x)))
})

# tapply
timing[["tapply"]] = system.time(
    r.tapply <- tapply(x, list(grp), function(x) list(sum(x), length(x)))
)

# by
timing[["by"]] = system.time(
    r.by <- by(x, list(grp), function(x) list(sum(x), length(x)), simplify = FALSE)
)

# aggregate
timing[["aggregate"]] = system.time(
    r.aggregate <- aggregate(x, list(grp), function(x) list(sum(x), length(x)), simplify = FALSE)
)

# dplyr
timing[["dplyr"]] = system.time({
    df = data_frame(x, grp)
    r.dplyr = summarise(group_by(df, grp), sum(x), n())
})

# data.table
timing[["data.table"]] = system.time({
    dt = setnames(setDT(list(x, grp)), c("x","grp"))
    r.data.table = dt[, .(sum(x), .N), grp]
})

# all output size match to group count
sapply(list(sapply=r.sapply, lapply=r.lapply, tapply=r.tapply, by=r.by, aggregate=r.aggregate, dplyr=r.dplyr, data.table=r.data.table), 
       function(x) (if(is.data.frame(x)) nrow else length)(x)==k)
#    sapply     lapply     tapply         by  aggregate      dplyr data.table 
#      TRUE       TRUE       TRUE       TRUE       TRUE       TRUE       TRUE 

# print timings
as.data.table(sapply(timing, `[[`, "elapsed"), keep.rownames = TRUE
              )[,.(fun = V1, elapsed = V2)
                ][order(-elapsed)]
#          fun elapsed
#1:  aggregate 109.139
#2:         by  25.738
#3:      dplyr  18.978
#4:     tapply  17.006
#5:     lapply  11.524
#6:     sapply  11.326
#7: data.table   2.686

Flatten List in LINQ

With query syntax:

var values =
from inner in outer
from value in inner
select value;

Run reg command in cmd (bat file)?

In command line it's better to use REG tool rather than REGEDIT:

REG IMPORT yourfile.reg

REG is designed for console mode, while REGEDIT is for graphical mode. This is why running regedit.exe /S yourfile.reg is a bad idea, since you will not be notified if the there's an error, whereas REG Tool will prompt:

>  REG IMPORT missing_file.reg

ERROR: Error opening the file. There may be a disk or file system error.

>  %windir%\System32\reg.exe /?

REG Operation [Parameter List]

  Operation  [ QUERY   | ADD    | DELETE  | COPY    |
               SAVE    | LOAD   | UNLOAD  | RESTORE |
               COMPARE | EXPORT | IMPORT  | FLAGS ]

Return Code: (Except for REG COMPARE)

  0 - Successful
  1 - Failed

For help on a specific operation type:

  REG Operation /?

Examples:

  REG QUERY /?
  REG ADD /?
  REG DELETE /?
  REG COPY /?
  REG SAVE /?
  REG RESTORE /?
  REG LOAD /?
  REG UNLOAD /?
  REG COMPARE /?
  REG EXPORT /?
  REG IMPORT /?
  REG FLAGS /?

Deserialize JSON into C# dynamic object?

The object you want DynamicJSONObject is included in the System.Web.Helpers.dll from the ASP.NET Web Pages package, which is part of WebMatrix.

Android Studio says "cannot resolve symbol" but project compiles

When i lived to this problem(red color codes but they work correctly) in my project;

As first, i made it that (File -> Indicate Cashes) --> (Invalidate and Restart).

As last, i resync my build.gradle file in my app. After problem was resolved.

How to use Google Translate API in my Java application?

Use java-google-translate-text-to-speech instead of Google Translate API v2 Java.

About java-google-translate-text-to-speech

Api unofficial with the main features of Google Translate in Java.

Easy to use!

It also provide text to speech api. If you want to translate the text "Hello!" in Romanian just write:

Translator translate = Translator.getInstance();
String text = translate.translate("Hello!", Language.ENGLISH, Language.ROMANIAN);
System.out.println(text); // "Buna ziua!" 

It's free!

As @r0ast3d correctly said:

Important: Google Translate API v2 is now available as a paid service. The courtesy limit for existing Translate API v2 projects created prior to August 24, 2011 will be reduced to zero on December 1, 2011. In addition, the number of requests your application can make per day will be limited.

This is correct: just see the official page:

Google Translate API is available as a paid service. See the Pricing and FAQ pages for details.

BUT, java-google-translate-text-to-speech is FREE!

Example!

I've created a sample application that demonstrates that this works. Try it here: https://github.com/IonicaBizau/text-to-speech

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

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

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

To prevent a memory leak, the JDBC Driver has been forcibly unregistered

Since version 6.0.24, Tomcat ships with a memory leak detection feature, which in turn can lead to this kind of warning messages when there's a JDBC 4.0 compatible driver in the webapp's /WEB-INF/lib which auto-registers itself during webapp's startup using the ServiceLoader API, but which did not auto-deregister itself during webapp's shutdown. This message is purely informal, Tomcat has already taken the memory leak prevention action accordingly.

What can you do?

  1. Ignore those warnings. Tomcat is doing its job right. The actual bug is in someone else's code (the JDBC driver in question), not in yours. Be happy that Tomcat did its job properly and wait until the JDBC driver vendor get it fixed so that you can upgrade the driver. On the other hand, you aren't supposed to drop a JDBC driver in webapp's /WEB-INF/lib, but only in server's /lib. If you still keep it in webapp's /WEB-INF/lib, then you should manually register and deregister it using a ServletContextListener.

  2. Downgrade to Tomcat 6.0.23 or older so that you will not be bothered with those warnings. But it will silently keep leaking memory. Not sure if that's good to know after all. Those kind of memory leaks are one of the major causes behind OutOfMemoryError issues during Tomcat hotdeployments.

  3. Move the JDBC driver to Tomcat's /lib folder and have a connection pooled datasource to manage the driver. Note that Tomcat's builtin DBCP does not deregister drivers properly on close. See also bug DBCP-322 which is closed as WONTFIX. You would rather like to replace DBCP by another connection pool which is doing its job better then DBCP. For example HikariCP or perhaps Tomcat JDBC Pool.

change <audio> src with javascript

Try this:

Replace:

audio.load();

with:

audio.play();

Remove insignificant trailing zeros from a number?

I needed to remove any trailing zeros but keep at least 2 decimals, including any zeros.
The numbers I'm working with are 6 decimal number strings, generated by .toFixed(6).

Expected Result:

var numstra = 12345.000010 // should return 12345.00001
var numstrb = 12345.100000 // should return 12345.10
var numstrc = 12345.000000 // should return 12345.00
var numstrd = 12345.123000 // should return 12345.123

Solution:

var numstr = 12345.100000

while (numstr[numstr.length-1] === "0") {           
    numstr = numstr.slice(0, -1)
    if (numstr[numstr.length-1] !== "0") {break;}
    if (numstr[numstr.length-3] === ".") {break;}
}

console.log(numstr) // 12345.10

Logic:

Run loop function if string last character is a zero.
Remove the last character and update the string variable.
If updated string last character is not a zero, end loop.
If updated string third to last character is a floating point, end loop.

ldconfig error: is not a symbolic link

Solved, at least at the point of the question.

I searched in the web before asking, an there were no conclusive solution, the reason why this error is: lib1.so and lib2.so are not OK, very probably where not compiled for a 64 PC, but for a 32 bits machine otherwise lib3.so is a 64 bits lib. At least that is my hipothesis.

VERY unfortunately ldconfig doesn't give a clean error message informing that it could not load the library, it only pumps:

ldconfig: /folder_where_the_wicked_lib_is/ is not a symbolic link

I solved this when I removed the libs not found by ldd over the binary. Now it's easier that I know where lies the problem.

My ld version: GNU ld version 2.20.51, and I don't know if a most recent version has a better message for its users.

Thanks.

Can I use DIV class and ID together in CSS?

You can also use as many classes as needed on a tag, but an id must be unique to the document. Also be careful of using too many divs, when another more semantic tag can do the job.

<p id="unique" class="x y z">Styled paragraph</p>

angularjs ng-style: background-image isn't working

This worked for me, curly braces are not required.

ng-style="{'background-image':'url(../../../app/img/notification/'+notification.icon+'.png)'}"

notification.icon here is scope variable.

Using Camera in the Android emulator

Some elaboration, in the hope of clarifying what has already been said:

As stated above, Webcams are supported natively in the current SDK, but only on recent android versions (4.0 and higher)

Webcam detection is automatic where present. In 4.0.3, the camera defaults to the front-facing camera so a lot of applications (especially pre-2.3 applications, which can only fetch the default camera, i.e. the back-facing one) will still show you the old checkerbox-with-moving-square stand-in instead.

I think some more info is available in the following post: Camera on Android Eclipse emulator:

Or at least, that's the most information I've been able to find--aside from the brief, uninformative statements in the release notes for the SDK tools.

how to display a javascript var in html body

You can do the same on document ready event like below

<script>
$(document).ready(function(){
 var number = 112;
    $("yourClass/Element/id...").html(number);
// $("yourClass/Element/id...").text(number);
});
</script>

or you can simply do it using document.write(number);.

Powershell v3 Invoke-WebRequest HTTPS error

An alternative implementation in pure (without Add-Type of source):

#requires -Version 5
#requires -PSEdition Desktop

class TrustAllCertsPolicy : System.Net.ICertificatePolicy {
    [bool] CheckValidationResult([System.Net.ServicePoint] $a,
                                 [System.Security.Cryptography.X509Certificates.X509Certificate] $b,
                                 [System.Net.WebRequest] $c,
                                 [int] $d) {
        return $true
    }
}
[System.Net.ServicePointManager]::CertificatePolicy = [TrustAllCertsPolicy]::new()

Delete last commit in bitbucket

In the first place, if you are working with other people on the same code repository, you should not delete a commit since when you force the update on the repository it will leave the local repositories of your coworkers in an illegal state (e.g. if they made commits after the one you deleted, those commits will be invalid since they were based on a now non-existent commit).

Said that, what you can do is revert the commit. This procedure is done differently (different commands) depending on the CVS you're using:

On git:

git revert <commit>

On mercurial:

hg backout <REV>

EDIT: The revert operation creates a new commit that does the opposite than the reverted commit (e.g. if the original commit added a line, the revert commit deletes that line), effectively removing the changes of the undesired commit without rewriting the repository history.

Can't append <script> element

This works:

$('body').append($("<script>alert('Hi!');<\/script>")[0]);

It seems like jQuery is doing something clever with scripts so you need to append the html element rather than jQuery object.

List append() in for loop

The list.append function does not return any value(but None), it just adds the value to the list you are using to call that method.

In the first loop round you will assign None (because the no-return of append) to a, then in the second round it will try to call a.append, as a is None it will raise the Exception you are seeing

You just need to change it to:

a=[]
for i in range(5):    
    a.append(i)
print(a)
# [0, 1, 2, 3, 4]

list.append is what is called a mutating or destructive method, i.e. it will destroy or mutate the previous object into a new one(or a new state).

If you would like to create a new list based in one list without destroying or mutating it you can do something like this:

a=['a', 'b', 'c']
result = a + ['d']

print result
# ['a', 'b', 'c', 'd']

print a
# ['a', 'b', 'c']

As a corollary only, you can mimic the append method by doing the following:

a=['a', 'b', 'c']
a = a + ['d']

print a
# ['a', 'b', 'c', 'd']

How can I define fieldset border color?

It works for me when I define the complete border property. (JSFiddle here)

.field_set{
 border: 1px #F00 solid;
}?

the reason is the border-style that is set to none by default for fieldsets. You need to override that as well.

Understanding `scale` in R

This is a late addition but I was looking for information on the scale function myself and though it might help somebody else as well.

To modify the response from Ricardo Saporta a little bit.
Scaling is not done using standard deviation, at least not in version 3.6.1 of R, I base this on "Becker, R. (2018). The new S language. CRC Press." and my own experimentation.

X.man.scaled <- X/sqrt(sum(X^2)/(length(X)-1))
X.aut.scaled <- scale(X, center = F)

The result of these rows are exactly the same, I show it without centering because of simplicity.

I would respond in a comment but did not have enough reputation.

surface plots in matplotlib

I just came across this same problem. I have evenly spaced data that is in 3 1-D arrays instead of the 2-D arrays that matplotlib's plot_surface wants. My data happened to be in a pandas.DataFrame so here is the matplotlib.plot_surface example with the modifications to plot 3 1-D arrays.

from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm
from matplotlib.ticker import LinearLocator, FormatStrFormatter
import matplotlib.pyplot as plt
import numpy as np

X = np.arange(-5, 5, 0.25)
Y = np.arange(-5, 5, 0.25)
X, Y = np.meshgrid(X, Y)
R = np.sqrt(X**2 + Y**2)
Z = np.sin(R)

fig = plt.figure()
ax = fig.gca(projection='3d')
surf = ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=cm.coolwarm,
    linewidth=0, antialiased=False)
ax.set_zlim(-1.01, 1.01)

ax.zaxis.set_major_locator(LinearLocator(10))
ax.zaxis.set_major_formatter(FormatStrFormatter('%.02f'))

fig.colorbar(surf, shrink=0.5, aspect=5)
plt.title('Original Code')

That is the original example. Adding this next bit on creates the same plot from 3 1-D arrays.

# ~~~~ MODIFICATION TO EXAMPLE BEGINS HERE ~~~~ #
import pandas as pd
from scipy.interpolate import griddata
# create 1D-arrays from the 2D-arrays
x = X.reshape(1600)
y = Y.reshape(1600)
z = Z.reshape(1600)
xyz = {'x': x, 'y': y, 'z': z}

# put the data into a pandas DataFrame (this is what my data looks like)
df = pd.DataFrame(xyz, index=range(len(xyz['x']))) 

# re-create the 2D-arrays
x1 = np.linspace(df['x'].min(), df['x'].max(), len(df['x'].unique()))
y1 = np.linspace(df['y'].min(), df['y'].max(), len(df['y'].unique()))
x2, y2 = np.meshgrid(x1, y1)
z2 = griddata((df['x'], df['y']), df['z'], (x2, y2), method='cubic')

fig = plt.figure()
ax = fig.gca(projection='3d')
surf = ax.plot_surface(x2, y2, z2, rstride=1, cstride=1, cmap=cm.coolwarm,
    linewidth=0, antialiased=False)
ax.set_zlim(-1.01, 1.01)

ax.zaxis.set_major_locator(LinearLocator(10))
ax.zaxis.set_major_formatter(FormatStrFormatter('%.02f'))

fig.colorbar(surf, shrink=0.5, aspect=5)
plt.title('Meshgrid Created from 3 1D Arrays')
# ~~~~ MODIFICATION TO EXAMPLE ENDS HERE ~~~~ #

plt.show()

Here are the resulting figures:

enter image description here enter image description here

Virtual Memory Usage from Java under Linux, too much memory used

One way of reducing the heap sice of a system with limited resources may be to play around with the -XX:MaxHeapFreeRatio variable. This is usually set to 70, and is the maximum percentage of the heap that is free before the GC shrinks it. Setting it to a lower value, and you will see in eg the jvisualvm profiler that a smaller heap sice is usually used for your program.

EDIT: To set small values for -XX:MaxHeapFreeRatio you must also set -XX:MinHeapFreeRatio Eg

java -XX:MinHeapFreeRatio=10 -XX:MaxHeapFreeRatio=25 HelloWorld

EDIT2: Added an example for a real application that starts and does the same task, one with default parameters and one with 10 and 25 as parameters. I didn't notice any real speed difference, although java in theory should use more time to increase the heap in the latter example.

Default parameters

At the end, max heap is 905, used heap is 378

MinHeap 10, MaxHeap 25

At the end, max heap is 722, used heap is 378

This actually have some inpact, as our application runs on a remote desktop server, and many users may run it at once.

How to "select distinct" across multiple data frame columns in pandas?

To solve a similar problem, I'm using groupby:

print(f"Distinct entries: {len(df.groupby(['col1', 'col2']))}")

Whether that's appropriate will depend on what you want to do with the result, though (in my case, I just wanted the equivalent of COUNT DISTINCT as shown).

Automatically resize images with browser size using CSS

This may be too simplistic of an answer (I am still new here), but what I have done in the past to remedy this situation is figured out the percentage of the screen I would like the image to take up. For example, there is one webpage I am working on where the logo must take up 30% of the screen size to look best. I played around and finally tried this code and it has worked for me thus far:

img {
width:30%;
height:auto;
}

That being said, this will change all of your images to be 30% of the screen size at all times. To get around this issue, simply make this a class and apply it to the image that you desire to be at 30% directly. Here is an example of the code I wrote to accomplish this on the aforementioned site:

the CSS portion:

.logo {
position:absolute;
right:25%;
top:0px;
width:30%;
height:auto;
}

the HTML portion:

<img src="logo_001_002.png" class="logo">

Alternatively, you could place ever image you hope to automatically resize into a div of its own and use the class tag option on each div (creating now class tags whenever needed), but I feel like that would cause a lot of extra work eventually. But, if the site calls for it: the site calls for it.

Hopefully this helps. Have a great day!

Include files from parent or other directory

Here's something I wrote with that problem in mind:

<?
function absolute_include($file)
         {
         /*
         $file is the file url relative to the root of your site.
         Yourdomain.com/folder/file.inc would be passed as
         "folder/file.inc"
         */

         $folder_depth = substr_count($_SERVER["PHP_SELF"] , "/");

         if($folder_depth == false)
            $folder_depth = 1;

         include(str_repeat("../", $folder_depth - 1) . $file);
         }
?>

hope it helps.

How to declare and display a variable in Oracle

If you are using pl/sql then the following code should work :

set server output on -- to retrieve and display a buffer

DECLARE

    v_text VARCHAR2(10); -- declare
BEGIN

    v_text := 'Hello';  --assign
    dbms_output.Put_line(v_text); --display
END; 

/

-- this must be use to execute pl/sql script

ReactJS - How to use comments?

This is how.

Valid:

...
render() {

  return (
    <p>
       {/* This is a comment, one line */}

       {// This is a block 
        // yoohoo
        // ...
       }

       {/* This is a block 
         yoohoo
         ...
         */
       }
    </p>
  )

}
...

Invalid:

...
render() {

  return (
    <p>
       {// This is not a comment! oops! }

       {//
        Invalid comment
       //}
    </p>
  )

}
...

How to free memory in Java?

Java uses managed memory, so the only way you can allocate memory is by using the new operator, and the only way you can deallocate memory is by relying on the garbage collector.

This memory management whitepaper (PDF) may help explain what's going on.

You can also call System.gc() to suggest that the garbage collector run immediately. However, the Java Runtime makes the final decision, not your code.

According to the Java documentation,

Calling the gc method suggests that the Java Virtual Machine expend effort toward recycling unused objects in order to make the memory they currently occupy available for quick reuse. When control returns from the method call, the Java Virtual Machine has made a best effort to reclaim space from all discarded objects.

How can I enable auto complete support in Notepad++?

Open Notepad++ and Settings -> Preferences -> Auto-Completion -> Check the Auto-insert options you want. this link will help alot: http://docs.notepad-plus-plus.org/index.php/Auto_Completion

how get yesterday and tomorrow datetime in c#

You can find this info right in the API reference.

var today = DateTime.Today;
var tomorrow = today.AddDays(1);
var yesterday = today.AddDays(-1);

How can I solve "Either the parameter @objname is ambiguous or the claimed @objtype (COLUMN) is wrong."?

I ran into this today and got it to work with:

EXECUTE sp_rename N'dbo.table_name.original_field_name', N'new_field_name', 'COLUMN' 

To get this syntax, I followed Martin Smith's advice above - open up the table in design view, rename the column and then click table designer | generate change script. This produced the script below which does the renaming in two steps:

/* To prevent any potential data loss issues, you should review this script in
   detail before running it outside the context of the database designer.*/
BEGIN TRANSACTION
SET QUOTED_IDENTIFIER ON
SET ARITHABORT ON
SET NUMERIC_ROUNDABORT OFF
SET CONCAT_NULL_YIELDS_NULL ON
SET ANSI_NULLS ON
SET ANSI_PADDING ON
SET ANSI_WARNINGS ON
COMMIT
BEGIN TRANSACTION
GO
EXECUTE sp_rename N'dbo.table_name.original_field_name', N'Tmp_new_field_name_1', COLUMN' 
GO
EXECUTE sp_rename N'dbo.table_name.Tmp_new_field_name_1', N'new_field_name', 'COLUMN' 
GO
ALTER TABLE dbo.table_name SET (LOCK_ESCALATION = TABLE)
GO
COMMIT

Generate war file from tomcat webapp folder

Its just like creating a WAR file of your project, you can do it in several ways (from Eclipse, command line, maven).

If you want to do from command line, the command is

jar -cvf my_web_app.war * 

Which means, "compress everything in this directory into a file named my_web_app.war" (c=create, v=verbose, f=file)

SVN Commit failed, access forbidden

As a new user to these two software packages, I experienced the exact same problem. As was also discovered above, my solution was to use the same case letters as is in the Repository path.

Here's a tip that I find helpful: In VisualSVN, you can right click on the path, then click "Copy URL to Clipboard" for pasting in Tortoise to be sure that the path is the identical case.

php: catch exception and continue execution, is it possible?

Sure:

try {
   throw new Exception('Something bad');
} catch (Exception $e) {
    // Do nothing
}

You might want to go have a read of the PHP documentation on Exceptions.

Change a web.config programmatically with C# (.NET)

Configuration config = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~");
ConnectionStringsSection section = config.GetSection("connectionStrings") as ConnectionStringsSection;
//section.SectionInformation.UnprotectSection();
section.SectionInformation.ProtectSection("DataProtectionConfigurationProvider");
config.Save();

How can I add "href" attribute to a link dynamically using JavaScript?

var a = document.getElementById('yourlinkId'); //or grab it by tagname etc
a.href = "somelink url"

Converting a datetime string to timestamp in Javascript

Seems like the problem is with the date format.

 var d = "17-09-2013 10:08",
 dArr = d.split('-'),
 ts = new Date(dArr[1] + "-" + dArr[0] + "-" + dArr[2]).getTime(); // 1379392680000

Preferred method to store PHP arrays (json_encode vs serialize)

I've written a blogpost about this subject: "Cache a large array: JSON, serialize or var_export?". In this post it is shown that serialize is the best choice for small to large sized arrays. For very large arrays (> 70MB) JSON is the better choice.

multiple figure in latex with captions

Look at the Subfloats section of http://en.wikibooks.org/wiki/LaTeX/Floats,_Figures_and_Captions.

\begin{figure}[htp]
  \centering
  \label{figur}\caption{equation...}

  \subfloat[Subcaption 1]{\label{figur:1}\includegraphics[width=60mm]{explicit3185.eps}}
  \subfloat[Subcaption 2]{\label{figur:2}\includegraphics[width=60mm]{explicit3183.eps}}
  \\
  \subfloat[Subcaption 3]{\label{figur:3}\includegraphics[width=60mm]{explicit1501.eps}}
  \subfloat[Subcaption 4]{\label{figur:4}\includegraphics[width=60mm]{explicit23185.eps}}
  \\
  \subfloat[Subcaption 5]{\label{figur:5}\includegraphics[width=60mm]{explicit23183.eps}}
  \subfloat[Subcaption 6]{\label{figur:6}\includegraphics[width=60mm]{explicit21501.eps}}

\end{figure}

Finding the average of a list

Why would you use reduce() for this when Python has a perfectly cromulent sum() function?

print sum(l) / float(len(l))

(The float() is necessary to force Python to do a floating-point division.)

Printing newlines with print() in R

You can also use a combination of cat and paste0

cat(paste0("File not supplied.\n", "Usage: ./program F=filename"))

I find this to be more useful when incorporating variables into the printout. For example:

file <- "myfile.txt"
cat(paste0("File not supplied.\n", "Usage: ./program F=", file))

How to get the position of a character in Python?

Just for completion, in the case I want to find the extension in a file name in order to check it, I need to find the last '.', in this case use rfind:

path = 'toto.titi.tata..xls'
path.find('.')
4
path.rfind('.')
15

in my case, I use the following, which works whatever the complete file name is:

filename_without_extension = complete_name[:complete_name.rfind('.')]

Embed a PowerPoint presentation into HTML

Google Docs can serve up PowerPoint (and PDF) documents in it's document viewer. You don't have to sign up for Google Docs, just upload it to your website, and call it from your page:

<iframe src="//docs.google.com/gview?url=https://www.yourwebsite.com/powerpoint.ppt&embedded=true" style="width:600px; height:500px;" frameborder="0"></iframe>

How to extract custom header value in Web API message handler?

Try something like this:

IEnumerable<string> headerValues = request.Headers.GetValues("MyCustomID");
var id = headerValues.FirstOrDefault();

There's also a TryGetValues method on Headers you can use if you're not always guaranteed to have access to the header.

How to remove a file from the index in git?

Depending on your workflow, this may be the kind of thing that you need rarely enough that there's little point in trying to figure out a command-line solution (unless you happen to be working without a graphical interface for some reason).

Just use one of the GUI-based tools that support index management, for example:

  • git gui <-- uses the Tk windowing framework -- similar style to gitk
  • git cola <-- a more modern-style GUI interface

These let you move files in and out of the index by point-and-click. They even have support for selecting and moving portions of a file (individual changes) to and from the index.


How about a different perspective: If you mess up while using one of the suggested, rather cryptic, commands:

  • git rm --cached [file]
  • git reset HEAD <file>

...you stand a real chance of losing data -- or at least making it hard to find. Unless you really need to do this with very high frequency, using a GUI tool is likely to be safer.


Working without the index

Based on the comments and votes, I've come to realize that a lot of people use the index all the time. I don't. Here's how:

  • Commit my entire working copy (the typical case): git commit -a
  • Commit just a few files: git commit (list of files)
  • Commit all but a few modified files: git commit -a then amend via git gui
  • Graphically review all changes to working copy: git difftool --dir-diff --tool=meld

ReactJS call parent method

React 16+

Child Component

import React from 'react'

class ChildComponent extends React.Component
{
    constructor(props){
        super(props);       
    }

    render()
    {
        return <div>
            <button onClick={()=>this.props.greetChild('child')}>Call parent Component</button>
        </div>
    }
}

export default ChildComponent;

Parent Component

import React from "react";
import ChildComponent from "./childComponent";

class MasterComponent extends React.Component
{
    constructor(props)
    {
        super(props);
        this.state={
            master:'master',
            message:''
        }
        this.greetHandler=this.greetHandler.bind(this);
    }

    greetHandler(childName){
        if(typeof(childName)=='object')
        {
            this.setState({            
                message:`this is ${this.state.master}`
            });
        }
        else
        {
            this.setState({            
                message:`this is ${childName}`
            });
        }

    }

    render()
    {
        return <div>
           <p> {this.state.message}</p>
            <button onClick={this.greetHandler}>Click Me</button>
            <ChildComponent greetChild={this.greetHandler}></ChildComponent>
        </div>
    }
}
export default  MasterComponent;

How to set variables in HIVE scripts

Most of the answers here have suggested to either use hiveconf or hivevar namespace to store the variable. And all those answers are right. However, there is one more namespace.

There are total three namespaces available for holding variables.

  1. hiveconf - hive started with this, all the hive configuration is stored as part of this conf. Initially, variable substitution was not part of hive and when it got introduced, all the user-defined variables were stored as part of this as well. Which is definitely not a good idea. So two more namespaces were created.
  2. hivevar: To store user variables
  3. system: To store system variables.

And so if you are storing a variable as part of a query (i.e. date or product_number) you should use hivevar namespace and not hiveconf namespace.

And this is how it works.

hiveconf is still the default namespace, so if you don't provide any namespace it will store your variable in hiveconf namespace.

However, when it comes to referring a variable, it's not true. By default it refers to hivevar namespace. Confusing, right? It can become clearer with the following example.

If you do not provide namespace as mentioned below, variable var will be stored in hiveconf namespace.

set var="default_namespace";

So, to access this you need to specify hiveconf namespace

select ${hiveconf:var};

And if you do not provide namespace it will give you an error as mentioned below, reason being that by default if you try to access a variable it checks in hivevar namespace only. And in hivevar there is no variable named var

select ${var}; 

We have explicitly provided hivevar namespace

set hivevar:var="hivevar_namespace";

as we are providing the namespace this will work.

select ${hivevar:var}; 

And as default, workspace used during referring a variable is hivevar, the following will work too.

select ${var};

Difference in System. exit(0) , System.exit(-1), System.exit(1 ) in Java

exit(0) generally used to indicate successful termination. exit(1) or exit(-1) or any other non-zero value indicates unsuccessful termination in general.

'git' is not recognized as an internal or external command

;C:\Program Files (x86)\Git\bin;C:\Program Files (x86)\Git\cmd

add above path in environment variables

note: path may differ but you should add both bin and cmd

How do I implement interfaces in python?

As mentioned by other here:

Interfaces are not necessary in Python. This is because Python has proper multiple inheritance, and also ducktyping, which means that the places where you must have interfaces in Java, you don't have to have them in Python.

That said, there are still several uses for interfaces. Some of them are covered by Pythons Abstract Base Classes, introduced in Python 2.6. They are useful, if you want to make base classes that cannot be instantiated, but provide a specific interface or part of an implementation.

Another usage is if you somehow want to specify that an object implements a specific interface, and you can use ABC's for that too by subclassing from them. Another way is zope.interface, a module that is a part of the Zope Component Architecture, a really awesomely cool component framework. Here you don't subclass from the interfaces, but instead mark classes (or even instances) as implementing an interface. This can also be used to look up components from a component registry. Supercool!

php: check if an array has duplicates

$duplicate = false;

 if(count(array) != count(array_unique(array))){
   $duplicate = true;
}

Read a zipped file as a pandas DataFrame

I think you want to open the ZipFile, which returns a file-like object, rather than read:

In [11]: crime2013 = pd.read_csv(z.open('crime_incidents_2013_CSV.csv'))

In [12]: crime2013
Out[12]:
<class 'pandas.core.frame.DataFrame'>
Int64Index: 24567 entries, 0 to 24566
Data columns (total 15 columns):
CCN                            24567  non-null values
REPORTDATETIME                 24567  non-null values
SHIFT                          24567  non-null values
OFFENSE                        24567  non-null values
METHOD                         24567  non-null values
LASTMODIFIEDDATE               24567  non-null values
BLOCKSITEADDRESS               24567  non-null values
BLOCKXCOORD                    24567  non-null values
BLOCKYCOORD                    24567  non-null values
WARD                           24563  non-null values
ANC                            24567  non-null values
DISTRICT                       24567  non-null values
PSA                            24567  non-null values
NEIGHBORHOODCLUSTER            24263  non-null values
BUSINESSIMPROVEMENTDISTRICT    3613  non-null values
dtypes: float64(4), int64(1), object(10)

How to globally replace a forward slash in a JavaScript string?

You need to wrap the forward slash to avoid cross browser issues or //commenting out.

str = 'this/that and/if';

var newstr = str.replace(/[/]/g, 'ForwardSlash');

How to access site through IP address when website is on a shared host?

According with the HTTP/1.1 standard, the shared IP hosted site can be accessed by a GET request with the IP as URL and a header of the host.

Here there are two examples(wget and curl): $ wget --header 'Host:somerandomservice.com' http://67.225.235.59 $ curl --header 'Host:somerandomservice.com' http://67.225.235.59

Resources:

https://en.wikipedia.org/wiki/Shared_web_hosting_service

http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.23

Sending multipart/formdata with jQuery.ajax

The FormData class does work, however in iOS Safari (on the iPhone at least) I wasn't able to use Raphael Schweikert's solution as is.

Mozilla Dev has a nice page on manipulating FormData objects.

So, add an empty form somewhere in your page, specifying the enctype:

<form enctype="multipart/form-data" method="post" name="fileinfo" id="fileinfo"></form>

Then, create FormData object as:

var data = new FormData($("#fileinfo"));

and proceed as in Raphael's code.

How are POST and GET variables handled in Python?

They are stored in the CGI fieldstorage object.

import cgi
form = cgi.FieldStorage()

print "The user entered %s" % form.getvalue("uservalue")

Add a custom attribute to a Laravel / Eloquent model on load?

The last thing on the Laravel Eloquent doc page is:

protected $appends = array('is_admin');

That can be used automatically to add new accessors to the model without any additional work like modifying methods like ::toArray().

Just create getFooBarAttribute(...) accessor and add the foo_bar to $appends array.

How to store decimal values in SQL Server?

In MySQL DB decimal(4,2) allows entering only a total of 4 digits. As you see in decimal(4,2), it means you can enter a total of 4 digits out of which two digits are meant for keeping after the decimal point.

So, if you enter 100.0 in MySQL database, it will show an error like "Out of Range Value for column".

So, you can enter in this range only: from 00.00 to 99.99.

how to write value into cell with vba code without auto type conversion?

Indeed, just as commented by Tim Williams, the way to make it work is pre-formatting as text. Thus, to do it all via VBA, just do that:

Cells(1, 1).NumberFormat = "@"
Cells(1, 1).Value = "1234,56"

Detect if HTML5 Video element is playing

I just looked at the link @tracevipin added (http://www.w3.org/2010/05/video/mediaevents.html), and I saw a property named "paused".

I have ust tested it and it works just fine.

Autoplay audio files on an iPad with HTML5

As of iOS 4.2.1, neither the fake click nor the .load() trick will work to autoplay audio on any iOS device. The only option I know of is to have the user actually perform a click action and begin playback in the click event handler without wrapping the .play() call in anything asynchronous (ajax, setTimeout, etc).

Someone please tell me if I'm mistaken. I had working loopholes for both iPad and iPhone before the most recent update, and all of them look like they've been closed.

Using DISTINCT and COUNT together in a MySQL Query

SELECTING DISTINCT PRODUCT AND DISPLAY COUNT PER PRODUCT

for another answer about this type of question this is my another answer for getting count of product base on product name distinct like this sample below:

Table Value

select * FROM Product

Counted Product Name

SELECT DISTINCT(Product_Name),
(SELECT COUNT(Product_Name) 
from Product  WHERE Product_Name = Prod.Product_Name)  
as `Product_Count`
from Product as Prod

Record Count: 4; Execution Time: 2ms

MySQL - Get row number on select

It's now builtin in MySQL 8.0 and MariaDB 10.2:

SELECT
  itemID, COUNT(*) as ordercount,
  ROW_NUMBER OVER (PARTITION BY itemID ORDER BY rank DESC) as rank
FROM orders
GROUP BY itemID ORDER BY rank DESC

How can I make a .NET Windows Forms application that only runs in the System Tray?

"System tray" application is just a regular win forms application, only difference is that it creates a icon in windows system tray area. In order to create sys.tray icon use NotifyIcon component , you can find it in Toolbox(Common controls), and modify it's properties: Icon, tool tip. Also it enables you to handle mouse click and double click messages.

And One more thing , in order to achieve look and feels or standard tray app. add followinf lines on your main form show event:

private void MainForm_Shown(object sender, EventArgs e)
{
    WindowState = FormWindowState.Minimized;
    Hide();
} 

Calculating the area under a curve given a set of coordinates, without knowing the function

The numpy and scipy libraries include the composite trapezoidal (numpy.trapz) and Simpson's (scipy.integrate.simps) rules.

Here's a simple example. In both trapz and simps, the argument dx=5 indicates that the spacing of the data along the x axis is 5 units.

from __future__ import print_function

import numpy as np
from scipy.integrate import simps
from numpy import trapz


# The y values.  A numpy array is used here,
# but a python list could also be used.
y = np.array([5, 20, 4, 18, 19, 18, 7, 4])

# Compute the area using the composite trapezoidal rule.
area = trapz(y, dx=5)
print("area =", area)

# Compute the area using the composite Simpson's rule.
area = simps(y, dx=5)
print("area =", area)

Output:

area = 452.5
area = 460.0

StringStream in C#

Since your Print() method presumably deals with Text data, could you rewrite it to accept a TextWriter parameter?

The library provides a StringWriter: TextWriter but not a StringStream. I suppose you could create one by wrapping a MemoryStream, but is it really necessary?


After the Update:

void Main() 
{
  string myString;  // outside using

  using (MemoryStream stream = new MemoryStream ())
  {
     Print(stream);
     myString = Encoding.UTF8.GetString(stream.ToArray());
  }
  ... 

}

You may want to change UTF8 to ASCII, depending on the encoding used by Print().

Laravel: PDOException: could not find driver

I faced the same problem while using sqlite 3:

  1. Make sure the changes made on .env.example and the same on the .env file.
  2. Then run $ sudo apt-get install php-sqlite3 on terminal.
  3. Finally $ php artisan migrate.

error: resource android:attr/fontVariationSettings not found

error: resource android:attr/fontVariationSettings not found

I got this error when i added ButterKnife library but upgrading compileSdkVersion to 28 and targetSdk to 28 solved my issue.

jQuery get mouse position within an element

If you make your parent element be "position: relative", then it will be the "offset parent" for the stuff you're tracking mouse events over. Thus the jQuery "position()" will be relative to that.

How can I find where I will be redirected using cURL?

You can use:

$redirectURL = curl_getinfo($ch,CURLINFO_REDIRECT_URL);

What is this date format? 2011-08-12T20:17:46.384Z

If you guys are looking for a solution for Android, you can use the following code to get the epoch seconds from the timestamp string.

public static long timestampToEpochSeconds(String srcTimestamp) {
    long epoch = 0;

    try {
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
            Instant instant = Instant.parse(srcTimestamp);
            epoch = instant.getEpochSecond();
        } else {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss.SSSSSS'Z'", Locale.getDefault());
            sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
            Date date = sdf.parse(srcTimestamp);
            if (date != null) {
                epoch = date.getTime() / 1000;
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

    return epoch;
}

Sample input: 2019-10-15T05:51:31.537979Z

Sample output: 1571128673

How can I detect the touch event of an UIImageView?

To add a touch event to a UIImageView, use the following in your .m file:

UITapGestureRecognizer *newTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(myTapMethod)];

[myImageView setUserInteractionEnabled:YES];

[myImageView addGestureRecognizer:newTap];


-(void)myTapMethod{
    // Treat image tap
}

How to pass params with history.push/Link/Redirect in react-router v4?

If you need to pass URL params

theres a great post explanation by Tyler McGinnis on his site, Link to the post

here are code examples:

  1. on the history.push component:

    this.props.history.push(`/home:${this.state.userID}`)

  2. on the router component you define the route:

    <Route path='/home:myKey' component={Home} />

  3. on the Home component:

componentDidMount(){
    const { myKey } = this.props.match.params
    console.log(myKey )
}

Mac SQLite editor

I use Liya from the Mac App Store, it's free, does the job, and the project is maintained (a month or so between updates as of Jan 2013).

I also test a lot on the device. You can access the SQLITE database on the device by:

  1. Add Application supports iTunes file sharing to the info.plist and setting it to YES
  2. Running the app on a device
  3. Open iTunes
  4. Select the device
  5. Select the "Apps" tab
  6. Scroll down to the "File Sharing" section and select the app
  7. The .sqlite file should appear in the right hand pane - select it and "Save to..."
  8. Once it's saved open it up in your favourite SQLITE editor

You can also edit it and copy it back.

EDIT: You can also do this through the Organizer in XCode

  1. Open the Organizer in XCode (Window > Organiser)
  2. Select the "Devices" tab
  3. Expand the device on the left that you want to download/upload data to
  4. Select Applications
  5. Select an Application in the main panel
  6. The panel at the bottom (Data files in Sandbox) will update with all the files within that application
  7. Choose Download and save it somewhere
  8. Find the file in Finder
  9. Right click and select "Show Package Contents"

You can now view, edit, and re-upload the package to your debug device. This can be really handy for keeping snapshots of different states to try out on other devices.

HTML/CSS - Adding an Icon to a button

You could add a span before the link with a specific class like so:

<div class="btn btn_red"><span class="icon"></span><a href="#">Crimson</a><span></span></div>

And then give that a specific width and a background image just like you are doing with the button itself.

.btn span.icon {
    background: url(imgs/icon.png) no-repeat;
    float: left;
    width: 10px;
    height: 40px;
}

I am no CSS guru but off the top of my head I think that should work.

Java 8 NullPointerException in Collectors.toMap

NullPointerException is by far the most frequently encountered exception (at least in my case). To avoid this I go defensive and add bunch of null checks and I end up having bloated and ugly code. Java 8 introduces Optional to handle null references so you can define nullable and non-nullable values.

That said, I would wrap all the nullable references in Optional container. We should also not break backward compatibility as well. Here is the code.

class Answer {
    private int id;
    private Optional<Boolean> answer;

    Answer() {
    }

    Answer(int id, Boolean answer) {
        this.id = id;
        this.answer = Optional.ofNullable(answer);
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    /**
     * Gets the answer which can be a null value. Use {@link #getAnswerAsOptional()} instead.
     *
     * @return the answer which can be a null value
     */
    public Boolean getAnswer() {
        // What should be the default value? If we return null the callers will be at higher risk of having NPE
        return answer.orElse(null);
    }

    /**
     * Gets the optional answer.
     *
     * @return the answer which is contained in {@code Optional}.
     */
    public Optional<Boolean> getAnswerAsOptional() {
        return answer;
    }

    /**
     * Gets the answer or the supplied default value.
     *
     * @return the answer or the supplied default value.
     */
    public boolean getAnswerOrDefault(boolean defaultValue) {
        return answer.orElse(defaultValue);
    }

    public void setAnswer(Boolean answer) {
        this.answer = Optional.ofNullable(answer);
    }
}

public class Main {
    public static void main(String[] args) {
        List<Answer> answerList = new ArrayList<>();

        answerList.add(new Answer(1, true));
        answerList.add(new Answer(2, true));
        answerList.add(new Answer(3, null));

        // map with optional answers (i.e. with null)
        Map<Integer, Optional<Boolean>> answerMapWithOptionals = answerList.stream()
                .collect(Collectors.toMap(Answer::getId, Answer::getAnswerAsOptional));

        // map in which null values are removed
        Map<Integer, Boolean> answerMapWithoutNulls = answerList.stream()
                .filter(a -> a.getAnswerAsOptional().isPresent())
                .collect(Collectors.toMap(Answer::getId, Answer::getAnswer));

        // map in which null values are treated as false by default
        Map<Integer, Boolean> answerMapWithDefaults = answerList.stream()
                .collect(Collectors.toMap(a -> a.getId(), a -> a.getAnswerOrDefault(false)));

        System.out.println("With Optional: " + answerMapWithOptionals);
        System.out.println("Without Nulls: " + answerMapWithoutNulls);
        System.out.println("Wit Defaults: " + answerMapWithDefaults);
    }
}

What do &lt; and &gt; stand for?

&gt; and &lt; is a character entity reference for the > and < character in HTML.

It is not possible to use the less than (<) or greater than (>) signs in your file, because the browser will mix them with tags.

for these difficulties you can use entity names(&gt;) and entity numbers(&#60;).

Transition of background-color

To me, it is better to put the transition codes with the original/minimum selectors than with the :hover or any other additional selectors:

_x000D_
_x000D_
#content #nav a {_x000D_
    background-color: #FF0;_x000D_
    _x000D_
    -webkit-transition: background-color 1000ms linear;_x000D_
    -moz-transition: background-color 1000ms linear;_x000D_
    -o-transition: background-color 1000ms linear;_x000D_
    -ms-transition: background-color 1000ms linear;_x000D_
    transition: background-color 1000ms linear;_x000D_
}_x000D_
_x000D_
#content #nav a:hover {_x000D_
    background-color: #AD310B;_x000D_
}
_x000D_
<div id="content">_x000D_
    <div id="nav">_x000D_
        <a href="#link1">Link 1</a>_x000D_
    </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

CSS opacity only to background color, not the text on it?

I had the same problem. I want a 100% transparent background color. Just use this code; it's worked great for me:

rgba(54, 25, 25, .00004);

You can see examples on the left side on this web page (the contact form area).

How to convert column with dtype as object to string in Pandas Dataframe

Did you try assigning it back to the column?

df['column'] = df['column'].astype('str') 

Referring to this question, the pandas dataframe stores the pointers to the strings and hence it is of type 'object'. As per the docs ,You could try:

df['column_new'] = df['column'].str.split(',') 

concat yesterdays date with a specific time

where date_dt = to_date(to_char(sysdate-1, 'YYYY-MM-DD') || ' 19:16:08', 'YYYY-MM-DD HH24:MI:SS') 

should work.

Declaring an unsigned int in Java

We needed unsigned numbers to model MySQL's unsigned TINYINT, SMALLINT, INT, BIGINT in jOOQ, which is why we have created jOOU, a minimalistic library offering wrapper types for unsigned integer numbers in Java. Example:

import static org.joou.Unsigned.*;

// and then...
UByte    b = ubyte(1);
UShort   s = ushort(1);
UInteger i = uint(1);
ULong    l = ulong(1);

All of these types extend java.lang.Number and can be converted into higher-order primitive types and BigInteger. Hope this helps.

(Disclaimer: I work for the company behind these libraries)

How to convert Nonetype to int or string?

int(value or 0)

This will use 0 in the case when you provide any value that Python considers False, such as None, 0, [], "", etc. Since 0 is False, you should only use 0 as the alternative value (otherwise you will find your 0s turning into that value).

int(0 if value is None else value)

This replaces only None with 0. Since we are testing for None specifically, you can use some other value as the replacement.

select count(*) from select

You're missing a FROM and you need to give the subquery an alias.

SELECT COUNT(*) FROM 
(
  SELECT DISTINCT a.my_id, a.last_name, a.first_name, b.temp_val
   FROM dbo.Table_A AS a 
   INNER JOIN dbo.Table_B AS b 
   ON a.a_id = b.a_id
) AS subquery;

How to get summary statistics by group

Using Hadley Wickham's purrr package this is quite simple. Use split to split the passed data_frame into groups, then use map to apply the summary function to each group.

library(purrr)

df %>% split(.$group) %>% map(summary)

Spring Boot - How to log all requests and responses with exceptions in single place?

Don't write any Interceptors, Filters, Components, Aspects, etc., this is a very common problem and has been solved many times over.

Spring Boot has a modules called Actuator, which provides HTTP request logging out of the box. There's an endpoint mapped to /trace (SB1.x) or /actuator/httptrace (SB2.0+) which will show you last 100 HTTP requests. You can customize it to log each request, or write to a DB.

To get the endpoints you want, you'll need the spring-boot-starter-actuator dependency, and also to "whitelist" the endpoints you're looking for, and possibly setup or disable security for it.

Also, where will this application run? Will you be using a PaaS? Hosting providers, Heroku for example, provide request logging as part of their service and you don't need to do any coding whatsoever then.

How do I apply a CSS class to Html.ActionLink in ASP.NET MVC?

This works for MVC 5

@Html.ActionLink("LinkText", "ActionName", new { id = item.id }, new { @class = "btn btn-success" })

Make sure that the controller has a parameterless public constructor error

I had the same issue and I resolved it by making changes in the UnityConfig.cs file In order to resolve the dependency issue in the UnityConfig.cs file you have to add:

public static void RegisterComponents()    
{
    var container = new UnityContainer();
    container.RegisterType<ITestService, TestService>();
    DependencyResolver.SetResolver(new UnityDependencyResolver(container));
}

Python 2: AttributeError: 'list' object has no attribute 'strip'

strip() is a method for strings, you are calling it on a list, hence the error.

>>> 'strip' in dir(str)
True
>>> 'strip' in dir(list)
False

To do what you want, just do

>>> l = ['Facebook;Google+;MySpace', 'Apple;Android']
>>> l1 = [elem.strip().split(';') for elem in l]
>>> print l1
[['Facebook', 'Google+', 'MySpace'], ['Apple', 'Android']]

Since, you want the elements to be in a single list (and not a list of lists), you have two options.

  1. Create an empty list and append elements to it.
  2. Flatten the list.

To do the first, follow the code:

>>> l1 = []
>>> for elem in l:
        l1.extend(elem.strip().split(';'))  
>>> l1
['Facebook', 'Google+', 'MySpace', 'Apple', 'Android']

To do the second, use itertools.chain

>>> l1 = [elem.strip().split(';') for elem in l]
>>> print l1
[['Facebook', 'Google+', 'MySpace'], ['Apple', 'Android']]
>>> from itertools import chain
>>> list(chain(*l1))
['Facebook', 'Google+', 'MySpace', 'Apple', 'Android']

PostgreSQL IF statement

From the docs

IF boolean-expression THEN
    statements
ELSE
    statements
END IF;

So in your above example the code should look as follows:

IF select count(*) from orders > 0
THEN
  DELETE from orders
ELSE 
  INSERT INTO orders values (1,2,3);
END IF;

You were missing: END IF;

Select element by exact match of its content

No, there's no jQuery (or CSS) selector that does that.

You can readily use filter:

$("p").filter(function() {
    return $(this).text() === "hello";
}).css("font-weight", "bold");

It's not a selector, but it does the job. :-)

If you want to handle whitespace before or after the "hello", you might throw a $.trim in there:

return $.trim($(this).text()) === "hello";

For the premature optimizers out there, if you don't care that it doesn't match <p><span>hello</span></p> and similar, you can avoid the calls to $ and text by using innerHTML directly:

return this.innerHTML === "hello";

...but you'd have to have a lot of paragraphs for it to matter, so many that you'd probably have other issues first. :-)