text:
Q: How to add Column in Drupal's content View using VBO? I want to add column into drupal's Content View.
In Drupal's admin panel, when we click on content Management-->Content-->List
the contents are loaded in table with columns Title|Type|Author|Status|Operations
I want add one more columns to this table and that is date and want to sort according to date.
How I can do this?

A: I wouldn't go through the trouble of altering that table. If you do so decide on going on that path here's a post that will help you: Add column to content list
The easiest way to do this is to install the Views module. Then

*

*add a new node type view

*add a page display

*Fields (After you add the fields you can put them in the desired order):

*

*Node: Title

*Node: Type

*Note: Published (Status)

*Node: Post date (Created)

*User: Name (Author)

*Sort criteria

*

*Node: Post date (Created)

*Basic settings

*

*Style: Table

*click the small settings (gear link next to it) and specify Default sort and which fields are Sortable.

You might have to do some small other tweaks for the view or fields. Views is a very powerful module and once you master it you can get just about any page you can image.


text:
Q: WordPress on a CentsOS 6.4 with high CPU loads I'm helping a friend out, he's running a CentosOS 6.4 server, with Apache/2.2.24 (Unix) httpd server. His site is running on WordPress 3.81 (latest version) and he's having 30,000 unique page views per day.
He is running this setup on a dedicated Intel Xeon Dual Core, 2.3GHz (4 threads), 5GB RAM server.
His load averages are way above 1 (around 14-16) which I know is wrong. As far as I'm concerned his hardware setup is fair.
Is there anything he can do to optimize his server other than upgrading hardware?
I was told that the plugins might make the troubles, here's a list of the plugins installed:
Askimet , All In One SEO Pack , Configurable Tag Cloud, Contact Form 7, Dave's Wordpress Live Search, Google XML Sitemaps, Multi-column Tag Map, Newsletter, Popular searches tag cloud, Search Metter, SEO Friendly Images, UpdraftPlus - Backup/Restore, Video Thumbnails, Video Thumbnails Pro, Wordpress Mass Email to users, WP-PAGENAVI, WP-PostRatings, WP-PostViews, WP Super Cache
Please let me know if any additional information is needed.

A: Fixing the performance problems on a server is a really hard job. There is no magic fix. Just collecting the baseline metrics will take at least a couple of days. A good performance analyst will then spend several hours looking at your current config before coming up with a proposal for intervention. This then needs to be tested over a comparable period to the baseline exercise.

he's having 30,000 unique page views per day.

Sorry, but this is almost a completely meaningless metric. The only information it conveys is about your level of experience, not about the demands placed on the system.
Worpress is a particularly slow and heavy piece of software. While there is a wealth of stuff which can be done to improve it's performance, it's way too complex to detail here. For a quick win move the output of the tag plugins into cacheable HTML fragments and install an ESI capable reverse cache.

A: Read http://www.kalzumeus.com/2012/02/09/why-i-dont-host-my-own-blog-anymore/
He talks about WordPress speed, what he did to make it faster, and links to http://speed.wpengine.com/ a tool to analyse a WordPress site and note any obvious causes of slowness for it.

redpajama_set_name: RedPajamaStackExchange


text:
Q: unexpected output when calculating the mean of dataset using tensorflow's mean function I am trying to calculate the mean  of a dataset using tensorflow
dataset = numpy.loadtxt("My_file.csv", delimiter = ';')
Y = dataset[100:151,1]
Mean = tf.reduce_mean(f.convert_to_tensor(Y, numpy.float32), axis = -1)

But I am getting this output error
Tensor("Mean:0", shape=(), dtype=float32)

Is there any clue what I am doing wrong. Thanks


text:
Q: Uncaught (in promise) Error: A listener indicated an asynchronous response by returning true, but the message channel closed before a response I am finding the 'Uncaught (in promise) Error: A listener indicated an asynchronous response by returning true, but the message channel closed before a response was received' error in the background.js. My chrome extension works but the dev tools displays a lot of these errors on background.js
I recently migrated my chrome extension from Manifest V2 to Manifest V3 and since then I am finding the error.
This is the place from where the error seems to be arising :
const browser = chrome || browser;

// Listen for messages from content script
browser.runtime.onMessage.addListener(
    function (request, sender, sendResponse) {
         var frameId = sender.frameId || 0;

            if (request.type == "connect") {
                connect(sender.tab, frameId);
                sendResponse({ success: true });
            } else if (request.type == "disconnect") {
                disconnect(sender.tab, frameId);
                sendResponse({ success: true });
            } else if (request.type == "send") {
                sendNativeMessage(request.data, sender.tab);
                document.addEventListener('nativeMessage',
                    function handleNativeMessage(e) {
                        sendResponse(e.detail);
                        document.removeEventListener(e.type, handleNativeMessage);
                    }, false);

               sendResponse({});
               return true;
            }
    });

The sendresponse is processed in ContentScript :
const browser = chrome || browser;
self.addEventListener("message", function(event){
    var request = event.data;
    if(request != null && request.type == "SendMessage")
    {
        ProcessNativeMessage(request.data);
    }

});

function ProcessNativeMessage(nativeMessageData) {
  var request = new Object();
  request.data = nativeMessageData;
  browser.runtime.sendMessage(request,handleExtensionResponse);
}

function handleExtensionResponse(value)
{
    //alert(value);
};

I played around by returning true, returning false, returning undefined, sending empty response and even disabling the other extensions but none of these changes worked.
I even tried changing the code with async/await as suggested here but it makes no difference.

A: Does anything change if you rewrite the code like this?
Anyway I can't reproduce an extension with native messaging, sorry.
P.S. Before any scientist decides to downvote me badly, I want to ensure that if the solution doesn't work I'm willing to cancel the answer.
const browser = chrome || browser;

var globSendResp, globReqTypeSend;      //(*)

// Listen for messages from content script
browser.runtime.onMessage.addListener(function(request, sender, sendResponse) {
    var frameId = sender.frameId || 0;
    globReqTypeSend = false;            //(*)
    if (request.type == "connect") {
        connect(sender.tab, frameId);
        sendResponse({ success: true });
    } else if (request.type == "disconnect") {
        disconnect(sender.tab, frameId);
        sendResponse({ success: true });
    } else if (request.type == "send") {
        globReqTypeSend = true;         //(*)
        globSendResp = sendResponse;    //(*)
        sendNativeMessage(request.data, sender.tab);
        //sendResponse({});             //(*)
        return true;
    }
});

document.addEventListener('nativeMessage', function handleNativeMessage(e) {
    if (globReqTypeSend)
        globSendResp(e.detail)
}, false);


text:
Q: Read data from ethernet on a docker container What kind of configuration for docker do I need to read data from host's ethernet port inside a container? On the host machine (Ubuntu 20.04.4), I go to network -> Wired -> IPv4 Method, select Manual and set the static address and netmask from where I can receive the data via a socket. When running the code inside a docker container that is on the default network (so no configuration related to networking at all), I don't receive any data.

A: The solution was to publish my port with UDP, like so:
ports:
- "50000:50000/udp"


text:
Q: Training data and testing data from the same sensor When using learning methords, We have training and testing data.
I'd like to confirm that
1)whether the training data and testing data must capture from the same sensor 2)What if they are from different sensors?
3) If they must be captured from the same sensor, are there any methods to uniform the data even they are not from the same sensor?
Thank you.

A: Yes, you would need both train and test data from the same sensor because of measurement error and detection bias that's specific to that sensor.  If the test data came from a sensor that's always different from the sensor training data came from, you could have total system failure.  Each sensor has it's own precision, bias, detection limits, etc, so that has to be distributed to both training and testing.
The idea with testing and training is not so much what you are thinking about, but rather the idea that when training the algorithm, the objects used in testing were never used in training.  It's called selection bias.  But you can have have objects from the same sensor used in training or testing.
If, however, the measurement wavelength or angle (pitch) of each sensor is different, then you are dealing more with a problem requiring MUlti-Signal Classification or Pisarenko harmonic decomposition.


text:
Q: Maxwell's Equation in Empty Space Consider Maxwell's equation
$$
\begin{cases}
\frac{\partial B}{\partial t} = - \text{c} \cdot \text{curl} (E), \\
\frac{\partial E}{\partial t} = \text{c} \cdot \text{curl} (B), \\
\text{div} (E) = 0, \\
\text{div} (B) = 0
\end{cases}
$$
for empty space. How do the second two equations play a role when solving this system of PDEs? Specifically, when using finite differences, why do the first two not supply enough information? It appears to me that, when doing finite differences, each step forward in time is completely determined by the first two equations.

A: If the pair $(E,B)$ satisfy the first two equations then $(E',B') = (E + \nabla\phi(x), B + \nabla\psi(x))$ also satisfy the same equations:
$$\frac{dE'}{dt} = \frac{dE}{dt} = c\nabla\times B = c\nabla\times B'$$
$$\frac{dB'}{dt} = \frac{dB}{dt} = -c\nabla\times E = -c\nabla\times E'$$
since $\nabla\times \nabla f \equiv 0$. Thus the first two equations only determine $(E,B)$ up to a time-independent curl-free part. To get a closed system we therefore need the last two equations.
Taking the divergence of your first two equations we get
$$\frac{d(\nabla\cdot E)}{dt} = 0 = \frac{d(\nabla\cdot B)}{dt}$$
so the divergence of the fields are conserved. Thus for a numerical evaluation the last two equations does not enter in the evolution (in a perfect world where the numerical method does not introduce a divergence). The way it enters is in the initial conditions.
The zero divergence conditions can serve as a good check that the numerical method is working as intended (evaluate the divergence of $E$ and $B$ as you integrate and check that it stays close to zero).


text:
Q: In Keras, how to load the best weights saved during training by the ModelCheckpoint callback? From the doc, I use:
checkpoint_filepath = 'tmp/checkpoint'
model_checkpoint_callback = keras.callbacks.ModelCheckpoint(
        filepath=checkpoint_filepath,
        save_weights_only=True,
        monitor='val_loss',
        mode='min',
        save_best_only=True)

But when running the training, I get:

OSError: Unable to create file (unable to open file: name =
......./tmp/checkpoint', errno = 21, error message = 'Is a directory', flags = 13, o_flags =
242)

Which indicates that the 'checkpoint_filepath' must be a path toward a file (and not a directory), so I replaced it with:
checkpoint_filepath = 'tmp/checkpoint/weights.{epoch:02d}-{val_loss:.2f}.hdf5'

But then, when I want to load the network (and to retrieve the best weights of course, the ones that correspond to the lowest val_loss!) with (also from the doc):
net.load_weights('tmp/checkpoint')

I get:

OSError: Unable to open file (file read failed: time = Sun Nov 20
09:39:54 2022 , filename =
......../tmp/checkpoint', file descriptor = 27, errno = 21, error message = 'Is a directory',
buf = 0x7ffeae8d2e50, total read size = 8, byt)

So, how do I load the weights with Keras so that it loads the best weights that were saved by the ModelCheckpoint callback ?


text:
Q: Firebase toObject with generic type It's my first question on StackOverflow, so if I'm doing something wrong, please help me.
I've been working on an Android application using Kotlin and Firebase Firestore and I have a data class with a generic type T property on it.
Well, my problem is: I'm getting an error when I try to use the toObject method to parse the Firestore object to my POJO. The error message says to use GenericTypeIndicator, but it doesn't exist on Firestore SDK. I tried to install the Firebase Database SDK to import this interface, but it didn't work as well.
Here's my POJO class:
@Parcelize
data class Policy<T : Parcelable>(var id: String = "",
                              var type: String = "",
                              var paid: Boolean = false,
                              var price: Double = 0.0,
                              var uid: String = "",
                              var policy: T? = null) : Parcelable

Here's my repository method:
override fun getPolicies(uid: String): Single<List<Policy<T>>> =
    Single.create {emitter ->
        db.collection(POLICIES_COLLECTION)
                .whereEqualTo(FIELD_UID, uid)
                .get()
                .addOnSuccessListener {
                    emitter.onSuccess(it.toObjects(Policy::class.java) as List<Policy<T>>)
                }
                .addOnFailureListener {
                    emitter.onError(it)
                }

    }

Anyone can help me to figure how to make it work?


text:
Q: Unable to solve nonlinear equation using scipy.optimize.fsolve I am using scipy.optimize.fsolve to solve a nonlinear equation in Fourier pseudospectral space but it does not work. It gives the same output as the input u0, which is a trivial solution. The equation I am trying to solve is:
$\frac{1}{2}\frac{\partial (u^{2})}{\partial x}+\frac{\partial^{2}u}{\partial x^{2}}+\nu\frac{\partial^{4}u}{\partial x^{4}}=0$
The code is given below. Can anyone please help me on how to get a non-trivial solution?
import numpy as np
import scipy.optimize

M = 16
nu = 0.4

def kssol(M):

    kkx = np.fft.fftfreq(2*M)*2.*M

    kx = kkx[0:M+1]

    def func(vec):

        linspec = -(kx**2)+(nu*(kx**4))
        lin = linspec*np.fft.rfft(vec)
        nlin = np.zeros_like(lin)
        nlinre = vec*vec
        nlin = 0.5*1j*kx*np.fft.rfft(nlinre)
        sol = lin+nlin
        rhs = np.zeros_like(sol, dtype='complex')
        sol -= rhs

        return np.fft.irfft(sol)

    u0 = np.zeros((2.*M,))
    u = scipy.optimize.fsolve(func, u0)

    return u


text:
Q: Why can't C++ locals captured by reference be accessed through the stack pointer? I noticed that compilers implement capture by reference by making an array on the stack of pointers to the captured locals, which can be passed to the lambda to access them. That surprised me because the compiler knows where the locals are relative to the stack pointer, so I thought it could just pass the stack pointer. That would make one less indirection in the lambda and save the work of putting the pointers on the stack. I was wondering why the compiler can't do that?
For example, this C++:
#include <functional>
extern void test(std::function<void()>& f);
int test2(int x, int y)
{
    std::function<void()> f([&]() { x += y; });
    test(f);
    return x;
}

generates this assembly on Clang 13 -O3 (comments mine):
mov     dword ptr [rsp + 8], edi    // put x on the stack
mov     dword ptr [rsp + 12], esi   // put y on the stack
lea     rax, [rsp + 8]
mov     qword ptr [rsp + 16], rax   // put &x on the stack
lea     rax, [rsp + 12]
mov     qword ptr [rsp + 24], rax   // put &y on the stack
mov     qword ptr [rsp + 40], offset std::_Function_handler<void (), test2(int, int)::$_0>::_M_invoke(std::_Any_data const&)
mov     qword ptr [rsp + 32], offset std::_Function_handler<void (), test2(int, int)::$_0>::_M_manager(std::_Any_data&, std::_Any_data const&, std::_Manager_operation)
lea     rdi, [rsp + 16]
call    test(std::function<void ()>&)

and similar on GCC and MSVC.

A: What you see is not the non optimized lambda, but all the stuff around std::function.
If you simplify your code to:
template < typename F>
void test(F& f )
{
    f();
}

int test2(int x, int y)
{
    auto f=[&]() { x += y; };
    test(f);
    return x;
}

int main()
{
    return test2(1,2);
}

The assembly becomes
test2(int, int):
        lea     eax, [rdi+rsi]
        ret
main:
        mov     eax, 3
        ret

Which is fully optimized out all the stuff and propagate the result as constant.
The the difference: without std::function vs with std::function

A: *

*Here is godbolt demo (extended a bit).

*I've added testABI to show that parameters to you function are passed by registry.

useTestABI():                        # @useTestABI()
        mov     edi, 3
        mov     esi, 5
        jmp     testABI(int, int)                    # TAILCALL

*So in test2 starts by creating x and y to create locals on stack so it would be possible to pass them by reference.

*After that lambda is created on stack, so addresses of x and y are saved to stack. Also addresses of functions to be invoked when lambda is used (polymorphism without vtable) are added to labda on stack

Now you do not know what test will do with f. It can clone f so in such case f have to be copied from stack to other place. Also on other side when test is compiled compiler do not know what kind of lambda was passed. Creating copy may have side effect or not. So creating a copy must be possible and must be compatible with predefined ABI.
So this shortcut you are describing is possible only when compiler could known content of test. When content of test is not know f must be fully created to make it possible to clone it when needed.


text:
Q: Image from database does not display on web page i am trying to display the image on web page from database , but it just displayed the file name of my image on web page
the code for fetching image is
<?php
error_reporting(0);
$query = "SELECT * FROM blog_posts";
$data  = mysqli_query($link, $query);
$total = mysqli_num_rows($data);

while ($result = mysqli_fetch_assoc($data)) {

    echo $result['title'] . "
" . $result['author'] . "
" . $result['file_name'] . "
" . $result['body'] . "
";

}

?>

A: just change this line
echo $result['title'] . "
" . $result['author'] . "

" . $result['body'] . "
";

but you should get the full directory of file not just name or
you should write it like this
$file_name ="/dir/dir/".$result['file_name'];

and after that you can put the $filename in img tag like this
echo "";


text:
Q: Missing data and Attributes selection My data is 1,785,000 records with 271 features. I'm trying to reduce number of features used to build the model.
Q1.  while exploring the data I found that some features are almost all missing data, like only 25 records has value for this feature and the others records has missing values, so I thought that is not informative enough and it's better to eleminate those features, am I right? and if I am right, for what level I can do that, I mean if 90%, 80%, etc.. of each feature are missing values, when I can decide to get rid of these features? (taking in consideration that it is the dependent variable is N/Y and only %1.157 of the whole data is belonging to Y).
Q2. for each individual in the dataset, there are 64 trait_type listed, where each one can take one of the values [1 or 3 or 5]. my question is: if some trait-type take only value [5] or missing dat for all the record, does it have any value or again we can eliminate that feature?
Q3. if the choice is to delete these features, how to delete column from data.frame in R?
Thank you
Update:
I'm trying to use caret package to do the variable selection.
I applied this:
ctrl<- rfeControl(functions = lmFuncs, method="cv", verbose = FALSE, returnResamp=
"final")

lmprofile<- rfe(x,y, sizes = subsets, rfeControl = ctrl)

where x is the data.frame that have 270 dependant variables and y is the factor of the independent variable which has value Y/N. I got this error:
Error in { :
  task 1 failed - "contrasts can be applied only to factors with 2 or more levels"
enter code here
In addition: There were 11 warnings (use warnings() to see them)

any help please?

A: Just because much of your data in one column is missing doesn't mean that column will not be predictive, it's just the same as having many of the same value in that column.
Of course there is a cutoff, if that column can only help you distinguish between a few cases (of many) then it can be removed and could only affect overall model strength a little.
To help you decide whether to keep the column, you could build a univariate model with it - where the dataset just includes that column and the dependant variable, and look at the strength of that model.  If it's not much better than random, then it's probably safe to drop the column.


text:
Q: Within a method m in a class C, isn't this.getClass() always C? Within a method m in a class C, isn't this.getClass() always C?

A: Nope:
public class C
{
    public void m()
    {
        System.out.println(this.getClass());
    }
}

public class Child extends C {}

Then:
new Child().m(); // Prints Child

A: No. Example:
public class Test {
  public static void main(String [] args) throws Exception {
    A a = new B();
    a.reportThis();
  }
}
class A {
  public void reportThis() {
    System.err.println(this.getClass().getName());
  }
}

class B extends A { }

A: No, it isn't. If there are subclasses.
class C {
   Class m() {
      return this.getClass();
   }
}
class D extends C { }

and then you can have:
C c = new D();
c.m(); // returns D.class

A: The keyword this refers to the object (instance of the class) that is in scope. It means the instance on which the method was called- which in turn means the instances of subclasses as well can be referred to by the keyword 'this'.


text:
Q: IE8 only using first session cookie Some background information about the problem:
My domain, is in this format: http://example.com/
Hosted On: Shared Hosting Server.
Protected Mode: Off.
Application suffers with: IE8.
Application doesn't suffer with: Chrome, or FireFox.
I log in to the application with the following:
function login(){
    session_regenerate_id();
    $_SESSION['thumbprint']=nonce(session_id().'thumbprint',86400);
}

function nonce($str,$expires){
    global $config;
    return sha1(date('Y-m-d H:i',ceil(time()/$expires)*$expires).$salt.$str);
}

After logging in, I log out with:
function logout(){
    session_unset();
    session_destroy();
    header("Location: http://example.com");
    die();
}

The Problem: If I log in, and log out, any other time I try to log in the session does not start. Why is this?

A: I initially had:
session_regenerate_id();

But this will not work becuase according to PHP manual:
"session_regenerate_id() will replace the current session id with a new one, and keep the current session information."
http://php.net/manual/en/function.session-regenerate-id.php
And becuase IE8:
"uses the first session cookie set and not the last as in Firefox."
http://anvilstudios.co.za/blog/php/session-cookies-faulty-in-ie8/
To fix this problem all you need to do is set:
session_regenerate_id(true);

Which deletes old session id and forces IE8 to use the new one.


text:
Q: Mandatory Merged Cell Input for excel 2016 I had a merged cell from D4 to H4, I want the cells to be mandatory. I had tried the following code but does not work.
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
Dim c As Range
Dim cel As Range

Set c = Range("D4:H4")

Application.EnableEvents = False
If Not Intersect(Target, c) Is Nothing Then
  For Each cel In c
    If cel.Text = "" Then
      Application.Goto reference:=c, Scroll:=True
      MsgBox ("Field Cannot Be Blank")
      Exit For
    End If
  Next cel
End If
Application.EnableEvents = True
End Sub

I also had another cell need to be mandatory, H2. This code already works, I want to combine the codes for D4 to H4 and H2 together.
Private Sub Workbook_BeforeClose(Cancel As Boolean)
If Cells(2, 8).Value = "" Then
  MsgBox "Cell H2 requires user input", vbInformation, "Please filled up the
  mandatory cells"
  Cancel = True
End If
End Sub

Any help and suggestion is appreciated.

A: Thanks to @Rik Sportel, I tried to remerged the cells and apply elseif statement and it works now.
Private Sub Workbook_BeforeClose(Cancel As Boolean)
If Cells(4, 4).Value = "" Then
  MsgBox "Cell D4 requires user input", vbInformation, "Please filled up the mandatory cells"
  Cancel = True
ElseIf Cells(2, 8).Value = "" Then
  MsgBox "Cell H2 requires user input", vbInformation, "Please filled up the mandatory cells"
  Cancel = True
End If
End Sub


text:
Q: Difference between a 'class diagram' and a 'design class diagram' I have an assignment that states the following criteria:
For this view you may use a truncated version of
your Design Class Diagram (DCD) including
only the architecturally significant classes.

For context, this is for the Logical View of a 4 + 1 Architectural View. How does a design class diagram (DCD) differ from a regular class diagram? Is it the UML diagram without the functions or variables included (i.e. just the names of the classes and their interactions with each other)?

A: Most of the time, people model their code. That's good! In that case, class diagram modeling is used to graphically represent the structure of (object-oriented) classes: class, method, attribute, annotations with stereotypes. Imagine all the JPA, Spring, whatever annotations in the class diagram of a JPA-J2EE based architecture...
As it's said above, the "design class diagram" should only design your domain model, from an architecture level. What are the basic entities your structural system rely on?
No details about the programming language, no "dto", "dao" or technical stuff like that.
Here's a good example I use: online shopping cart domain model. It only contains the  architecturally significant classes.
HTH, Tom

A: Still its amibigous to understand. The main difference between analysis class diagrams and design class diagram is the analysis phase focus on designing a class diagram without concerning about the implementation detail. where as, desgin modelling concern with the implementaion and architechture since, it the high-level static view of the system.


text:
Q: How do I run a login system and comment system that will also display the username when posting in one server/port? I am currently working on a project that needs a login/registration system which than goes to a comment system. I want to be able to run that comment system and than display the username of the person who posted the comment. The problem is I have a socket.io comment system that runs express. At the same time the login system uses express. Resulting to the fact that I can only run one of them at a time. In my case the login system is working fine but the comment system cannot post or display any comments.
Below: I have only just started to learn nodejs so, there might several errors. I also have two server files one for the login system and one for the comment system.
this is how I have configured the files


text:
Q: setting one line item 'active' at a time in vue I have a small unordered list in a vue template:

New Comment

Note

and I then have a data variable for commentActive and a function I call to set the input name:
data () {
    return {
        commentActive: false,
    }
},
methods: {
   setInputName(str) {
     this.inputName = str;
     this.commentActive = true;
   },

}

And this is functional but it is obviously setting BOTH inputs to active when I click on one of them. How do I alter this to only set the clicked line item active?

A: You need to use a unique identifier to determine which comment is active. In the most rudimentary way using your current setup:

    New Comment

    Note

setInputName(str) {
  this.inputName = str;
  this.commentActive = str;
},

The adjustment that we made is to ensure that the commentActive matches the str that we've used. You can change that identifier to anything else, and pass additional arguments if you so choose.


text:
Q: Send an array of strings to NSPasteBoard How would be the best way to send an array of strings or numbers to the pasteboard?
I've tried using [pasteBoard writeObjects:] but it looks like I have to subclass NSArray to do that, it asks for a protocol.
Maybe archiving and unarchiving or other ideas?
Thank you,
Jose.

A: First convert the array to a string.
Next write it to the pasteboard.
NSMutableArray *array = [[NSMutableArray alloc]initWithObjects:@"First Line",@"Second Line",nil];
NSPasteboard * pasteBoard = [NSPasteboard generalPasteboard];
NSString * string = [array componentsJoinedByString: @"\n"];
[pasteBoard declareTypes:[NSArray arrayWithObject:NSStringPboardType] owner:nil];
[pasteBoard setString:string forType:NSStringPboardType];

A: You can add a category to NSString to add strings to the pasteboard:
@implementation NSString (PasteboardGoodies)
- (void) sendToPasteboard
{
        [[NSPasteboard generalPasteboard]
            declareTypes: [NSArray arrayWithObject: NSStringPboardType]
            owner:nil];
        [[NSPasteboard generalPasteboard]
            setString: self
            forType: NSStringPboardType];
} // sendToPasteboard

@end // PasteboardGoodies


text:
Q: Time between to nucleus to explode From the position of a non-moving observer, two nucleus A and B are moving with relative velocity $u_{a}=ac$ and $u_{b}=bc$ where, $a,b$ constants that $0<a<b<1$ and $c$ the speed of light.
Observer O found that after time $t$, the two nucleus expode simultaneously. Which is the time lapse between the explosion of B from the nucleus A?
MY solution:
The velocity of B from observer A is $\frac{u_{A}+u_{B}}{1+\frac{u_{A}u_{B}}{c^2}}=\frac{a+b}{1+ab}$.
Time in the system of A from observer O is $$t_{A}=\frac{t-u_{A}c}{\sqrt{1-\frac{u_{A}^2}{c}}}=\frac{t-a^2t}{\sqrt{1-a^2}}=t\sqrt{1-a^2}$$
The distance between A and B is $x=u_{B,A}\cdot t=\frac{a+b}{1+ab}ct$,
so the time of the B explosion from A is $$\frac{t_{a}-u_{B,A}t_{a}}{\sqrt{1-\frac{u_{B,A}^2}{c^2}}}=\frac{1-\frac{a+b}{1+ab}a}{\sqrt{1-(\frac{a+b}{1+ab})^{2}}}\sqrt{1-a^2}t$$.
I want to ask if my proof is correct, since I am new to Special Relativity Theory (as a 19-year old electrical engineering student).
Any answer or comment that helps would be appreciated.


text:
Q: Как из подмассивов создать самостоятельные массивы с уникальным адресом? Есть матрица корреляции со значениями от -1 до 1. Нам необходимо удалить все ненужные значения в этой матрице, например: все значения меньше -0,2 и больше 0,2. Удаляем их. Вместо удаленных значений остаются NaN.
Наша цель - избавиться от Nan.
Получившийся массив разбиваем по столбцам. Получается переменная с подмассивами.
np.random.seed(31415)
df = pd.DataFrame(np.random.randint(20, size=(10, 5)), columns=list("abcde"))
df_corr = df.corr()
df_corr = df_corr[df_corr.abs().le(0.2)]
b = np.hsplit(df_corr, 5)

Вопрос:
Как эти подмассивы сделать самостоятельными массивами с присвоением уникального адреса автоматически (переменной), попутно избавившись в них от Nan, например при помощи df.dropna(how='all'), чтобы не обрабатывать каждый отдельно вручную?

A: Если я правильно понял вопрос:
import pandas as pd

np.random.seed(31415)
df = pd.DataFrame(np.random.randint(20, size=(10, 5)), columns=list("abcde"))
df_corr = df.corr()
df_corr = df_corr[df_corr.abs().le(0.2)]

          a         b         c         d         e
a       NaN       NaN       NaN -0.000653  0.076438
b       NaN       NaN -0.096274 -0.088437       NaN
c       NaN -0.096274       NaN -0.184259 -0.035054
d -0.000653 -0.088437 -0.184259       NaN       NaN
e  0.076438       NaN -0.035054       NaN       NaN

делаем просто:
s = [df_corr[col].dropna().values for col in df_corr.columns]

тогда s:
[array([-0.00065349,  0.07643783]),
 array([-0.09627375, -0.08843669]),
 array([-0.09627375, -0.18425867, -0.03505434]),
 array([-0.00065349, -0.08843669, -0.18425867]),
 array([ 0.07643783, -0.03505434])]


text:
Q: The delay between neutrinos and gammas in a supernova, and the absolute mass scale of neutrinos In a supernova explosion (of some type), there is a huge amount of neutrinos and gamma rays produced by a runaway nuclear reaction at the stellar core. In a recent comment, dmckee noted that the neutrinos actually make it out of the supernova earlier than the gamma rays because the latter do scatter in trying to get out, and that the precise details of this delay, if measured, could shed light on just how small the (nonzero) neutrino mass is.
Is there some simple way of explaining the different models at stake, or what the essential physics is behind this? Is there some accessible reference about this?

A: The time delay between neutrinos and photons does not tell us directly about the absolute mass of the neutrinos. The time delay between a neutrino of mass $m$ and a massless neutrino does:
$$
\Delta t = \frac{d}{v} - \frac{d}{c} \approx 0.5 \left(\frac{mc^2}{E}\right)^2 d,
$$
where $\Delta t$ is the time delay in seconds, $v \approx c[1-\frac{1}{2}\left(\frac{mc^2}{E}\right)^2]$ from relativistic calculation, $d$ the distance to the supernova in 10 kpc (a "typical" value for Galactic supernova), neutrino rest mass $m$ in eV and neutrino energy in MeV. So it is a propagation-speed problem.
As for the reason of the delay between the neutrinos and the photons, several pieces of information should be helpful:

*

*It is hot in the core of the supernova -- so hot that the photons scatter a lot with free electrons before escaping from the core (see comment for a more detailed version); (electromagnetic interaction)

*Yet it is not hot enough to influence two of the three neutrinos, $\nu_{\mu}$ and $\nu_{\tau}$, almost at all, and only slightly for another ($\nu_{e}$); they just fly out of the core. (weak interaction)

*So this is a different-interaction (or, cross-section) problem.

Take SN1987A for example, the neutrinos arrived 2-3 hours before the photons. On the other hand, $\Delta t$ calculated above, if detected, would be  $\leq 1$ sec. With these two values and a bit more thinking, you might conclude that this "time of flight" method could not constrain very well the neutrinos with smaller-than-eV masses; and you would be right. There are better ways to do that. Here is a reference: https://arxiv.org/abs/astro-ph/0701677.


text:
Q: How can I set Ember embedded association keys to match expected nested_attributes_for format on the Rails side? I've got an Ember model with a nested association. When I POST to the Rails server, Ember is sending:
  Parameters: {"parent"=>{"name"=>"Jim", "kid"=>{"name"=>'Sara'}}

On the Rails side, the parent accepts_nested_attributes_for kid, which means that the Rails model is expecting:
  Parameters: {"parent"=>{"name"=>"Jim", "kid_attributes"=>{"name"=>'Sara'}}

I'm currently handling this by editing the params hash in the Rails controller before I call create on the parent model. That's a hack, clearly. I'm sure there's some way to reconfigure the expected key for embedded associations. (I'm thinking it'd be preferable to do this on the  client-side, but I don't have strong feelings about it.)
Any advice for how to handle this? Either on the Rails side or the Ember side is fine. Thanks.


text:
Q: Beaglebone Black SPI and GPIO Good Day,
I have a project on the beaglebone black that needs to use SPI and GPIO my problem is I can't seem to use GPIO as an input when I try to use the BB-SPIDEV0-00A0 overlay. I tried and tried using different spi overlays with exclusive use pins and ends up the board not booting properly and recovered the uEnv.txt the nth time, I think I have problems with my pinmux and want to know what am I missing. I'm using the lastest debian image form BBB. I'm using python for this project.
Thanks.


text:
Q: OpenGL - object outline I'm trying to implement a selection-outline feature. This is what I get up to now.

As you can see, the objects are selected correctly when the mouse hovers and a contour is drawn around the selected object.
What I would like to do now is to outline the visible edges of the object in this way

In the image on the left is what I have now, and in the right image is what I want to achieve.
This is the procedure I use now.
void paintGL()
{
    /* ... */

    int w = geometry().width();
    int h = geometry().height();

    glEnable(GL_DEPTH_TEST);
    glDepthFunc(GL_LESS);

    glEnable(GL_STENCIL_TEST);
    glStencilFunc(GL_NOTEQUAL, 1, 0xFF);
    glStencilOp(GL_KEEP, GL_KEEP, GL_REPLACE);
    glStencilMask(0xFF);

    setClearColor(Qt::GlobalColor::darkGray);

    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);

    glStencilMask(0x00);
    DrawGeometry();

    if (HoveredSphere != RgbFromColorToString(Qt::GlobalColor::black))
    {
        glBindFramebuffer(GL_FRAMEBUFFER, addFBO(FBOIndex::OUTLINE));
        {
            glStencilFunc(GL_ALWAYS, 1, 0xFF);
            glStencilMask(0xFF);

            glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);

            DrawOutline(HoveredSphere, 1.0f - 0.025f);
        }
        glBindFramebuffer(GL_FRAMEBUFFER, defaultFramebufferObject());

        glBindFramebuffer(GL_READ_FRAMEBUFFER, addFBO(FBOIndex::OUTLINE));
        glBindFramebuffer(GL_DRAW_FRAMEBUFFER, defaultFramebufferObject());
        {
            // copy stencil buffer
            GLbitfield mask = GL_STENCIL_BUFFER_BIT;
            glBlitFramebuffer(0, 0, w, h, 0, 0, w, h, mask, GL_NEAREST);

            glStencilFunc(GL_NOTEQUAL, 1, 0xFF);
            glStencilMask(0x00);

            glDepthFunc(GL_LEQUAL);
            DrawOutline(HoveredSphere, 1.0f);
        }
        glBindFramebuffer(GL_FRAMEBUFFER, defaultFramebufferObject());
    }

    update();
}

Where DrawGeometry draws all the objects, and DrawOutline draws the selected object scaled by the factor passed as the second parameter.
Thanks for any suggestions.

A: Thanks to the advice of @Andrea I found the following solution.
outline fragment shader
#version 450

uniform sampler2D silhouette;

in FragData
{
    smooth vec2 coords;
} frag;

out vec4 PixelColor;

void main()
{
    // outline thickness
    int w = 3;

    // if the pixel is black (we are on the silhouette)
    if (texture(silhouette, frag.coords).xyz == vec3(0.0f))
    {
        vec2 size = 1.0f / textureSize(silhouette, 0);

        for (int i = -w; i <= +w; i++)
        {
            for (int j = -w; j <= +w; j++)
            {
                if (i == 0 && j == 0)
                {
                    continue;
                }

                vec2 offset = vec2(i, j) * size;

                // and if one of the pixel-neighbor is white (we are on the border)
                if (texture(silhouette, frag.coords + offset).xyz == vec3(1.0f))
                {
                    PixelColor = vec4(vec3(1.0f), 1.0f);
                    return;
                }
            }
        }
    }

    discard;
}

Now I still have a small problem when the selected object is at the edge of the window.

As you can see, the outline is cut sharply.
I tried to "play" with glTexParameter on the parameters GL_TEXTURE_WRAP_S and GL_TEXTURE_WRAP_T.
In the image above you can see the effect I get with
glTexParameters(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameters(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);

while in the image below you can see the effect I get with
glTexParameterfv(GL_TEXTURE_2D, GL_TEXTURE_BORDER_COLOR, &(QVector4D (1.0f, 1.0f, 1.0f, 1.0f)[0]));
glTexParameters(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_BORDER);
glTexParameters(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_BORDER);

I would like the outline to show up at the edge of the window, but only where necessary.
Thanks a lot!

A: By following the tips of @MichaelMahn, I found a solution.
First of all, I draw the silhouette of the visible parts of the selected object in a texture.

And then I use this texture to calculate the outline by checking the neighboring pixels to figure out whether or not I stand on the edge of the silhouette.

outline fragment shader
#version 450

uniform sampler2D silhouette;

in FragData
{
    smooth vec2 coords;
} frag;

out vec4 PixelColor;

void main()
{
    // if the pixel is black (we are on the silhouette)
    if (texture(silhouette, frag.coords).xyz == vec3(0.0f))
    {
        vec2 size = 1.0f / textureSize(silhouette, 0);

        for (int i = -1; i <= +1; i++)
        {
            for (int j = -1; j <= +1; j++)
            {
                if (i == 0 && j == 0)
                {
                    continue;
                }

                vec2 offset = vec2(i, j) * size;

                // and if one of the neighboring pixels is white (we are on the border)
                if (texture(silhouette, frag.coords + offset).xyz == vec3(1.0f))
                {
                    PixelColor = vec4(vec3(1.0f), 1.0f);
                    return;
                }
            }
        }
    }

    discard;
}

paintgl
void paintGL()
{
    int w = geometry().width();
    int h = geometry().height();

    setClearColor(Qt::GlobalColor::darkGray);

    glEnable(GL_DEPTH_TEST);
    glDepthFunc(GL_LESS);

    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    DrawGeometry();

    // if we hover a sphere
    if (HoveredSphere != RgbFromColorToString(Qt::GlobalColor::black))
    {
        glBindFramebuffer(GL_READ_FRAMEBUFFER, defaultFramebufferObject());
        glBindFramebuffer(GL_DRAW_FRAMEBUFFER, addFBO(FBOIndex::SILHOUETTE));
        {
            // copy depth buffer
            GLbitfield mask = GL_DEPTH_BUFFER_BIT;
            glBlitFramebuffer(0, 0, w, h, 0, 0, w, h, mask, GL_NEAREST);

            // set clear color
            setClearColor(Qt::GlobalColor::white);
            // enable depth test
            glEnable(GL_DEPTH_TEST);
            glDepthFunc(GL_LEQUAL);
            // clear color buffer
            glClear(GL_COLOR_BUFFER_BIT);

            // draw silhouette
            DrawSilhouette(HoveredSphere);
        }
        glBindFramebuffer(GL_FRAMEBUFFER, defaultFramebufferObject());

        // clear depth buffer
        glClear(GL_DEPTH_BUFFER_BIT);

        // draw outline
        DrawOutline();
    }
}

PROBLEM :: Now I'd like to parameterize the width of the contour, whose thickness is currently fixed at 1 pixel.
Thank you so much for any suggestion!


text:
Q: Intersection of 3D lines How to find intersection point of lines $p... \frac{x + 1}{0} = \frac{y - 2}{-1} = \frac{z}{1}$ and $q... \frac{x - 1}{-1} = \frac{y + 6}{3} = \frac{z + 6}{4}$?

A: Let $\frac{x + 1}{0} = \frac{y - 2}{-1} = \frac{z}{1}=t\in\mathbb{R}$. Then $x=-1, y=2-t, z=t$. So, the parametric form of the first line is $c_1(t)=(-1,2-t,t),\ t\in\mathbb{R}$. If we do the same for the second line, we get it's parametric form $c_2(t)=(1-t, 3t-6,4t-6),\ t\in\mathbb{R}$. Thus,
$$c_1(t)=c_2(t) \iff t=2. $$ Consequently, the intersection point is $A(-1,0,2)$.


text:
Q: Office Interop reading incorrect cell values Trying to iterate through the rows and cells on an excel spreadsheet, deleting empty ones. I'm using the following routine to do so.
foreach(Range row in sheet.UsedRange.Rows)
{
    for (int i = 0; i < row.Columns.Count; i++)
    {
        Range cell = row.Cells[1, i + 1];
        if (cell.Value == null || String.IsNullOrEmpty(cell.Value.ToString()))
        {
            cell.Delete();
        }
    }
}

Which works fine for the first two rows. However, it then seems to go haywire.
The third row is completely empty. Yet as it iterates through the columns, when this loop gets to column "I", it reads a value there. The value is what's actually in row 4, column "J".
After that, it just gets worse, missing whole rows and reading incorrect values from the rows it does find.
I am baffled by this. Is there something obvious that I have missed?

A: Yes, you are missing something very obvious. You are deleting cells. After that operation, your calculation of which cell to pick doesn't work any more.
If you delete a cell, all other cells will move up. That causes your row.Cells[1, i + 1] to be incorrect. If you for example delete one cell in row 2, the value of the cell in the same column in row 3 will never get checked, since it is in row 2 then.
The direction of shift on deletion may also be a factor - you can control it by passing a parameter to the Delete function.
Simply recheck the same column when you delete one:
foreach (Range row in Globals.ThisAddIn.Application.ActiveWorkbook.ActiveSheet.UsedRange.Rows)
{
    for (int i = 0; i < row.Columns.Count; i++)
    {
        Range cel = row.Cells[1, i + 1];
        if (cel.Value == null || String.IsNullOrEmpty(cel.Value.ToString()))
        {
            // default shift is up
            cel.Delete();
            // to shift left use cel.Delete(XlDeleteShiftDirection.xlShiftToLeft);
            i--; // this will do
        }
    }
}


text:
Q: Pen on ThinkPad Yoga 370 in Arch Linux registers touch events when there are none I have a ThinkPad Yoga 370 with an active AES stylus. I run the latest Arch Linux-based Manjaro 4.14.48-2-MANJARO. To get the pen to work in e.g. xournal I installed libinput 1.11.0-1 and xf86-input-wacom 0.36.1-1 and the pen works now.
However my problem comes undeterministically after some time using it. When I write, at some point driver issues arise, where when I move the pen close to the display, an event is triggered that moves the mouse pointer according to where the pen is, without the pen touching the display. This is normal behaviour. The problem is that on the instance this pen is in range event is fired, for some reason a pen touched the display event is fired instead, so that a click is issued. When I hover over a button that button is pressed, when I hover over my document in xournal a dot is drawn.
Repeatedly moving the pen to and from the display makes the problem go away for a while, but it always returns.


text:
Q: SQL Join to return data from The Same Column in the same table to two diffrent rows in result (Star Wars Example) Newbie question about joining tables.  I want to retrieve a name from a column TWICE in a SQL statement, and I'm running in circles.
I Have two Tables -  "Company" & "People"
Table -"People"

ID
Name
Phone

1
Luke
555-1212

2
Leia
555-1234

3
Han
999-8888

4
Anikin
888-9876

5
Obi-wan
555-1212

6
R2-D2
#% - **!?

Table - "Company"

ID
CompanyName
PrimaryContact
AltContact

1
Speeders R Us
5
1

2
Droid Repair World
6
4

3
Luke's Second Hand Store
1
4

4
Cloak World
4
5

5
Ye Old Blaster Shoppe
3
2

If I want to get a result that gives BOTH the Contact Names for a Company, How would I do it?
I can get the PrimaryContact to JOIN Properly using something like...
SELECT C.*, P.Name as 'Primary'
FROM `Company` C
Join People P on
C.PrimaryContact = P.ID
WHERE C.ID =3

which successfully returns

ID
CompanyName
PrimaryContact
AltContact
Primary

3
Luke's Second Hand Store
1
4
Luke

But for the life of me, I can't figure out how to modify this SQL to also return "Anikin" as the Alternate Contact.  Is this an example of where a UNION statement would help?

A: You can join to the same table multiple times, just give a new alias every time.
Join People P on  C.PrimaryContact = P.ID

Join People P1 on  C.AltContact = P1.ID

 Join People altcontact on  C.AltContact = altcontact.ID

Join People P256 on  C.yetanotheralternateContact = P256.ID

A: You need to to join for ecervy contact another Persons table
SELECT C.ID,C.CompanyName, P.Name as 'Primary' , P.Phone As 'primary_Phone', P2.Name on 'Alternative', P2.Phone as 'Alternatibe_Phone
FROM `Company` C
Join People P on
C.PrimaryContact = P.ID
Join People P2 on
C.AltContact = P2.ID
WHERE C.ID


text:
Q: App crashing due to two differnet Async Tasks? So I have been working on this code for a while now trying to implement Google Visions into my prior app that displays an image from pixabay then tells me the tags of the photo.I had both the google vision app and pixabay app work just fine on their own. In this new version it should give me tags and the labels found by Google Visions but, whenever I activate the UP command on the sensors it crashes.
Here is my code:
import android.annotation.TargetApi;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.media.MediaPlayer;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Vibrator;
import android.speech.tts.TextToSpeech;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ImageView;
import android.widget.TextView;

import com.google.api.client.extensions.android.http.AndroidHttp;
import com.google.api.client.googleapis.json.GoogleJsonResponseException;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.gson.GsonFactory;
import com.google.api.services.vision.v1.Vision;
import com.google.api.services.vision.v1.VisionRequest;
import com.google.api.services.vision.v1.VisionRequestInitializer;
import com.google.api.services.vision.v1.model.AnnotateImageRequest;
import com.google.api.services.vision.v1.model.BatchAnnotateImagesRequest;
import com.google.api.services.vision.v1.model.BatchAnnotateImagesResponse;
import com.google.api.services.vision.v1.model.EntityAnnotation;
import com.google.api.services.vision.v1.model.Feature;
import com.google.api.services.vision.v1.model.Image;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import static edu.ggc.lutz.recipe.pixabaysamplerwalkthrough.R.id.tvLabels;
import static edu.ggc.lutz.recipe.pixabaysamplerwalkthrough.R.id.tvTags;

public class MainActivity extends AppCompatActivity implements SensorEventListener {

    public static final String PIXABAY = "Pixabay";
    private ImageView imageView;
    private static PixabayQueryResult result;
    private String tags;
    long numberOfHits;
    long selected;

    float[] gravity = new float[3];
    float[] accel = new float[3];
    private static final float ALPHA = 0.80f; // weighing factor used by the low pass filter
    private static final String TAG = "OMNI";
    private static final float VERTICAL_TOL = 0.3f;
    private SensorManager manager;
    private long lastUpdate;
    private MediaPlayer popPlayer;
    private MediaPlayer backgroundPlayer;
    private TextToSpeech tts;
    private TextView[] tvGravity;
    private TextView[] tvAcceleration;

    private boolean isDown = false;
    private boolean isUp = false;

    private static final String CLOUD_VISION_API_KEY = "AIzaSyCt35MZjvD_3ynTbYmeUuBFyMbYrjXUmzs";
    private static final String ANDROID_CERT_HEADER = "X-Android-Cert";
    private static final String ANDROID_PACKAGE_HEADER = "X-Android-Package";

    private static final String TAGgoogle = MainActivity.class.getSimpleName();

    private TextView pixtags;
    private TextView googlelab;

    private String urlString;

    private Bitmap bitmapT;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        pixtags= (TextView) findViewById(tvTags);

        googlelab= (TextView) findViewById(tvLabels);

       /* FloatingActionButton fab = (FloatingActionButton) findViewById(fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                PixabayFetchTask task = new PixabayFetchTask();
                String service = "https://pixabay.com/api/";
                String key = "5535853-23bc4a5e307cd5d1a5e16ebcc";
                String query_params = "&editor_choice=true&safesearch=true&image_type=photo";
                String urlString = service + "?key=" + key + query_params;
                task.execute(urlString);

            }
        });*/

    imageView= (ImageView) findViewById(R.id.imageView);

        tts = new TextToSpeech(this, new TextToSpeech.OnInitListener() {
            @Override
            public void onInit(int status) {
                int result1=0;
                if(status == TextToSpeech.SUCCESS) {
                    result1 = tts.setLanguage(Locale.US);
                }
                if( result1 == TextToSpeech.LANG_MISSING_DATA || result1== TextToSpeech.LANG_NOT_SUPPORTED){
                    Log.e("TTS", "This Language is not supported");
                }
                else
                {
                    Log.e("TTS", "Inizalization Failed");
                }
            }
        });

        //////////////////////////
        manager = (SensorManager) getSystemService(SENSOR_SERVICE);
        lastUpdate = System.currentTimeMillis();

        backgroundPlayer = MediaPlayer.create(this, R.raw.mistsoftime4tmono);

        //////////////////////////
      //callCloudVision("https://pixabay.com/get/eb36b90f2df1053ed95c4518b7494395e67fe7d604b0154892f2c67da7eabc_640.jpg");
    }

    ///////////////////////////////
    @Override
    protected void onResume() {
        super.onResume();

        manager.registerListener(this, manager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
                SensorManager.SENSOR_DELAY_UI);
        backgroundPlayer.start();

    }

    //////////////////////////////
    @Override
    protected void onPause() {
        super.onPause();
        manager.unregisterListener(this);
        backgroundPlayer.pause();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);

        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        Intent intent = new Intent(this, About.class);

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            startActivity(intent);
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    public static long getRandomLong(long minimum, long maximum)
    {
        return (long) (Math.random()* (maximum- minimum))+ minimum;
    }

    @Override
    public void onAccuracyChanged(Sensor sensor, int accuracy) {

    }

    @Override
    public void onSensorChanged(SensorEvent event) {

        gravity[0] = lowPass(event.values[0], gravity[0]);
        gravity[1] = lowPass(event.values[1], gravity[1]);
        gravity[2] = lowPass(event.values[2], gravity[2]);

        accel[0] = highPass(event.values[0], accel[0]);
        accel[1] = highPass(event.values[1], accel[1]);
        accel[2] = highPass(event.values[2], accel[2]);

        long actualTime = System.currentTimeMillis();

        if (actualTime - lastUpdate > 100) {
            if (inRange(gravity[2], -9.81f, VERTICAL_TOL)) {

                Log.i(TAG, "Down");

                if (!isDown) {
                    Vibrator v = (Vibrator) this.getApplicationContext().getSystemService(Context.VIBRATOR_SERVICE);
                    v.vibrate(500);
                    PixabayFetchTask task = new PixabayFetchTask();
                    String service = "https://pixabay.com/api/";
                    String key = "5535853-23bc4a5e307cd5d1a5e16ebcc";
                    String query_params = "&editor_choice=true&safesearch=true&image_type=photo";
                    urlString = service + "?key=" + key + query_params;
                    task.execute(urlString);
                    backgroundPlayer.setVolume(0.1f, 0.1f);
                    tts.speak("The device is pointing down", TextToSpeech.QUEUE_FLUSH, null);
                    backgroundPlayer.setVolume(1.0f, 1.0f);
                    isDown = true;
                    isUp = false;

                }

            } else if (inRange(gravity[2], 9.81f, VERTICAL_TOL)) {
                if (!isUp) {
                    try {
                        callCloudVision(urlString);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    backgroundPlayer.setVolume(0.1f, 0.1f);
                    Log.i(TAG, "Up");
                    tags= (String) result.getTags((int)selected);
                    pixtags.setText("Tags: "+tags, null);
                 /*   Snackbar.make(imageView, tags, Snackbar.LENGTH_LONG)
                            .setAction("Action", null).show();*/
                    tts.speak(tags.toString(), TextToSpeech.QUEUE_ADD, null);

                    //tts.speak("up", TextToSpeech.QUEUE_FLUSH, null);
                    backgroundPlayer.setVolume(1.0f, 1.0f);
                    isUp = true;
                    isDown = false;
                }

            } else {
                Log.i(TAG, "In between");
                //isDown = false;  // Rubbish!
                //isUp = false;
            }
            lastUpdate = actualTime;
        }

    }

    private boolean inRange(float value, float target,  float tol) {
        return value >= target-tol && value <= target+tol;
    }

    // de-emphasize transient forces
    private float lowPass(float current, float gravity) {
        return current * (1-ALPHA) + gravity * ALPHA; // ALPHA indicates the influence of past observations
    }

    // de-emphasize constant forces
    private float highPass(float current, float gravity) {
        return current - gravity;
    }

    class PixabayFetchTask extends AsyncTask<String, Void, PixabayQueryResult> {

        /**
         * Override this method to perform a computation on a background thread. The
         * specified parameters are the parameters passed to {@link #execute}
         * by the caller of this task.
         *

         * This method can call {@link #publishProgress} to publish updates
         * on the UI thread.
         *
         * @param params The parameters of the task.
         * @return A result, defined by the subclass of this task.
         * @see #onPreExecute()
         * @see #onPostExecute
         * @see #publishProgress
         */
        @Override
        protected PixabayQueryResult doInBackground(String... params) {

            Log.v(PIXABAY,"String[0] =" + params[0]);

            if(result==null || result.isExpired()) {

                try {
                    String line;
                    URL u = new URL(params[0]);
                    HttpURLConnection conn = (HttpURLConnection) u.openConnection();
                    InputStream in = new BufferedInputStream(conn.getInputStream());
                    BufferedReader reader = new BufferedReader(new InputStreamReader(in));
                    StringBuilder json = new StringBuilder();
                    while ((line = reader.readLine()) != null) json.append(line);
                    result = new PixabayQueryResult(json.toString());

                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return result;
        }

        /**
         *
Runs on the UI thread after {@link #doInBackground}. The
         * specified result is the value returned by {@link #doInBackground}.

         *

         *
This method won't be invoked if the task was cancelled.

         *
         * @param bitmap The result of the operation computed by {@link #doInBackground}.
         * @see #onPreExecute
         * @see #doInBackground
         * @see #onCancelled(Object)
         */
        @Override
        protected void onPostExecute(PixabayQueryResult result) {
            super.onPostExecute(result);
           numberOfHits= result.size();
             selected = getRandomLong(0, numberOfHits);
             Bitmap bitmap= result.getBitmap((int)selected);
            imageView.setImageBitmap(bitmap);
           /* try {
                callCloudVision(urlString);
            } catch (IOException e) {
                e.printStackTrace();
            }*/

        }
    }

    private void callCloudVision(final String loc) throws IOException {
        // Switch text to loading
        googlelab.setText(R.string.loading_message);

        // Do the real work in an async task, because we need to use the network anyway
        new AsyncTask<Object, Bitmap, String>() {
            @Override
            protected String doInBackground(Object... params) {
                try {
                    HttpTransport httpTransport = AndroidHttp.newCompatibleTransport();
                    JsonFactory jsonFactory = GsonFactory.getDefaultInstance();

                    VisionRequestInitializer requestInitializer =
                            new VisionRequestInitializer(CLOUD_VISION_API_KEY) {
                                /**
                                 * We override this so we can inject important identifying fields into the HTTP
                                 * headers. This enables use of a restricted cloud platform API key.
                                 */
                                @Override
                                protected void initializeVisionRequest(VisionRequest<?> visionRequest)
                                        throws IOException {
                                    super.initializeVisionRequest(visionRequest);

                                    String packageName = getPackageName();
                                    visionRequest.getRequestHeaders().set(ANDROID_PACKAGE_HEADER, packageName);

                                    String sig = PackageManagerUtils.getSignature(getPackageManager(), packageName);

                                    visionRequest.getRequestHeaders().set(ANDROID_CERT_HEADER, sig);
                                }
                            };

                    Vision.Builder builder = new Vision.Builder(httpTransport, jsonFactory, null);
                    builder.setVisionRequestInitializer(requestInitializer);

                    Vision vision = builder.build();

                    BatchAnnotateImagesRequest batchAnnotateImagesRequest =
                            new BatchAnnotateImagesRequest();
                    batchAnnotateImagesRequest.setRequests(new ArrayList<AnnotateImageRequest>() {{
                        AnnotateImageRequest annotateImageRequest = new AnnotateImageRequest();

                        Bitmap bitmap = null;
                        try {
                            InputStream stream = new URL(loc).openStream();
                            bitmap = BitmapFactory.decodeStream(stream);
                            publishProgress(bitmap);
                        } catch (IOException e) {
                            e.printStackTrace();
                        }

                        // Add the image
                        Image base64EncodedImage = new Image();
                        // Convert the bitmap to a JPEG
                        // Just in case it's a format that Android understands but Cloud Vision

                        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();

                       bitmap.compress(Bitmap.CompressFormat.JPEG, 90, byteArrayOutputStream);

                        byte[] imageBytes = byteArrayOutputStream.toByteArray();

                        // Base64 encode the JPEG
                        base64EncodedImage.encodeContent(imageBytes);
                        annotateImageRequest.setImage(base64EncodedImage);

                        // add the features we want
                        annotateImageRequest.setFeatures(new ArrayList<Feature>() {{
                            Feature labelDetection = new Feature();
                            labelDetection.setType("LABEL_DETECTION");
                            labelDetection.setMaxResults(10);
                            add(labelDetection);
                        }});

                        // Add the list of one thing to the request
                        add(annotateImageRequest);
                    }});

                    Vision.Images.Annotate annotateRequest =
                            vision.images().annotate(batchAnnotateImagesRequest);
                    // Due to a bug: requests to Vision API containing large images fail when GZipped.
                    annotateRequest.setDisableGZipContent(true);
                    Log.d(TAGgoogle, "created Cloud Vision request object, sending request");

                    BatchAnnotateImagesResponse response = annotateRequest.execute();
                    return convertResponseToString(response);

                } catch (GoogleJsonResponseException e) {
                    Log.d(TAGgoogle, "failed to make API request because " + e.getContent());
                } catch (IOException e) {
                    Log.d(TAGgoogle, "failed to make API request because of other IOException " +
                            e.getMessage());
                }
                return "Cloud Vision API request failed. Check logs for details.";
            }

            /**
             * Runs on the UI thread after {@link #publishProgress} is invoked.
             * The specified values are the values passed to {@link #publishProgress}.
             *
             * @param bitmaps The values indicating progress.
             * @see #publishProgress
             * @see #doInBackground
             */
            @Override
            protected void onProgressUpdate(Bitmap... bitmaps) {
                super.onProgressUpdate(bitmaps);
                imageView.setImageBitmap(bitmaps[0]);
            }

            protected void onPostExecute(String result) {

                googlelab.setText(result);

            }
        }.execute();
    }
    private String convertResponseToString(BatchAnnotateImagesResponse response) {
        String message = "Labels:\n\n";

        List<EntityAnnotation> labels = response.getResponses().get(0).getLabelAnnotations();
        if (labels != null) {
            for (EntityAnnotation label : labels) {
                message += String.format(Locale.US, "%.3f: %s", label.getScore(), label.getDescription());
                message += "\n";
            }
        } else {
            message += "nothing";
        }

        return message;
    }

}

Here is the it gives me error:
E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #3
Process: edu.ggc.lutz.recipe.pixabaysamplerwalkthrough, PID: 21223    java.lang.RuntimeException: An error occurred while executing doInBackground()
      at android.os.AsyncTask$3.done(AsyncTask.java:309)
    at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:354)
          at java.util.concurrent.FutureTask.setException(FutureTask.java:223)
           at java.util.concurrent.FutureTask.run(FutureTask.java:242)
           at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234)
  at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
         at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
                 at java.lang.Thread.run(Thread.java:818)
              Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean android.graphics.Bitmap.compress(android.graphics.Bitmap$CompressFormat, int, java.io.OutputStream)' on a null object reference
           at edu.ggc.lutz.recipe.pixabaysamplerwalkthrough.MainActivity$2$2.<init>(MainActivity.java:419)
    at edu.ggc.lutz.recipe.pixabaysamplerwalkthrough.MainActivity$2.doInBackground(MainActivity.java:400)
              at edu.ggc.lutz.recipe.pixabaysamplerwalkthrough.MainActivity$2.doInBackground(MainActivity.java:366)
             at android.os.AsyncTask$2.call(AsyncTask.java:295)                at java.util.concurrent.FutureTask.run(FutureTask.java:237)
             at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234)
             at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
                at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
            at java.lang.Thread.run(Thread.java:818)

There is another error that says something about the text to speech but I think that is the result of this error.
I believe it has something to do with running two different Async tasks at the same time overloading it or that fact a null value it getting passed in causing the error.


text:
Q: Kendo inline grid editing error when posting a Csla.Net child object I have a Csla.Net parent + list of child model and in my grid I'm binding to a collection of child records of type BusinessBase.  Using Kendo grid inline grid editing, the Update method fails during the model binding as it cannot create an instance of an interface.
This problem is on the Parent property, which on a Csla.Net child object is defined as Csla.Core.IParent in the base class.
Now I get it that the model binder is struggling here as it cannot possibly spin up an interface.
My thought is that sure, I can flatten or reshape the models here and use a viewmodel to work around this, but is there any way to stop the Parent property either serializing down into the grid in the first place or configure the grid to ignore the Parent property when posting back?
Here's some Fiddler output showing the error.
[MissingMethodException: Cannot create an instance of an interface.]
   System.RuntimeTypeHandle.CreateInstance(RuntimeType type, Boolean publicOnly, Boolean noCheck, Boolean& canBeCached, RuntimeMethodHandleInternal& ctor, Boolean& bNeedSecurityCheck) +0
   System.RuntimeType.CreateInstanceSlow(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache, StackCrawlMark& stackMark) +113
   System.RuntimeType.CreateInstanceDefaultCtor(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache, StackCrawlMark& stackMark) +232
   System.Activator.CreateInstance(Type type, Boolean nonPublic) +83
   System.Activator.CreateInstance(Type type) +66
   System.Web.Mvc.DefaultModelBinder.CreateModel(ControllerContext controllerContext, ModelBindingContext bindingContext, Type modelType) +554

[MissingMethodException: Cannot create an instance of an interface. Object type 'Csla.Core.IParent'.]
   System.Web.Mvc.DefaultModelBinder.CreateModel(ControllerContext controllerContext, ModelBindingContext bindingContext, Type modelType) +630
   Csla.Web.Mvc.CslaModelBinder.CreateModel(ControllerContext controllerContext, ModelBindingContext bindingContext, Type modelType) +119
   System.Web.Mvc.DefaultModelBinder.BindComplexModel(ControllerContext controllerContext, ModelBindingContext bindingContext) +1135
   System.Web.Mvc.DefaultModelBinder.BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) +631
   Csla.Web.Mvc.CslaModelBinder.BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) +206
   Castle.Proxies.Invocations.DefaultModelBinder_BindModel.InvokeMethodOnTarget() +199
   Castle.DynamicProxy.AbstractInvocation.Proceed() +117

Thanks.


text:
Q: He starts work every day at 9:00 am Is it correct to put clock information at the end of the sentence if there is another time adverb such as in the mornings, every day or on weekdays in the sentence?
Does it sound natural?

He starts work every day at 9:00 am.


text:
Q: Gradle: How to map Lists from configuration-closure to extension settings I have this (working) code, which is extended from the gradle documentation
https://docs.gradle.org/4.10.3/userguide/custom_plugins.html#sec:implementing_a_dsl
class User {
    String name
}

class Group {
    User user
}

class GreetingPluginExtension {
    String message
    final Group group

    @javax.inject.Inject
    GreetingPluginExtension(ObjectFactory objectFactory) {
        group = objectFactory.newInstance(Group)
        group.user = objectFactory.newInstance(User)
    }

    void group(Action<? super Group> action) {
        action.execute(group)
    }

    void user(Action<? super User> action) {
        action.execute(group.user)
    }
}

class GreetingPlugin implements Plugin<Project> {
    void apply(Project project) {
        // Create the extension, passing in an ObjectFactory for it to use
        def extension = project.extensions.create('greeting', GreetingPluginExtension, project.objects)
        project.task('hello') {
            doLast {
                    println "${extension.message} from ${extension.group.user.name}"
            }
        }
    }
}

The configuration closure looks like this:
greeting {
    message = 'Hello'
    group {
        user {
            name = 'tom'
        }
    }
}

But I would like to have a List of users an I tried:
class User {
    String name
}

class Group {
    ArrayList<User> users
}

class GreetingPluginExtension {
    String message
    final Group group

    @javax.inject.Inject
    GreetingPluginExtension(ObjectFactory objectFactory) {
        // Create a Person instance
        group = objectFactory.newInstance(Group)
        group.users = []
    }

    void group(Action<? super Group> action) {
        action.execute(group)
    }

    void users(Action<? super ArrayList<User>> action) {
        action.execute(group.users)
    }
}

class GreetingPlugin implements Plugin<Project> {
    void apply(Project project) {
        // Create the extension, passing in an ObjectFactory for it to use
        def extension = project.extensions.create('greeting', GreetingPluginExtension, project.objects)
        project.task('hello') {
            doLast {
                extension.group.users.each {

                    println "${extension.message} from ${it.name}"
                }

            }
        }
    }
}

with this closure:
greeting {
    message = 'Hello'
    group {
        users = [
                {name = 'tom'} ,
                {name = 'tim'}
        ]
    }
}

my output is the following:
Hello from myProjectName
Hello from myProjectName

which is not the expected output but the rootProject.name
The output has the right number of elements, but is not referenced to the user.
How can I fix this? I would also appreciate informations about other approaches to map nested objects (and lists) into the extension-setting.
Greetings Tom

A: The following slightly modified version I believe does what you intended:
apply plugin: GreetingPlugin

greeting {
    message = 'Hello'
    group {
      user(name: 'tom')
      user(name: 'tim')
    }
}

class User {
    String name
}

class Group {
    ArrayList<User> users = []

    def user(props) {
      users << new User(props)
    }
}

class GreetingPluginExtension {
    String message
    final Group group

    @javax.inject.Inject
    GreetingPluginExtension(ObjectFactory objectFactory) {
        // Create a Person instance
        group = objectFactory.newInstance(Group)
    }

    void group(Action<? super Group> action) {
        action.execute(group)
    }
}

class GreetingPlugin implements Plugin<Project> {
    void apply(Project project) {
        // Create the extension, passing in an ObjectFactory for it to use
        def extension = project.extensions.create('greeting', GreetingPluginExtension, project.objects)
        project.task('hello') {
            doLast {
                extension.group.users.each {
                    println "${extension.message} from ${it.name}"
                }

            }
        }
    }
}

When run, it prints:
~> gradle hello

> Task :hello
Hello from tom
Hello from tim

BUILD SUCCESSFUL in 0s
1 actionable task: 1 executed

Note that I have removed the method:
void users(Action<? super ArrayList<User>> action)

as it is not needed for the above to work. I also changed the dsl somewhat. I actually think the changed dsl looks more readable and idiomatic but this is of course a matter of taste.
Note also that if you want to send in more properties to the user (say email), you can do this without modifying the scaffolding code, i.e.:
greeting {
    message = 'Hello'
    group {
      user(name: 'tom', email: 'tom@wonderland.org')
      user(name: 'tim', email: 'tim@wonderland.org')
    }
}
class User {
    String name
    String email
}

If you were specifically looking for how you make a doubly nested configuration closure for a collection work, this does not solve your problem, but it does give you a reasonably clean way of accomplishing what the build script intended.


text:
Q: Query optimization and takes less execution time CASE-1:
SELECT * FROM A
JOIN B ON B.CustomerID=A.CustomerID

CASE-2:
SELECT * FROM A
JOIN (SELECT * FROM B) C
ON C.CustomerID =A.CustomerID

Which CASE is efficient ?

A: Please run SET STATISTICS IO ON and run one of your queries and check the number of pages beeing read in your message tab.
A lower execution time doesn't mean that it was more efficient, there are other dependencies like what else was running at the same time in the background?
With number of pages read you can be sure which query uses more or less amount of actual work.
Also have a look at the execution plans, they might be the same...


text:
Q: My app has not stopped when i run react-native run-android I got an error when i run react-native run-android that it's not working! I run adb logcat *:E, i recieved message error: Didn't find class "android.support.v4.app.CoreComponentFactory" on path: DexPathList[[],nativeLibraryDirectories=[/system/priv-app/GoogleSdkSetup/lib/x86, /system/lib, /system/lib]]
Does anyone help me fix this bug! Thank very so much!

A: Just clean the build and run it will go away
cd android
gradlew clean


text:
Q: Image not showing in iPhone Simulator I dragged an image from the Media Library in my Interface Builder and can see the image in my xib. However, when I open up the iPhone Simulator the image isn't there. Do I need to put code into the program's .m or .h to be able to show the image I have on IB?

A: You need to add the Image to the "Resources" Folder in your Application Directory, so that the Image can be copied to your target "Copy Bundle Resources", this folder contains all the resources your application is using. Otherwise when the iPhone Simulator runs it will not find the image
In order to add an Image to the Resources ctrl+click the folder and select add..-> existing files, then select your image and click Add.
Hope that is clear.
-Oscar

A: I have had this and this point came to light when images from one designer worked fine but from another not.  If it is a PNG then make sure it has been saved/exported with "interlaced" turned ON / ticked or whatever, this worked for me.
It is very strange it appears in the Interface Builder but in the simulator it is absent!

A: Well I never used IB that much for that to understand what you're doing.
But, the steps that I used to take is:

*

*Make sure the image resources path is correct, and it's local to the project, not referenced from an unknown path.

*Make sure it's shown in UIImageView inspector in the IB.

*Select the image name inside the inspector.

*Make sure the image is displayed in the UIImageView placeholder.
If things go wrong with IB, I'd rather write code, initialize UIImageView instance at the right position. It's less headache for debugging.

A: If by 'opening the Simulator' you mean that you select Simulate Interface from Interface Builder's File menu, then yes, that will not work.
To run your application in the simulator you will have to hit the Build and Run button in Xcode.

A: Is the "hidden" box checked in IB?  Or maybe in your code or in IB you set alpha to zero?  Just to make sure, connect the image in IB to your code in the .h file, and in your .m type this in your viewDidLoad: function:

image.alpha = 1;
image.hidden = NO;

Try this and tell me if it works!

A: Image can be any where in application folder as long it's included in project, when you select particular image from left pane , in right pane under "Target Membership" check if check-box is checked for  target

A: The problem could also be related to a problem or inconsistency with the images format as Recycled Steel pointed out.
In my particular case, I dragged .JPG files into my Images.xcassets and used those.
It turns out these images rendered correctly in my Storyboards, but were not displayed on the emulator.
To fix this, I converted the .jpg to .png files (with GIMP/Photoshop or any other image processing software) and now it works both on the storyboard and on the emulator.

A: IMAGE MUST BE ADDED TO THE CORRECT TARGET!
When adding the image you need to add it to the target that you need. Whether it's a custom keyboard or something else.
Silly solution but at times one could forget!


text:
Q: Spring-boot: add application to tomcat server I have a back-end which is build on spring-boot and then some custom code from my school built upon that.
The front-end is pure angular application which I serve from a different server trough a gulp serve.
They're only connected by REST calls.
There's already an authentication module running on the backend and to now I need to serve this angular application from the same tomcat server the back-end is running on so it can also use this authentication module.
I've found this about multiple connectors so I copied it as following class to set up multiple connectors:
@ConfigurationProperties
public class TomcatConfiguration {

    @Bean
    public EmbeddedServletContainerFactory servletContainer() {
        TomcatEmbeddedServletContainerFactory tomcat = new TomcatEmbeddedServletContainerFactory();
        //tomcat.addAdditionalTomcatConnectors(createSslConnector());
        return tomcat;
    }

    private Connector createSslConnector() {
        Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol");
        Http11NioProtocol protocol = (Http11NioProtocol) connector.getProtocolHandler();
        try {
            File keystore = new ClassPathResource("keystore").getFile();
            File truststore = new ClassPathResource("keystore").getFile();
            connector.setScheme("https");
            connector.setSecure(true);
            connector.setPort(8443);
            protocol.setSSLEnabled(true);
            protocol.setKeystoreFile(keystore.getAbsolutePath());
            protocol.setKeystorePass("changeit");
            protocol.setTruststoreFile(truststore.getAbsolutePath());
            protocol.setTruststorePass("changeit");
            protocol.setKeyAlias("apitester");
            return connector;
        } catch (IOException ex) {
            throw new IllegalStateException("can't access keystore: [" + "keystore"
                    + "] or truststore: [" + "keystore" + "]", ex);
        }
    }
}

Problem is that I don't see or find how I should setup these connectors so they serve from my angularJS build folder.
Upon searching I came upon Spring-Boot : How can I add tomcat connectors to bind to controller but I'm not sure if in that solution I should change my current application or make a parent application for both applications.
My current application main looks like this:
@Configuration
@ComponentScan({"be.ugent.lca","be.ugent.sherpa.configuration"})
@EnableAutoConfiguration
@EnableSpringDataWebSupport
public class Application extends SpringBootServletInitializer{
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);

    }
}

If possible I'd like some more info about what connectors are in the spring-boot context.
If this is not the way to go I'd like someone to be able to conform this second solution or suggest a change in my code.
I'm really not sure enough about these solution that I want to go breaking my application over it. (though it's backed up with github)

A: Just place your AngularJS + other front-end assets into src/main/resources/static folder, Spring Boot will serve them automatically.


text:
Q: class java.lang.Boolean cannot be cast to class java.util.ArrayList I'm trying to read an ArrayList of objects from a BinaryI/O but I keep getting the error "class java.lang.Boolean cannot be cast to class java.util.ArrayList (java.lang.Boolean and java.util.ArrayList are in module java.base of loader 'bootstrap')"
This is the code
public void readAdmin(){
     try{
         File file = new File("Administrators.dat");
         file.createNewFile();
         ObjectInputStream input = new ObjectInputStream(new FileInputStream("Administrators.dat"));
         ArrayList<Administrator> adms = (ArrayList<Administrator>) input.readObject();
         usercontroller.setAdmins(adms);

     }
     catch(IOException e){
         System.out.println("Input of administrator data error.");
     }
     catch (ClassNotFoundException cn){
         System.out.println("Administrator class not existent.");
     }

The line "ArrayList adms = (ArrayList) input.readObject();" seems to be the one causing the error when I call the "readAdmin" method in main.
Any ideas on how I can fix this?


text:
Q: Приведение типов в Java Познаю ООП и Java на примере андроида. Столкнулся с проблемой, которую постарался описать. Прошу вашей помощи, гуру Явы!
Есть такой набор классов: модели круг и сфера, которые наследуются от общей  абстрактной модели EntityModel. Для каждой модели будет свой адаптер, все адаптеры моделей наследуются от абстрактного адаптера.
abstract public class EntityModel{}
class Circle extends EntityModel{}
class Sphere extends EntityModel{}

abstract public class EntityArrayAdapter extends ArrayAdapter{
   protected List<? extend EntityModel> items;
   public EntityArrayAdapter(List<? extend EntityModel> items){
      this.items = items;
   }
}
public class CirclesArrayAdapter extends EntityArrayAdapter{
   public B(List<Circle> circles){
      super(circles);
      this.items = circles;
   }
   public void run(int position){
      Circle p = this.items.get(position);
   }
}

В классе CirclesArrayAdapter всё хорошо до момента
Circle p = this.items.get(position);

Здесь IDE мне подсвечивает следующее:

Как мне решить проблему, что бы в каждом адаптере не создавать свойство items?

A: Проблема решена, спасибо @metalurgus
Circle p = (Circle) this.items.get(position);


text:
Q: How do I use the quartz scheduler with Python? Is there a guide or tutorial on how to use the quartz Scheduler with Python.
Is there an existing API for Python?

A: Given that Quartz is a Java application/library, the simplest thing to do may be to run it within Jython.
Failing that, and if you simply want to control the configuration of jobs from Python, perhaps the JDBC-JobStore is of use, and you could write jobs into the database via Python. You'll still need an instance of Quartz running in a JVM. However, I'm not sure how well supported that is as a scenario.
Finally, you may be able to talk to a running Quartz instance via JMX. You'll need a JMX client, and consequently you'll need to spawn off a Java JMX client from your Python process.
I think (regrettably) there's a non-trivial mismatch between a Quartz instance (in Java) and your Python code.


text:
Q: Screenshot for all open windows I wanted to include this code in my script, everything fits so far. Unfortunately, only a black image is created, exactly as the original creator of the post has already written it. Unfortunately, he did not describe exactly how he could solve the problem, so I ask here, maybe someone has an answer for me?
Screenshot of all open windows
He wrote the following in his post, which i don't understand what he means:

Blockquote
I finally found the issue.
I had changed windows 7 settings for best performance, once I changed it to normal Aero settings. It works as expected.


text:
Q: How to open Dialog Box in android? I am selecting an image from gallery with the Intent method of android.
Now after selecting the image,
i want to ask user in a dialog box where he has to select Yes or No.
How do i do that?
Code:
            Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
            if (intent.resolveActivity(getPackageManager()) != null)
            {
                startActivityForResult(intent, 1);
            }

I want to open dialog here on

onActivityResult

, after selecting the image.

A: here is how to make dialog box
new AlertDialog.Builder(context)
    .setTitle("Delete entry")
    .setMessage("Are you sure you want to delete this entry?")

    // Specifying a listener allows you to take an action before dismissing the dialog.
    // The dialog is automatically dismissed when a dialog button is clicked.
    .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) {
            // Continue with delete operation
        }
     })

    // A null listener allows the button to dismiss the dialog and take no further action.
    .setNegativeButton(android.R.string.no, null)
    .setIcon(android.R.drawable.ic_dialog_alert)
    .show();


text:
Q: C# Save modified image in panel I am attempting to save an image as modified by graphics tools such as pens and shapes that can be drawn onto the image. I have done this using a panel with background image and trying to set up a bit map that will save changes within this panel:
    private void saveToolStripButton_Click(object sender, EventArgs e)
    {
        //sets panel1 contents as bit map to be saved at set locations
        int width = panel1.Size.Width;
        int height = panel1.Size.Height;

        using (Bitmap bmp = new Bitmap(width, height))
        {
            panel1.DrawToBitmap(bmp, new Rectangle(0, 0, width, height));
            bmp.Save(@"C:\Users\Me\Pics\testBitmap.jpeg", ImageFormat.Jpeg);
        }
        MessageBox.Show("Your image has been saved");
     }

Once the save button is clicked, the image saves ok but the changes made with the graphics tools do not show up. Can anyone suggest a solution?
Here is some code regarding the graphics tool i've set up for use within the panel:
    {
        InitializeComponent();
        //Create graphics object in panel1
        g = panel1.CreateGraphics();
    }

    private void btnExit2_Click(object sender, EventArgs e)
    {
        this.Close();
    }
    Graphics g;
    //set a drawing boolean
    bool draw = false;
    private void panel1_MouseDown(object sender, MouseEventArgs e)
    {
        draw = true;
        if (drawSq)
        {
            SolidBrush brush = new SolidBrush(Color.FromArgb(128, 255, 0, 0));
            if (toolStripTextBox1.Text != "")
            {
                g.FillRectangle(brush, e.X, e.Y, Convert.ToInt32(toolStripTextBox1.Text), Convert.ToInt32(toolStripTextBox1.Text));
            }
            else if (toolStripTextBox1.Text == "")
            {
               MessageBox.Show("Please enter a shape size");
            }

            draw = false;
            drawSq = false;
        }
    }

and more:
      private void panel1_MouseUp(object sender, MouseEventArgs e)
    {
        draw = false;
        mouseX = null;
        mouseY = null;
    }
    //null values allow freehand style drawing
    int? mouseX = null;
    int? mouseY = null;
    private void panel1_MouseMove(object sender, MouseEventArgs e)
    {
        //creates a pen tool and sets properties by mouse location
        if (draw)
        {
            Pen pen = new Pen(btnColor.ForeColor, float.Parse(txtBox1.Text));
            g.DrawLine(pen, new Point(mouseX ?? e.X, mouseY ?? e.Y), new Point(e.X, e.Y));
            mouseX = e.X;
            mouseY = e.Y;
        }
    }

A: Let's try to fix this.
Start by creating your image first:
Bitmap bmp;

protected override void OnLoad(EventArgs e) {
  base.OnLoad(e);
  bmp = new Bitmap(panel1.ClientSize.Width, panel1.ClientSize.Height);
}

Now when you want to draw on it:
void panel1_MouseMove(object sender, MouseEventArgs e) {
  if (e.Button == MouseButtons.Left) {
    using (Graphics g = Graphics.FromImage(bmp)) {
      g.FillEllipse(Brushes.Red, new Rectangle(e.X - 4, e.Y - 4, 8, 8));
    }
    panel1.Invalidate();
  }
}

And display the results:
void panel1_Paint(object sender, PaintEventArgs e) {
  e.Graphics.DrawImage(bmp, Point.Empty);
}

To save, just use your bitmap:
bmp.Save(@"c:\filename.png", ImageFormat.Png);

Use Double buffering with Panel to avoid the flickering.

A: This will works fine. I tested it and worked well........
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Imaging;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace drawing
{
    public partial class Form2 : Form
    {
        Graphics g;
        bool startPaint = false;
        int? initX = null;
        int? initY = null;

        bool drawSquare = false;
        bool drawRectangle = false;
        bool drawCircle = false;
        public Form2()
        {
            InitializeComponent();

            bmp = new Bitmap(panel1.ClientSize.Width, panel1.ClientSize.Height);

        }
        Bitmap bmp;

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

        }
        void panel1_MouseMove(object sender, MouseEventArgs e)
        {
            if (startPaint)
            {
                using ( g = Graphics.FromImage(bmp))
                {
                  //  g.FillEllipse(Brushes.Black, new Rectangle(e.X, e.Y , 5, 5));

                    Pen p = new Pen(btn_PenColor.BackColor, float.Parse(cmb_PenSize.Text));
                    g.DrawLine(p, new Point(initX ?? e.X, initY ?? e.Y), new Point(e.X, e.Y));
                    initX = e.X;
                    initY = e.Y;
                    //g.DrawImage(bmp, new Rectangle(e.X - 4, e.Y - 4, 8, 8));
                }
                panel1.Invalidate();
            }
        }
        private void pnl_Draw_MouseDown(object sender, MouseEventArgs e)
        {
            startPaint = true;
             if (drawSquare)
             {
                 //Use Solid Brush for filling the graphic shapes
                 SolidBrush sb = new SolidBrush(btn_PenColor.BackColor);
                 //setting the width and height same for creating square.
                 //Getting the width and Heigt value from Textbox(txt_ShapeSize)
                 g.FillRectangle(sb, e.X, e.Y, int.Parse(txt_ShapeSize.Text), int.Parse(txt_ShapeSize.Text));
                 //setting startPaint and drawSquare value to false for creating one graphic on one click.
                 startPaint = false;
                 drawSquare = false;
             }
             if (drawRectangle)
             {
                 SolidBrush sb = new SolidBrush(btn_PenColor.BackColor);
                 //setting the width twice of the height
                 g.FillRectangle(sb, e.X, e.Y, 2 * int.Parse(txt_ShapeSize.Text), int.Parse(txt_ShapeSize.Text));
                 startPaint = false;
                 drawRectangle = false;
             }
             if (drawCircle)
             {
                 SolidBrush sb = new SolidBrush(btn_PenColor.BackColor);
                 g.FillEllipse(sb, e.X, e.Y, int.Parse(txt_ShapeSize.Text), int.Parse(txt_ShapeSize.Text));
                 startPaint = false;
                 drawCircle = false;
             }
        }
         private void pnl_Draw_MouseUp(object sender, MouseEventArgs e)
        {
            startPaint = false;
            initX = null;
            initY = null;
        }
        void panel1_Paint(object sender, PaintEventArgs e)
        {
            e.Graphics.DrawImage(bmp, Point.Empty);
        }

        private void button1_Click(object sender, EventArgs e)
        {
            bmp.Save("D://filename.jpg", ImageFormat.Png);
        }

    }
}


text:
Q: How to flatten and group this HashMap, using streams? Given mapping of letters to numbers, I would like to return a list of Strings, where each String is a comma delimited list of the letters grouped by their associated number.
For this map
    Map<String, Integer> map = new HashMap<String, Integer>();
    map.put("A", 1);
    map.put("B", 2);
    map.put("C", 4);
    map.put("D", 1);
    map.put("E", 1);
    map.put("F", 2);

I would like to return a List containing:
"A,D,E" "B,F", "C"

Any suggestions how this can be accomplished using the 1.8 streaming functions?

A: This way doesn't reference map after it's initially streamed, and makes maximal use of the streaming facilities:
return map.entrySet().stream()
    .collect(Collectors.groupingBy(
        Map.Entry::getValue,
        Collectors.mapping(Map.Entry::getKey, Collectors.joining(","))))
    .values().stream().collect(Collectors.toList());

Or more concisely, but with less usage of streams (thanks @Kartik):
return new ArrayList<>(map.entrySet().stream()
    .collect(Collectors.groupingBy(
        Map.Entry::getValue,
        Collectors.mapping(Map.Entry::getKey, Collectors.joining(","))))
    .values());

In either of those, if you add TreeMap::new as an argument between the two existing arguments to Collectors.groupingBy, the "inside" pieces will be sorted.

A: You can first group entries by value, and then use Collectors.joining(","):
List<String> result = map.entrySet().stream()
        .collect(Collectors.groupingBy(Map.Entry::getValue))
        .values().stream()
        .map(e -> e.stream()
                .map(Map.Entry::getKey)
                .collect(Collectors.joining(",")))
        .collect(Collectors.toList());

A: Here's my attempt
List<String> results = map
    .entrySet()
    .stream()
    .collect(
        Collectors.groupingBy(
            Map.Entry::getValue,
            Collectors.mapping(
                Map.Entry::getKey,
                Collectors.toList())))
    .values()
    .stream()
    .map(letters -> String.join(",", letters))
    .collect(Collectors.toList());