text:
Q: Integrating a 2D Array into a Calendar Printing Program I've decided to start learning to code on my own from a C++ textbook and one of the challenges is to create a program that prints the calendar of a given year, in this style for each month:
-------------January-------------

Sun  Mon  Tue  Wed  Thu  Fri  Sat
                          1    2
 3    4    5    6    7    8    9
10   11   12   13   14   16   17
18   19   20   21   22   23   24
25   26   27   28   29   30   31

I have the whole program written out here in Microsoft Visual Studio, but another one of the challenges is to then convert the data from the two 1D arrays from the getMonthName and dayNumber function into one function with a 2D array that gathers both the month name and the day number, using this array:
// the first number is the month and second number is the last day of the month.
int yearly[12][2] =
{{1,31},{2,28},{3,31},{4,30},{5,31},{6,30},{7,31},{8,31},{9,30},{10,31},{11,30},{12,31}};

The textbook doesn't explain 2D arrays very well, but I know the basics. I just don't know how to go about referencing the contents of the array. Can I assign all the "month number" values of the array to a variable, like I have here for the variable monthNumber, and just go from there? If someone could perhaps provide an example on how one would do this, I'd greatly appreciate it. I'm trying to absorb as much information as I can, so if you could explain how your example works as well, I'd be over the moon.
#include <iomanip>
#include <string>
#include <iostream>

using namespace std;

int dayNumber(int day, int month, int year)
{

    static int t[] = { 0, 3, 2, 5, 0, 3, 5, 1,
                       4, 6, 2, 4 };
    year -= month < 3;
    return (year + year / 4 - year / 100 +
        year / 400 + t[month - 1] + day) % 7;
}

string getMonthName(int monthNumber)
{
    string months[] = { "January", "February", "March",
                       "April", "May", "June",
                       "July", "August", "September",
                       "October", "November", "December"};

    return (months[monthNumber]);
}

//number of days in month
int numberOfDays(int monthNumber, int year)
{
    // january
    if (monthNumber == 0)
        return (31);

    // february
    if (monthNumber == 1)
        return (28);

    // march
    if (monthNumber == 2)
        return (31);

    // april
    if (monthNumber == 3)
        return (30);

    // may
    if (monthNumber == 4)
        return (31);

    // june
    if (monthNumber == 5)
        return (30);

    // july
    if (monthNumber == 6)
        return (31);

    // august
    if (monthNumber == 7)
        return (31);

    // september
    if (monthNumber == 8)
        return (30);

    // october
    if (monthNumber == 9)
        return (31);

    // november
    if (monthNumber == 10)
        return (30);

    // december
    if (monthNumber == 11)
        return (31);
}

// display calendar function
void printCalendar(int year)
{
    printf ("         Calendar - 2021", year);
    int days;

    // day from 0 - 6
    int current = dayNumber(1, 1, year);

    for (int i = 0; i < 12; i++)
    {
        days = numberOfDays(i, year);

        // current month display
        printf("\n  ------------%s-------------\n",
               getMonthName(i).c_str());

        //columns
        printf("  Sun  Mon  Tue  Wed  Thu  Fri  Sat\n");

        // spaces
        int k;
        for (k = 0; k < current; k++)
            printf("     ");

        for (int j = 1; j <= days; j++)
        {
            printf("%5d", j);

            if (++k > 6)
            {
                k = 0;
                printf("\n");
            }
        }

        if (k)
            printf("\n");

        current = k;
    }

    return;
}

// main function
int main()
{
    int year = 2021;
    printCalendar(year);

    return (0);
}

Please let me know if you need any more info, I'll be happy to provide more.

A: I declared a global variable int yearly[12][2];
snippet line 90:
for (int i = 0; i < 12; i++)
    {
        days = numberOfDays(i, year);
        yearly[i][0] = i; //month
        yearly[i][1] = days;//days
        ... ...

The for loop is executed 12 times, and each i corresponds to a month.
Yearly [i][0] is the month  and yearly [i][1] is the days of the month.
What a 2D array looks like:
          column
   Row 0 [0][1]
       1 [0][1]
       2 [0][1]
        ... ...
       11[0][1]

Example of printing a 2D array:
 for (int Row= 0; Row< 12; Row++)
    {
        std::cout << "{";
        for (int column= 0; column< 2; column++)
        {
            std::cout << yearly[Row][column]<<",";
        }
        std::cout << "}"<<std::endl;
    }


text:
Q: How to en-/disable Menu-Object programmatically in Swift I would like to en-/disable a Menu-Object programmatically in Swift. I found something one the Apple Developer Library: https://developer.apple.com/library/mac/documentation/Cocoa/Reference/ApplicationKit/Classes/NSMenuItem_Class/#//apple_ref/occ/instp/NSMenuItem/enabled
But how to get a reference to the Menu-Object with the code and set its state programmatically?

A: For Swift 4+, some of the code in Barath's Answer has become deprecated.  I also think the code is more adaptable by searching for menuitem titles rather than their index:
let mainMenu = NSApplication.shared.mainMenu!
let subMenu = mainMenu.item(withTitle: "Edit")?.submenu

subMenu?.item(withTitle: "Cut")?.isEnabled = false

Also, setting isEnabled to true or false will not toggle menu items as long as setAutoenablesItems is set to true.  It can be disabled from the storyboard or programmatically.

A: Enable or Disable menu item without subclassing with the following code.
let mainMenu = NSApplication.sharedApplication().mainMenu!
let appMenu = mainMenu.itemAtIndex(0)!.submenu

appMenu?.itemWithTitle("Title")?.enabled = false

A: You can just set the enabled-attribute programmatically: menObj.enabled = false

A: Simple Solution with Swift 5+
hamburgerMenuItem.isEnabled = false

redpajama_set_name: RedPajamaStackExchange


text:
Q: No Plot Outout From 'ggplot2' In Shiny App First, a disclaimer: I am enrolled in the Coursera "Developing Data Products" course.  I was in the course last month, but work obligations took up a lot of my time and I was unable to complete the course by the deadline.  I continued to work on the course project and re-enrolled for the January course offering, which just started.
I have watched the videos on coursera and the tutorial series on the Shiny specific site through RStudio.com.  I have everything working except for the plot output from the ggplot.  The problem is there is no output.  There are no error messages, either.  I can't figure it out, so I'm hoping someone here can look at my code and point me in the right direction.
My R code is below.
Thank you!  (In advance.)
Rich
ui.R:
## Coursera Data Science Specialization
#  Class: Delivering Data Products
#
#  Author: Richard Ian Carpenter
#  Date Created: 14 Dec 2015
#  Data Updated: 06 Jan 2016
#
## NOTES:
#
## I am repeating this course, unrolled from Dec 2015 course due to work obligations.
#
## Beyond the notes and videos for the class and the Shiny website, I used the
#  following:
#
## This Stack Overflow question from 2013 helped with correcting my R code:
#  http://stackoverflow.com/questions/18762962/passing-variable-names-to-model-in-shiny-app
#
## This shiny example to get the regression output to be in the same format
#  that R uses, instead of a table: https://rich.shinyapps.io/regression/
#

library(shiny)
library(ggplot2)
data("mtcars")

mtcars <- mtcars

ui <- fluidPage(
      sidebarPanel(
            selectInput("dependent", "Dependent Variable:", c(names(mtcars))),
            uiOutput("independent"),
            checkboxInput("factor", "Create factor variables (am, cyl, etc.)?")
      ),

      mainPanel(
            tabsetPanel(
                  tabPanel("Regression Plot",
                           plotOutput("regPlot")),
                  tabPanel("Regression Summary",
                           verbatimTextOutput("regSummary")))
            )
)

server.R:
## Coursera Data Science Specialization
#  Class: Delivering Data Products
#
#  Author: Richard Ian Carpenter
#  Date Created: 14 Dec 2015
#  Data Updated: 06 Jan 2016
#
## NOTES:
#
## I am repeating this course, unrolled from Dec 2015 course due to work obligations.
#
## Beyond the notes and videos for the class and the Shiny website, I used the
#  following:
#
## This Stack Overflow question from 2013 helped with correcting my R code:
#  http://stackoverflow.com/questions/18762962/passing-variable-names-to-model-in-shiny-app
#
## This shiny example to get the regression output to be in the same format
#  that R uses, instead of a table: https://rich.shinyapps.io/regression/
#

library(shiny)
library(ggplot2)
data("mtcars")

mtcars <- mtcars

server <- (function(input, output) {

      output$independent <- renderUI({
                            checkboxGroupInput(
                               "independent", "Independent Variables:",
                               names(mtcars)[!names(mtcars) %in% input$dependent],

                               if(input$factor) {
                                   mtcars$cyl <- as.factor(mtcars$cyl)
                                   mtcars$vs <- as.factor(mtcars$vs)
                                   mtcars$am <- as.factor(mtcars$am)
                                   mtcars$gear <- as.factor(mtcars$gear)
                                   mtcars$carb <- as.factor(mtcars$carb)
                               }

                               )
                            })

      regression <- reactive({
                       lm(paste(input$dependent," ~ ",
                          paste(input$independent,
                                collapse = " + ")),
                          data = mtcars)
                    })

      output$regPlot <- reactive({

            renderPlot({p <- ggplot(regression(),
                             aes(x = paste(input$independent, collapse = " + "),
                                 y = input$dependent,
                                 environment = environment())
                             )

                        p <- p + geom_point() #+ geom_smooth()

                        print(p)

            }, height = 700)
        })

      output$regSummary <- renderPrint({
                         if(!is.null(input$independent)){
                                    summary(regression())
                         } else {
                              print("Please select the model's dependent and independent variables.")
                         }
                        })
})


text:
Q: Render the point shapefile and raster layer together as single image I have a point layer as one shapefile and MrSid file as raster layer. How to overlap these two layers and clip the merged layer and render it as an output image file?

A: In QGIS - Turn both layers on - File > Import/Export > Export Map to Image
Set your view to the map extent that you want and voila
But im also guessing that perhaps you are wanting something more specific, like a specific output file format, or a geographically located output raster dataset, so perhaps update your question wit some more info on this and we can help


text:
Q: How to call complete and abandon when processing messages from Azure service bus queue using Camel Azure service Bus How to call abandon and complete methods using camel azure service bus?
My code snippet:
from(azureServicebus("queueName")
                     .connectionString("connectionString")
                     .receiverAsyncClient(new ServiceBusClientBuilder().connectionString("connectionString").receiver().queueName().disableAutoComplete().buildAsyncClient())
                     .serviceBusReceiveMode(ServiceBusReceiveMode.PEEK_LOCK)
                     .serviceBusType(azureServiceBusQueueType)
                     .prefetchCount(50)
                     .maxAutoLockRenewDuration(Duration.ofMinutes(10))
.onException(Exception.class)
.process(//abandon((some exception happened and the message is not send to "to" endpoint)))
.end()
.to("endpoint").process(//complete(when message is send to "to" endpoint))
.end();

build.gradle:
implementation "org.apache.camel:azure-servicebus:3.16.0"


text:
Q: How do I disable / enable sections of my website with PHP + Checkboxes? I need help with enableing/disableing parts of my website.

Disabled Sections:

    <form id="e-d-check" method="post">
        <input type="checkbox" name="SRS" onchange="document.getElementById('e-d-check').submit()">SkiRegionSimulator 2012</input>
        <input type="checkbox" name="Bilder" onchange="document.getElementById('e-d-check').submit()">Bilder</input>
        <input type="checkbox" name="KWS" onchange="document.getElementById('e-d-check').submit()">Klimawandel-Stunde</input>
    </form>

                Name
                Größe
                Datum
                Download

            <?php
                if (isset($_POST['SRS'])) {
                    echo 'Disabled SkiRegionSimulator 2012';
                } else {
                    include'SRS.php';
                }
            ?>

Everytime I uncheck the box it checks itself again...

A: Check if this works for you:
<?php
    $disabled = array();
    $disabled['SRS'] = isset($_POST['SRS']) && (int)$_POST['SRS'] === 1;
    $disabled['Bilder'] = isset($_POST['Bilder']) && (int)$_POST['Bilder'] === 1;
    $disabled['KWS'] = isset($_POST['KWS']) && (int)$_POST['KWS'] === 1;
?>

Disabled Sections:

<form id="e-d-check" method="post">
    <input type="checkbox" value="1" <?php if($disabled['SRS'] === true) echo "checked"; ?> name="SRS" onchange="document.getElementById('e-d-check').submit()">SkiRegionSimulator 2012</input>
    <input type="checkbox" value="1" <?php if($disabled['Bilder'] === true) echo "checked"; ?> name="Bilder" onchange="document.getElementById('e-d-check').submit()">Bilder</input>
    <input type="checkbox" value="1" <?php if($disabled['KWS'] === true) echo "checked"; ?> name="KWS" onchange="document.getElementById('e-d-check').submit()">Klimawandel-Stunde</input>
</form>

            Name
            Größe
            Datum
            Download

        <?php
            if ($disabled['SRS'] === true) {
                echo 'Disabled SkiRegionSimulator 2012';
            } else {
                include'SRS.php';
            }
        ?>

We control what checkbox is checked by using the (guess!) checked attribute. If you are using XHTML then change checked to checked="checked"

A: A different but similar approach with submit onclick.
<?php
$check_SRS = "";
$check_Bilder = "";
$check_KWS = "";
if (isset($_POST['SRS']) && intval($_POST['SRS']) == 1) { $check_SRS = "checked";}
if (isset($_POST['Bilder']) && intval($_POST['Bilder']) == 1) { $check_Bilder = "checked";}
if (isset($_POST['KWS']) && intval($_POST['KWS']) == 1) { $check_KWS = "checked";}
?>

Disabled Sections:

   <form id="e-d-check" method="post">
     <input type="checkbox" name="SRS" value="1" onclick="submit()" <?php echo htmlspecialchars($check_SRS); ?>>SkiRegionSimulator 2012</input>
     <input type="checkbox" name="Bilder" value="1" onclick="submit()" <?php echo htmlspecialchars($check_Bilder); ?>>Bilder</input>
     <input type="checkbox" name="KWS" value="1" onclick="submit()" <?php echo htmlspecialchars($check_KWS); ?>>Klimawandel-Stunde</input>
   </form>

    Name
    Größe
    Datum
    Download

  <?php
  if (isset($_POST['SRS']) && intval($_POST['SRS']) == 1) {
    echo 'Disabled SkiRegionSimulator 2012';
  } else {
    include'SRS.php';
  }
  ?>

A version of elseif statements to accommodate what are assumed to be the other includes depending on the state of the checkboxes - if one only can be checked:
<?php
if(intval($_POST['SRS']) == 1){
   echo 'Disabled SkiRegionSimulator 2012';
}elseif(intval($_POST['SRS']) != 1){
   include'SRS.php';
}elseif(intval($_POST['Bilder']) == 1){
   echo 'Disabled Bilder';
}elseif(intval($_POST['Bilder']) != 1){
   include'Bilder.php';
}elseif(intval($_POST['KWS']) == 1){
   echo 'Disabled KWS';
}elseif(intval($_POST['KWS']) != 1){
   include'KWS.php';
}
?>

if more than one can be checked:
 <?php
 if(intval($_POST['SRS']) == 1){
 echo 'Disabled SkiRegionSimulator 2012';
 }else{
 include'SRS.php';
 }

 if(intval($_POST['Bilder']) == 1){
 echo 'Disabled Bilder';
 }else{
 include'Bilder.php';
 }

 if(intval($_POST['KWS']) == 1){
 echo 'Disabled KWS';
 }else{
 include'KWS.php';
 }
 ?>


text:
Q: Masking your web scraping activities to look like normal browser surfing activities? I'm using the Html Agility Pack and I keep getting this error. "The remote server returned an error: (500) Internal Server Error." on certain pages.
Now I'm not sure what this is, as I can use Firefox to get to these pages without any problems.
I have a feeling the website itself is blocking and not sending a response. Is there a way I can make my HTML agility pack call more like a call that is being called from FireFox?
I've already set a timer in there so it only sends to the website every 20 seconds.
Is there any other method I can use?

A: Set a User-Agent similar to a regular browser. A User agent is a http header being passed by the http client(browser) to identify itself to the server.

A: There are a lot of ways servers can detect scraping and its really just an arms race between the scraper and the scrapee(?), depending on how bad one or the other wants to access/protect data.  Some of the things to help you go undetected are:

*

*Make sure all http headers sent over are the same as a normal browser, especially the user agent and the url referrer.

*Download all images and css scripts like a normal browser would, in the order a browser would.

*Make sure any cookies that are set are sent over with each subsequent request

*Make sure requests are throttled according to the sites robots.txt

*Make sure you aren't following any no-follow links because the server could be setting up a honeypot where they stop serving your ip requests

*Get a bunch of proxy servers to vary your ip address

*Make sure the site hasn't started sending you captcha's because they think you are a robot.

Again, the list could go on depending on how sophisticated the server setup is.


text:
Q: Onblur event is not getting called in chrome I have a requirement as when the user once completes entering the text field I want to do some operation on that text field.
HTML:

    <input type="text" id="convenience_chargespopup" onkeypress="return isNumber(event)"  onblur="addZeros()" class="m-wrap span12" placeholder="Convinience Charges"/>

Javascript:
$(document).ready(function() {
    function addZeros() {
        alert('sssssssssss');
    }
});

The addZeros() function is never being getting called.
Could anybody please help me?

A: AddZeros is scoped inside another function, (your unnecessary DOM ready handler), so is not visible to the attribute-based events.
if using jQuery it is best to not use attribute-based events with jQuery... Connect them in jQuery so that the code and event registration are together (also allows multiple handlers per event).
Html:

   <input type="text" id="convenience_chargespopup" class="m-wrap span12" placeholder="Convinience Charges"/>

Code:
$(document).ready(function() {
    $('#convenience_chargespopup').blur(function(){
        alert('sssssssssss');
    }).keypress(function(){
        return isNumber(event)
    });
});

Note: I usually prefer the shortcut DOM ready handler:
$(function() {
    $('#convenience_chargespopup').blur(function(){
        alert('sssssssssss');
    }).keypress(function(){
        return isNumber(event)
    });
});


text:
Q: Using the embedding layer as the input for an encoder I want to use the embedding layer as the input for encoder, however I got an error as follow.  My input y is a time series data with shape of 1*84. Could you please help me with that?
import numpy
import torch.nn as nn

r_input    = torch.nn.Embedding(84, 10)
activation  = nn.functional.relu
mu_r      = nn.Linear(10, 6)
log_var_r = nn.Linear(10, 6)

y = np.random.rand(1,84)

def encode_r(y):
    y         = torch.reshape(y, (-1, 1, 84)) # torch.Size([batch_size, 1, 84])
    hidden    = torch.flatten(activation(r_input(y)), start_dim = 1)
    z_mu      = mu_r(hidden)
    z_log_var = log_var_r(hidden)
    return z_mu, z_log_var```

Error: RuntimeError: Expected tensor for argument #1 'indices' to have one of the following scalar types: Long, Int; but got torch.cuda.FloatTensor instead (while checking arguments for embedding)

A: According to this thread: https://discuss.pytorch.org/t/expected-tensor-for-argument-1-indices-to-have-scalar-type-long-but-got-cpufloattensor-instead-while-checking-arguments-for-embedding/32441/4, it seems that one possible solution would be to ensure embeddings have integer values and not float values in them (by embeddings we mean the lookup table not an actual embedding vector).


text:
Q: Is it possible to use Nautilus Actions with Nemo file manager? I have installed Nemo (initially a Nautilus fork) in Ubuntu 14.04.1 LTS.
I used to use Nautilus actions with Nautilus. Now that I have installed Nemo, I can't use them anymore.
I was wondering if there is any way to use Nautilus actions and the Configuration tool with Nemo - as it is a fork of Nautilus.

*

*Can Nautilus actions be used in Nemo? How?

*Is the Nautilus actions tool (editor) usable for Nemo?

A: Found this on the Arch wiki -

.nemo_action files can be used to create menu entries in the pop-up dialog that comes up since these files are read by nemo whenever you right click. You can invoke a script from these .nemo_action files that does your job, similar to what nautilus-actions does.
You can have a look at /usr/share/nemo/actions/sample.nemo_action and /usr/share/nemo/actions/myaction.py to get an idea of how it works. These files have detailed information on what each field in the action files indicates.
You can visit this website for an example.
Edit :
Nemo actions are similar to nautilus actions in content but vary with respect to the extension name.
In nautilus, newly created actions and menus will be stored on the disk as .desktop files.
The nautilus-actions tool, a graphical editor for nautilus actions, will therefore not work with nemo because it looks for .desktop files, not .nemo_action files.
Summary -
Nautilus scripts can be used if invoked by .nemo_action files, just like nautilus action .desktop files did, and these in turn can be adapted for that purpose. nautilus-actions tool is NOT usable for Nemo due to the difference in paths and extension names.

A: I use Nemo without Cinnamon on Ubuntu 14.04 using a PPA.
Nemo is much more configurable then Nautilus. Whether or not that is "better" then Nautilus is a matter of taste IMHO.  I prefer complex things over simple ones… :-)
That being said, defining your personal Nemo actions or nemo scripts is very straightforward: scripts can be copied verbatim in 90+% of cases and actions can be defined yourself easily (I made my own "Add to VLC" and "Open with BackInTime" in 5 minutes flat by using the provided example)  You can also find tons of user-designed actions around the web.
There are tons of extensions readily available, so the need to define your own actions is hardly needed…

A: Summing up what I have learned from the main answer:

*

*Nemo or Nautilus actions are similar in content  and purpose (namely, adding menu items) but vary with respect to the extension name. (In nautilus, newly created actions and menus will be stored on the disk as .desktop files, In nemo as nemo_action files.) They invoke certain commands including scripts (which are in this sense called nautilus or nemo scripts). Therefore, nautilus scripts can be used if invoked by nemo_action files, just like nautilus actions did, and these can be adapted for that purpose

*The nautilus-actions tool, a graphical editor for nautilus actions, will therefore not work with nemo because it looks for .desktop files, not .nemo_action files.


text:
Q: Proving solution space for $y'+a_0y=0$ has $\{{e^{-a_{0}t}}\}$ as a basis I am trying to prove that the solution space for $y'+a_0y=0$ has $\{{e^{-a_{0}t}}\}$ as a basis. (From Friedberg Linear Algebra Thm2.30)

First we can see that ${e^{-a_{0}t}}$ is a solution since
$y'(t)+a_0y(t)=-a_0e^{-a_0t} +a_0e^{-a_{0}t}=0$
Suppose $x(t)$ is any solution. Then $x'(t)=-a_0x(t)$ for all $t \in R$. I do not understand this part. Why is the derivative of $x(t)$ of that form? Is it assumed that all solutions have the form of the basis?

Define $z(t)=e^{a_0t}x(t)$.I do not understand how they came to this? Why would they make such definition?

$z'(t)=0$ and since $z$ is identically zero, $z$ is a constant function.

Thus, there exists $k \in C$ such that
$z(t)=e^{a_0t}x(t)=k$ for all $t \in R$.

Therefore $x(t)=ke^{-a_0t}$ ending the proof.

A: Suppose $x$ is a solution to $y'+a_0 y=0$. Then since $x$ solves the differential equation, it must be that $x'(t)+a_0x(t)=0$ for all $t$, implying that $x'(t)=-a_0x(t)$. Define $z(t)=e^{a_0 t}x(t)$. We choose this definition of $z$ in order to conveniently show that the arbitrary solution $x$ takes the form of the exponential basis function. Differentiating $z$, we find that
\begin{equation*}
z'(t) = e^{a_0 t}x(t) + e^{a_0 t} x'(t),
\end{equation*}
by the product rule. Substituting our form for $x'$, this becomes
\begin{equation*}
z'(t) = a_0e^{a_0 t}x(t) + e^{a_0 t} (-a_0 x(t)) = 0,
\end{equation*}
which holds for all $t$. Therefore, it must be that $z(t) = k$ for some constant $k$. By our definition of $z$, this implies that
\begin{equation*}
z(t) = e^{a_0 t}x(t) = k,
\end{equation*}
which shows that
\begin{equation*}
x(t) = ke^{-a_0 t}.
\end{equation*}


text:
Q: How do I set a specific table in kafka sink connector? I am using confluent kafka connector.
I want to insert data into a specific table, TB_TEST_KAFKA, in the sink connector.
I have already created the table.
auto.create=false.
I don't know a properties table name key of the sink connector.
I'm trying to insert into specific table, TB_TEST_KAFKA,
connector.class=io.confluent.connect.jdbc.JdbcSinkConnector
errors.log.include.messages=true
dialect.name=SqlServerDatabaseDialect
connection.password=####
tasks.max=1
topics=test-topic
auto.evolve=false
connection.user=kafkauser
auto.create=false
connection.url=jdbc:sqlserver://####:1433;databaseName=TEST
errors.log.enable=true
insert.mode=insert
db.name=TB_TEST_KAFKA

But error
Caused by: org.apache.kafka.connect.errors.ConnectException: Table "TB_TEST_KAFKA" is missing and auto-creation is disabled
at io.confluent.connect.jdbc.sink.DbStructure.create(DbStructure.java:116)
at io.confluent.connect.jdbc.sink.DbStructure.createOrAmendIfNecessary(DbStructure.java:68)
at io.confluent.connect.jdbc.sink.BufferedRecords.add(BufferedRecords.java:123)
at io.confluent.connect.jdbc.sink.JdbcDbWriter.write(JdbcDbWriter.java:73)
at io.confluent.connect.jdbc.sink.JdbcSinkTask.put(JdbcSinkTask.java:75)
at org.apache.kafka.connect.runtime.WorkerSinkTask.deliverMessages(WorkerSinkTask.java:586)
... 10 more

Is there any way to put it into the table??

A: JDBC Sink connector use the topic name as the basis for the naming of the table that it populates. You can use the RegExRouter to customize the name of the table (add these lines to your connector properties):
transforms=renameTopic
transforms.renameTopic.type=org.apache.kafka.connect.transforms.RegexRouter
transforms.renameTopic.regex=test-topic
transforms.renameTopic.replacement=TB_TEST_KAFKA


text:
Q: Javascript translation not working properly I've translated some text in a javascript file with translation.js, I've done it the following way:
I've defined the translator.
define([
'mage/translate',
];

After that, I translated my text.
 $.mage.__('excl. VAT')

And added the translation in the CSV file.
The strange thing is, that sometimes it get's translated and sometimes not...
Did I miss something?

A: Best approach for this would be to use 'domReady!' in your define to make sure document is fully loaded once translation is applied.
define([
    'jquery',
    'underscore',
    'domReady!'
], function ($, _) {...}

A: I wrote a post here regard to my the same issue. You can read to understand why it happens and how to fix
https://mrvts.wordpress.com/2018/07/19/magento-2-javascript-translation-sometime-translate-sometime-not-work-why-and-how-to-fix/

A: it's about timing the translation. Magento had the same Problem in the Checkout or the Catalog in early Versions.
Here is an example: In an old Version, the Add to Cart Button was not translated anymore after adding the product to cart. The old Version had the translation in the initialization function:
https://github.com/magento/magento2/blob/628687b491d2d95e164388bb2f4b97be41a1e211/app/code/Magento/Catalog/view/frontend/web/js/catalog-add-to-cart.js#L23
while the new version has the translation in the handler function
https://github.com/magento/magento2/blob/develop/app/code/Magento/Catalog/view/frontend/web/js/catalog-add-to-cart.js#L121
Since all Javascript resources are loaded asynchronously, it may happen, that your component is loaded before the translation component is initialized.
The solution is, to translate the text as late as possible. For example, instead of being translated the Initialization function, it could be translated in a getText() function which is bound to the HTML element.
You should also take a look at the file pub/static/frontend/Your/Theme/<language>/js-translation.json (or something similar)
This File should contain all translations that are used in the theme's Javascript files and should contain your own translation. It gets regenerated if you delete it (at least in developer mode) and is also cached in the local storage of the browser.

A: it throw error if you use __ so follow below code
require([
    'jquery', // jquery Library
    'mage/translate'
   ], function($,$t){
         alert($t('Enter Your message here'));

    });

A: You must use $.mage.__('excl. VAT') as it will be automatically parsed by an internal magento code and generate a JSON file in pub/static folder
eg : pub/static/frontend/Magento/Luma/fr_FR/js-translation.json
BUT be aware that Magento will only parse js and html files. So if you use this $.mage.__('...') in phtml files it will not be translated.


text:
Q: Positive integers expressed in the form : $\frac{a^b+c}{a+c}$ Note : This problem has no specific source .
Is it true that :

Every positive integer $n$ greater than $1$ can be expressed in the form :
$n=\frac{a^b+c}{a+c}$ , where $a,b>1$ , and $c \in \mathbb{Z} \backslash \{0\}$

I am able to prove following :
$\forall a , \exists ~b,c$ such that : $a+c \mid a^b+c$ , where $b>1$
Proof :
$n=\frac{a^b+c}{a+c}=\frac{a^b-a}{a+c}+1$ , therefore it is sufficient to prove :
$a+c \mid a(a^{b-1}-1)$
If $a+c \mid a$ then $b$ can be any positive integer .
If $a+c \not \mid a$ then we have to prove : $a+c \mid a^{b-1}-1$
or , in other words :
$a^{b-1} \equiv 1 \pmod {a+c}$
Now , for every $a$ there is a number $c$ such that : $\gcd(a,a+c)=1$
According to Euler Theorem :
$a^{\varphi(a+c)} \equiv 1 \pmod {a+c}$
Hence , we can write :
$b-1=\varphi(a+c) \Rightarrow b=1+\varphi(a+c)$
Since $\varphi(a+c)\geq 1$ it follows $b>1$
Q.E.D.
But , this is only necessary condition .

A: Let $a = n$, $b = 3$, $c = n^2$. This does it.

A: Hint $\ $ If $\rm\:b,c\:$ are independent of $\rm\:n\:$ and $\rm\:a\:$ is a polynomial in $\rm\:n\:$ of degree $\rm\:d\:$ then comparing degrees in $\rm\:a^b+c = n\:(a+c)\:$ $\Rightarrow$ $\rm\:db = d+1,\:$ so $\rm\:d(b-1) = 1,\:$ hence $\rm\:d=1,\:b=2.\:$ Plugging in undetermined coefficients $\rm\:a\: =\: a_1\: n + a_0 \:$ yields $\rm\:a_1 = 1,\:a_0 = -1,\:$  hence
$$\rm\ \frac{a^b+c}{a+c}\ =\ \frac{(n-1)^2 - 1}{(n-1)-1}\ =\ \frac{n^2 - 2n}{n-2}\ =\ n$$

A: Do you know Fermat's Little Theorem? It is a useful tool here...


text:
Q: Matlab Increase thickness of lines of 3d bars I have a 3D bar chart. Let me clarify, I do not want to edit the width of the bar graph as I have already done that. However, there are black lines that outline each bar. Is there a way to make these thicker?
Everything I have search pays reference to the width of the bars themselves, not the black lines enclosing them.

A: At last, I found the answer to my own question the minute after I ask it.
Simply:
set(j,'LineWidth',1.5)

EDIT: As Luis mentioned, j is the handle such that j = bar3(...)
Sorry should have included that.


text:
Q: how to convert integer time to time object in python I have following pandas dataframe
  code     time
  1        170000
  2        70000
  3        123000
  4        120000

My desired dataframe is following
  code     time       new_time
  1        170000     17:00:00
  2        70000      07:00:00
  3        123000     00:30:00
  4        120000     00:00:00

I am doing following in python
data['new_time'] = [time.strftime('%H:%M:%S', time.gmtime(x)) for x in data['time']]
data['new_time'] = pd.to_datetime(data['new_time']).dt.time

It's giving me some weird conversion. How can I do it?

A: Use the format argument in pd.to_datetime (no need for the list comprehension or the time module):
data['new_time'] = pd.to_datetime(data.time, format='%H%M%S').dt.time

>>> data
   code    time  new_time
0     1  170000  17:00:00
1     2   70000  07:00:00
2     3  123000  12:30:00
3     4  120000  12:00:00


text:
Q: How to use jsoniter codegen with Android? I'm building an Android app from scratch that will ingest JSON data from an HTTP API, convert to POJOs, and then utilize these POJOs throughout the app for various logic.
Because I'm starting from scratch, I did some research to figure out what I think is the best library to handle these API requests. Feel free to correct me if I'm entirely wrong, because I had a lot of trouble finding more recent information, but it seems to me like Retrofit is one of the faster libraries for doing this (I know, it's a 2013 link, but I didn't find a lot of "recent" information on this subject)
Looking into Retrofit, it utilizes "converters" to parse the raw response text to a POJO. By default they include things like GSON, Jackson, Mochi, and several other things I haven't heard of. Some further Googling suggests jsoniter is the fastest option (this is actually from 2018)
Looking around, I found someone who created a converter for Retrofit that uses jsoniter (last updated December 2017)
The README for this project mentions that the default decoding mode is DecodingMode.REFLECTION_MODE. Looking at jsoniter's own docs on the subject, Reflection mode sounds like it's the slowest option. For performance they recommend either Dynamic Code Generation or Static Code Generation. After reading through their documentation on Static Code Generation, they provide a link to an example for Android
This demo was last updated December 2017, so it's not that old. But I can't seem to get the code to work in my own project. I copied the following to my build.gradle file (from their build.gradle file):
afterEvaluate {
    android.applicationVariants.all { variant ->
        variant.javaCompiler.finalizedBy(jsoniterStaticCodgen)
    }
}

task jsoniterStaticCodgen(type:JavaExec) {
    classpath configurations.getByName(android.sourceSets.main.compileConfigurationName)
    classpath project.buildDir.toString() + '/intermediates/classes/release'
    classpath project.buildDir.toString() + '/intermediates/classes/debug'
    main = 'com.jsoniter.static_codegen.StaticCodegen'
    args 'com.mycompany.myapplication.CodegenConfig'
    workingDir = android.sourceSets.main.java.srcDirs[0].toString()
    standardOutput = System.out
    errorOutput = System.err
}

I then tried hitting the Sync Now button in Android Studio and was met with the following error:
ERROR: Could not get unknown property 'applicationVariants' for object of type com.android.build.gradle.LibraryExtension.

What am I doing wrong?


text:
Q: Having trouble with kern_return_t error I am getting the following error when I try to compile with the code below it. I don't know how to fix it. I have googled. Also asked others, but nobody has been able to help me.
Compiling on mac through theos.
I would really appreciate it if someone can help me.
Error output
error: assigning to
  'kern_return_t' (aka 'int') from incompatible type 'uint *'
  (aka 'unsigned int *')
err = reinterpret_cast<uint *>(address* sizeof(data));

Code
bool writeData(vm_address_t address,  string str) {

//declaring variables

kern_return_t err = 0;
mach_port_t port = mach_task_self();

size_t find = str.find("0x");

if (find != -1) {

    str.replace(find, 2, "");
}

int len = str.size();

 char data[len / 2];

int x = 0;

for(int i = 0; i < len; i += 2) {

    string dat = str.substr(i, 2);
    uint8_t tmp;
    sscanf(dat.c_str(), "%hhx", &tmp);
    data[x] = tmp;
    x++;

}

//set memory protections to allow us writing code there

err = vm_protect(port, (vm_address_t)address, sizeof(data), NO, VM_PROT_READ | VM_PROT_WRITE | VM_PROT_COPY);

//check if the protection fails

if (err != KERN_SUCCESS)
    return FALSE;

//write code to memory

err = reinterpret_cast<uint64_t *>(address* sizeof(data));

if (err != KERN_SUCCESS)
    return FALSE;

//set the protections back to normal so the app can access this address as usual

err = vm_protect(port, (vm_address_t)address, sizeof(data), NO, VM_PROT_READ | VM_PROT_EXECUTE);

if (err != KERN_SUCCESS)
    return FALSE;

return TRUE;

}


text:
Q: Class assign in React Currently I am using redux-form, and now I have to connect my reduxForm component to my redux storage. So, looking at the docs I have to do something like:
// Decorate with reduxForm(). It will read the initialValues prop provided by connect()
InitializeFromStateForm = reduxForm({
  form: 'initializeFromState'  // a unique identifier for this form
})(InitializeFromStateForm)

// You have to connect() to any reducers that you wish to connect to yourself
InitializeFromStateForm = connect(
  state => ({
    initialValues: state.account.data // pull initial values from account reducer
  }),
  { load: loadAccount }               // bind account loading action creator
)(InitializeFromStateForm)

export default InitializeFromStateForm

I did something like that in my component but, eslint is giving me an error:
no-class-asign
Should I disable this rule for using it with redux-form or does exist a way to manage this kind of things?

A: You don't really need to reassign the class. Why not do something like
// Decorate with reduxForm(). It will read the initialValues prop provided by connect()
const reduxFormDecorator = reduxForm({
  form: 'initializeFromState'  // a unique identifier for this form
});

const reduxConnector = connect(
  state => ({
    initialValues: state.account.data // pull initial values from account reducer
  }),
  { load: loadAccount }               // bind account loading action creator
);

export default reduxConnector(reduxFormDecorator(InitializeFromStateForm));


text:
Q: How to get pasted value from Reactjs onPaste event if i have an Reactjs input text element with onPaste event assigned to it, how could I get the pasted value in the response?
at the moment what i get in the console is a SyntheticClipboardEvent with all properties as null. I read that the console.log is a async checker so thats why the majority of values are null as they are looking ahead.
However I am wondering how to get the value.
Cheers

A: onPaste: function(e) {
    console.log(e.clipboardData.getData('Text'));
},

A: Here is maybe a simpler "no paste" example using React hooks
export default function NoPasteExample() {
  const classes = useStyles();
  const [val, setVal] = React.useState("");
  const [pasted, setPasted] = React.useState(false);

  const handleChange = e => {
    if (!pasted) {
      setVal(e.target.value);
    }
    setPasted(false);
  };

  const handlePaste = () => {
    setPasted(true);
  };
  return (
    <form className={classes.root} noValidate autoComplete="off">
      <div>
        <TextField
          value={val}
          onPaste={handlePaste}
          onChange={e => handleChange(e)}
        />
      </div>
    </form>
  );
}

live demo: https://codesandbox.io/s/material-demo-w61eo?fontsize=14&hidenavigation=1&theme=dark

A: https://developer.mozilla.org/en-US/docs/Web/API/DataTransfer/types

The formats are Unicode strings giving the type or format of the data,
  generally given by a MIME type. Some values that are not MIME types
  are special-cased for legacy reasons (for example "text").

example:
onPaste: function(e) {
    console.log(e.clipboardData.getData('Text'));
    console.log(e.clipboardData.getData('text/plain'));
    console.log(e.clipboardData.getData('text/html'));
    console.log(e.clipboardData.getData('text/rtf'));

    console.log(e.clipboardData.getData('Url'));
    console.log(e.clipboardData.getData('text/uri-list'));
    console.log(e.clipboardData.getData('text/x-moz-url'));
}

A: the data can be found on clipboardData, and parsed to string as follows:
event.clipboardData.items[0].getAsString(text=>{
  // do something
})

A: first include Facebook DataTransfer module:
var DataTransfer = require('fbjs/lib/DataTransfer');

then you can do:
onPaste: function (evt) {
       var data = new DataTransfer(evt.clipboardData);

       var text = data.getText();
       var html = data.getHTML();
       var files = data.getFiles();
},

you welcome ;)

A: For me this is quick and worked.
onPaste event fires before the input's value is changed.

So we need to use e.persist()

<input
   onPaste={(e)=>{
    e.persist();
    setTimeout(()=>{ this.handleChange(e)},4)}
   }
   value={this.state.value}/>


text:
Q: Admob ios x64 error I'm trying to test Admob Banner on iPad Mini Retina. Now I'm getting this error:

Undefined symbols for architecture arm64:
  "_SCNetworkReachabilityCreateWithAddress", referenced from:
        l002 in libGoogleAdMobAds.a(GADGestureUtil.o)   "_AudioServicesPlaySystemSound", referenced from:
        -[GADDefaultGMSGHandler didReceiveVibrateNotification:] in libGoogleAdMobAds.a(GADDefaultGMSGHandler.o)
  "_AudioSessionInitialize", referenced from:
        -[GADDevice audioRouteUsingAudioToolkit] in libGoogleAdMobAds.a(GADDevice.o)   "_OBJC_CLASS_$_AVAudioSession",
  referenced from:
        objc-class-ref in libGoogleAdMobAds.a(GADDevice.o)   "_AVAudioSessionPortHeadphones", referenced from:
        -[GADDevice audioRouteUsingAVAudioSession] in libGoogleAdMobAds.a(GADDevice.o)   "_AudioSessionGetProperty",
  referenced from:
        -[GADDevice audioRouteUsingAudioToolkit] in libGoogleAdMobAds.a(GADDevice.o)
  "_OBJC_CLASS_$_MFMailComposeViewController", referenced from:
        objc-class-ref in libGoogleAdMobAds.a(GADOpener.o)   "_SCNetworkReachabilityGetFlags", referenced from:
        l002 in libGoogleAdMobAds.a(GADGestureUtil.o)   "_SCNetworkReachabilitySetCallback", referenced from:
        -[GADNetworkChecker startNetworkChecking] in libGoogleAdMobAds.a(GADNetworkChecker.o)
  "_OBJC_CLASS_$_MFMessageComposeViewController", referenced from:
        objc-class-ref in libGoogleAdMobAds.a(GADOpener.o)   "_AVAudioSessionPortBuiltInSpeaker", referenced from:
        -[GADDevice audioRouteUsingAVAudioSession] in libGoogleAdMobAds.a(GADDevice.o)
  "_OBJC_CLASS_$_SKStoreProductViewController", referenced from:
        objc-class-ref in libGoogleAdMobAds.a(GADOpener.o)   "_SCNetworkReachabilityScheduleWithRunLoop", referenced from:
        -[GADNetworkChecker startNetworkChecking] in libGoogleAdMobAds.a(GADNetworkChecker.o)
  "_OBJC_CLASS_$_CTTelephonyNetworkInfo", referenced from:
        objc-class-ref in libGoogleAdMobAds.a(GADDevice.o)   "_SCNetworkReachabilityUnscheduleFromRunLoop", referenced from:
        -[GADNetworkChecker stopNetworkChecking] in libGoogleAdMobAds.a(GADNetworkChecker.o)
  "_SCNetworkReachabilityCreateWithName", referenced from:
        -[GADNetworkChecker startNetworkChecking] in libGoogleAdMobAds.a(GADNetworkChecker.o)
  "_SKStoreProductParameterITunesItemIdentifier", referenced from:
        -[GADOpener openInAppStore:fallbackURLString:] in libGoogleAdMobAds.a(GADOpener.o) ld: symbol(s) not found for
  architecture arm64 clang: error: linker command failed with exit code
  1 (use -v to see invocation)

I found a solution which removes some errors. It is to add some Frameworks. List of them:

*

*AudioToolbox.Framework

*MessageUI.Framework

*SystemConfiguration.Framework

*CoreGraphics.Framework

*CoreData.Framework

*AdSupport.Framework

*MediaPlayer.framework
But anyway I have got this error:

Undefined symbols for architecture arm64:
  "_OBJC_CLASS_$_AVAudioSession", referenced from:
        objc-class-ref in libGoogleAdMobAds.a(GADDevice.o)   "_AVAudioSessionPortBuiltInSpeaker", referenced from:
        -[GADDevice audioRouteUsingAVAudioSession] in libGoogleAdMobAds.a(GADDevice.o)
  "_OBJC_CLASS_$_CTTelephonyNetworkInfo", referenced from:
        objc-class-ref in libGoogleAdMobAds.a(GADDevice.o)   "_AVAudioSessionPortHeadphones", referenced from:
        -[GADDevice audioRouteUsingAVAudioSession] in libGoogleAdMobAds.a(GADDevice.o)
  "_OBJC_CLASS_$_SKStoreProductViewController", referenced from:
        objc-class-ref in libGoogleAdMobAds.a(GADOpener.o)   "_SKStoreProductParameterITunesItemIdentifier", referenced from:
        -[GADOpener openInAppStore:fallbackURLString:] in libGoogleAdMobAds.a(GADOpener.o) ld: symbol(s) not found for
  architecture arm64 clang: error: linker command failed with exit code
  1 (use -v to see invocation)

How to solve this issue?

A: Just add following frameworks BuildSettings -> Build Phase -> Link Binary with libraries
StoreKit.framework
CoreTelephony.framework
AVFoundation.framework


text:
Q: Displaying XML Child Data with PHP and SimpleXML I am new to PHP as well as XML.  I am attempting to pull specific elements from what I believe are child elements of the XML file.
The main class is <events> and there are multiple <event> within the <events> class.  I am trying to pull specific data from the XML file and display them.
<?php
$xml = simplexml_load_file('http://xml.pinnaclesports.com/pinnaclefeed.aspx?sporttype=Football&sportsubtype=nfl');
foreach($xml->children() as $event){
    echo $event->participants->participant->participant_name . ", ";
    echo $event->participants->participant[1]->participant_name . ", ";
    echo $event->periods->period->spread->spread_visiting . ", ";
    echo $event->periods->period->total->over_adjust . "
";
}
?>

Here is the output, with no PHP error_log entries:
, , ,
, , ,
, , ,
, , ,

I appreciate any and all help.

A: To access nested elements, you can simply follow element path starting from the context element (event) to the target element. It will be a lot easier to see the path/hierarchy if you format the XML properly :
foreach($xml->children() as $event) {
    echo $event->participants->participant->participant_name . ", ";
    echo $event->participants->participant[1]->participant_name . ", ";
    echo $event->periods->period->spread->spread_visiting . ", ";
    echo $event->periods->period->total->over_adjust . "
";
}

eval.in demo
output :
Denver Broncos, San Diego Chargers, -3, 101


text:
Q: Confused about relation between header and implementation file I'm working with Code::Blocks. When I create a header-file foo.h and put forward-declarations as well as implementation into it, compilation works fine. Creating a foo.cpp file and putting nothing into it still works. But when I include the header-file within the implementation file, but keep the implementation in the header-file, I get an error about multiple declarations.
Example from my current Project
// header-file `GKit/math/blendprocs.cpp`
#include "GKit/utils/Color.h"

#ifndef _GKIT_MATH_BLENDPROCS_H_
#define _GKIT_MATH_BLENDPROCS_H_

    namespace GKit {
        namespace math {

            void blendAoverB(GKIT_COLORBLENDPROC_ARGSX) {
                D.a = A.a + (1 - A.a) * B.a;
                D.r = (A.a * A.r + (1 - A.a) * B.a * B.r) / D.a;
                D.g = (A.a * A.g + (1 - A.a) * B.a * B.g) / D.a;
                D.b = (A.a * A.b + (1 - A.a) * B.a * B.b) / D.a;
                GKIT_UTILS_COLOR_NORMALIZE(D);
            }

        }
    }

#endif // _GKIT_MATH_BLENDPROCS_H_

// implementation-file `GKit/math/blendprocs.cpp`
#include "GKit/math/blendprocs.h"

// Compilation output
-------------- Build: Debug in GKit ---------------

Compiling: GKit\math\blendprocs.cpp
Linking console executable: bin_debug\GKit.exe
build_debug\GKit\math\blendprocs.o:C:\Users\niklas\Desktop\GKit/./GKit/math/blendprocs.h:10: multiple definition of `GKit::math::blendAoverB(GKit::utils::Color const&, GKit::utils::Color const&, GKit::utils::Color&)'
build_debug\main.o:C:\Users\niklas\Desktop\GKit/./GKit/math/blendprocs.h:10: first defined here
collect2: ld returned 1 exit status
Process terminated with status 1 (0 minutes, 0 seconds)
2 errors, 0 warnings

Can you please help me understanding this error?

A: In your header-file you would typically only put:
// header-file `GKit/math/blendprocs.cpp`
#ifndef _GKIT_MATH_BLENDPROCS_H_
#define _GKIT_MATH_BLENDPROCS_H_

#include "GKit/utils/Color.h"

namespace GKit {
    namespace math {

        void blendAoverB(GKIT_COLORBLENDPROC_ARGSX);

    }
}

#endif // _GKIT_MATH_BLENDPROCS_H_

And then in your CPP-file you put the actual implementation:
// implementation-file `GKit/math/blendprocs.cpp`
#include "GKit/math/blendprocs.h"

namespace GKit {
    namespace math {

        void blendAoverB(GKIT_COLORBLENDPROC_ARGSX) {
            D.a = A.a + (1 - A.a) * B.a;
            D.r = (A.a * A.r + (1 - A.a) * B.a * B.r) / D.a;
            D.g = (A.a * A.g + (1 - A.a) * B.a * B.g) / D.a;
            D.b = (A.a * A.b + (1 - A.a) * B.a * B.b) / D.a;
            GKIT_UTILS_COLOR_NORMALIZE(D);
        }

    }
}

Otherwise the implementation of your function will end up in all CPP-files that includes the header, which will confuse the linker when it tries to resolve the address of blendAoverB since it can find it in all object-files whose corresponding CPP-file included the header-file with the implementation.
On a side-note, it's better to put the include-guards (the #ifndef _GKIT_MATH_BLENDPROCS_H_ before anything else in your header-file (except maybe for comments).

A: You have a definition in a header. That definition will be duplicated in any source file that includes that header; since it's usually an error to have more than one definition in a program, the build fails. This is known as the One Definition Rule, sometime cryptically referred to as ODR.
The two best options are either:

*

*Move the definition into a source file, leaving just a declaration in the header, or

*Add inline to the definition; this relaxes the rule and allows multiple definitions in a program, as long as they are all identical.

Also, you shouldn't use reserved names for your include guards; you should remove the initial _ from _GKIT_MATH_BLENDPROCS_H_; and it's better to put those guards right at the start of the header, before any #include directives.

A: You should either inline your implementation or put the implementation in the cpp file, not both.
// header "GKit/math/blendprocs.h"
#pragma once

#include "GKit/utils/Color.h"

namespace GKit {
        namespace math {
            void blendAoverB(GKIT_COLORBLENDPROC_ARGSX);
        }
    }

// implementation "GKit/math/blendprocs.cpp"
#include "GKit/math/blendprocs.h"

namespace GKit {
        namespace math {

            void blendAoverB(GKIT_COLORBLENDPROC_ARGSX) {
                D.a = A.a + (1 - A.a) * B.a;
                D.r = (A.a * A.r + (1 - A.a) * B.a * B.r) / D.a;
                D.g = (A.a * A.g + (1 - A.a) * B.a * B.g) / D.a;
                D.b = (A.a * A.b + (1 - A.a) * B.a * B.b) / D.a;
                GKIT_UTILS_COLOR_NORMALIZE(D);
            }

        }
    }

Or alternately inline it properly in the header using the inline keyword.
// header "GKit/math/blendprocs.h"
#pragma once

#include "GKit/utils/Color.h"

    namespace GKit {
        namespace math {
            inline void blendAoverB(GKIT_COLORBLENDPROC_ARGSX) {
                D.a = A.a + (1 - A.a) * B.a;
                D.r = (A.a * A.r + (1 - A.a) * B.a * B.r) / D.a;
                D.g = (A.a * A.g + (1 - A.a) * B.a * B.g) / D.a;
                D.b = (A.a * A.b + (1 - A.a) * B.a * B.b) / D.a;
                GKIT_UTILS_COLOR_NORMALIZE(D);
            }
        }
    }

A: This is exactly what messages said. You should get familiar with Inline and ODR.  You cant have multiple definition it is against ODR. I Guess your blendprocs.cpp is included more than once in different compilation units. it is related to Why aren't my compile guards preventing multiple definition inclusions?
ODR:
http://en.wikipedia.org/wiki/One_Definition_Rule


text:
Q: Prompt the user for a String. Show the text along with the first and last character I am having trouble with figuring out how to identify the last letter of the string input. I'm not sure if I should be using a char[] instead of a string. Should I use a char for the first and last letter or a String?
public static void main(String[] args) {
    Scanner keyboard = new Scanner(System.in);
    System.out.println("Enter some text");
    String input = keyboard.nextLine();
    System.out.println("You entered: " + input);

    if (input.length() == 1) {
        char firstLetter = input.charAt(0);
        firstLetter = Character.toLowerCase(firstLetter);

        if (firstLetter == 'U' || firstLetter == 'S' || firstLetter == 'b' || firstLetter == 'B'
                || firstLetter == 'x') {
            System.out.println("First letter: " + firstLetter);
        }

        if (firstLetter == 'a' || firstLetter == 't' || firstLetter == 'x') {
            System.out.println("Last letter: " + firstLetter);
        }
    }

}

A: This might help you:
public static void main(String[] args) throws Exception {

    System.out.println("Enter a string: \n");
    Scanner scanner = new Scanner(System.in);
    String input = scanner.nextLine();
    if (input.length() > 0) {
        System.out.println("You entered: " + input);
        System.out.println("Last charcter: " + input.charAt(0));
        System.out.println("Last charcter: " + input.charAt(input.length() - 1));
    }
    scanner.close();

}


text:
Q: Visual Studio Cordova, building iOS package via remote agent issues We've been building a mobile application in Visual Studid Community 2015 using the Cordova platform with the aim to publish to Android and iOS.
Android we have no issues with but want to submit the app to Apple.  The problem is that we tried setting up a remote agent the last couple of days but have ran into a brick wall.
On our Macbook Pro we've installed node latest version as we are running Cordova CLI 5.4.1.  Also we've installed xCode latest version.  Signed up for Apple's developer program, created a distribution profile, got our certificate etc.  In other words we've ticked all the boxes.
Now the issue is once we try running the remote agent and trying to connect remotely via Visual Studio to our Mac to submit to the Apple store.  If we use remote agent we get the follwoing 404 error in Mac's terminal:
GET /certs/{pin number} 200 12ms - 3.49kb
GET /modules/taco-remote 404 3ms

And in Visual Studio the following pop up:
Unable to connect to remote iOS build server. Underlying exception:
The remote server returned an error: (404) not found.

If we try to use remotebuild we get an error "error parsing JSON remotebuild.config".
We've tried finding documentation or information on either of these but everything just points back to: http://taco.visualstudio.com/en-us/docs/ios-guide/ for remote build or Visual Studio's pages on how to install and run remote agent.
We've followed those steps 10 times but just keep on getting the same error.  If we try from another computer's Visual Studio we get an error "Could not resolve host" though the host name is definitely correct.
We are using Visual Studio Community 2015.
Any ideas?


text:
Q: Getting java.lang.ClassCastException in my app I am making an e-commerce app and I am making Cart for the app here is my code
Controller.java
package com.example.android.namkeen;

import android.app.Application;

import java.util.ArrayList;

/**
 * Created by SONY on 02-10-2016.
 */
public class Controller extends Application
{
    private ArrayList<ModelProducts> myproducts = new ArrayList<ModelProducts>();
    private ModelCart myCart = new ModelCart();
    public ModelProducts getProducts(int pPosition){
        return myproducts.get(pPosition);
    }
    public void  setProducts(ModelProducts products){
        myproducts.add(products);
    }
    public ModelCart getCart(){
        return myCart;
    }
    public int  getProductArraylistsize(){
        return myproducts.size();
    }
}

ModelCart.java
package com.example.android.namkeen;

import java.util.ArrayList;

public class ModelCart {
    private ArrayList<ModelProducts> cartItems = new ArrayList<ModelProducts>();
    public ModelProducts getProducts(int position){
        return cartItems.get(position);
    }
    public void setProducts(ModelProducts Products){
        cartItems.add(Products);
    }
    public int getCartsize(){

        return cartItems.size();
    }
    public boolean CheckProductInCart(ModelProducts aproduct){
        return cartItems.contains(aproduct);
    }
}

ModelProducts.java
package com.example.android.namkeen;

/**
 * Created by SONY on 02-10-2016.
 */
public class ModelProducts {
    private String productName;
    private String productDesc;
    private int productPrice;
    public ModelProducts(String productName,String productDesc,int productPrice){
        this.productName = productName;
        this.productDesc = productDesc;
        this.productPrice = productPrice;
    }

    public String getProductName(){
        return productName;
    }

    public String getProductDesc(){
        return productDesc;
    }

    public int getProductPrice(){
        return productPrice;
    }
}

and this is the main activity in which I am making a custom view and I am using controller class to add the products
 package com.example.android.namkeen;

    import android.content.Intent;
    import android.graphics.Typeface;
    import android.os.Bundle;
    import android.support.v7.app.ActionBar;
    import android.support.v7.app.AppCompatActivity;
    import android.util.Log;
    import android.util.TypedValue;
    import android.view.View;
    import android.widget.Button;
    import android.widget.LinearLayout;
    import android.widget.TextView;
    import android.widget.Toast;

    public class CartMain extends AppCompatActivity {
        /** Called when the activity is first created. */
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);

            final LinearLayout layout = (LinearLayout)findViewById(R.id.linearMain);
            final Button btn = (Button)findViewById(R.id.second);
            final Controller ct = (Controller) getApplicationContext();//getting error in this line
            ModelProducts products = null;
            int Price=30;
            products = new ModelProducts("Plain Maath", "Plain salted \n big sized mathri", Price);
            ct.setProducts(products);
         /*   for(int i= 1; i<=7;i++)
            {
                int Price = 15+ i;
                products = new ModelProducts("Product Item" +i, "Description"+i, Price);
                ct.setProducts(products);
            }*/
            int productsize = ct.getProductArraylistsize();
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ActionBar.LayoutParams.WRAP_CONTENT, ActionBar.LayoutParams.WRAP_CONTENT);
            for (int j=0;j< productsize;j++){
                String pName = ct.getProducts(j).getProductName();
                int pPrice = ct.getProducts(j).getProductPrice();
                String desc = ct.getProducts(j).getProductDesc();
                LinearLayout la = new LinearLayout(this);
                la.setOrientation(LinearLayout.HORIZONTAL);

                LinearLayout la1 = new LinearLayout(this);
                la1.setOrientation(LinearLayout.VERTICAL);

                TextView tv = new TextView(this);
                tv.setText(" " + pName + " ");
                tv.setTypeface(null, Typeface.BOLD);
                tv.setTextSize(TypedValue.COMPLEX_UNIT_SP, 22F);
                la1.addView(tv);

                TextView des = new TextView(this);
                des.setText(" " + desc + " ");

                la1.addView(des);

                TextView tv1 = new TextView(this);
                tv1.setText(" "+"Rs"+pPrice+"/250gm"+" ");
                la1.addView(tv1);
                la.addView(la1);

                final Button btn1 = new Button(this);
                btn1.setId(j+1);
                btn1.setText("Add to Cart");
                btn1.setLayoutParams(params);
                final int index = j;
                btn1.setOnClickListener(new View.OnClickListener()
                {
                    public void onClick(View v) {
    // TODO Auto-generated method stub
                        Log.i("TAG", "index:"+index);
                        ModelProducts productsObject = ct.getProducts(index);
                        if(!ct.getCart().CheckProductInCart(productsObject)){
                            btn1.setText("Item Added");
                            ct.getCart().setProducts(productsObject);
                            Toast.makeText(getApplicationContext(), "New CartSize:" +ct.getCart().getCartsize(),Toast.LENGTH_LONG).show();
                        }else{
                            Toast.makeText(getApplicationContext(), "Products"+(index+1)+"Already Added",Toast.LENGTH_LONG ).show();
                        }
                    }
                });
                la.addView(btn1);
                layout.addView(la);
            }
            btn.setOnClickListener(new View.OnClickListener()
            {
                @Override
                public void onClick(View v) {
    // TODO Auto-generated method stub
                    Intent in = new Intent(getBaseContext(),Screen2.class);
                    startActivity(in);
                }
            });
        }
    }

This is the code which will work when  checkout button will be clicked in the cart activity
Screen2.java
package com.example.android.namkeen;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;

/**
 * Created by SONY on 02-10-2016.
 */
public class Screen2 extends AppCompatActivity
{
    /* (non-Javadoc)
    * @see android.app.Activity#onCreate(android.os.Bundle) */
    @Override
    protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.screen2);

        TextView showCartContent = (TextView)findViewById(R.id.showcart);
        final Controller ct = (Controller)getApplicationContext();
        final int CartSize = ct.getCart().getCartsize();
        String show = "";
        for(int i=0;i<CartSize;i++){
            String pName = ct.getCart().getProducts(i).getProductName();
            int  pPrice = ct.getCart().getProducts(i).getProductPrice();
            String pDisc = ct.getCart().getProducts(i).getProductDesc();
            show += "Product Name:"+pName+" "+"Price : "+pPrice+""+"Discription : "+pDisc+""+    "-----------------------------------";
        }
        showCartContent.setText(show);
    }
}

I am doing everything correct but when I am running this code it is giving this exception error
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.android.namkeen/com.example.android.namkeen.CartMain}: java.lang.ClassCastException: android.app.Application cannot be cast to com.example.android.namkeen.Controller
Caused by: java.lang.ClassCastException: android.app.Application cannot be cast to com.example.android.namkeen.Controller
                                                                                at com.example.android.namkeen.CartMain.onCreate(CartMain.java:32)
I am not able to understand what should I do where I should change my code
please help thanks in advance

A: You should use getApplication() instead of getApplicationContext() when you want to retrieve the Application instance.
Also hope you declared the Controller class as the Application class in your manifest file.
Also it is not the best idea to subclass your Application class just to store data in it... You should use a singleton class instead.


text:
Q: SQL select by date from today I'm studying SQL (Using MariaDB 10.2) and I'm using a huge example database I found online. It has an 'employees' table, and this one has a 'birth_date' column of 'date' type. I want to select all those employees who are more than 50 years old, for example, or maybe those who will be 25 years old on an specific date . Is there a way to do something like this?

A: You can add or subtract intervals to dates:
SELECT *
FROM   employee
WHERE  birth_date <= NOW() - INTERVAL 50 YEAR

A: Assuming t-sql, then for those over 50 today, use:
select * from employees where datediff(year, birth_date, now()) > 50

For those who will be 25 on a certain date use:
select * from employees where datediff(year, birthdate, certain_date) = 25

A: Use this
SELECT * FROM myTable WHERE DATE(myDate) = DATE(NOW())

This is for MySql DB

A: You can use INTERVAL function which you can add or subtract Dates:
SELECT * FROM employee WHERE birth_date <= (NOW() - INTERVAL 50 YEAR);

*

*NOW() -----> Present Date

*-INTERVAL 50 YEAR -----> Subtract that Date to 50 Years


text:
Q: Oracle expdp without data Will there be any impact if expdp is used and the table has no data to be exported? For example, we run a job to perform expdp and the table to be dumped has no records at the instance the job was run, will there be exceptions for this? Should this be handled by another checking?

A: I just tried it, and it looks like it works just fine.
Estimate in progress using BLOCKS method...
Processing object type TABLE_EXPORT/TABLE/TABLE_DATA
Total estimation using BLOCKS method: 0 KB
Processing object type TABLE_EXPORT/TABLE/TABLE
Processing object type TABLE_EXPORT/TABLE/STATISTICS/TABLE_STATISTICS
. . exported "SYSTEM"."BONUS"                                0 KB       0 rows
Master table "SYSTEM"."SYS_EXPORT_TABLE_01" successfully loaded/unloaded
******************************************************************************
Dump file set for SYSTEM.SYS_EXPORT_TABLE_01 is:
  /usr/lib/oracle/xe/app/oracle/admin/XE/dpdump/exp.dmp
Job "SYSTEM"."SYS_EXPORT_TABLE_01" successfully completed at 22:10:10

If you were to import the dump file, it should recreate the table  but (obviously) without any rows.

A: There will be no exception if you export an empty table.  The export utility will just export the metadata for the table (i.e. the DDL).

A: expdp will export empty tables.  Trying to export tables using the legacy export functions will not export empty tables.
Please see my blog post here on the subject.
http://tsells.wordpress.com/2011/02/10/oracle-11g2-does-not-export-empty-tables-when-using-exp-exe/

A: There is no question of exception in data pump unless until you mention a wrong table name. It should work properly.
I found many datapump options reference here http://www.acehints.com/p/site-map.html


text:
Q: OpenGL Depth buffer in orthographic projection If I use orthographic projection in OpenGL, but still set different z-values to my objects, does it still be visible in Depth Buffer?
I mean, in color buffer everything looks plain and at one distance. But wherever they will "colorized" in different shades? Does depth buffer "understand" depth in  orthographic projection?

A: A depth buffer has nothing to do with the projection matrix. Simply put, a z-buffer takes note of the closest Z-value at a given point. As things are drawn it looks at the current value. If the new value is less then the existing value it is accepted and the z buffer is updated. If the value is greater then the value, behind the current value, it is discarded. The depth buffer has nothing to do with color. I think you might be confusing blending with depth testing.
For example, say you have two quads A & B.
A.z =  - 1.0f;
B.z =  - 2.0f;
If you assume that both quads have the same dimensions, outside of their Z value, then you can see how drawing both would be a waste. Since quad A is in front of quad B it is a waste to draw quad B. What the depth buffer does is checks the zcords. In this example if you had enabled depth testing & a depth buffer quad B would never have been drawn because the depth testing would have shown it was occluded by quad A.


text:
Q: Apply through dataframe I have a simple data frame with two columns and two rows. I am trying to iterate through each row to find what words are in column two that are not in column one. Sample data:
testdata <- data.frame(rbind(one = c("mango rasberry","mango rasberry blueberry"),
                   two = c("kiwi strawberry","kiwi strawberry passionfruit")))

So, the output should be a third column added to testdata that contains "Blueberry" in row 1 and "passionfruit" in row 2.
This is the function that I have so far:
extract <- function(input) {
  extra<- apply(x, function(x) x[setdiff(unlist(str_split(input[,1]," ")), unlist(str_split(input[,2]," ")))])
  extra
}

I'm getting the following error:

"argument "FUN" is missing, with no default "

Do you know what a good solution to this would be? Thank you for your help.

A: Try:
testdata <- data.frame(rbind(one = c("mango rasberry","mango rasberry blueberry"),
                             two = c("kiwi strawberry","kiwi strawberry passionfruit")), stringsAsFactors = F)

testdata$differences <- apply(testdata, 1, function(x) {
    x1 <- unlist(strsplit(x[1], split = " "))
    x2 <- unlist(strsplit(x[2], split = " "))
    ifelse(length(x1) > length(x2), base::setdiff(x1,x2), base::setdiff(x2,x1))
})

The problem is that setdiff starts with the first argument and works from there. If it looks in the first argument and sees that all its elements are matched in the second one, then it does not consider that there are differences. So, the vector with the most number of elements should be the first argument in this case.
You could have also done it by taking the difference of the union() and the intersect() as follows:
apply(testdata, 1, function(x) {
    x1 <- unlist(strsplit(x[1], split = " "))
    x2 <- unlist(strsplit(x[2], split = " "))
    base::setdiff(base::union(x1,x2), base::intersect(x1,x2))
})

Desired output:
X1              X2                           differences
mango rasberry  mango rasberry blueberry     blueberry
kiwi strawberry kiwi strawberry passionfruit passionfruit

I hope this helps.


text:
Q: How to remove hours, minutes, and seconds from a Unix timestamp? Without having to convert it to datetime, how can I get the date from a Unix timestamps? In other words, I would like to remove hours, minutes and seconds from the time stamp and get the numbers that represent the date only.

A: I know you asked "without having to convert to datetime", but I really think this is the best method.
>>> t
1430103943.581003
>>> datetime.date(datetime.fromtimestamp(t)).strftime("%s")
'1430056800'

To do it manually will require knowing about all the special cases, leap years, leap seconds etc.  It's impractical and all the heavy lifting has already been done for you by datetime, so why bother?

A: If running the script in a UNIX like OS, you can use the date command -

>>>import subprocess
>>>process=subprocess.Popen(['date','-d','@1430106933', '+%Y%m%d'], stdout=subprocess.PIPE)
>>>out,err = process.communicate()
>>>print out
20150426


text:
Q: How to select users having only particular tag not another tag I have the following db schema

I need to get the fname, lname of the user who have tag name 'A' and also they should not have tag name 'B'.For example User X has both tag A, tag B, He should not be included in the result whereas if another user Y only have Tag 'A' he should be included in the result. Is this possible without sub query?Do i have to alter the schema?

A: *

*You can GROUP BY on user id and name.

*Use HAVING clause with SUM() aggregation to filter out cases.

*If a user does not have a tag 'B', SUM(name = 'B') will be zero, post joins.

Try the following:
SELECT
  u.user_id,
  u.fname,
  u.lname
FROM
  user AS u
JOIN tags AS t ON t.user_id = u.user_id
JOIN tags_def AS td ON td.tag_id = t.tag_id
GROUP BY
  u.user_id,
  u.fname,
  u.lname
HAVING
  SUM(td.name = 'A') AND
  SUM(td.name = 'B') = 0


text:
Q: Flash Builder 4.5 vs MySQL = )/&(%&{[](/&¤#%$£@ I'm stuck in Adobe Flash Builder 4.5.1. I'm trying to connect to a MySQL-database, running locally. When Flash Builder tries to connect with the build-in tool, the program returns this:
""¹FÿÖ–4® ™'ÔûOØÓ:¶›õÊ&A‰ô"‰@§Å�§ç¢Ô�'´ÖfÅêÅ™FgÖç."
I have MySQL, Zend and Apache2, all in it newest truest form. I have, as it requests "Amf.production = false". I have tried changing the characterset of the database. I have tried moving the database to a different computer. I have tried connecting to a different remote (www) database. All with same result.
What could be wrong?


text:
Q: Where is the kibana error log? Is there a kibana error log? QUESTION: how do I debug kibana?  Is there an error log?

*

*PROBLEM 1: kibana 4 won't stay up

*PROBLEM 2: I don't know where/if kibana 4 is logging errors

DETAILS:
Here's me starting kibana, making a request to the port, getting nothing, and checking the service again.  The service doesn't stay up, but I'm not sure why.
vagrant@default-ubuntu-1204:/opt/kibana/current/config$ sudo service kibana start
kibana start/running, process 11774

vagrant@default-ubuntu-1204:/opt/kibana/current/config$ curl -XGET 'http://localhost:5601'
curl: (7) couldn't connect to host

vagrant@default-ubuntu-1204:/opt/kibana/current/config$ sudo service kibana status
kibana stop/waiting

Here's the nginx log, reporting when I curl -XGET from port 80, which is forwarding to port 5601:
2015/06/15 17:32:17 [error] 9082#0: *11 connect() failed (111: Connection refused) while connecting to upstream, client: 127.0.0.1, server: kibana, request: "GET / HTTP/1.1", upstream: "http://127.0.0.1:5601/", host: "localhost"

UPDATE: I may have overthought this a bit.  I'm still interested in ways to view the kibana log, however!  Any suggestions are appreciated!
I've noticed that when I run kibana from the command-line, I see errors that are more descriptive than a "Connection refused":
vagrant@default-ubuntu-1204:/opt/kibana/current$ bin/kibana
{"@timestamp":"2015-06-15T22:04:43.344Z","level":"error","message":"Service Unavailable","node_env":"production","error":{"message":"Service Unavailable","name":"Error","stack":"Error: Service Unavailable\n  at respond (/usr/local/kibana-4.0.2/src/node_modules/elasticsearch/src/lib/transport.js:235:15)\n  at checkRespForFailure (/usr/local/kibana-4.0.2/src/node_modules/elasticsearch/src/lib/transport.js:203:7)\n  at HttpConnector.<anonymous> (/usr/local/kibana-4.0.2/src/node_modules/elasticsearch/src/lib/connectors/http.js:156:7)\n  at IncomingMessage.bound (/usr/local/kibana-4.0.2/src/node_modules/elasticsearch/node_modules/lodash-node/modern/internals/baseBind.js:56:17)\n  at IncomingMessage.emit (events.js:117:20)\n  at _stream_readable.js:944:16\n  at process._tickCallback (node.js:442:13)\n"}}
{"@timestamp":"2015-06-15T22:04:43.346Z","level":"fatal","message":"Service Unavailable","node_env":"production","error":{"message":"Service Unavailable","name":"Error","stack":"Error: Service Unavailable\n  at respond (/usr/local/kibana-4.0.2/src/node_modules/elasticsearch/src/lib/transport.js:235:15)\n  at checkRespForFailure (/usr/local/kibana-4.0.2/src/node_modules/elasticsearch/src/lib/transport.js:203:7)\n  at HttpConnector.<anonymous> (/usr/local/kibana-4.0.2/src/node_modules/elasticsearch/src/lib/connectors/http.js:156:7)\n  at IncomingMessage.bound (/usr/local/kibana-4.0.2/src/node_modules/elasticsearch/node_modules/lodash-node/modern/internals/baseBind.js:56:17)\n  at IncomingMessage.emit (events.js:117:20)\n  at _stream_readable.js:944:16\n  at process._tickCallback (node.js:442:13)\n"}}
vagrant@default-ubuntu-1204:/opt/kibana/current$

A: Kibana 4 logs to stdout by default. Here is an excerpt of the config/kibana.yml defaults:
# Enables you specify a file where Kibana stores log output.
# logging.dest: stdout

So when invoking it with service, use the log capture method of that service. For example, on a Linux distribution using Systemd / systemctl (e.g. RHEL 7+):
journalctl -u kibana.service
One way may be to modify init scripts to use the --log-file option (if it still exists), but I think the proper solution is to properly configure your instance YAML file. For example, add this to your config/kibana.yml:
logging.dest: /var/log/kibana.log

Note that the Kibana process must be able to write to the file you specify, or the process will die without information (it can be quite confusing).
As for the --log-file option, I think this is reserved for CLI operations, rather than automation.

A: In kibana 4.0.2 there is no --log-file option. If I start kibana as a service with systemctl start kibana I find log in  /var/log/messages

A: It seems that you need to pass a flag "-l, --log-file"
https://github.com/elastic/kibana/issues/3407
Usage: kibana [options]

Kibana is an open source (Apache Licensed), browser based analytics and search dashboard for Elasticsearch.

Options:

    -h, --help                 output usage information
    -V, --version              output the version number
    -e, --elasticsearch <uri>  Elasticsearch instance
    -c, --config <path>        Path to the config file
    -p, --port <port>          The port to bind to
    -q, --quiet                Turns off logging
    -H, --host <host>          The host to bind to
    -l, --log-file <path>      The file to log to
    --plugins <path>           Path to scan for plugins

If you use the init script to run as a service, maybe you will need to customize it.

A: Kibana doesn't have a log file by default. but you can set it up using log_file Kibana server property - https://www.elastic.co/guide/en/kibana/current/kibana-server-properties.html

A: For kibana 6.x on Windows, edit the shortcut to "kibana -l " folder must exist.


text:
Q: Replace InnerHTML With Cookie Logging I've got some javascript code for replacing innerHTML of a element when clicked. Now i've got the code for that and it does work great! But one small issue is that, I want the webserver to remember the change when innerHTML of an element was replaced. So the webserver remembers the change and doesn't return to its default state. Whether with database or in Cookie, sessionStorage, localStorage.
document.getElementById("replace1").innerHTML = localStorage.getItem("replace1");

function loadDoc() {
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
     localStorage.setItem("replace1",this.responseText);
    }
  };
  xhttp.open("GET", "https://natevanghacks.com/replacements/yoinkexecutor2.html", true);
  xhttp.send();
}

A: Try something like this in AJAX:
localStorage.setItem("replace1",this.responseText);

And after body onload:
document.getElementById("replace1").innerHTML = localStorage.getItem("replace1");

Edit:
  function loadSavedData(){
    var data=localStorage.getItem("replace1");
    document.getElementById("replace1").innerHTML = data?data:'No Data found';
  }
  function deleteData(){
    localStorage.removeItem("replace1");
  }
  function loadDoc() {
    var xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function() {
      if (this.readyState == 4 && this.status == 200) {
        localStorage.setItem("replace1",this.responseText);
        document.getElementById("replace1").innerHTML =this.responseText;
        console.log(this.responseText);
      }
    };
    xhttp.open("GET", "filename.html", true); //put your filename here...
    xhttp.send();
  }

<button onclick="loadDoc()">Send request and load Data
</button>
<button onclick="loadSavedData()">load Saved Data
</button>
<button onclick="deleteData()">Delete saved Data
</button>

Note: You should run this file on http:// or https:// protocols only


text:
Q: email address extraction I would like a php script, i imagine it will need sql for storage, that logs in to my gmail goes through all my emails and extracts the to from and cc and the email addresses within the text of the email, from forwarded and multiply forwarded emails, and tags them as where the came from ie to from cc and inline.
whats the best way to go about it i have no idea where to start

A: Here's a pseudocode using PHP - each step should be simple enough to implement on its own.

*

*connect to database using the mysqli extension

*log into gmail using the imap extension and its functions

*

*get a list of folders

*for each folder

*

*get a list of messages, and their headers

*for each message (you may want to check and reject obvious spam here)

*get message headers and body

*look for the From: To: CC: and BCC: headers

*store those into database (those are your tags)

*use a regular expression to match possible e-mail addresses

*if matches found:

*

*store them into database, linked with the tags

*disconnect from gmail

*disconnect from database

A: This should be a good place to start:
http://code.google.com/apis/gmail/


text:
Q: Posting of link shows correct image not until then when I waited about one hour, why? When I create a new HTML page, I have the property tag for "og: image".
After that, I copy the link into Facebook and don't get the correct image.
When I try this some minutes later (about one hour or only 20 minutes), I get the correct image.
It makes no sense for me. Has anyone an advice?

A: Try using Open Graph Debugger
(Here is link: Open Graph Debugger)
after you create your post. This should basically force Facebook to process your Open Graph tags. Facebook need some time processing these tags. You can kind of automate it with AJAX to call OG Debugger, but Facebook will not like it I suppose.


text:
Q: How to get the number of lines written in IText 7 I'm upgrating from IText 5 to IText 7. The code below is from version 5 which has a method to get the actual number of lines written. How can I accomplish the same using IText 7?
Paragraph p = new Paragraph(veryLongText, font);
ColumnText column1 = new ColumnText(writer.DirectContent);
column1.SetSimpleColumn(bottomX, bottomY, topX, 100);
column1.AddElement(p);
column1.Go(true);

noOfLines = column1.LinesWritten; <---- No of Lines

A: Layout mechanism in iText 7 is much more complex and feature-rich than mechanism in iText 5, and notion of written lines might be very much opinion-based in many complex layout cases. That's why the number of written lines is not maintained by the layout engine and is not available for query. However, it's very easy to extend your elements/renderers to support calculating the number of written lines. Here is how to do it. First, you need to override a Paragraph to aggregate the number of lines and ParagraphRenderer to provide the info of the lines written back to Paragraph:
private static class LineCountingParagraph extends Paragraph {
    private int linesWritten = 0;

    public LineCountingParagraph(String text) {
        super(text);
    }

    public void addWrittenLines(int toAdd) {
        linesWritten += toAdd;
    }

    public int getNumberOfWrittenLines() {
        return linesWritten;
    }

    @Override
    protected IRenderer makeNewRenderer() {
        return new LineCountingParagraphRenderer(this);
    }
}

private static class LineCountingParagraphRenderer extends ParagraphRenderer {
    public LineCountingParagraphRenderer(LineCountingParagraph modelElement) {
        super(modelElement);
    }

    @Override
    public void drawChildren(DrawContext drawContext) {
        ((LineCountingParagraph)modelElement).addWrittenLines(lines.size());
        super.drawChildren(drawContext);
    }

    @Override
    public IRenderer getNextRenderer() {
        return new LineCountingParagraphRenderer((LineCountingParagraph) modelElement);
    }
}

Now, just use the customized classes instead of the standard ones and query the information after an element was added to a Document or Canvas:
LineCountingParagraph p = new LineCountingParagraph("text");
document.add(p);
System.out.println(p.getNumberOfWrittenLines());

Note that this mechanism also allows you to calculate the number of lines written that satisfy some condition. You can analyze elements in lines list.


text:
Q: How to map an Oracle NUMBER to a C# type with Entity Framework without exceptions We have a table in Oracle 12 (11 in production), with a column with type NUMBER with unspecified precision and scale. I try to load it into an decimal, but I get an InvalidCastException. Sure, not every NUMBER can fit into a decimal, but the used values are not that high:
1000
0.2777777777778
9.76944444444444  (only this value causes an exception)
277.7777777778
1

When I copy/paste these values into C#, there is no problem:
decimal thisWorks = 9.76944444444444m;

It doesn't help when I specify precision HasPrecision(38,19) with the Fluent API. I also narrowed the Linq query down to only the row and column I need.
Then I decided to use a string type, so I can do the conversion myself later. But that results in the exact same exception with the exact same strack-trace... Stack-trace (application specific part removed):
Result Message:
Test method NimbusT.UnitTests.Data.Repositories.EntityRepositories.TUnitRepositoryTest.SelectAll_Test threw exception:
System.InvalidCastException: Specified cast is not valid.
Result StackTrace:
at Oracle.ManagedDataAccess.Client.OracleDataReader.GetDecimal(Int32 i)
   at Oracle.ManagedDataAccess.Client.OracleDataReader.GetValue(Int32 i)
   at System.Data.Entity.Core.Common.Internal.Materialization.Shaper.ErrorHandlingValueReader`1.GetUntypedValueDefault(DbDataReader reader, Int32 ordinal)
   at System.Data.Entity.Core.Common.Internal.Materialization.Shaper.ErrorHandlingValueReader`1.GetValue(DbDataReader reader, Int32 ordinal)
   at System.Data.Entity.Core.Common.Internal.Materialization.Shaper.GetColumnValueWithErrorHandling[TColumn](Int32 ordinal)
   at lambda_method(Closure , Shaper )
   at System.Data.Entity.Core.Common.Internal.Materialization.Coordinator`1.ReadNextElement(Shaper shaper)
   at System.Data.Entity.Core.Common.Internal.Materialization.Shaper`1.SimpleEnumerator.MoveNext()
   at System.Data.Entity.Internal.LazyEnumerator`1.MoveNext()
   at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)
   at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)

Seems the Oracle.ManagedDataAccess.Client (the one we use) uses GetDecimal for the string type as well.
When I use double as column type there is no problem, but we don't want to use doubles. This problem is probably the easiest to solve by applying a specific precision to the column, but database changes are pretty difficult around here.
Does anyone have an idea how to work with this, without database changes?


text:
Q: Python functools.reduce, how to reduce a list a return a new one Answering a question I notice that I don't know how to return a list after doing append inside a reduce, for example
import functools

futures = [1,2,3]
records = functools.reduce((lambda res, future: res if (res.append(str(future))  == None) else res), futures, [])

I want the list ['1', '2', '3'], it is just a minimal example, because I want to do more than map values.
Is there a another way that this horrible if that I put inside the lambda?

A: You don't have to mutate the result list in your lambda; reduce takes the return value of the function as the result. So your lambda can be as simple as
lambda res, future: res+[str(future)]


text:
Q: Curated .bib example file Is there any .bib example file that is canonical in the community?
Ideally, such a file would

*

*Carry entries of all types (book, inproceedings, misc, etc.),

*Have entries with optional fields filled (for instance, an article entry with a doi, and one without),

*Use strings and crossereferences,

*Optionally offer more "modern" features of BibLaTex (such as software entries),

*Contain mostly freely accessible references,

*Be under an open source licence.

I found some files such as this one on tug, but it is not satisfactory. As of now, I believe biblatex/biblatex-examples.bib is my best option, but maybe I did miss something?


text:
Q: How to write a test case for abstract class method Here is my code, I want to write a unit test for Build method as part of writing a test case for class D.
public class X
{

}

public interface IB
{
    X GetX(X value);
}

public class B : IB
{
    public X GetX(X value)
    {
        //ToDo:
    }
}

public abstract class A
{
    private IB obj;
    public A(IB obj)
    {
        this.obj = obj;
    }
    public X Build()
    {
        return obj.GetX();
    }
}

public class D : A
{
    public void display()
    {
        //TODO
    }
}

//Test Method

[Test]

public void Test_Build(){
var mock = new Mock<IB>();

var objA = new D();
objA.Build();

}

here is my test method. While calling build method my code is throwing an exception because of not passing the instance of IB. I not sure how to pass a mock object of IB to abstract class A through child class D.

A: This is because Constructors are not inherited in C#.
Your base class, A has a constructor that takes an instance of IB and intialises the field.
However your inheriting class has no constructor specified and so has a Default parameterless constructor.
You need to provide a constructor for D that takes an instance of IB and then pass this upto the base constructor like this
public D(IB instanceOfIB)
    : base(instanceofIB)
{
    //do other things here if you want or leave empty
}


text:
Q: How can I convert an ldap object to integer in a python function? I have created python function to search through an ldap object as below:
def my_search(l, baseDN, searchScope=ldap.SCOPE_ONELEVEL, searchFilter="objectClass=*", retrieveAttributes=None):
    logger.console("Reachedhere")
    try:
        logger.console("Reachedhereinsidetry\n")
        ldap_result_id =       l.search_s(baseDN,searchScope,searchFilter,retrieveAttributes)
        logger.console("Gotresult\n")

So I invoke this keyword now in a Robot Testcase as so:
*** Settings ***
Documentation     This testsuite checks the LDAP functionalities of DB nodes.
Resource          ../../COMMON/Libraries/SDL-DB-COMMON-LIB.txt
Library           ../../COMMON/Libraries/pythonldap.py

*** Test Cases ***
Perform Ldap Operations
    ${ldapObj}    ldapopen    ${DB_1_EXT_APP_IP}
    Log to Console    ${ldapObj}
    ${SearchReturn}    my_search    ${ldapObj}    "uid=5000000,ds=CRIBER,o=D,dc=CN"    ldap.SCOPE_ONELEVEL    "objectClass=*"    None

When I run this TC, it throws me an error in the search like so:
TypeError: an integer is required

The error is definitely in "ldap_result_id =       l.search_s(baseDN,searchScope,searchFilter,retrieveAttributes)" line, since I'm able to print the earlier comments.
What is the issue here?
The issue here is the scope level which cannot be passed as above from Robot. The changes I did was :
def my_search(l, baseDN, searchScopeLevel, searchFilter="objectClass=*", retrieveAttributes=None):
try:
    if searchScopeLevel == 'ONE':
        searchScope=ldap.SCOPE_ONELEVEL
    elif searchScopeLevel == 'BASE':
        searchScope=ldap.SCOPE_BASE
    elif searchScopeLevel == 'SUB':
        searchScope=ldap.SCOPE_SUBTREE
    ldap_result_id = l.search(baseDN,searchScope,searchFilter,retrieveAttributes)

Robot TC Changes :
*** Test Cases ***
Perform Ldap Operations
    ${ldapObj}    ldapopen    ${DB_1_EXT_APP_IP}
    ${SearchReturn}    my_search    ${ldapObj}        uid=205000000,ds=CRIBER,o=DEFT,dc=C    ONE    objectClass=*

And the issue is resolved. :)

A: Presuming the exception is raised in the my_search method - by default the arguments to methods in RF are casted to string. Thus this call:
${SearchReturn}    my_search    ${ldapObj}    "uid=2620105000000,ds=SUBSCRIBER,o=DEFAULT,dc=C-NTDB"    ldap.SCOPE_ONELEVEL    "objectClass=*"    None

Has a number of issues:

*

*the baseDN argument will have an actual value "uid=2620105000000,ds=SUBSCRIBER,o=DEFAULT,dc=C-NTDB" - i.e. with the quotation marks included, thus probably not what you're aiming for; remove them

*the same for the searchFilter - remove the quotes in the call

*the searchScope, which probably is your problem, will receive the value ldap.SCOPE_ONELEVEL - a string with this content. This most probably is a constant defined in your ldap module; the safest bet that it'll work is to provide the integer value of that const - integers are given in the format ${1}, but that's hardly sustainable. Perhaps you could export it and the other constants in the COMMON/Libraries/pythonldap.py library, and use it in the test cases

*finally, the retrieveAttributes argument will receive the string literal "None", not the None datatype you probably want; to get it, use this RF builtin variable - ${None}
HTH, and again - provide more details to receive on-the-spot answers.


text:
Q: Implementation of a NOT gate with two transistors - Why not one? I just encountered this implementation of a NOT gate:

My question is: Why do we need the lower transistor? Why can't we do this:

Thanks!

A: ...because to represent logical 0 you need (close to) 0 Volts and not just a floating output.

A: In addition to the previous answers, the NOT gate CAN be implemented using a MOSFET and a resistor:

simulate this circuit – Schematic created using CircuitLab
But the problem here is the current that will be constantly flowing while In is high. The transistor will be then conducting, effectively closing the circuit with current around \$V(1)/R_1\$.

A: In your example, what pulls the output down to ground? Essentially when the PFET is off, you will be left with the output signal floating. If it is required to drive another logic gate for example, then it will not be able to sink current to discharge any parasitic capacitance of the next stage.
CMOS is what is known as 'fully restored logic' because you have two transistors which can pull to opposite power rails meaning that the output voltage levels are equal to the power rails.
This is advantageous behaviour if for example you need to chain multiple CMOS devices together. Without fully restored logic, then your digital signal will get lower and lower with each gate until the signal gets corrupted (a 1 is no longer high enough voltage to represent a 1). This need far outweighs the space cost of the extra transistor.

A: Actually both varieties are used, two transistor and one-transistor (although the latter is not how you drew it).
The first is called push-pull[totem-pole also called active pullup], and the second is called open-drain.
Push-pull outputs can both source (supply Vcc) and sink (ground) outputs.  Open-drain can only sink outputs.  The Vcc supply must come from somewhere else (usually a pull-up resistor).
The 74HC04, with six inverters, is an example of push-pull outputs.  The 74HC05, also with six inverters is an example of open-drain outputs.
Here is the output stage of each inverter on the 74HC05:

When the input is ground, the output is floating.  When the input is high, the output is grounded.
There are two common applications of open-drain outputs:
1) Connecting more than one output to the same line. This is called a wired-OR. For example, you may have a normally high reset pin on a device, which is reset from both a microcontroller pin and another source, say a pushbutton. The reset pin is tied high with a pull-up resistor. The microcontroller is configured as an open-drain output. The pushbutton is tied to ground when pushed. If either the microcontroller pulls its output to 0, or the pushbutton is pressed, the device will be reset.
2) Controlling devices connected to different supply voltages. Say you have a relay that requires 20 mA, but a voltage of 5 volts. But your microcontroller output can only drive pins up to its power supply (VCC) voltage of 3.3v. With an open-drain output, you can connect one side of the relay to 5 V, and the other to the output pin of the microcontroller. When the output of the microcontroller in is 1, nothing happens (again, acts like the pin is disconnected). When it is set to 0, this grounds the bottom side of the relay completing the circuit and operating the relay.

A: You need something to both source and sink current.  Transistor gates look like capacitors and they have to be charged and discharged.  If you can't sink current, then the only way the transistor will turn off is to wait for the charge in the gate to leak out, which could take quite a long time.  It is possible to replace one transistor with a resistor, but resistors take up a HUGE amount of silicon area as opposed to transistors, and the output drive characteristics will be asymmmetric.  The static power consumption will also become state dependent.  Using another transistor results in symmetric output drive and low static power consumption.
NMOS logic generally uses only the lower transistor, plus a pull up of either a resistor or a weak transistor configured as an always-on pull-up.  CMOS logic uses transistors on both sides, sized to be symmetrical in drive strength.  CMOS also fully regenerates the logic level after each gate.

A: You are correct, it can be done with one transistor. What you drew needs a way to pull the output down to 0v when the transistor is off, a resistor will do that.
The two transistor version has the advantage that it uses very little power when the output is either high or low. The one transistor version you drew will use some power when the output is high [current thru the required pull-down resistor].
To reduce this power you would want to make this resistor a large value [lower current], but then the current available to discharge capacitive loads would be reduced,making the transition time from output high to low longer [slower]. If you make the resistor smaller it gets faster but uses more power.
The two transistor version gets around this by having low static power and fast tpdHL and tpdHL times.