text:
Q: what is the procedure for file-opener2 to work for any internal link to a pdf file? I am building a Cordova app for android, made up of a (large) number of files. Most of them have intenal links to pdf files such as this one:
DOC140416-1.pdf"

To access them from the app, I downloaded the file-opener2 plugin from GitHub. It installed nicely in the plugin folder in the newly created directory: cordova-plugin-file-opener2
I then found the following snipet which I pasted in the index.js
cordova.plugins.fileOpener2.open(
    filePath,
    fileMIMEType,
    {
        error : function(){ },
        success : function(){ }
    }
);

And finally I added
<plugin name="FileOpener" value="com.phonegap.plugins.fileopener.FileOpener"/>

to the config.xml.
As most of you can probably tell (stop laughin'!), tapping on the links fails miserably (though working well of vourse on my pc, since the borwsers are fitted for pdf files).
Can I get some help from you guys?
Many thanks!

A: FileOpener plugin is only to open the dialog, it can not open your PDF file. It will just prompt you in which application you want to open the file.
As you are saying it may have file types other than PDF, so you have three options.

*

*Download the file and then prompt user in which application they want to open the file by
FileOpener plugin.

*Open the file using system's default browser to download it.

*Open the link in google doc viewer by passing the url.

Ref:Phonegap InAppBrowser display pdf 2.7.0


text:
Q: Sequential Search array for loop condition If length of array in sequential search is not given and there is a lot of out of order indexing,

*

*how many times we should execute the for loop?

*what should be the condition of for loop?

I counted indexing again and again.
#include <iostream>
using namespace std;
int main() {
  int array[] = {10,  20, 30, 40, 50, 60, 70, 80, 90, 100, 200,
                 300, 400, 5006, 110, 550, 440, 330, 331, 41};

  // length of array is not provided

  int i, n, loc = -1;
  cout << "Enter value to find" << endl;
  cin >> n;
  for (i = 0; i < 5; i++) {
    if (array[i] == n) {
      loc = i;
    }
  }
  if (loc == -1)
    cout << "Number is not found in array" << endl;
  else
    cout << "the number is found at position " << loc << " and is " << n;
  return 0;
}

For loop Condition for unknown length array in sequential search

A: You can extract the size of an array using std::size()
int array[] = {10,  20, 30, 40, 50, 60, 70, 80, 90, 100, 200,
               300, 400, 5006, 110, 550, 440, 330, 331, 41};
int arraySize = std::size(array);

// Now you can iterate over the array with:

for (int loop = 0; loop < arraySize; ++loop) {
    if (array[loop] == n) {
        loc = loop;
    }
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: cocos2d 2.0 not loading ipad graphics I have the suffixes for iPad and iPad retina screen devices defined as -ipad and -ipadhd for my ccFileUtils for my universal app, and I also have all my graphics included in the correct size for iPad and the retina iPad with the correct suffixes... However whenever I run the app in the simulator it shows the standard without suffix images :/ Like so...

A: This was a silly error nothing to do with the coding in the end. I checked the file-type of the image in question (Background-iPadhd.png) and it turned out even though it has the extension .png it was in fact a .psd file. It's possible to accidentally save files with a .png extension but in the .psd format if you write the filename as xxx.png but leave the format as .psd when saving from photoshop.


text:
Q: .MSI window disappears after I launch it on Windows 10 I am trying to install a driver for the HP laserjet 1300 on Windows 10 x64. I have downloaded the .msi file with the driver from the official HP site.
When I execute the file it starts and after some seconds the window disappears.
I tried to reset msi register to default by downloading msi.reg file from the Windows site. But no luck.
Also, I tried to unregister and reregister msiexec but that didn't solve the problem.
Can someone help me?


text:
Q: No loitering sign: "Police Take Notice" I'm a native English speaker and I've never been able to really parse this one.  Is it a command aimed at the police? If so, shouldn't it be "police, take notice"?  Is this construction used anywhere except these kind of signs?
Examples from GIS

A: It's a sign which informs the police that the property in question is privately owned and any person or persons trespassing aren't supposed to be there. The sign also gives the police the freedom to enter the property and remove any such persons if necessary without the direct approval of the owner, as the approval is implied in the sign.
And thus, the sign is there to inform the public that they cannot trespass and that the police take notice over how this sign is respected. The sign is correct and no comma is missing.

A: I agree this is odd, and bad grammar no matter what it means. My understanding of these signs is that they are required in many places in order for the police to be able to enforce protection of private property without the invitation of the property owner.
Ie, where the local laws are written this way:
Pretend you own a large field, and someone is camping in the back of it.
If you have a sign that says "no trespassing" or "no camping, police take notice", the sign is granting permission for the police to come onto your property and see who is camping back there.
If you do NOT have a sign, then the police would not be allowed to enter your property unless you invited them -- for instance, by calling them and saying "somebody is camping in my field! help!"
I'm pretty sure that's what the signs mean, but you're right about the grammar being incorrect.

A: It is effectively saying "The police do/will take notice". It's similar to you saying "Dogs run". It's a statement of fact.

A: I have never seen such a sign in the US and it certainly is grammatically incorrect.  If it is commanding the police to take notice, then it should have a colon.  If it is informing that the police do take notice, then it is missing the article ( the ) and the verb ( do ).


text:
Q: How to show that there is no relationship I have some data which I am using to show that there is no relationship between two variables. (Or only a weak one.) In a previous writeup, I included the scatterplot showing no visible relationship, as well as the Pearson's and Spearman's correlation coefficients, which were both low. One of the reviewers commented that the statistics in the paper were weak and we 'only showed some correlations'. Is there any better way to show that there is little/no relationship between these variables? I have transformed the data using every reasonable transformation (log, square root, exponentiation), and even averaged the values for each datapoint, though it seems to me that that is falling prey to the ecological fallacy. Nothing. Not even a hint of a pattern anywhere.
Obviously, I can't show everything I tried. I want to show that there is no (or at least little) relationship, because common wisdom is that there should be a strong one. The fact that there is not a strong relationship is a surprising result. I know that you can't prove the null hypothesis, but I would like to show as much as possible that any other options are unlikely.
How do I convincingly show that there is no relationship between the variables? (Other than hypothesis-testing my correlations, which I am planning to do, but that doesn't show that there is no relationship.)
Note that both variables have heavy-tailed distributions - does that make a difference to the answer?
Below is a scatterplot of my data.

A: One approach is to start by determining what you consider to be little relationship (ideally this should be done before any look at the data, possibly having an expert in the field who has not seen your data or summaries help her will make this more objective).  For example you might consider any correlations between -0.1 and 0.1 to be "little" or meaningless, or some other boundaries.  This region is sometimes called the equivalence region.  Now compute a confidence interval on your correlation, if the CI falls completely inside your equivalence or little importance region, then that is strong evidence that if there is a relationship, it is not worth getting excited about or worrying about.  If part of the confidence interval extends past your bounds then that implies that there is a chance that the true relationship could be in the interesting region and you need more study/data to narrow the interval.
If you (or the reviewers) are concerned that there may be some transformations of the variables that show more of a relationship, then you could first run the ACE (Alternating Conditional Expectations) algorithm on the data.  This tries to find the transformations that give the highest correlation between variables.  If ACE cannot find a transformation (or pair of transformations) with a high correlation then there likely are not any reasonably smooth transformations that would.
Edit:
Additionally you may want to consider this paper:

 Buja, A., Cook, D. Hofmann, H., Lawrence, M. Lee, E.-K., Swayne,
 D.F and Wickham, H. (2009) Statistical Inference for exploratory
 data analysis and model diagnostics Phil. Trans. R. Soc. A 2009
 367, 4361-4383 doi: 10.1098/rsta.2009.0120

Including some of the suggested plots where you have permuted to guarantee no real relationship as a comparison may be convincing to the reviewers/audience that your date is consistent with no (or little) relationship.

A: If you have enough data, an alternative way would be to estimate the empirical joint distribution, and pit it against the product of the marginal distributions. Here too the null hypothesis would be $f_{XY}(x,y) = f_X(x)f_Y(y)$  (i.e. independence), and you will try to disprove it.
This CV post How to compare joint distribution to product of marginal distributions?
elaborates, and the various comments there provide also references you can look up.


text:
Q: Lcov process is stuck in file read I am running lcov to capture the code coverage but my lcov process is stuck somewhere.
Here is the strace and lsof output:
strace -p 9167
strace: Process 9167 attached
fcntl(3, F_SETLKW, {l_type=F_RDLCK, l_whence=SEEK_SET, l_start=0, l_len=0}

/sbin/lsof -p 9167
COMMAND  PID    USER   FD   TYPE DEVICE SIZE/OFF       NODE NAME
gcov    9167  admin  cwd    DIR   0,88    20480 3196209040 /linux-gcc4-64/gcov/obj/reset_manager (rw-tap2-data.xyz.com:/cs44_nb/build)
gcov    9167 admin  rtd    DIR  253,0     4096          2 /
gcov    9167 admin  txt    REG  253,0   318928    9214523 /usr/bin/gcov
gcov    9167 admin  mem    REG  253,0  2156272    9177394 /usr/lib64/libc-2.17.so
gcov    9167 admin  mem    REG  253,0  1136944    9177402 /usr/lib64/libm-2.17.so
gcov    9167 admin  mem    REG  253,0   163312    9177387 /usr/lib64/ld-2.17.so
gcov    9167 admin    0u   CHR  136,9      0t0         12 /dev/pts/9
gcov    9167 admin    1w   CHR    1,3      0t0       1028 /dev/null
gcov    9167 admin    2u   CHR  136,9      0t0         12 /dev/pts/9
gcov    9167 admin    3r   REG   0,88    10800 3208575778 /linux-gcc4-64/gcov/obj/reset_manager/COInfo.gcda (rw-tap2-data.xyz.com:/cs44_nb/build)

Can someone Pls help me to debug this further?
Here are other details:
gdb version:  10.3.0
lcov version: 1.15.0

Thanks
I tried to run strace/lcov to debug this.


text:
Q: How should I get a list of duplicate sublists in a list? I'm attempting to create functions that'll allow me to get a list of the unique sublists of a list. The functions are working for some lists of lists and not for others and I'm not sure why.
What would be a working, robust way to get the indices of the duplicate sublists and then to build a list of them?
The following minimal working example illustrates the functionality. The duplicates are found for list a but found incorrectly for list b.
def indices_of_list_element_duplicates(x):
    seen = set()
    for index, element in enumerate(x):
        if isinstance(element, list):
            element = tuple(element)
        if element not in seen:
            seen.add(element)
        else:
            yield index

def list_element_duplicates(x):
    indices = list(indices_of_list_element_duplicates(x))
    return [x[index] for index in indices]

a = [[1, 2], [1, 2], [2, 2], [3, 2], [4, 2], [5, 2], [5, 2]]

print(list_element_duplicates(a))

print("--------------------------------------------------------------------------------")

b = [[10], [15], [20], [10, 10], [10, 15], [10, 20], [15, 10], [15, 15], [15, 20], [20, 10], [20, 15], [20, 20], [10, 10, 10], [10, 10, 15], [10, 10, 20], [10, 15, 10], [10, 15, 15], [10, 15, 20], [10, 20, 10], [10, 20, 15], [10, 20, 20], [15, 10, 10], [15, 10, 15], [15, 10, 20], [15, 15, 10], [15, 15, 15], [15, 15, 20], [15, 20, 10], [15, 20, 15], [15, 20, 20], [20, 10, 10], [20, 10, 15], [20, 10, 20], [20, 15, 10], [20, 15, 15], [20, 15, 20], [20, 20, 10], [20, 20, 15], [20, 20, 20], [10], [15], [20], [10, 10], [10, 15], [10, 20], [15, 10], [15, 15], [15, 20], [20, 10], [20, 15], [20, 20], [10, 10, 10], [10, 10, 15], [10, 10, 20], [10, 15, 10], [10, 15, 15], [10, 15, 20], [10, 20, 10], [10, 20, 15], [10, 20, 20], [15, 10, 10], [15, 10, 15], [15, 10, 20], [15, 15, 10], [15, 15, 15], [15, 15, 20], [15, 20, 10], [15, 20, 15], [15, 20, 20], [20, 10, 10], [20, 10, 15], [20, 10, 20], [20, 15, 10], [20, 15, 15], [20, 15, 20], [20, 20, 10], [20, 20, 15], [20, 20, 20], [10], [15], [20], [10, 10], [10, 15], [10, 20], [15, 10], [15, 15], [15, 20], [20, 10], [20, 15], [20, 20], [10, 10, 10], [10, 10, 15], [10, 10, 20], [10, 15, 10], [10, 15, 15], [10, 15, 20], [10, 20, 10], [10, 20, 15], [10, 20, 20], [15, 10, 10], [15, 10, 15], [15, 10, 20], [15, 15, 10], [15, 15, 15], [15, 15, 20], [15, 20, 10], [15, 20, 15], [15, 20, 20], [20, 10, 10], [20, 10, 15], [20, 10, 20], [20, 15, 10], [20, 15, 15], [20, 15, 20], [20, 20, 10], [20, 20, 15], [20, 20, 20], [10], [15], [20], [10, 10], [10, 15], [10, 20], [15, 10], [15, 15], [15, 20], [20, 10], [20, 15], [20, 20], [10, 10, 10], [10, 10, 15], [10, 10, 20], [10, 15, 10], [10, 15, 15], [10, 15, 20], [10, 20, 10], [10, 20, 15], [10, 20, 20], [15, 10, 10], [15, 10, 15], [15, 10, 20], [15, 15, 10], [15, 15, 15], [15, 15, 20], [15, 20, 10], [15, 20, 15], [15, 20, 20], [20, 10, 10], [20, 10, 15], [20, 10, 20], [20, 15, 10], [20, 15, 15], [20, 15, 20], [20, 20, 10], [20, 20, 15], [20, 20, 20]]

print(list_element_duplicates(b))

A: You could use a Counter dict mapping the sublists to tuple and get the counts only keeping the sublists whose count is > 1:
from collections import Counter
a = [[1, 2], [1, 2], [2, 2], [3, 2], [4, 2], [5, 2], [5, 2]]

cn = Counter(map(tuple,a))

print([sub for sub in a if cn[tuple(sub)] > 1])

to work for mixed types and get unique returns:
from collections import Counter

a = [[1, 2], [1, 2], [2, 2], [3, 2], [4, 2], [5, 2], [5, 2], "foo", 123, 123]

def counts(x):
    for ele in x:
        if isinstance(ele, Hashable):
            yield ele
        else:
            yield tuple(ele)

def unique_dupes(x):
    cnts = Counter(counts(x))
    for ele in x:
        t = ele
        if not isinstance(ele, Hashable):
            t = tuple(ele)
        if cnts[t] > 1:
            yield ele
            del cnts[t]

print(list(unique_dupes(a)))

Output:
 [[1, 2], [5, 2], 123]

A: The issue must come from these lines:
if isinstance(element, list):
    element = tuple(element)
if element not in seen:
    seen.add(element)

So what happens is if you had already in seen say for example [10,15] and then you want to check [15,10] in seen, it will return FALSE.
A fix for that and while you consider [x,y] to be the same as [y,x], is to sort each element you check, this way:
if isinstance(element, list):
    element = tuple(sorted(element))
if element not in seen:
    seen.add(element)

A: Its easy with  list comprehension
list_a = [[1, 2], [1, 2], [2, 2], [3, 2], [4, 2], [5, 2], [5, 2]]

    unique_list=[]
    duplicate_list=[]
    sorted_list=[sorted(item) for item in list_a]

    final_list=[unique_list.append(item) if item not in unique_list else duplicate_list.append(item) for item in sorted_list]
    print(unique_list)
    print(duplicate_list)

A: Python lists have a beautiful built in function for this called count. Using this you can do:
a = [[1, 2], [1, 2], [2, 2], [3, 2], [4, 2], [5, 2], [5, 2]]
dups = list()

for e in a:
    if a.count(e) > 1:
        dups.append(e)

This will give you a list called dups containing [[1,2],[1,2],[5,2],[5,2]]


text:
Q: Why cannot I convert from 'Nonetype' to float? I am trying to save the solutions of this optimization problem but they are Nonetype. Therefore I want to convert them to float but I get this error:

float() argument must be a string or a number, not 'NoneType'

It is rare due to in the printed solution from results.write() x1 is 6.57142857142857.
from coopr . pyomo import *
from pyomo.opt import SolverFactory

def create_model(N=[], M=[], c={}, a={}, b={}):
    model = ConcreteModel()
    model.x = Var(N, within=NonNegativeReals)
    model.obj = Objective(expr=sum(c[i]*model.x[i] for i in N))
    def con_rule(model, m):
        return sum(a[i,m]*model.x[i] for i in N) >= b[m]
    model.con = Constraint(M, rule=con_rule)
    return model
model = create_model(N = [1,2], M = [1,2], c = {1:1, 2:2},
a = {(1,1):5, (2,1):4, (1,2):7, (2,2):3},
b = {1:11, 2:46})

#model.pprint()

instance = model.create()
#instance.pprint()
opt = SolverFactory("glpk")
results = opt.solve(instance, load_solutions=False)
results.write()

x_1=float( model.x[1].value)
#x_2=float( model.x[2].value or 0)

A: First, model.create() is deprecated on the most recent version of Pyomo. I believe it is now renamed to model.create_instance.
Second, you are solving the instance object returned from model.create(), which is a different object from model. Therefore, you should be accessing the .value attribute of variables on the instance object and not the model object.
Third, you are starting from a ConcreteModel, which means there is no need to call model.create() (or model.create_instance()). This is simply creating an unnecessary copy of what is already a "concrete instance". I.e., you could send the model object to the solver and the code accessing .value would work as is.
The create_instance method is only necessary when you start from an AbstractModel, where you then typically pass the name of some .dat file to it.


text:
Q: Show an Android style toast notification using HTML/CSS/JavaScript Normally when you would like to make a user aware of something you use an alert.
Now say I would like to do that but in a Android toast like way, namely a popup that shows up on screen but then a few seconds later disappears by itself so the user won't have to bother closing it, like the image below.
How could something like this be achieved in the web?
Note: Doing a touch interface so that's the reason I would like to have it in this way

A: The easier way is to make a holder where you put your message. That holder will be hidden.

Event Created

You add some CSS magic
.error {
    width:200px;
    height:20px;
    height:auto;
    position:absolute;
    left:50%;
    margin-left:-100px;
    bottom:10px;
    background-color: #383838;
    color: #F0F0F0;
    font-family: Calibri;
    font-size: 20px;
    padding:10px;
    text-align:center;
    border-radius: 2px;
    -webkit-box-shadow: 0px 0px 24px -1px rgba(56, 56, 56, 1);
    -moz-box-shadow: 0px 0px 24px -1px rgba(56, 56, 56, 1);
    box-shadow: 0px 0px 24px -1px rgba(56, 56, 56, 1);
}

Then with a simple script you can show it for a few seconds. Use .stop() if necessary
$('.error').fadeIn(400).delay(3000).fadeOut(400); //fade out after 3 seconds

$('button').click(function () {
    $('.error').text($(this).data('text')).fadeIn(400).delay(3000).fadeOut(400);
});
body, html {
    height:100%;
    width:100%;
    min-height:100%;
    padding:0;
    margin:0;
}
.error {
    width:200px;
    height:20px;
    height:auto;
    position:absolute;
    left:50%;
    margin-left:-100px;
    bottom:10px;
    background-color: #383838;
    color: #F0F0F0;
    font-family: Calibri;
    font-size: 20px;
    padding:10px;
    text-align:center;
    border-radius: 2px;
    -webkit-box-shadow: 0px 0px 24px -1px rgba(56, 56, 56, 1);
    -moz-box-shadow: 0px 0px 24px -1px rgba(56, 56, 56, 1);
    box-shadow: 0px 0px 24px -1px rgba(56, 56, 56, 1);
}

<button data-text='I did something!'>Do something!</button>

jsFiddle version
This is a very basic example that can then be changed into a function with parameters which will give the text, color, duration and anything else you may need.
Below a more advanced (unnecessarily complicated) way (kinda like a plugin). Here is also a fiddle version.

(function($) {
  $.fn.aToast = function(options) {

    var $this = $(this),
      settings = $.extend({
        fadeOut: 400,
        fadeIn: 400,
        delay: 3000,
        text: 'Whoops! Something happened and I showed up.',
        toastListenEvent: 'click',
        aClass: false
      }, options),
      $at = false,
      aTevents = false;

    settings.toastListenEvent = settings.toastListenEvent + ' a-Toast';
    settings.aClass = 'aToast-view-message'
                  + (settings.aClass ? ' ' + settings.aClass : '')
    if ($('[data-aToast=true]:not(.aToast-init)').length)
      $this = $this.add($('[data-aToast=true]:not(.aToast-init)')
                                       .addClass('aToast-init'));

    function _remove() {
      $(this).stop().remove();
    }

    function _displayDiv() {
      $('.aToast-view-message').hide();
      var da = $(this).data('atoast-text');
      var $div = $('
', {
          text: da ? da : settings.text,
          class: settings.aClass
        }).stop().fadeIn(settings.fadeIn)
        .delay(settings.delay)
        .fadeOut(settings.fadeOut, _remove)
        .appendTo('body');
    }

    $this.not('[data-aToast=false]').on(settings.toastListenEvent, _displayDiv);

  };
}(jQuery));

$('button').aToast({
  aClass: 'users-dont-care-about-this-class-name'
});

$('div').aToast({
  aClass: 'hehe',
  toastListenEvent: 'mouseenter',
  text: 'Okay, this is not working'
});

/* or

$().aToast({
    aClass: 'users-dont-care-about-this-class-name'
});

To listen to data-aToast only

*/
body,
html {
  height: 100%;
  width: 100%;
  min-height: 100%;
  padding: 0;
  margin: 0;
}
.aToast-view-message {
  width: 200px;
  height: 20px;
  height: auto;
  position: absolute;
  left: 50%;
  margin-left: -100px;
  bottom: 10px;
  background-color: #383838;
  color: #F0F0F0;
  font-family: Calibri;
  font-size: 20px;
  padding: 10px;
  text-align: center;
  border-radius: 2px;
  -webkit-box-shadow: 0px 0px 24px -1px rgba(56, 56, 56, 1);
  -moz-box-shadow: 0px 0px 24px -1px rgba(56, 56, 56, 1);
  box-shadow: 0px 0px 24px -1px rgba(56, 56, 56, 1);
}

<button>Here goes nothing</button>
<input type='button' data-aToast='true' data-aToast-text='Hey there.' value='Woop!' />

I am a div! Hover me

A: Here's a simple CSS and Javascript solution. (Uses Jquery, but doesn't need to).

$("#clickme").click(function() {
      $("body").append("Hello World!");

      setTimeout(function(){
        $(".toast").remove();
      },3000);
});
.toast {
  position: fixed;
  display:block;

  bottom: 2em;
  height: 2em;
  width: 10em;
  left: calc(50% - 5em);

  animation: toast-fade-in 1s 2 alternate;

  background-color: black;
  border-radius: 2em;

  color: white;
  text-align: center;
  padding: 1em;
  line-height: 2em;

  opacity: 0;

}

@keyframes toast-fade-in {
  from {
    opacity: 0;
  }

  to {
    opacity: 1;
  }
}

<input id = "clickme" type = "button" value = "click me!"/>

A:
If you want notification like this. Then code and instruction is here (Excuse me koding.com :)))
HTML side (add end of body)

CSS side
.kdnotification{display:none}
.kdnotification a{text-shadow:0 1px 0 #444}
.kdnotification{position:fixed;padding:10px;z-index:20001;-webkit-border-radius:5px;-moz-border-radius:5px;border-radius:5px}
.kdnotification .kdnotification-title{color:#fff;font-size:24px;line-height:36px;margin:2px;font-weight:700}
.kdnotification .kdnotification-content{font-size:16px;line-height:18px;color:#fff}
.kdnotification .kdnotification-timer{position:absolute;top:21px;right:25px;color:#fff;line-height:15px;text-align:center;font-size:15px;width:20px;height:24px}
.kdnotification a{position:absolute;cursor:pointer;display:block;top:24px;right:5px;line-height:24px;text-align:center;font-size:24px;text-decoration:none;color:#fff;width:20px;height:24px}
.kdnotification-title{font-size:18px;line-height:28px;float:none}
.kdnotification-title{font-size:12px;line-height:16px;font-weight:400;float:none}
.kdnotification.mini{-webkit-border-radius:0 0 5px 5px;-moz-border-radius:0 0 5px 5px;border-radius:0 0 5px 5px;padding:1px;-webkit-box-shadow:0 0 1px 1px rgba(255,255,255,.1),inset 0 0 2px #000;-moz-box-shadow:0 0 1px 1px rgba(255,255,255,.1),inset 0 0 2px #000;box-shadow:0 0 1px 1px rgba(255,255,255,.1),inset 0 0 2px #000}
.kdnotification-title{font-size:12px;line-height:16px;font-weight:400;float:none;padding:2px 10px}
.kdnotification.mini .kdnotification-title p{padding:0 10px}
.kdnotification.mini.error{background:rgba(185,74,72,.9);font-weight:600}
.kdnotification.mini.success{background:rgba(70,136,71,.8);font-weight:600}

JS side (of course using jquery library)
function notify(message,status){
  $('.kdnotification-title').html(message);
  funcking();
  if(status == 1){
    $('#notification').css({'background-color':'rgba(0,0,0,.4)'}).fadeIn('slow').delay(5000).fadeOut('slow');
  } else {
    $('#notification').css({'background-color':'rgba(216,0,12,.6)'}).fadeIn('slow').delay(3000).fadeOut('slow');
  }
}

function funcking(){
    var kd=$('.kdnotification');
    var viewportHeight = $(window).height(),
        viewportWidth = $(window).width(),
        kdheight = kd.height(),kdwidth = kd.width(),
        hdiff = viewportHeight - kdheight,
        vdiff = viewportWidth - kdwidth,
        left= vdiff/2,
        top = hdiff/2;
    kd.css({'top':top+'px','left':left+'px'});
}

Use case
if(success){
  notify("Success message",1);
} else {
  notify("Error message",0);
}

A: You have some good libraries on internet to mimic the native android toast message:

*

*Toastr

*https://github.com/jadjoubran/Android-Toast (Javascript)

*https://github.com/akquinet/jquery-toastmessage-plugin (jQuery)

*https://gist.github.com/kamranzafar/3136584 (jQuery Mobile)

Basically is a div with the message with some CSS and an animation to show and hide.

A: Here is a Notify-js  library that  borrows a lot from Toastr and simplifies it to something similar to android-toast.
It shows a div with some messages in it.

A: I suggest you use this light and simple ToastMaker library which exactly matches with the android toast look & feel & it is only 1KB in size.

$('#mybutton').click(()=>{ToastMaker("This is a toast notification!")});

<link rel="stylesheet" type="text/css" href="https://unpkg.com/toastmaker/dist/toastmaker.min.css">

<button id="mybutton">Show Toast</button>

Visit this page to check more examples with beautiful styled toast messages


text:
Q: Best way to industrialize raspberry pi 3b+ I work on a Raspberry project, the purpose of this project is to use a Raspberry to control an industrial machine.
My customer would like to produce several hundred Raspberry.
I have an custom Raspbian image and I would like to know how "flash" my image on this several Raspberry in an industrial way.

For the moment, the customer wants to use an Raspberry Pi3b+.

Do you have any ideas ?

A: Kinda off-topic question for here. But, we are using one of these SD card duplicators if that helps.


text:
Q: NetBeans IDE 7.0  I created my Java EE Project with GlassFish server and Java EE 6. It was working good when i was created the project, but i closed my netbeans(there wasn't any fault just closed the NetBeans) and started my NetBeans.

Then problem on the title has faced. And i re-installed my NetBeans
  many times. So i can't solve it. PLEASE HELP ME! NETBEANS GEEKS!

A: I'm not sure if you solved this already but I had this same problem just now. All I did to fix it was select a new server from the list provided when you click on the 'resolve this issue' after right-clicking on your web project. I selected apache tomcat, not the bundled version but the one I installed onto my computer and setup myself. The project then accepted that as the proper server to use and ran just fine.

A: Right click on the project and it gives at the bottom an option to resolve Server references, so once you click there, it gives the option to add the server (tomcat or glassfish), that worked for me.

A: Go to the following place in your project's directory:
/home/<path-to-your-project>/nbproject/private

or
c:\<path-to-your-project>\nbproject\private

and check if the paths to GlassFish are correct in the private.properties file for the following properties:
j2ee.server.domain=
j2ee.server.home=
j2ee.server.instance=
j2ee.server.middleware=


text:
Q: How to display a mplfinance chart in tkinter When I execute this code I have 2 frames. Is there any way to display this in one root frame?
import pandas as pd
import mplfinance as mpf
from tkinter import *
root = Tk()
root.title("candle")
root.geometry('600x550')

def candle():

    file  = 'BTC-USD.csv'

    data = pd.read_csv(file)

    print(data.info())
    data.Date = pd.to_datetime(data.Date)
    data = data.set_index('Date')
    print(data)
    mpf.plot(data, type='candle', mav=(20),volume=True, style='yahoo')

button = Button(root, text="grapg", comand=candle())
button.pack()

root.mainloop()

Below is my output of above code:

A: The approach that I have seen work most often is to call mpf.plot() first, outside of tkinter, with kwarg returnfig=True.   Then use the figure returned by mpf.plot() to create your tkinter canvas, something like this:
fig, axlist = mpf.plot(data,type='candle',mav=(20),volume=True,
                       style='yahoo',returnfig=True)
canvas = FigureCanvasTkAgg(fig)

See also

*

*https://github.com/matplotlib/mplfinance/issues/440#issuecomment-911653228

*https://github.com/matplotlib/mplfinance/wiki/TkInter-Example

*https://github.com/matplotlib/mplfinance/issues/304


text:
Q: Optimizing the Layout of Arbitrary Shapes in a Plane I am trying to create an algorithm that can take a set of objects and organize them in a given area such that a box bounding all of the shapes is optimized (either by area used, or by maximizing the span along one of the dimensions, etc.). All of the shapes are closed and bounded.
The purpose of this is to try and minimize material waste from using a laser cutter. The shapes are generated in CAD and can read into this algorithm. The algorithm will then take arguments for the working area (effective laser cutting area) as well as the minimum separation between any two objects, then attempt to organize the objects within the specified dimensions while trying to minimize the area usage. Alternatively, the algorithm can also try to maximize the object locations along one axis while minimizing the span along the other dimension. This would be akin to cutting off a smaller workpiece to cut from.
Ideally, the algorithm would be able to make translations AND rotations, but rotations aren't necessary.
For example, this Picture depicts the required transformation.
It should work with an arbitrary, but small (<25) number of objects.
Lastly, I don't expect anyone to solve this for me, but I would appreciate help toward either finding an algorithm that can do this, or developing my own. Thank you.

A: I dont know to what extent you want to create said algorithm or how you want to implement it, But i know of a program called OptiNest that can do  what you ask. It organizes geometric shapes to optimize the layout and minimize waste on a plane, i think in an autocad format.


text:
Q: Action App\Http\Controllers\FrontendController@search not defined What is the problem?This is Laravel 8.
index.blade.php
{!! Form::open(['action' => 'FrontendController@search','method'=> 'GET']) !!}

FrontendController
    public function search(Request $request){
          $brand = DB::table('products')->select('brand_name')->distinct()->get()->pluck('brand_name')->sort();

          $pro = POST::query();

          if($request->filled('brand_name')){
            $pro->where('brand_name',$request->brand_name);
          }

          return view('frontend.products.index',[
            'brand'=>$brand,
            'products'=>$pro->get(),
          ]);
       }

A: {!! Form::open(['url' => route('set your url'),'method'=> 'GET']) !!}

FrontendController@search this type is not probably used in laravel 8. it is used in lower version of laravel


text:
Q: Laravel missing required parameter for [Route: show] [URI: {lang}/listings/{id}] [Missing parameter: id] I'm making a CRUD app with login/register and localization functionalities in laravel 9. I have a list of posts in my index page which each have a link to a page that displays the single post.
everything worked well before i added the localization functionality but now when I try to get a single post I get this error:

Missing required parameter for [Route: show] [URI: {lang}/listings/{id}] [Missing parameter: id].

Here's my code:
The link components in view that goes to the show single post page:

     $listing->id, 'lang' => App::getLocale()]) }}">
        {{ $listing->title }}

The route for the show page in my routes/web.php:
Route::group(['prefix' => '{lang}'], function () {
    Route::get('/listings/{id}', [listingController::class, 'show'])
        ->name('show');
});

The show function in controllers/listingController.php:
public function show($lang, $id)
{
    $listing = Listing::find($id);

    return $listing ? view('listings.show', ['listing' => $listing]) : abort('404');
}

I'm passing both the lang and id parameters but I still get the missing parameters error.
The $listing variable in my view page is passed through Listing model and listingController. It contains all the listing posts and is not null, so I know that's not causing the issue.

Edit: these are all the routes after running PHP artisan route:list command
ANY       / ..................................................................................... Illuminate\Routing › RedirectController
POST      _ignition/execute-solution ...................... ignition.executeSolution › Spatie\LaravelIgnition › ExecuteSolutionController
GET|HEAD  _ignition/health-check .................................. ignition.healthCheck › Spatie\LaravelIgnition › HealthCheckController
POST      _ignition/update-config ............................... ignition.updateConfig › Spatie\LaravelIgnition › UpdateConfigController
GET|HEAD  api/user ......................................................................................................................
GET|HEAD  sanctum/csrf-cookie ......................................... sanctum.csrf-cookie › Laravel\Sanctum › CsrfCookieController@show
GET|HEAD  {lang} ........................................................................................ index › listingController@index
POST      {lang}/listings ....................................................................... listingsStore › listingController@store
GET|HEAD  {lang}/listings/create .............................................................. listingsCreate › listingController@create
GET|HEAD  {lang}/listings/manage ...................................................................... manage › listingController@manage
GET|HEAD  {lang}/listings/{id} ............................................................................ show › listingController@show
PUT       {lang}/listings/{listing} ........................................................... listingsUpdate › listingController@update
DELETE    {lang}/listings/{listing} ......................................................... listingsDestroy › listingController@destroy
GET|HEAD  {lang}/listings/{listing}/edit .......................................................... listingsEdit › listingController@edit
POST      {lang}/logout .................................................................................. logout › userController@logout
GET|HEAD  {lang}/register .............................................................................. register › userController@create
POST      {lang}/users ..................................................................................... users › userController@store
POST      {lang}/users/authenticate .......................................................... authenticate › userController@authenticate
GET|HEAD  {lang}/users/login ............................................................................... login › userController@login

Edit 2:
My listing.show view file:
<x-layout>
@include('partials/_search')

 Back

<x-card class="p-10">

        logo ? asset('storage/' . $listing->logo) : asset('images/no-image.png')}}"
            alt=""
        />

            {{$listing->title}}

            {{$listing->company}}

        <x-listing-tags :tags="$listing->tags"/>

            {{$listing->location}}

                Job Description

                {{$listing->description}}
                email}}"
                    class="block bg-laravel text-white mt-6 py-2 rounded-xl hover:opacity-80"
                    >
                    Contact Employer

                website}}"
                    target="_blank"
                    class="block bg-black text-white py-2 rounded-xl hover:opacity-80"
                    > Visit
                    Website

</x-card>

A: There was a link in a component within a component within my layout component (3 times nested) that passed only one param, I fixed it by adding another param. It's always a better idea to do localization before defining your routes so that you notice an error immediately instead of having to spend hours going through all your view files.


text:
Q: compatible total order of hasse diagram So I was assigned this problem for homework and I was able to all of them except for part D I would really appreciate any help or hints
I have no clue where to start I looked through my book and everything anything would be appreciated

A: We need to obtain a total ordering such that whenever $a < b$ in the partial ordering, we also have $a<b$ in this total ordering.  Looking at the Hasse diagram, just pick out the minimal elements one by one.  If there is more than one minimal element, pick any one arbitrarily.  For example, first pick $e$ say, then $f, c,d,b,a$.  This ordering $e<f<c<d<b<a$ is a total ordering compatible with the given partial ordering.  Another order is $f,e,d,c,b,a$.  In all cases, $e$ would be before $b$ and before $c$, $f$ would be before $c$ and before $d$, and $a$ would be last.  This algorithm of removing minimal elements one by one is called topological sort.


text:
Q: Drill down in google chart dashboard
Can anyone suggest me wth the code to  achieve drill down feature in google chat dashboard.

Say If i click on year its should drill down to next level say month and then to weeks and then days.
its called drill down feature.
This is code is for chart...I want to know how to use in dashboard-with say category filter.

Regards,
Prajna

A: Here is my example with dashboard.


text:
Q: Google Cloud Storage : Can we Get file or Search file based on meta data? While Uploading Object , I have assigned metadata using x-goog-meta-<keyname>.
Currently to get file , we have to use Get Object using Key/Filename.
I want know is it possible like Get Object using META-DATA ?
Is there any way we can directly get/search file by passing metadata ?
Thanks!

A: No, you cannot.
You can retrieve the metadata via the object name, but you cannot retrieve the object name via the metadata.
If you really needed to, you could create a second bucket that contained objects with the metadata names with data or metadata that referred to the original object name in the first bucket.


text:
Q: Programmatically add default data to custom module - Odoo v9 community I have a custom module, which inherits fleet.vehicle.log.services model
This is a custom module.
What I'm trying to do, is to add default data to just two fields of it, let me explain myself.
The model has these mandatory fields:
vehicle_id
cost_id
cost_type

And I've inherited/added these ones:
x_location_src_id
x_location_dest_id

These are stock locations, what I want is to add default stock locations to this model, but just the locations, not the mandatory fields.
So far, I've tried like this, in my data/location_data.xml file:
<record id="location_default" model="fleet.vehicle.log.services">
    <field name="vehicle_id">1</field>
    <field name="cost_id">2</field>
    <field name="cost_type">fuel</field>
    <field name="x_location_src_id">ReparacionUnidades</field>
    <field name="x_location_dest_id">ReparacionUnidades</field>
</record>

But it doesn't work for me, because, as I've said, I don't need the first three fields, just the last two ones.
So, as this is the only way to add default data by QWeb/XMl, I think there is a way to overcome this, by some attributes or maybe programmatically with python.
Do You have a clue on how to do it in some other way?
As I said, I want to bypass the fact that I have to add these other fields, because it makes no sense to me.
Any ideas?
Maybe some logic or attributes into stock.locations and not directly into this fleet.vehicle.log.services model?

A: In the new api you can override the field from the inherited model and assign a default value either using a static value or a function. Here is an example
class Partner(models.Model):
    _inherit = 'res.partner'

ASSIGNING A STATIC DEFAULT VALUE
    email = fields.Char(default='static@value.com')

ASSIGNING A PROGRAMMATIC DEFAULT VALUE
    def _email_default(self):
        return 'programmatic@value.com'

    email = fields.Char(default=_email_default)

Using the old api you can do something similar, using a different syntax.
class Partner(osv.osv):
    _inherit = 'res.partner'

    _columns = {
        'email': fields.char('Email')
    }

PROGRAMMATIC MEANS OF ASSIGNING DEFAULT VALUE
    def _email_default(self, cr, uid, ctx={}):
        return 'programmatic@value.com'

    _defaults = {
        'email': _email_default,
    }

STATIC METHOD OF ASSIGNING A DEFAULT VALUE
    _defaults = {
        'email': 'static@value.com',
    }


text:
Q: How can I insert image by POI library correctly in Android? When I insert the image, EXCEL can't read file. "Excel found unreadable content in..." I would like to insert some image as well as text.
When I insert image (first code), EXCEL in PC can't read the file.
EXCEL says "Excel found unreadable content in..."
But, when I skip the code about inserting the image (just add text on EXCEL)
EXCEL can read the file well (second code)
How can I correct my code?
I worked by Android Studio 3.2.1 and Galaxy S6
//1st code (insert text and image)
package com.example.yonghwan.d20xlsservicesave1;

import android.content.Intent;
import android.os.Environment;
import android.support.v4.app.NotificationManagerCompat;
import android.support.v7.app.AppCompatActivity;

import android.os.Bundle;
import android.widget.Toast;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.ClientAnchor;
import org.apache.poi.ss.usermodel.Picture;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.util.IOUtils;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFClientAnchor;
import org.apache.poi.xssf.usermodel.XSSFCreationHelper;
import org.apache.poi.xssf.usermodel.XSSFDrawing;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Set;

public class MainActivity extends AppCompatActivity {

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

        boolean isPermissionAllowed = isNotiPermissionAllowed();
        if(!isPermissionAllowed) {
            Intent intent = new Intent("android.settings.ACTION_NOTIFICATION_LISTENER_SETTINGS");
            startActivity(intent);
        }

        String storageDir = Environment.getExternalStorageDirectory().getAbsolutePath();
        File dir = new File(storageDir);
        if (!dir.exists()) dir.mkdir();
        String path = storageDir + "/Test5.xlsx";
        File xlsFile = new File(path);

        try {
            storageDir = Environment.getExternalStorageDirectory().getAbsolutePath()
                    + "/" + Environment.DIRECTORY_DCIM + "/Noti";
            path = storageDir + "/EXTRA.jpg";
            File iconFile = new File(path);
            InputStream inputStream = new FileInputStream(iconFile);
            byte[] bytes = IOUtils.toByteArray(inputStream);

            FileInputStream fileInputStream = new FileInputStream(xlsFile);
            XSSFWorkbook workbook = new XSSFWorkbook(fileInputStream);
            XSSFSheet sheet = (XSSFSheet) workbook.getSheet("Sheet1");
            int rowNumber = sheet.getLastRowNum();

            int pictureIndex = workbook.addPicture(bytes, XSSFWorkbook.PICTURE_TYPE_JPEG);
            inputStream.close();

            XSSFCreationHelper helper = workbook.getCreationHelper();
            XSSFDrawing drawing = sheet.createDrawingPatriarch();
            XSSFClientAnchor anchor = helper.createClientAnchor();

            XSSFRow row = sheet.createRow(rowNumber+1);
            XSSFCell cell = row.createCell(1);
            cell.setCellValue("Image test : " + String.valueOf(rowNumber));
            anchor = new XSSFClientAnchor();
            anchor.setCol1(0);
            anchor.setCol2(1);
            anchor.setRow1(rowNumber+1);
            anchor.setRow2(rowNumber+2);

            anchor.setAnchorType(ClientAnchor.MOVE_DONT_RESIZE);

            Picture picture = drawing.createPicture(anchor, pictureIndex);

            OutputStream outputStream = new FileOutputStream(xlsFile);
            workbook.write(outputStream);
            outputStream.flush();
            outputStream.close();
            Toast.makeText(getApplicationContext(), "File Saved Successfully", Toast.LENGTH_LONG).show();
        } catch (Exception e) {
            e.printStackTrace();
            Toast.makeText(getApplicationContext(), "Failed to save File", Toast.LENGTH_LONG).show();
        }

    }

    private boolean isNotiPermissionAllowed() {
        Set<String> notiListenerSet = NotificationManagerCompat.getEnabledListenerPackages(this);
        String myPackageName = getPackageName();

        for(String packageName : notiListenerSet) {
            if(packageName == null) {
                continue;
            }
            if(packageName.equals(myPackageName)) {
                return true;
            }
        }

        return false;
    }

}

//2nd code (insert text only)
package com.example.yonghwan.d20xlsservicesave1;

import android.content.Intent;
import android.os.Environment;
import android.support.v4.app.NotificationManagerCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Toast;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.ClientAnchor;
import org.apache.poi.ss.usermodel.Picture;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.util.IOUtils;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFClientAnchor;
import org.apache.poi.xssf.usermodel.XSSFCreationHelper;
import org.apache.poi.xssf.usermodel.XSSFDrawing;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Set;

public class MainActivity extends AppCompatActivity {

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

        boolean isPermissionAllowed = isNotiPermissionAllowed();
        if(!isPermissionAllowed) {
            Intent intent = new Intent("android.settings.ACTION_NOTIFICATION_LISTENER_SETTINGS");
            startActivity(intent);
        }

        String storageDir = Environment.getExternalStorageDirectory().getAbsolutePath();
        File dir = new File(storageDir);
        if (!dir.exists()) dir.mkdir();
        String path = storageDir + "/Test5.xlsx";
        File xlsFile = new File(path);

        try {
            storageDir = Environment.getExternalStorageDirectory().getAbsolutePath()
                    + "/" + Environment.DIRECTORY_DCIM + "/Noti";
            path = storageDir + "/EXTRA.jpg";
            File iconFile = new File(path);
            InputStream inputStream = new FileInputStream(iconFile);
            byte[] bytes = IOUtils.toByteArray(inputStream);

            FileInputStream fileInputStream = new FileInputStream(xlsFile);
            XSSFWorkbook workbook = new XSSFWorkbook(fileInputStream);
            XSSFSheet sheet = (XSSFSheet) workbook.getSheet("Sheet1");
            int rowNumber = sheet.getLastRowNum();

//            int pictureIndex = workbook.addPicture(bytes, XSSFWorkbook.PICTURE_TYPE_JPEG);
//            inputStream.close();

//            XSSFCreationHelper helper = workbook.getCreationHelper();
//            XSSFDrawing drawing = sheet.createDrawingPatriarch();
//            XSSFClientAnchor anchor = helper.createClientAnchor();

            XSSFRow row = sheet.createRow(rowNumber+1);
            XSSFCell cell = row.createCell(1);
            cell.setCellValue("Image test : " + String.valueOf(rowNumber));
//            anchor = new XSSFClientAnchor();
//            anchor.setCol1(0);
//            anchor.setCol2(1);
//            anchor.setRow1(rowNumber+1);
//            anchor.setRow2(rowNumber+2);

//            anchor.setAnchorType(ClientAnchor.MOVE_DONT_RESIZE);

//            Picture picture = drawing.createPicture(anchor, pictureIndex);

            OutputStream outputStream = new FileOutputStream(xlsFile);
            workbook.write(outputStream);
            outputStream.flush();
            outputStream.close();
            Toast.makeText(getApplicationContext(), "File Saved Successfully", Toast.LENGTH_LONG).show();
        } catch (Exception e) {
            e.printStackTrace();
            Toast.makeText(getApplicationContext(), "Failed to save File", Toast.LENGTH_LONG).show();
        }

    }

    private boolean isNotiPermissionAllowed() {
        Set<String> notiListenerSet = NotificationManagerCompat.getEnabledListenerPackages(this);
        String myPackageName = getPackageName();

        for(String packageName : notiListenerSet) {
            if(packageName == null) {
                continue;
            }
            if(packageName.equals(myPackageName)) {
                return true;
            }
        }

        return false;
    }

}


text:
Q: Nested Lists in LINQ to SQL I'm trying to get all items that have a data equal to (1 OR 2) AND a data equal to (6 OR 7)
var oneFromEachList = new[] {
    new[] {1,2}, // 1 OR 2
    new[] {6,7}, // AND 6 OR 7
};

// item.dataList is an IEnumerable<int>
DbSet<Table>.Where(item => oneFromEachList.All(list => item.dataList.Any(list.Contains)))

This query is what I want to do, but it can't be converted to SQL, I get: "The nested query is not supported. Operation1='Case' Operation2='Collect'"
Note that the oneFromEachList object is known before the query is executed (it's not from the database). I guess it's possible to build an Expression by composing .Where statements? This seems very complicated for what it is though...

A: I think this is what you're going for:
var query = DbSet<Table>()
foreach(var list in oneFromEachList)
   query = query.Where(item => item.dataList.Any(list.Contains));

You could turn this into a one-liner by using Aggregate():
oneFromEachList.Aggregate(DbSet<Table>(), (q, l) => q.Where(item => item.dataList.Any(l.Contains)));

But either way you're not going to be able to accomplish what you're looking for without either composing multiple Where clauses or doing some manual expression building.


text:
Q: Using Hibernate package to access database from another package I have divided my project into 2 packages. I'm using Maven.
package 1
It's a hibernate package, means it contains POJO classes, DAO classes and interfaces, BO classes and interfaces, and hibernate configurations. It generates a JAR file.
package 2
It's a JSF package, containing only web pages and managed beans, I'm also using ICEfaces.
My goal is to include the JAR file of the first package in the build path of the 2nd package, and use the methods of the BO classes to access the database from the web pages.
First I will list all configurations files of the first package:
AppContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">

    <bean id="bankBankBO"
         class="bdl.cdr.core.bo.impl.BankBankBOImpl" >
        <property name="bankBankDAO" ref="bankBankDAO" />
    </bean>

    <bean id="bankBankDAO"
         class="bdl.cdr.core.dao.impl.BankBankDAOImpl" >
        <property name="sessionFactory" ref="sessionFactory" />
    </bean>

</beans>

DataSource.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">

    <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="location">
            <value>jdbc.properties</value>
        </property>
    </bean>

    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="${jdbc.driverClassName}" />
        <property name="url" value="${jdbc.url}" />
        <property name="username" value="${jdbc.username}" />
        <property name="password" value="${jdbc.password}" />
    </bean>
</beans>

HibernateSessionFactory.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">

<!-- Hibernate session factory -->
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">

    <property name="dataSource">
      <ref bean="dataSource"/>
    </property>

    <property name="hibernateProperties">
       <props>
         <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
         <prop key="hibernate.show_sql">true</prop>
         <prop key="current_session_context_class">org.hibernate.context.ThreadLocalSessionContext</prop>
       </props>
    </property>

    <property name="annotatedClasses">
    <list>
        <value>bdl.cdr.core.pojo.BankBank</value>
    </list>
    </property>

    </bean>
</beans>

jdbc.properties
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/db2inst1
jdbc.username=root
jdbc.password=root

BeanLocations.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-2.5.xsd">

    <!-- Database Configuration -->
    <import resource="DataSource.xml"/>
    <import resource="HibernateSessionFactory.xml"/>
    <import resource="AppContext.xml"/>

</beans>

I'm using JUnit to test, and everything is working fine.
Now what I did is to take the JAR file built by Maven and I included it in the Build Path of the 2nd Package.
And this is what I tried to do:
I created a Service Factory (or BO Factory) class:
public class ServiceFactory {

    public static BankBankBO bankBankService;

    public static BankBankBO getBankBankService() {
        return bankBankService;
    }
}

In faces-config.xml I added the following:
<managed-bean>
        <managed-bean-name>serviceFactory</managed-bean-name>
        <managed-bean-class>bdl.cdr.portlet.utils.ServiceFactory</managed-bean-class>
        <managed-bean-scope>application</managed-bean-scope>
        <managed-property>
            <property-name>bankBankService</property-name>
            <property-class>bdl.cdr.core.bo.BankBankBO</property-class>
            <value>#{bankBankBO}</value>
        </managed-property>
    </managed-bean>

In another bean linked to a web page, I created a click event on a button:
public void print(ActionEvent ae) {
        ServiceFactory.getBankBankService().findAll();
    }

The findAll method, should return the list of all Banks from the database, the return type is the POJO class from the hibernate package, called BankBank.
After clicking the button, I receive the following exception:
SEVERE: Received 'java.lang.NullPointerException' when invoking action listener '#{jasperBean.print}' for component '_t38'
Jul 12, 2014 11:42:29 PM javax.faces.event.MethodExpressionActionListener processAction
SEVERE: java.lang.NullPointerException
    at bdl.cdr.portlet.managedbeans.main.interfacemodule.JasperBean.print(JasperBean.java:75)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at com.sun.el.parser.AstValue.invoke(AstValue.java:234)
    at com.sun.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:297)
    at com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:105)
    at javax.faces.event.MethodExpressionActionListener.processAction(MethodExpressionActionListener.java:148)
    at javax.faces.event.ActionEvent.processListener(ActionEvent.java:88)
    at javax.faces.component.UIComponentBase.broadcast(UIComponentBase.java:775)
    at javax.faces.component.UICommand.broadcast(UICommand.java:300)
    at javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:786)
    at javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1251)
    at com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:81)
    at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
    at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:118)
    at javax.faces.webapp.FacesServlet.service(FacesServlet.java:593)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:293)
    at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:861)
    at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:606)
    at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:489)
    at java.lang.Thread.run(Thread.java:744)

Jul 12, 2014 11:42:29 PM org.icefaces.impl.application.ExtendedExceptionHandler handle
WARNING: queued exception
javax.faces.event.AbortProcessingException: /index.xhtml @23,74 actionListener="#{jasperBean.print}": java.lang.NullPointerException
    at javax.faces.event.MethodExpressionActionListener.processAction(MethodExpressionActionListener.java:182)
    at javax.faces.event.ActionEvent.processListener(ActionEvent.java:88)
    at javax.faces.component.UIComponentBase.broadcast(UIComponentBase.java:775)
    at javax.faces.component.UICommand.broadcast(UICommand.java:300)
    at javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:786)
    at javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1251)
    at com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:81)
    at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
    at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:118)
    at javax.faces.webapp.FacesServlet.service(FacesServlet.java:593)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:293)
    at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:861)
    at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:606)
    at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:489)
    at java.lang.Thread.run(Thread.java:744)
Caused by: java.lang.NullPointerException
    at bdl.cdr.portlet.managedbeans.main.interfacemodule.JasperBean.print(JasperBean.java:75)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at com.sun.el.parser.AstValue.invoke(AstValue.java:234)
    at com.sun.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:297)
    at com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:105)
    at javax.faces.event.MethodExpressionActionListener.processAction(MethodExpressionActionListener.java:148)
    ... 21 more

Jul 12, 2014 11:42:29 PM com.sun.faces.context.AjaxExceptionHandlerImpl log
SEVERE: JSF1073: javax.faces.event.AbortProcessingException caught during processing of INVOKE_APPLICATION 5 : UIComponent-ClientId=j_idt37:_t38, Message=/index.xhtml @23,74 actionListener="#{jasperBean.print}": java.lang.NullPointerException
Jul 12, 2014 11:42:29 PM com.sun.faces.context.AjaxExceptionHandlerImpl log
SEVERE: /index.xhtml @23,74 actionListener="#{jasperBean.print}": java.lang.NullPointerException
javax.faces.event.AbortProcessingException: /index.xhtml @23,74 actionListener="#{jasperBean.print}": java.lang.NullPointerException
    at javax.faces.event.MethodExpressionActionListener.processAction(MethodExpressionActionListener.java:182)
    at javax.faces.event.ActionEvent.processListener(ActionEvent.java:88)
    at javax.faces.component.UIComponentBase.broadcast(UIComponentBase.java:775)
    at javax.faces.component.UICommand.broadcast(UICommand.java:300)
    at javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:786)
    at javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1251)
    at com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:81)
    at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
    at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:118)
    at javax.faces.webapp.FacesServlet.service(FacesServlet.java:593)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:293)
    at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:861)
    at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:606)
    at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:489)
    at java.lang.Thread.run(Thread.java:744)
Caused by: java.lang.NullPointerException
    at bdl.cdr.portlet.managedbeans.main.interfacemodule.JasperBean.print(JasperBean.java:75)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at com.sun.el.parser.AstValue.invoke(AstValue.java:234)
    at com.sun.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:297)
    at com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:105)
    at javax.faces.event.MethodExpressionActionListener.processAction(MethodExpressionActionListener.java:148)
    ... 21 more

I can provide the contents of all other classes and files, web.xml , faces-config.xml and whatever you need.
Thanks.

A: bankBankBO is Spring Bean, while ServiceFactory is JSF Managed Bean, so injection of bankBankService isn't working.
You must add this:
<application>
    <view-handler>com.sun.facelets.FaceletViewHandler</view-handler>
    <variable-resolver>org.springframework.web.jsf.DelegatingVariableResolver</variable-resolver>
</application>

to your faces-config.xml, in order to enable spring beans to jsf beans injection.


text:
Q: "Field 'name' doesn't have a default value" when `name` is explicitly being provided I'm having a very strange error. The extra weird thing is that it only happens on the development host, but not locally, despite that both are running the exact same code. The only difference is what database they're writing to, but I can insert just fine at the mysql console.
If I try the following query at the Rails console:
Category.create!(:name => "FOOBAR", :parent_id => 141)
I get this error:
ActiveRecord::StatementInvalid: Mysql2::Error: Field 'name' doesn't have a default value:
INSERT INTO `taxons` (`type`, `parent_id`, `created_at`, `updated_at`) VALUES ('Category',
141, '2020-02-05 18:48:54', '2020-02-05 18:48:54')

I'm literally providing the value for name, so I don't understand why it's not using it when it tries to create and validate the new record.
ETA: It's definitely a database issue, because if I run the local code with the development database, I get the same error. I can't directly make changes to the database (i.e. I have to ask the devops team to do it), but I guess the real question is about what needs to change there for this to work? The difference between the two databases is that locally, it allows for name to have DEFAULT NULL, and on development, it's NOT NULL, but why should this be necessary, if I'm always supplying a value for name?

A: I edited database.yml to specify strict: false. Problem solved.


text:
Q: How do I disable Shutter plugins? Shutter is a nice software but it takes a while to load. I observed that initially it loads some plugins (eg:upload-plugin). Is there a way to disable these plugins so that shutter loads quickly?
please illustrate how to do this.

A: The initialization of plugins should only appear once (e.g. after updating Shutter or a fresh install of Ubuntu). If this dialogue appears every time you start Shutter it is simply a bug.
There is an updated version of Shutter in our PPA. Please give it a try to see if it is fixed.
sudo add-apt-repository ppa:shutter/ppa
sudo apt-get update && sudo apt-get install shutter

A: I was seeing weird behavior, where I'd try to start shutter and I'd get a screen saying, Updating upload plugin information. And that screen would just sit there for 1-2 minutes.
Trying to start shutter from the commandline, it was outputting messages about /usr/share/shutter/resources/system/upload_plugins/upload/vgyme.pm
So I tried simply getting rid of that upload directory (moving it to a backup location, just in case):
sudo mv /usr/share/shutter/resources/system/upload_plugins/upload ~/backup_upload

I then rebooted (which I think was the core of my problems), and now starting shutter works just fine. So whether they were the problem or not, I think I'll happily leave those plugins out.


text:
Q: how import a model from .pb file '''
with tf.Session() as sess:
    model_filename="./model/skipGram-word2Vec/saved_model.pb"
    with gfile.FastGFile(model_filename,'rb') as f:
        graph_def=tf.GraphDef()
        graph_def.ParseFromString(f.read())
        sess.graph.as_default()
        result=tf.import_graph_def(graph_def,name='')
        print(sess.run(result))

'''
then ,the error occured:
DecodeError: Wrong wire type in tag.

A: Here is how you can load the model from .pb file in tensorflow 2.0
import tensorflow as tf

GRAPH_PB_PATH = './frozen_model.pb'
with tf.compat.v1.Session() as sess:
   print("load graph")
   with tf.io.gfile.GFile(GRAPH_PB_PATH,'rb') as f:
       graph_def = tf.compat.v1.GraphDef()
   graph_def.ParseFromString(f.read())
   sess.graph.as_default()
   tf.import_graph_def(graph_def, name='')
   graph_nodes=[n for n in graph_def.node]
   names = []
   for t in graph_nodes:
      names.append(t.name)
   print(names)


text:
Q: Custom Java Annotation to ignore integration tests on CI server I was thinking it would be handy to have a custom annotation for junit methods and classes that contain integration tests. This annotation would effectively act like the @Ignore junit annotation when the tests are being executed on our CI (Jenkins) server and the test would run as normal on local dev machines. To determine if the machine running the tests should allow integration test execution I would check System.getenv("WORKSPACE") to see if it exists/contains "jenkins".
I haven't written annotations before and am not familiar with junit's implementation details. Is what I'm describing possible? If so, how would I go about this?

A: JUnit 5
JUnit 5 has Environment Variable Conditions for this purpose. In your case, try add the following:

@Test
@EnabledIfEnvironmentVariable(named = "WORKSPACE", matches = "jenkins")
void onlyOnJenkins() {
    // ...
}

@Test
@DisabledIfEnvironmentVariable(named = "WORKSPACE", matches = "jenkins")
void notOnJenkins() {
    // ...
}

Note that the matches annotation attribute is a regex that supports wildcards. For details, please read the JavaDoc of @EnabledIfEnvironmentVariable and @DisabledIfEnvironmentVariable
The Conditional Test Execution chapter in the JUnit user guide has  more annotations and examples that you may find useful.

JUnit 4
Please read this answer to learn how org.junit.Assume can be used to conditionally execute tests.

A: Great information, thank you! I'm going to have to add a tech debt item in our backlog for upgrading to Junit 5.
However, Assume did exactly what I needed. I was able to add the following to my test class:
    @Before
    public void checkHost(){
        final String workspaceKey = "WORKSPACE";
        final String workspaceValue = System.getenv(workspaceKey);
        final boolean isJenkins = StringUtils.contains(workspaceValue, "Jenkins");
        log.info("checkHost(): " + workspaceKey + ":" + workspaceValue + " -> isJenkins: " + isJenkins);
        assumeFalse(isJenkins);
    }


text:
Q: How to add placeholder on input in Symfony 4 form? In my Symfony 4 form, I am try to get a placeholder for my input. I tried the below but I get an error that it is not allowed. Any ideas how else I can achieve this?

        ->add('firstname', TextType::class, ['label' => 'Vorname ', 'placeholder' => 'Your name',])

As suggested in the documentation I have also tried the below, here I am not getting an error, just nothing is rendering.

        ->add('firstname', TextType::class, ['label' => 'Vorname '], ['attr' => ['placeholder' => 'Vorname ']])

A: You need to do like this :
->add('firstname', TextType::class, array(
      'label' => 'Vorname ',
      'attr' => array(
          'placeholder' => 'hereYourPlaceHolder'
      )
 ))

As they say in the documentation

A: This also works, by rendering the items individually and adding an attribute in the twig!

{{ form_label(form.firstname) }}
{{ form_widget(form.firstname, {'attr': {'placeholder': 'FIRSTNAME'}}) }}

A: The documentation of Symfony 6 suggests two ways.
The first option is inside the yourForm.php:
->add('name', TextType::class,
    [
        'label'    => 'Name *',
        'attr' => ['placeholder' => 'Name *'],
        'required' => true
    ])

The second option is inside the twig template:
{{ form_label(form.name) }}
{{ form_widget(form.name, {'attr': {'placeholder': 'Name*' }}) }}

You can find more information in the official documentation of Symfony 6 FormType

A: This is worked in Symfony 4
            ->add('fullName', null, [
                'label' => 'Kontaktperson',
                'attr' => [
                    'placeholder' => 'Contact person name'
                ],
            ])

More details: http://toihid.com/?p=326


text:
Q: How to word the results if a chi-square test of independence is significant, but no single post-hoc test is? I ran a chi-square test of independence on a 2-dimensional cross table, which resulted in a significant p-value.
I then ran post-hoc tests for all pairs of populations and adjusting by a bonferroni correction (I used the function chisq.post.hoc from the fifer package in R, if that matters).
There, no single pair was significant.
I understand that this can happen and is not out of the ordinary, but it's hard to put a justification for this result in writing. How would you word this situation correctly? I am thinking of something to the likes of:

The significant p-value of the chi-squared test on the whole cross table suggests a dependency between the variables A and B. However, no specific group was found in the subsequent post-hoc tests, meaning that the overall dependency could not be linked to a specific pair of populations.

To me, this sounds correct but not helpful. Is there a better way to describe what the significant overall-test means if no single pair of population is found in the post-hoc tests?

A: Taking a stab:

A chi-squared test works by assuming that variables A and B are
  independent and then looking for evidence that contradicts that
  assumption. The stronger the overall evidence against independence,
  the lower the p-value will be. In this case, the low p-value from the
  test on the whole table suggests significant evidence for a dependency
  between variables A and B. A follow-up post hoc analysis found that
  the overall conclusion results from the accumulation of small amounts of
  evidence from many cells in the table rather than from large
  contributions of evidence from any particular cells.


text:
Q: CJK Languages Pronunciation APIs Are there any good (preferably open) APIs or databases of pronunciation audio files for Chinese/Japanese/Korean languages? I've been looking around, but somehow couldn't find anything other than Forvo or Google Translate. Both are an overkill for me, since I only need data for those languages, and only pronunciations, no translations.

A: How many words are you looking for? Downloading up to 1000 files per day is free with the Forvo API. And if you need all that many more, it would be fair to pay them.
If a transcription is good enough for you, there are good open-source dictionaries for Chinese, and Korean can be converted syllable-by-syllable because Korean uses an alphabet. Japanese is the only difficulty, since Japanese characters are often pronounced differently according to the context.


text:
Q: Finding the lowest value y can have in $y = \frac{1}{2}(e^x - e^{-x}) + \frac{n}{2}(e^x + e^{-x }) $ How can I find the lowest value $y$ can have when $n$ is greater than or equal to $2$ using only algebra?
$$y = \frac{1}{2}(e^x - e^{-x}) + \frac{n}{2}(e^x + e^{-x })$$

A: Using AM-GM inequality
$$
y=\frac{(n+1)e^x+(n-1)e^{-x}}{2}\ge\sqrt{(n+1)(n-1)}=\sqrt{n^2-1}.
$$
Equality when $(n+1)e^x=(n-1)e^{-x}$ $\Rightarrow$ $x=\frac{1}{2}\ln\frac{n-1}{n+1}$.

A: Hint
The minimum or maximum would be reached when $\frac{dy}{dx}=0$.
So, consider $$y =  \frac{1}{2}(e^x - e^{-x})  + \frac{n}{2}(e^x + e^{-x
})$$ Compute $\frac{dy}{dx}$, set it equal to $0$, solve for $x$ (which will be a function of $n$) and plug the value back in $y$.
Do not forget to use the second derivative test to verify that $y$ is at a minimum.

A: Solution without differentiation.
Given is
$$
y = \frac{1}{2} \Big( \exp(x) - \exp(-x) \Big)
+ \frac{n}{2} \Big( \exp(x) + \exp(-x) \Big).
$$

Step 1:
$$
y = \frac{n+1}{2} \exp(x) + \frac{n-1}{2} \exp(-x).
$$

Step 2:
$$
y = \frac{n+1}{2} \exp(-a) \exp(x+a) + \frac{n-1}{2} \exp(a) \exp(-[x+a]).
$$

Step 3:
Find $a$ such that
$$
\frac{n+1}{2} \exp(-a) : \frac{n-1}{2} \exp(a) = 1,
$$

so solve
$$
\frac{n+1}{n-1} \exp(-2a) = 1 \Rightarrow a = \log \sqrt{ \frac{n+1}{n-1} }.
$$

Step 4:
$$
y = \frac{\sqrt{n^2-1}}{2}
\Big[ \exp(x+a) + \exp(-[x+a]) \Big]
$$

Step 5:
$$
y = \sqrt{n^2-1}
\Bigg[ 1 + \Big[ \tfrac{1}{2} \exp(\tfrac{1}{2}[x+a])
- \tfrac{1}{2}\exp(-\tfrac{1}{2} [x+a]) \Big]^2  \Bigg]
$$

You can read out the minimum, as $y$ has the form $y = a ( 1 + \xi^2)$.
The minimum is $a$ for $\xi=0$.
The minimum is given by
$$
\sqrt{n^2-1}
$$
for
$$
x = \frac{1}{2} \log \frac{n-1}{n+1}.
$$


text:
Q: How to model ui flow for ecommerce app in compose I'm building ecommerce app in compose where I have several composable screen like cart screen, address selection screen, payment selection screen etc and navigating them via navigation library.
I am not sure how to store temporary data until user reach last screen. For example, how to store what address (addressId is fine) is selected from address screen, which payment method selected from payment selection screen etc?


text:
Q: How to get views from fragments in onClick I have an activity with a String array and a Drawable array. I create fragments using a for loop in the onCreate according to the length of the arrays and use the String array to fill TextViews in the fragments.
I made the fragments clickable and added onClick in the fragment class.
I want to get the text from the fragment the user clicks, but when I click it only gets the text from the first fragment. How can I read the textviews in the different fragments.
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                            Bundle savedInstanceState) {
        int layoutId = getArguments().getInt("layout");
        View rootView = inflater.inflate(layoutId, container, false);
        TextView fragmentText = (TextView) rootView.findViewById(R.id.fragTextView);
        fragmentText.setText(getArguments().getString("fragText"));
        ImageView fragmentImage = (ImageView) rootView.findViewById(R.id.fragImageView);
        fragmentImage.setImageResource(getArguments().getInt("pic"));
        rootView.setOnClickListener(this);
        return rootView;
    }
        @Override
        public void onClick(View v) {

            String s = ((TextView)v.getRootView().findViewById(R.id.fragTextView)).getText().toString();
            Intent intent = new Intent(v.getContext(), LevelActivity.class);
            intent.putExtra("exerciseId", s);
            startActivity(intent);
        }

Thanks


text:
Q: Overwriting onclick value using jQuery I'm attempting to create a function that will select all anchor tags with both http and _gaq (because a lot of the links have event tracking on them), and then add Google Analytics cross-domain tracking linker method to the onclick event:
        $("a[href*='http:'][onclick*='_gaq']").each(function(){
            var href = this.href;
            var onclick = $(this).attr('onclick');
            var linker = "['_link', "+ "'"+href+"'"+"],";
            var output = [onclick.substr(0,10), linker, onclick.substr(10), " return false;"].join('');

            console.log('output : '+output);
         });

When I run this, it outputs:
output : _gaq.push(['_link', 'http://google.com'],['_trackEvent','dude','dude','dude']); return false;
This is what I'd like the new value for onclick to be, so I'm wondering how can I have the output value 'overwrite' the old onclick value?
I've also created a jsfiddle to illustrate.
Appreciate any help or suggestions.

A: Try
$("a[href*='http:'][onclick*='_gaq']").each(function(e){
    var href = this.href;
    var onclick = $(this).attr('onclick');
    var linker = "['_link', "+ "'"+href+"'"+"],";
    var output = [onclick.substr(0,10), linker, onclick.substr(10), " return false;"].join('');
    $(this).attr('onclick', output);
});

A: I found this question which probably gets you the answer you want:
$("a[href*='http:'][onclick*='_gaq']").each(function(){
     var href = this.href;
     var onclick = $(this).attr('onclick');
     var linker = "['_link', "+ "'"+href+"'"+"],";
     var output = [onclick.substr(0,10), linker, onclick.substr(10), " return false;"].join('');

     $(this).attr('onclick','').unbind('click');  // Get rid of the old one
     var f = new Function(output);                // create a function
     $(this).click(f);                            // Add your new onclick
  });

Edit: I was Led astray by a more recent comment with 26 upvotes. Switching back to my original form.
26 votes Yet it doesn't seem to work!, compare
http://jsfiddle.net/TN2wr/
with
http://jsfiddle.net/TN2wr/1/


text:
Q: How to have brackets completion in the terminal? I want my terminal to automatically close my brackets, quotation marks, etc.
For example, I want to type ( and I want it to complete to
(|)

where | represents the mouse cursor.
Is there a way to do this? If so, how?

A: bash reads ~/.inputrc file, which allows binding certain keys to macros. In our case, we need macro that automatically types in "()" and Ctrl+b (which is move back one word ) shortcut.
Open the file with gedit or any other text editor and type in the following
 "\C-]":"()\C-b"

That will bind Ctrl + ] to do what you want. Now open terminal or call a new instance of the shell and test it out.
You can try binding it to any other keyboard short-cut, but there is only so much you can do.


text:
Q: Vertx get event loop msg number I'm trying to find a way to get the current number of message that I have in the event loop.
I want to put some logs to know if the message are getting enqueue.
I have this Iterator, but I dont think it is since are eventExecutor
        Context context = vertx.getOrCreateContext();
        ContextInternal contextInt = (ContextInternal) context;
        EventLoop eventLoop = contextInt.nettyEventLoop();

Regards.

A: If you cast the result of .nettyEventLoop() as a NioEventLoop you can invoke the .pendingTasks method that should give you the information about the number of tasks scheduled in the event loop.
NioEventLoop eventLoop = (NioEventLoop) ci.nettyEventLoop();
System.out.println(eventLoop.pendingTasks());

JavaDoc about NioEventLoop implementation:
https://netty.io/4.0/api/io/netty/channel/nio/NioEventLoop.html


text:
Q: CSS not positioning properly - Safari I've a web page that has two divs, one on the left, one on the right. I've got these positioned using float: left/right;
All is well in FireFox, IE (including IE6!!!) and Chrome. But for some reason in Safari, the right hand div is turning up underneath the left hand div. So, I put a border around the divs and i notice that in Safari only, the right hand div thinks it's part of the other div. I've checked the page for divs and closing divs and all looks good.
I'm also a bit confused as to why it works in Chrome but not Safari. Are these two browsers both Webkit browsers??
All help appreciated

A: The "most universally accepted" method to do most left/right divs is to float both divs left, clearing the float immediately after.  The easiest way to clear is to add a div immediately after the two divs with the following:

That will ensure that anything after the floated elements is not getting bumped around by the float properties, which will cascade throughout until they are closed.
Now, some browsers have issues with margins/padding (mostly IE).  Temporarily assign a background (if there already isn't one) and a width that's smaller than you'd expect to need it--i.e. if you wanted two divs that are both 50% of the screen, assign both a 48% width for testing purposes.  Now, does that solve the problem?  If so, Safari might be reacting negatively to the floats/margins set on those divs.  Tweak the margins and padding, rinse, repeat.
Main content floated divs can get to be a mess in a hurry, especially if you're trying to go 100% of a parent or the screen in general.  You can easily get by this with a css reset or my personal favorite, a grid system like 960.gs  Otherwise, you're left to do arbitrary tweaking that either a) looks good only in --most-- browsers or b) uses painful browser-specific stylesheets.  No thanks on either!

A: Try this, It will fix your problem

.container{ clear:both}
.container .label-info {  float:right; position:relative; min-width:100px;}
.container label {  float:left;}

Right side

  My Label

A: Relating to the answer above (by bpeterson76)
Mine got fixed by adding to the parent HTML tag which contains the float as:
style="width: 100%;"

I know this might be an old question, but i face this issue today as well.
Hope that helps someone.


text:
Q: Registration of Apple Pass Type Certificate I implement feature of issuing Apple Wallet Pass for one of my clients.
I plan to offer this feature to another clients. For each client Apple Pass Type Certificate is required.
Who have to register Apple Pass Type Certificate. Me or my client? From one side I don`t want to add some difficulties for my clients and it is easy to register certificate by my self. From another side I am not sure which risk I will have in this case.
Thanks for help.

A: Your client has to provide you with the certificate.
There is an extensive attachment (Attachment 5) in the developer terms and conditions (you can find these under documents when logged into the Apple Developer Portal) that details how certificates can per used.

Pass Type ID Usage and Restrictions
You may use the Pass Type ID only for purposes of digitally signing
  Your Pass for use with Wallet and/or for purposes of using the APN
  service with Your Pass.  You may distribute Your Pass Type ID as
  incorporated into Your Pass in accordance with Section 2 below only so
  long as such distribution is under Your own trademark or brand. To the
  extent that You reference a third party's trademark or brand within
  Your Pass (e.g., a store coupon for a particular good), You represent
  and warrant that You have any necessary rights.  You agree not to
  share, provide or transfer Your Pass Type ID to any third party
  (except for a Service Provider and only to the limited extent
  permitted herein), nor use Your Pass Type ID to sign a third party's
  pass


text:
Q: To test convergence of infinite series $x^2(\log 2)^p + x^3(\log 3)^p + x^4(\log 4)^p +\dots$
To test convergence of infinite series $x^2(\log 2)^p + x^3(\log 3)^p + x^4(\log 4)^p +\dots$

My approach to the above problem:
let $u_n = x^{(n+1)}(\log(n+1))^p$. the $u_{(n+1)}= x^{(n+2)}(\log(n+2))^p$
now, $n \log\frac{u_n}{u_{n+1}}$=n\log($\frac{1}{x}$) + n$p$[\log(\log(n(1+$\frac{1}{n}$))-(\log(n(1+$\frac{2}{n}$)))]. After that I have used the expansion for $\log (1+x)$ and got stuck.
It seems if I take the limit of $n \log\frac{u_n}{u_{n+1}}$, i.e $\lim_{n\to\infty}n \log\frac{u_n}{u_{n+1}}$ =$\infty$ $(>1)
$$\Rightarrow$The series seems to be convergent, which is not the answer. Please clarify the mistake and guide me.

A: Testing the infinite series:
$$x^2\ln^{\text{p}}(2)+x^3\ln^{\text{p}}(3)+x^4\ln^{\text{p}}(4)+\dots=\sum_{n=2}^{\infty}x^n\ln^{\text{p}}(n)$$
Use the ratio test:
$$\lim_{n\to\infty}\left|\frac{x^{n+1}\ln^{\text{p}}(n+1)}{x^n\ln^{\text{p}}(n)}\right|=\lim_{n\to\infty}\left|x\cdot\frac{\ln^{\text{p}}(n+1)}{\ln^{\text{p}}(n)}\right|=|x|\cdot\lim_{n\to\infty}\left|\frac{\ln^{\text{p}}(n+1)}{\ln^{\text{p}}(n)}\right|=|x|$$
By the ratio test, the series converges when $|x|<1$.

For, the limit:
$$\lim_{n\to\infty}\left|\frac{\ln^{\text{p}}(n+1)}{\ln^{\text{p}}(n)}\right|=\left[\lim_{n\to\infty}\left|\frac{\ln(n+1)}{\ln(n)}\right|\right]^{\text{p}}=\left[\lim_{n\to\infty}\left|\frac{\frac{1}{1+n}}{\frac{1}{n}}\right|\right]^{\text{p}}=\left[\lim_{n\to\infty}\left|\frac{1}{1+\frac{1}{n}}\right|\right]^{\text{p}}=1$$

A: The point is that the coefficient $(\log n)^p$ grows very slowly ($p$ being fixed). Therefore the series should have the same radius of convergence as the geometric series $x+x^2+x^3+\ldots$, something easily established using the ratio test. Using the expansion of log is not the right approach here.

A: There are a lot of possibilties to check convergence.
E.g. the ratio test here for $p\ge 0$ is:
$$|\frac{x^{n+1}(\ln(n+1))^p}{x^n(\ln n)^p}|=|x|(\frac{\ln(n+1)}{\ln n})^p<1$$
This means $|x|<(\frac{\ln n}{\ln(n+1)})^p<1$: Convergence for $|x|<1$.


text:
Q: How to Link to mosquitto lib in cmake? I have installed mosquitto lib in my Rpi using this tutorial.
/usr/local/bin has mosquitto_pub and mosquitto_sub and the mosquitto server deamon is in /usr/local/sbin.
Then trying to link the library in my cmake file as follow.
cmake_minimum_required(VERSION 2.6)

PROJECT(MosquittoTest)
# The version number.
set (VERSION_MAJOR 1)
set (VERSION_MINOR 0)

include_directories("${PROJECT_BINARY_DIR}")

# Linked libariries
#For MQTT
#location of raspicam's cmake file is /usr/src/raspicam-0.1.3/build
link_directories(/usr/local/sbin)
target_link_libraries (MosquittoTest  mosquitto)

ADD_EXECUTABLE(MosquittoTest MosquittoTest.cpp)

# add the install targets
install (TARGETS MosquittoTest DESTINATION bin)
install (FILES MosquittoInterface.h DESTINATION include)

Then I have error as Can't specify link library for target MosquittoTest.
Somebody has link the mosquitto lib in gcc make as
CC = gcc
CFLAGS = -I
DEPS = mosquitto.h

LIBS = -llibmosquitto

%.o: %.c $(DEPS)
    $(CC) -c -o $@ $< $(CFLAGS)

make: test.c
    $(CC) -m32 -Wall -o $@ $^ $(CFLAGS) $(LIBS)

.PHONY: clean

What could be wrong with my cmake file?

A: Using Modern CMake, you can use pkg-config imported targets like so:
cmake_minimum_required(VERSION 3.0)
project(MosquittoTest VERSION 0.1)

find_package(PkgConfig REQUIRED)
pkg_check_modules(Mosquitto IMPORTED_TARGET libmosquitto REQUIRED)

add_executable(${PROJECT_NAME} MosquittoTest.cpp MosquittoInterface.h)
set_target_properties(${PROJECT_NAME} PROPERTIES VERSION ${PROJECT_VERSION})
target_link_library(${PROJECT_NAME} PkgConfig::Mosquitto)

include(GNUInstallDirs)
install(TARGETS ${PROJECT_NAME})
install(FILES MosquittoInterface.h DESTINATION ${CMAKE_INSTALL_INCLUDEDIR})

All compile options, link options, link targets, etc... will be set for you.

A: The mosquitto library is called mosquitto not libmosquitto.
JimsFridge: JimsFridge.cpp StopWatch.cpp
    $(CXX) $^ -o $@ -lwiringPi -lstdc++ -lmosquitto


text:
Q: Find an orthogonal basis of inner product Let's define dot procduct $<A,B>=Trace(A B^T)$ over $M_{n \times n}(\mathbb{R})$
Find basis or system of equations describing an orthogonal $W^\perp$ subspace to subspace $W$ which consist of matrices whose trace is $0$
I'd be greatful for any hints, since I don't know how to start this one


text:
Q: ERROR: The install method you used for conda--probably either `pip install conda` or `easy_install conda`--is not compatible I need conda environment to run some python repositiory. Earlier I had code in my windows PC, I installed the Anaconda shell and every thing else was good to go.. easy peasy!!
But, now I have moved to the code to the server(because of memory requirements). Im using Putty client to access that server and all the operations must be performed using the Putty shell. How do I run conda from there? I installed conda using pip install conda but every time I try to run conda command, it throws following error
ERROR: The install method you used for conda--probably either `pip install conda`
or `easy_install conda`--is not compatible with using conda as an application.
If your intention is to install conda as a standalone application, currently
supported install methods include the Anaconda installer and the miniconda
installer.  You can download the miniconda installer from
https://conda.io/miniconda.html.

upon searching, I found out that the conda that is being installed using pip is corrupted. so I went ahead and installed mini conda as per the instructions in the following link:
https://mediawiki.middlebury.edu/CS/Useful_Tools

It did install the miniconda smoothly but if it try to run it still gives me same error as above.
can any one help? do I need to unistall the conda which I installed using pip?

A: You need to reopen the terminal for the changes to take effect!

A: Did you uninstall the first installation of conda. It seems like you didn't that's why every time you run conda you get the same error because it refers to the first installation one. If you did uninstall it and you still get the error make sure to add miniconda to PATH.

A: The better option is reinstall anaconda.
Download the installer.
https://www.anaconda.com/products/individual#Downloads]
Create an anaconda folder
mkdir
wget https://repo.anaconda.com/archive/Anaconda3-2021.05-Linux-x86_64.sh
Go to your home directory
cd ~
Tape
sha256sum /home/username/anaconda/Anaconda3-2021.05-Linux-x86_64.sh
Go to Anaconda Folder.
cd anaconda
tapr
ash Anaconda3-2021.05-Linux-x86_64.sh
Select yes for all installation options.
Check the installation:
conda --v


text:
Q: There is an error on trying to run grunt watch Whenever I run grunt watch I get the following error:

grunt[48126]: ../src/node_contextify.cc:627:static void node::contextify::ContextifyScript::New(const FunctionCallbackInfo<v8::Value> &): Assertion `args[1]->IsString()' failed.
 1: 0x10003a5ab node::Abort() [/usr/local/bin/node]
 2: 0x1000396aa node::AddEnvironmentCleanupHook(v8::Isolate*, void (*)(void*), void*) [/usr/local/bin/node]
 3: 0x10005d027 node::contextify::ContextifyScript::New(v8::FunctionCallbackInfo<v8::Value> const&) [/usr/local/bin/node]
 4: 0x1001d2524 v8::internal::FunctionCallbackArguments::Call(v8::internal::CallHandlerInfo*) [/usr/local/bin/node]
 5: 0x1001d18ce v8::internal::MaybeHandle<v8::internal::Object> v8::internal::(anonymous namespace)::HandleApiCallHelper<true>(v8::internal::Isolate*, v8::internal::Handle<v8::internal::HeapObject>, v8::internal::Handle<v8::internal::HeapObject>, v8::internal::Handle<v8::internal::FunctionTemplateInfo>, v8::internal::Handle<v8::internal::Object>, v8::internal::BuiltinArguments) [/usr/local/bin/node]
 6: 0x1001d134a v8::internal::Builtin_Impl_HandleApiCall(v8::internal::BuiltinArguments, v8::internal::Isolate*) [/usr/local/bin/node]
 7: 0x12a0f384fb7d
Abort trap: 6

I have grunt-cli@1.3.2 installed globally and the following on local dev dependencies in my project:

    "grunt": "^1.0.1",
    "grunt-contrib-clean": "^1.0.0",
    "grunt-contrib-jshint": "^1.1.0",
    "grunt-contrib-requirejs": "^1.0.0",
    "grunt-contrib-sass": "^1.0.0",
    "grunt-contrib-watch": "^1.1.0",
    "grunt-grunticon": "^2.3.1",
    "grunt-includes": "^1.0.0",
    "grunt-sass": "^2.1.0",

A: So I had my node at 11.0.0 which wasn't compatible with grunt. I downgraded it to 8.1.0 and it now works.

A: Run the following command:
npm i natives


text:
Q: Java auto mouse I am making a program which plays minesweeper automaticaly. I am using the mouse press function to click the squares. Is there a way of giving focus to the minesweeper program without clicking on the tab at the bottom of the monitor??? Thanks

A: You  can simulate mouse click using Robot (not rajni :P).

*

*Here is example

A:
Is there a way of giving focus to the minesweeper program without clicking on the tab at the bottom of the monitor?

You mean the Windows task bar?
An application automatically gets focus when it is started. If the user clicks on another applcation then the user must also request focus to go back to the application by clicking on the task bar or by using Alt-Tab.
If your program doesn't have focus then you can't just grab focus, because the user is in control of the desktop and not your program.