Q:

Is there an easier way to make these axios post reqest?

I'm trying to upload multiple images to cloudinary via api in my react app using axios.
I'm new to promises, so I'm not sure if I'm using the right approach here.
I am able to upload all the images to cloudinary; however, the response I get is the confusing part, as with the response I need to pass the images' urls to an object, so I can send them to an email using mailgun.
Here is my code to upload the images:
if(payment === "success") {
axios
    .all([
        props.imgForProduct.map((img) => {
            const fd = new FormData();
            fd.append("file", img);
            fd.append("upload_preset", "sublimation");
            return axios
                .post(
                    "https://api.cloudinary.com/v1_1/ahkji7ation/image/upload",
                    fd
                )
                .then(async (res) => {
                    return (imgUrl = res.data.secure_url);
                })
                .catch((err) => console.log(err));
        }),

        props.screenshot.map((img) => {
            const fd = new FormData();
            fd.append("file", img);
            fd.append("upload_preset", "sublimation");
            return axios
                .post(
                    "https://api.cloudinary.com/v1_1/ahkji7ation/image/upload",
                    fd
                )
                .then(async (res) => {
                    return (imgScrSht = res.data.secure_url);
                })
                .catch((err) => console.log(err));
        }),
    ])
    .then(
        axios.spread(async (...res) => {
            imgUrl.push(res[0][0]);
            imgScrSht.push(res[1][0]);

            let dataObj = {
                email: props.email,
                img: imgUrl,
                screenshot: imgScrSht,
            };
            console.log(dataObj);

            new Promise((resolve, reject) => {
                axios.post("/email_to_ayp_sublimation", dataObj);
                resolve((res) => {
                    console.log(res);
                });
                reject((err) => {
                    console.log(err);
                });
            });
        })
    )
    .catch((err) => console.error(err));
}

When I console log the dataObj this is what I'm sending in the last call (the new Promise):
screenshot: Array(1)
0: Promise {<resolved>: "https://res.cloudinary.com/ahkji7ation/image/u…
590871936/ahkji7ation/kqebmkjfj0prmyygls2y.jpg"}
length: 1
__proto__: Array(0)

I'm receiving [object Object] in the backend, instead of the url I need. Can anybody help me sort this out?
Thanks in advance

A:

I think the issue is with your axios.all(...) code. You are passing in two values but the values have .map inside them which are returning urls. Because of this, axios.post() on both indexes will upload the images but axios.all() will have the return values from the .map() function which is an array of promises. You can try something like this.
async function uploadImages(imgForProduct, screenshots) {
  const URL = "https://api.cloudinary.com/v1_1/ahkji7ation/image/upload";

  //Collect all the form datas for img and screenshots
  const imgForProductFormData = imgForProduct.map((img) => {
    const fd = new FormData();
    fd.append("file", img);
    fd.append("upload_preset", "sublimation");
    return fd;
  });
  const screenShotsFormData = screenshots.map((img) => {
    const fd = new FormData();
    fd.append("file", img);
    fd.append("upload_preset", "sublimation");
    return fd;
  });

  const imgForProductRequests = imgForProductFormData.map(
    async (fd) => await axios.post(URL, fd).catch((err) => null)
  );
  const screenshotsRequests = screenShotsFormData.map(
    async (fd) => await axios.post(URL, fd).catch((err) => null)
  );

  try {
    const imgForProductResponses = await axios.all(imgForProductRequests);
    imgForProductResponses.map((res) => (res[0] ? imgUrl.push(res.data.secure_url) : null));

    const screenshotsResponses = await axios.all(screenshotsRequests);
    screenshotsResponses.map((res) => (res[0] ?imgScrSht.push(res.data.secure_url) : null));

    let dataObj = {
      email: props.email,
      img: imgUrl,
      screenshot: imgScrSht,
    };
    console.log(dataObj);

    new Promise((resolve, reject) => {
      axios.post("/email_to_ayp_sublimation", dataObj);
      resolve((res) => {
        console.log(res);
      });
      reject((err) => {
        console.log(err);
      });
    });
  } catch(err) {console.log(err)}
}

Hope this works!


Q:

Invalid Foreign Key Relationship when retrieving from class

I've a parent object (Product) and a child (Inventory). I'm trying to retrieve the value of the child object from a class that I've created.
public class DisplayProducts {
    private Product__c products;

public DisplayProducts(Product__c item) {
    this.products = item;

}

// Properties for use in the Visualforce view
public String name {
    get { return products.Name; }
}

public String colour {
//error here
        get { return  products.Inventorys__r.Colour__c; }
//products.Inventorys__r[0].Colour__c; --> only retrive the first element, dosen't seems to work
    }

public class Product {

public List<DisplayProducts> getProducts() {

        if(products == null) {
            products = new List<DisplayProducts>();

            for(Product__c item : [Select ProductID__c,Name, Price__c, (SELECT Inventory__c.Size__c, Inventory__c.Colour__c,  Inventory__c.Quantity__c FROM Product__c.Inventorys__r)
                From Product__c WHERE ProductID__c = :prodID]) {

                products.add(new DisplayProducts(item));
            }

        }
    return products;
}

}

However I keep getting a compile error: invalid FK relationship. Why is that so?
When I retrieve the object using SOQL statement it works perfectly.
Select Name,  (SELECT Inventory__c.Colour__c FROM Product__c.Inventorys__r)  From Product__c];

but why it doesn't work in the Display Class? Thank you.

A:

products.Inventorys__r will return list of child records .
The return type of your method is a string .Hence you may need to return a list of child records .
If you need  the child array you can use something like below
  public List< Inventory__c> colour {
        get { return  products.Inventorys__r;}//return list of Inventory records and this would be list data type
   }


Q:

Use of hyphens when qualifying a noun

I am editing a bit of text, and I need to know: should there be a hyphen in the following passage?
"While transecting the designated territory, survey-team members collected numerous artifacts."
Could it just be "survey team members"? Or "survey team-members"?

A:

They are members of a survey team, so the three-word compound is produced from the two-word compound of survey + team and the word members.
Hence the logical possibilities of all the permutations of closed, open and hypenated are:

survey team members (all open).
surveyteam members (closed + open)
surveyteammembers (all closed)
survey-team members (hyptenated + open)
survey team–members (open and dash)
survey-team–members (hyphenated and dash).
surveyteam-members (closed and hypen).

Note that we don't try closing team and members if we haven't closed survey and team, as we would never close a compound where part of the compound was itself an open or hyphenated compound.
Note also that we use an en-dash (–) not a hyphen (-) when part of a compound is itself an open or hyphenated compound.
Now, of those possibilities, closed compounds are not common in English, unless the term is heavily used, or we are seeking to coin a specific new meaning, so let's remove them from the list:

survey team members (all open).
survey-team members (hyptenated + open)
survey team–members (open and dash)
survey-team–members (hyphenated and dash).

These are each cases one could make an argument for, and it becomes more a matter of judgement now. One guide is to consider the possibility of misreading if one's eye happened upon the right most part of the compound. Since members must be members of something, if our eye hits upon "members" alone on a page, we're going to seek to find out what they are members of, so the en-dash offers little to help. We can therefore dismiss the two possibilities that use a dash:

survey team members (all open).
survey-team members (hyptenated + open)

Of the remaining two, there's less to argue very strongly in favour of one or the other. I started writing this answer thinking I was going to say both of these could be reasonably chosen, but I'd lean toward that with the hyphen. I now think I'd lean toward that with no hyphen. They're definitely both allowable, there's only matters of taste and preference to pick between them. As a tie-breaker, hyphenated forms seem to be increasingly less common, which argues for using the fully-open "survey team members".
I would possibly change my mind in the context of the wider piece. If there were other teams involved in what it described, that would lean me toward hyphenating, because the risk of misreading without it has increased. Conversely, if the survey team/survey-team are mentioned repeatedly, that would lean me against hyphenating, as the repetition of the phrase decreases the risk of misreading, and slightly increases the visual irritation of the hyphen.
If you're writing or editing to a particular style-guide, then what it has to say about compound nouns over-rules this, though even they can be quite vague on this matter, some times.


Q:

Selenium Webdriver Testing - Python

I wonder, what is the advantage of using selenium for automation if at the end of the test he emits no reports where the test passed or failed?

A:

Selenium isn't actually a testing framework, it's a browser driver.  You don't write tests in Selenium any more than you write GUI apps in OpenGL.  You usually write tests in a unit testing framework like unittest, or something like nose or lettuce built on top of it.  Your tests then use Selenium to interact with a browser, as they use a database API to access the DB or an HTTP library to communicate with web services.


Q:

Calling click event of a button serverside

How can I click or load the click() event of a button in codebehind?
I already tried
      btn.Click();

but this gives an error. I am using ASP.NET

A:

I will assume that you have a button called Button1
and that you have double clicked it to create an event handler.
To simulate the button click in code, you simply
call the event handler:
Button1_Click(object sender, EventArgs e).
e.g. in your Page Load Event
protected void Page_Load(object sender, EventArgs e)
{
    //This simulates the button click from within your code.
    Button1_Click(Button1, EventArgs.Empty);
}

protected void Button1_Click(object sender, EventArgs e)
{
    //Do some stuff in the button click event handler.
}

A:

If you don't need the context provided by the sender and eventargs then you can just refactor to create a method (eg DoStuff()) and make your event handler just call that. Then when you want to call the same functionality from elsewhere you can just call DoStuff(). It really depends on whether you want to actually simulate a click or not. If you want to simulate a click then other methods are better.

A:

Do you wish to call all the event handlers attached to the button, or just one?
If just one, call the handler:
 btn.btn_Click(btn, new EventArgs());

If all of them, trigger the event:
 var tmpEvent = btn.Click;
 if (tmpEvent != null)
      tmpEvent(btn, new EventArgs());


Q:

Bullets and pasting into flow document

I need to paste some rtf text from a datagrid into a flow document. I want to paste it at the caret position in the richtextbox. This works except when i have a bullet or Numbered list. It will paste it before the bullet or number.
I have searched every where for this with no luck.
private void dgStandardText_MouseDoubleClick(object sender, MouseButtonEventArgs e) {
 if (dgStandardText.SelectedItems.Count > 0) {
  foreach(DataRowView row in dgStandardText.SelectedItems) {
   byte[] byteArray = Encoding.ASCII.GetBytes(row[3].ToString());
   using(MemoryStream ms = new MemoryStream(byteArray)) {
    TextRange tr = new TextRange(txtAreaText.CaretPosition, txtAreaText.CaretPosition);
    tr.Load(ms, DataFormats.Rtf);
   }
  }
 }
 NeedSave = true;
 dgStandardText.SelectedItems.Clear();
}

 Before Paste
 After Paste

A:

This seems to happen when the content you're pasting includes block elements, as opposed to inline elements.  For plain text, WPF seems to treat newlines (e.g., \r\n) as paragraph breaks, so multi-line content would be translated into multiple blocks.  What you want to do is insert just the inline content from each of those source blocks, such that it goes into the current block of the target document (in this case, a list item).  Do this for the first source block, then insert a paragraph break, update the caret position, and move on to the next block.
Is the content of the grid row actually RTF content, or is it plain text?  If it's plain text, then this should be pretty straightforward.  Try changing your foreach loop body to something like this:
var text = row[3].ToString();

var lines = text.Split(
    new[] { '\r', '\n' },
    StringSplitOptions.RemoveEmptyEntries);

foreach (var line in lines)
{
    var p = txtAreaText.CaretPosition;

    txtAreaText.BeginChange();

    p.InsertTextInRun(line);
    p = p.InsertParagraphBreak();

    txtAreaText.EndChange();
    txtAreaText.CaretPosition = p;
}

Now, if the source content really is RTF, then things will get more complicated.  I suspect you'll need to load it into an in-memory flow document and walk through the elements to figure out where the paragraph breaks are.  For each paragraph, locate the inline contents that intersect the selection range, and insert them into the target document.  Insert a paragraph break when you reach the end of each paragraph in the source range, just like in the example above.
I'm afraid the Documents API is the one area of WPF that I haven't explored very thoroughly, so I can only give you a general idea of what to do.  Perhaps someone else can provide more detail.


Q:

How to make webhooks working with nginx+gunicorn+django+pytelegrambotapi

I'm trying to deploy telegram bot(usign pyTelegramBotApi) on django, using nginx+gunicorn.
I already have fomain and Let's Encrypt cert for it, https is working and django rendered pages are accessible.
But I have no idea, why bot isn't receiving any data.
Am I doing something wrong on deployment step?
Django view to handle webhooks:
def telegram(request):
    if request.method == 'POST':
        json_string = request.POST.get()
        update = telebot.types.Update.de_json(json_string)
        bot.process_new_updates([update])
    return HttpResponse('')

def set_hook(request):
    bot.remove_webhook()
    bot.set_webhook(url='https://<my domain>.tk/bot{}'.format(API_TOKEN))
    return HttpResponse('')

nginx config:
server {
    server_name <my domain>.tk www.<my domain>.tk default_server;
    listen 80;

    return 301 https://<my domain>.tk;
}

server {
    server_name www.<my domain>.tk;
    listen 443 ssl http2;

    ssl_certificate /etc/letsencrypt/live/<my domain>.tk/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/<my domain>.tk/privkey.pem;
    ssl_trusted_certificate /etc/letsencrypt/live/<my domain>.tk/chain.pem;

    ssl_stapling on;
    ssl_stapling_verify on;

    add_header Strict-Transport-Security "max-age=31536000";

    return 301 https://<my domain>.tk$request_uri;
}

server {

    server_name <my domain>.tk;
    listen 443 ssl http2;

    ssl_certificate /etc/letsencrypt/live/<my domain>.tk/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/<my domain>.tk/privkey.pem;
    ssl_trusted_certificate /etc/letsencrypt/live/<my domain>.tk/chain.pem;

    ssl_stapling on;
    ssl_stapling_verify on;

    add_header Strict-Transport-Security "max-age=31536000";

    add_header X-Frame-Options "SAMEORIGIN";

    location /.well-known {
        root /var/www/html; # Понадобится для letsencrypt
    }

    location = /favicon.ico {
        alias /home/ubuntu/<my domain>/static/favicon.ico;
    }
    location = /robots.txt {
        alias /home/ubuntu/<my domain>/static/robots.txt;
    }

    location /static/ {
        root /home/ubuntu/<my domain>/;
    }
    location /media/ {
        root /home/ubuntu/<my domain>/;
    }

    location / {
        include proxy_params;
        proxy_pass http://unix:/home/ubuntu/<my domain>/socket.sock;
    }
}

GUnicorn service conf:
[Unit]
Description=gunicorn daemon
After=network.target

[Service]
User=ubuntu
Group=www-data
WorkingDirectory=/home/ubuntu/<my domain>/
ExecStart=/home/ubuntu/<my domain>/venv/bin/gunicorn --access-logfile - --error-logfile error.log --workers 2 --bind unix:/home/ubuntu/<my domain>/socket.sock fri_weekend_bot.wsgi:application

[Install]
WantedBy=multi-user.target

A:

My problem was hiding inside django part.
By default, all django views require CSRF auth.
All I had to do is to place @csrf_exempt decorator on telegram() view to avoid this.
@csrf_exempt
def telegram(request):
    if request.method == 'POST':
        json_string = json.dumps(json.loads(request.body))
        update = telebot.types.Update.de_json(json_string)
        bot.process_new_updates([update])
    return HttpResponse('')


Q:

:iCal Event not added into organizer calendar

I am creating ics file with 2 attendee and a organizer.
Event is properly creating for both attendees and response is also received when they accept/reject the event. I am sending same invite to organizer as well. On organizer end, event is not adding into their calendar (accept/reject buttons are grayed out). Following two messages are showing:

At the meeting organizer, you do not need to respond to the meeting.
Meeting cannot be found in the Calendar.

How I can change the event so that it also create in organizer calendar?
BEGIN:VCALENDAR
PRODID:-//Appointment Confirmation Event//EN
VERSION:2.0
CALSCALE:GREGORIAN
METHOD:REQUEST
BEGIN:VEVENT
DTSTART:20200506T190000Z
DTEND:20200506T200000Z
DTSTAMP:20200506T190000Z
ORGANIZER:mailto:test1@test.com
UID:Interview_47461@sterlinghoffman.com
ATTENDEE;PARTSTAT=NEEDS-ACTION;ROLE=REQ_PARTICIPANT;RSVP=TRUE:mailto:test2@test.com
ATTENDEE;PARTSTAT=NEEDS-ACTION;ROLE=REQ_PARTICIPANT;RSVP=TRUE:mailto:test3@test.com
X-MICROSOFT-CDO-OWNERAPPTID:-486846808
CREATED:20200504T130737Z
DESCRIPTION:
LOCATION:at 3423
SEQUENCE:0
SUMMARY:Phone Meeting
TRANSP:OPAQUE
END:VEVENT
END:VCALENDAR

I tried with adding organizer as attendee but it not works.
ATTENDEE;PARTSTAT=ACCEPTED;ROLE=CHAIR;RSVP=TRUE;mailto:test1@test.com

A:

Since it sounds like the ics file is not being generated by the organisers outlook calendar, then two possible solutions suggest themselves:
1) On the assumption that it would be redundant / duplication to add an event to organisers calendar (who would be assumed by the application to have already created the event in itself) possibly the more robust solution for across calendar applications: add a sent-by, as per https://icalendar.org/iCalendar-RFC-5545/3-8-4-3-organizer.html
ORGANIZER;SENT-BY="mailto:jane_doe@example.com":
  mailto:jsmith@example.com

2) This might be an outlook bug.  A quick search come up with same error messages https://developermessaging.azurewebsites.net/2011/09/30/accepting-ical-appts-in-outlook-when-you-are-the-organiser/ and indicates a hotfix. See also How can I add an ICS meeting automatically to the Organizer's calendar?
See also:
iCalendar does not create an event for organizer
ics not updating organizer calendar,
Sending iCalendar to an user who's also the organizer of the event (the last comment to answer about redundancy to add to organiser


Q:

PHP - Same post is showing instead of the next post

        <?php
        $paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
        $args = array(
            'post_type' => 'post',
            'posts_per_page' => 7,
            'paged' => $paged );
        $wp_query = new WP_Query($args);
        $count = 0;

        while ( have_posts() ) : the_post(); ?>
            <?php echo get_the_title(); ?>
            <?php
                $count++;
                if ($count === 1) { ?>

<?php echo get_the_title(); ?>

                                <?php $content = get_the_content(); echo mb_strimwidth($content, 0, 200, '...');?>

            <?php }
                while ($count <= 2) {
                    $count++ ?>

<?php echo get_the_title(); ?>

                                <?php $content = get_the_content(); echo mb_strimwidth($content, 0, 200, '...');?>

            <?php }
                while ($count <= 4) {
                    $count++ ?>

<?php echo get_the_title(); ?>

                                <?php $content = get_the_content(); echo mb_strimwidth($content, 0, 200, '...');?>

            <?php }
            ?>
        <?php endwhile; ?>

        <?php next_posts_link( '← Older posts', $wp_query ->max_num_pages); ?>
        <?php previous_posts_link( 'Newer posts →' ); ?>

I'm struggling to understand why the if and while statements are looping the same post but directly after this line:
while ( have_posts()) : the_post();

Where I am echoing the title this shows the list of posts instead.
What I am trying to achieve here is create a different html layout for each post that is outputted in the loop.
Cheers

A:

I think you are trying to loop over your query result as shown in the WP_Query official documentation.
Also, not sure why you would do while loops like you were inside the main post loop itself so I changed those to if statements.
Something like this is what I believe you are after:
<?php
        $paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
        $args = array(
            'post_type' => 'post',
            'posts_per_page' => 7,
            'paged' => $paged );
        $wp_query = new WP_Query($args);
        $count = 0;

        if(! $wp_query->have_posts())
            die('no posts!'); // ADDED - Handle this more elegantly

        while ( $wp_query->have_posts() ) : $wp_query->the_post(); // ADDED - Use query result object?>
            <?php echo get_the_title(); ?>
            <?php
                $count++;
                if ($count === 1) { ?>

<?php echo get_the_title(); ?>

                                <?php $content = get_the_content(); echo mb_strimwidth($content, 0, 200, '...');?>

            <?php }
                if ($count <= 2) {
                    ?>

<?php echo get_the_title(); ?>

                                <?php $content = get_the_content(); echo mb_strimwidth($content, 0, 200, '...');?>

            <?php }
                if  ($count <= 4) { // ADDED - Be careful, this will fire as well as the if statement above it since they are both <= 2
                    ?>

<?php echo get_the_title(); ?>

                                <?php $content = get_the_content(); echo mb_strimwidth($content, 0, 200, '...');?>

            <?php }
            ?>
        <?php endwhile; ?>

        <?php next_posts_link( '← Older posts', $wp_query ->max_num_pages); ?>
        <?php previous_posts_link( 'Newer posts →' ); ?>


Q:

An explanation from Calvinist about why Cain's offering is not accepted by God?

This question is following the question before, where Calvin said :

We must, however, notice the order here observed by Moses; for he does
  not simply state that the worship which Abel had paid was pleasing to
  God, but he begins with the person of the offerer; by which he
  signifies, that God will regard no works with favor except those the
  doer of which is already previously accepted and approved by him

The bold sentence from Calvin's quotation above, lead to a conclusion that :
1. God elect Abel before the foundation of the world.
2. He regenerate Abel in time and give him faith, don't know when but before the offering event.
3. Those 2 points above causing Abel do a correct offering.
4. Now God has a reason to look with favor on Abel + his offering.
5. and now God can give him approval as righteous through his offering.
So, "God begins with the person of the offerer" as in this case is number 1 and number 2.
The logical conclusion about Cain is :
Because God did not elect Cain and God did not regenerate Cain in time and give Cain faith then Cain offering is not accepted by God. He had no regard for Cain and his offering as mentioned in Gen 4:5.
My question : (according to the Calvinist)
1. What is the cause of Cain's offering is not accepted by God ?
2. Has God regenerated Cain and gave him faith by the time God speak to Cain as read in verse 6 and 7 ?

A:

Why does God approve of Abel as righteous because of his offering?
You stated this in point 5 of your question, and though it wasn’t explicitly asked, I wanted to address it because it is contrary to our first principles. Conversely, God approves of Abel’s offering because of his righteousness- a righteousness, like all godly righteousness, that comes to him by faith. When Calvin says, "God begins with the person of the offerer" he means that the value of the offering is that it is an expression of adoration, and not that it is an attempt to gain approval; the value of the sacrifice exists solely in the heart of the offerer, because the approval of God cannot be earned, except so perfectly.
What is the cause of Cain's offering not being accepted by God ?
In Book 2 of Calvin’s Institutes of the Christian Religion, Calvin discusses the episode of Cain and Abel. He offers an interpretation of Genesis 4:7 that is not common, even among modern translations of the passage, acknowledging the error of Catholic translators.

They adduce the passage of Genesis, “Unto thee shall be his desire, and thou shalt rule over him,” (Gen. 4:7). This they interpret of sin, as if the Lord were promising Cain that the dominion of sin should not prevail over his mind, if he would labour in subduing it. We, however, maintain that it is much more agreeable to the context to understand the words as referring to Abel, it being there the purpose of God to point out the injustice of the envy which Cain had conceived against his brother. And this He does in two ways, by showing, first, that it was vain to think he could, by means of wickedness, surpass his brother in the favour of God, by whom nothing is esteemed but righteousness; and, secondly, how ungrateful he was for the kindness he had already received, in not being able to bear with a brother who had been subjected to his authority.

Now, it helps to remember that the Reformers, among other complaints, rejected the teaching of the Roman Church that justification is a consequence of godly living. The concern of the Catholic presbyters was the moral living of their congregants and their dedication to the authority of Rome, and their teaching reflected that concern. It is not surprising that a person with such a perspective regarding righteousness would naturally adopt an interpretation that God spoke to Cain, saying that he ought to overcome his temptation through labour. To the contrary, Calvin posits that God was prophesying the very domination over Abel that Cain was later to display, in a similar way that He demolishes the pride of the wicked throughout the narrative that follows Genesis, which culminates in his demolition of all wickedness.
Calvin continues, giving the objector the benefit of the doubt by supposing that 4:7 does refer to sin. He posits then that the words constitute either an order or a promise, and examines both cases. In so doing, he addresses your second question.
Has God regenerated Cain and gave him faith by the time God speak to Cain as read in verse 6 and 7 ?
If God had regenerated Cain, he would have been able to speak the words in that passage as a promise, that is, offering assurance. It is common throughout the scriptures for God, through visions, prophets, or apostles, to offer the assurance of justification- a promise- to the elect. Calvin considers this as he continues.

If so, his words contain either an order or a promise. If an order, we have already demonstrated that this is no proof of man’s ability; if a promise, where is the fulfillment of the promise when Cain yielded to the sin over which he ought to have prevailed?

Because Cain fails, Calvin concludes that the passage cannot be a promise, lest the word of God fail, and must therefore be a command, then makes a statement that I believe answers your question.

For, if the dominion spoken of refers to sin, no man can have any doubt that the form of expression is imperative, declaring not what we are able, but what it is our duty to do, even if beyond our ability. Although both the nature of the case, and the rule of grammatical construction, require that it be regarded as a comparison between Cain and Abel, we think the only preference given to the younger brother was, that the elder made himself inferior by his own wickedness.

But surely Cain had faith. One might ask, how could a man such as Cain, who heard the voice of God, lack faith? What is the difference between the faith of Cain and that of Abel?
In the third book of Institutes, On Faith, Calvin answers.

But since the heart of man is not brought to faith by every word of God, we must still consider what it is that faith properly has respect to in the word. The declaration of God to Adam was, “Thou shalt surely die,” (Gen. 2:17); and to Cain, “The voice of thy brother’s blood crieth unto me from the ground,” (Gen. 4:10); but these, so far from being fitted to establish faith, tend only to shake it. At the same time, we deny not that it is the office of faith to assent to the truth of God whenever, whatever, and in whatever way he speaks: we are only inquiring what faith can find in the word of God to lean and rest upon. When conscience sees only wrath and indignation, how can it but tremble and be afraid? And how can it avoid shunning the God whom it thus dreads? But faith ought to seek God, not shun him. It is evident, therefore, that we have not yet obtained a full definition of faith, it being impossible to give the name to every kind of knowledge of the divine will.

It is not the practice of faithfulness or measure of faith that is concomitant with the approval of God, but indeed a faith with a specific object and nature. God did not approve of Cain’s sacrifice because with it he sought the favor of God, and even to surpass the favor of his brother. Abel on the other hand loved God and did not seek righteousness with his sacrifice, but offered it as an expression of his adoration. Cain’s heart was hard, and so though he had “faith” in the sense of knowledge of the existence and identity of God, he lacked faith in the sense of knowledge that God himself is the sole source of righteousness by favor, that is, by grace, and that his favor is not obtained as recompense by sacrifice and labor, but a gift given according to trust and love that are the product of illumination by his Spirit.
Calvin returns to the episode in his commentary on Hebrews 11:4, saying,

The Apostle’s object in this chapter is to show, that however excellent were the works of the saints, it was from faith they derived their value, their worthiness, and all their excellences; and hence follows what he has already intimated, that the fathers pleased God by faith alone.
Now he commends faith here on two accounts, — it renders obedience to God, for it attempts and undertakes nothing, but what is according to the rule of God’s word, — and it relies on God’s promises, and thus it gains the value and worth which belongs to works from his grace alone. Hence, wherever the word faith is found in this chapter, we must bear in mind, that the Apostle speaks of it, in order that the Jews might regard no other rule than God’s word, and might also depend alone on his promises.
He says, first, that Abel’s sacrifice was for no other reason preferable to that of his brother, except that it was sanctified by faith: for surely the fat of brute animals did not smell so sweetly, that it could, by its odor, pacify God. The Scripture indeed shows plainly, why God accepted his sacrifice, for Moses’s words are these, “God had respect to Abel, and to his gifts.” It is hence obvious to conclude, that his sacrifice was accepted, because he himself was graciously accepted. But how did he obtain this favor, except that his heart was purified by faith.


Q:

Drawing zoomable audio waveform timeline in Javascript

I have raw 44,1 kHz audio data from a song as Javascript array and I'd like to create a zoomable timeline out of it.
Example timeline from Audacity:

Since there are millions of timepoints normal Javascript graphics libraries probably don't cut it: I think, not sure, that normal graph libraries will die on this many timepoints. But does there exist already libraries for this sort of visualization for JS? Canvas, webGL, SVG all are acceptable solutions.
A solution preferably with zoom and pan.
Note that this happens strictly on client side and server-side solutions are not accetable.

A:

I've looked into this same problem pretty extensively. To the best of my knowledge, the only existing project that does close to what you want is wavesurfer.js.  I haven't used it, but the screenshots and the description sound promising.
See also this question.
Best of luck.


Q:

Tomcat specific webapp slowdown

Today in the company where I work we received a report about one of our webapps not working.
The first thing we did was look at the hardware utilization:

Processor: 5%;
Memory: 68%;
Disk IO capacity: 4%;
Network: 1Mbps/1Gbps;

After some tests we saw that, indeed, the webapp pages weren't loading, some time after the webapp timeouts.
Other webapps in the exactly same tomcat instance were working fine and fast as ever, no problem with them. We tried to restart/reload the webapp but it still didn't get it working. Finally we restarted tomcat which corrected the issue for now.
There were no restarts or redeploys since yesterday when it was working fine. We believe this may be a periodic bug of some sort so we want to correct it soon.
Does anyone know of any steps we may take to investigate what it might have been?

A:

It seems related to lock on IO.
If you are using linux, the first thing is do is to check open files by using the command lsof . If you see a lot of opened files by your app, you have to check in the code that every InputStream/OutputStream are closed (even in exception handling code).
An other common source of issues is related to thread starvation, see http://tomcat.apache.org/tomcat-9.0-doc/config/valve.html#Stuck_Thread_Detection_Valve


Q:

Microservices architecture: Divide micro services by user roles alone

I have encountered the following design requirement in an app marketplace like project from a client in which users can rate games/apps they download (only in a special way more helpful than traditional marketplaces).
My question is regarding microservices architecture,
If I have a game user, app owner, market place moderator and market place admin roles and they have common API's they are using but also different ones where in some cases, for example, user can review an app but only moderator and admin can edit that review, so basically I can approach the design by having a microservice that is responsible for app reviews and have a single method SaveOrUpdateAppReview and then based on authentication and authorization both user, moderator and admin could call this method but update will only work for moderator and admin or I can perhaps split it into microservices based on roles, so ill have AppReview microservice having only createReview method and AppReviewModeration microservice in which will have both createReview (as moderator can also create a review) and editReview).
This example repeats itself in many workflows and use-cases, e.g 2, the app owner cannot change app price under certain conditions but admin can, so perhaps the method that enables it to do it should only be under App Admin microservice?
To sum it up, if different roles have different APIs they require, should I handle it in the design level, splitting/dividing it into different microservices or is it part of an internal authorization claim based logic and each method should check if its create or update and enable/disable accordingly.
Regards,
James

A:

Don't couple architecture to authorization policy. It's normal and expected to have code blocks branching on the user's permissions. Depending on how complex it is, you can keep it out of the way of other business logic by putting it in decorators / middleware.
If you have several frontends (e.g. game user and app owner are different apps), it can make sense to have a dedicated microservice sitting behind each one. This would then turn around and consume a common set of platform services. This can save you from having frontend-specific concerns in e.g. the review store layer. But it adds a lot of complexity, and as with all microservices architectures, you don't want to do this until your team is so big that you have to.


Q:

Jersey: saving data in-memory

I am building a simple REST web service using Java and Jersey. I want to store some data in-memory that can be accessed during the time that the server is online. For example:
http://localhost:8080/register/<someusername>
would add  to an ArrayList/HashMap/etc that can be accessed by
http://localhost:8080/list
which would list the registered users.
How can I accomplish this?
I'm aware that this is not a great way to go about storing data, but for the purposes of my project I'd like it to only be saved while the server is online, and have everything fully reset when it's restarted/stopped/whatever.

A:

If you want this data be all same of all clients, then you can use
@Context
ServletContext servletContext;
Then, put the attribute there and fetch from this attribute on each invocation.

If you have some framework, like spring, then you can get/set value with its facilities.


Q:

Joomla login page, if user is already logged redirect to home page

I think I'm missing something in the Joomla login behaviour.
I read a lot of post but can't find the answer of what I looking for.
Let's say you have login page (ie: yoursite.com/login), if you login, Joomla correctly brings you to the target page you choose.
The problem is :
if you then go back to the login page yoursite.com/login, the redirect doesn't work no more. In fact if you refresh the page the login fields vanish and all it remains is the logout button.
I tried
$user = JFactory::getUser();

if($user->id == 1)
{
// redirect here
}

I tried in Joomla 2.5 and 3.x, the behaviour is the same. Am I missing something?

A:

Because it's not the same layout.
If the user is guest, you are looking at the "default_login.php" layout, which - I gather - is the one you already modified.
But if the user is logged, you are looking at the "default_logout.php" layout, which you need to override as well.


Q:

How to break up excel spreadsheet into separate excel sheets separated by rows

Hi I have an excel spreadsheet with about 10,000 records and about 8 columns.  I would like to break up the excel spreadsheet into different spreadsheets containing data from 250 rows each.  So for example.
Spread sheet 1 would have 250 rows
Spread sheet 2 would have another 250 rows (251-500 from the original 10,000 list) and so on so forth until it's all completed.  It should also retain the original header on each spreadsheet.
Any one can help?

A:

This should work assuming data from A1:Z1000. Just change the range, workbook name and "save as" path as needed.
Sub generateSheets()

Dim sheetName As String
Dim headerRng As Range

Set headerRng = Workbooks("GenerateSheetsTest.xlsm").Worksheets("sheet1").Range("A1:Z1")

Application.ScreenUpdating = False

For i = 0 To 1000 Step 250
sheetName = "Until" & i + 250
Set NewBook = Workbooks.Add
headerRng.Copy
NewBook.Worksheets("Sheet1").Range("A1").PasteSpecial (xlPasteValues)
Workbooks("GenerateSheetsTest.xlsm").Worksheets("sheet1").Range("A" & i + 2 & ":Z" & i + 251).Copy
NewBook.Worksheets("Sheet1").Range("A2").PasteSpecial (xlPasteValues)
NewBook.SaveAs fileName:="C:\Users\" & Environ$("username") & "\Documents\Output\" & sheetName & ".xlsx"
ActiveSheet.Range("A1").Select
ActiveWorkbook.Close True
Next i

Application.ScreenUpdating = True

End Sub


Q:

HTML link that forces refresh?

Is there a way to construct a link to a URL that forces the browser to ignore any cache it might have for that URL?
We have some websites that have recently changed after literally years of static content. Users click shortcuts, favorites, or type URL's to these sites and get old, cached content. I would like to have a page with a link that goes to the same URL but forces the browser to get the fresh content.
is that possible? Cross-browser?

A:

Change all the links to the page with a nonsense query parameter: products.html?happy=days
Change all the resources on the page to use another nonsense query parameter: style.css?the=fonz

You can do it in a systematic way using dates or timestamps or version numbers, or haphazardly using sitcoms, muppets, mountain ranges, and small mammals.

A:

Add a url parameter to the end of the href with a unique value, say new Date().getTime():
...somePage.html?time=123456789


Q:

is there a way to get the result of web3's encodeFunctionCall with ethers?

I'm using web3 to get the RLP encoded data for a function call like so
const safeTransferFrom: any = tokenERC1155Abi.find((f) => f.name === 'safeTransferFrom');
const params: Array<any> = [identity, minterAddr, 1, amount, '0x0'];
web3.eth.abi.encodeFunctionCall(safeTransferFrom, params);

is there a way to achieve the same result with the ethers.js library?

A:

The equivalent in ethers.js involves first creating an "interface" object and calling a method on that:
> let ABI = [ "function transfer(address to, uint amount)" ];
> let iface = new ethers.utils.Interface(ABI);
> iface.encodeFunctionData("transfer", [ <function_params> ])

Taken from here


Q:

The last digit of pi (in terms of Banach limits)

Let $\phi : l^\infty \to \mathbb C$ be a Banach limit, and define the sequence $\{x_k\}_{k\geq 0}$ to be the digits in the 10-base decimal expansion of $\pi$. Note that
$$\{x_k\}_{k\geq 0} \in l^\infty$$
and so we can talk about $\phi(\{x_k\}_{k\geq 0})$.
What it is? Note that Banach limits don't have to be unique.
Now consider the real number $\sqrt 2$. What is its last number? Finally, consider any element $x\in \mathbb R$. Can we say about the last digit of $x$, in the sense of Banach limits as considered above?

A:

Concerning last question about general $x\in\mathbb{R}$ and concerning the twice upvoted comment (under the original question)  that claims the limit is 4.5 for almost all $x$:
I think the opposite is true (see proof below): almost all (in the sense of the Lebesgue measure) real numbers do not have a unique Banach limit. Unless $\pi$ is an exception to this (and I don't know whether it is), your first question does not have a well-defined answer: The 'last digit' of $\pi$ is different for different choices of the Banach limit $\phi$.
Proof of claim: According to a theorem of Lorentz, a sequence $(x_k)_{k=0}^{\infty}$ has a unique Banach limit $L\in\mathbb{R}$ if and only if its averages $\overline{x}_{n,p}:=\frac{x_n+\dots+x_{n+p-1}}{p}$ converge to $L$ as $p\to\infty$, uniformly in $n$. In formulas $\forall \epsilon>0: \exists p_0\in\mathbb{N}: \forall p\geq p_0: \forall n\in\mathbb{N}:|\overline{x}_{n,p}-L|<\epsilon$. In particular, just by rewriting this definition in set form and choosing $\epsilon:=1$, this implies that $x\in \bigcap_{m\in\mathbb{N}}A_{p_0,m}$ for some $p_0\in\mathbb{N}$, where $A_{p_0,m}:=\{x:|\overline{x}_{mp_0,p_0}-L|<1\}$.
If we assume for simplicity that $(x_k)_{k=0}^{\infty}$ are the digits of $x\in[0,1]$, the events $(A_{p_0,m})_{m\in\mathbb{N}}$ are independent under the Lebesgue probability measure on $[0,1]$ (since the digits themselves are independent random variables) and have probability less than $1$. This shows $P(\bigcap_{m\in\mathbb{N}}A_{p_0,m})=0$ for all $p_0\in\mathbb{N}$, or,  if we denote by $B_L$ the reals with unique Banach limit $L$, that $P(B_L)=0$ for all $L\in\mathbb{R}$. Since $\mathbb{R}$ is uncountable, it could happen that $P(\bigcup_{L} B_L)>0$. However, this is not the case since $P(\bigcup_{L\not= 4.5}B_L)=0$ by the law of large numbers.


Q:

What are the file formats for different mobile platforms

I am trying to learn more about mobile application development. iOS applications are contained in a 'ipa' file.
What are the file formats for android, BlackBerry and Windows Phone Mobile.

A:

We're talking about application distribution format, right?

Windows Phone 7: XAP. It's a renamed ZIP.
Android: APK. It's a renamed ZIP.
Windows Mobile: CAB. Also a compressed format, similar but not identical to ZIP. Many popular archivers can open those.
Blackberry: ALX for sideloading, JAD and COD for over-the-air installation. JAD is a text file, COD is binary but no idea what's in it.
Samsung bada: ZIP. As simple as that.

Note that Windows Phone 7 and Windows Mobile (6.x and below) have quite different app distribution models. WinMo exposes its filesystem, so a specific app distibution format is not, technically, necessary - you can copy an EXE to Program Files and run it all you want. Some old school apps expect you to do just that. CABs are more convenient, though - they install by single click.
WinPhone7 only supports installing from MS Marketplace. XAP is the format the compiler emits and that you submit to the Marketplace.
All those are packaging formats. Those files typically contain the executable, libraries (if any), resources, assets, and a manifest that describes the app. If you're wondering about the format of the executable - that's a whole another question.


Q:

Nullpointerexception when adding to List "Edit source lookup path"

I'm trying to create a gridView of images. I am copying this android developers tutorial however they hardcoded the drawables into an Integer[], whereas I have to set mine to what the user chooses. mListContents is populated with objects. path and pathA are both initiated with a value. This is all confirmed with the debugger. When it gets to mList.add(pathA) it throws a nullpointerexception. When debugging it says "source not found" in the ActivityThread and gives me the option to "Edit source lookup path". Any issues changing from the tutorials Integer[] to a List<Integer>?
    public class ImageAdapter extends BaseAdapter {
    private Context mContext;
    private int mMenuId;
    dbhelper db;

    List<ClothingItem> mListContents;
    List<Integer> mList;

    public ImageAdapter(Context c, int menuId) {
        mListContents = new ArrayList<ObjectGeneric>();
        mContext = c;
        mMenuId = menuId;
        db = new dbhelper(mContext);
        setList(mMenuId);
        setDrawableList();
    }

 private void setDrawableList(){
            for(ObjectGeneric item : mListContents){
                int path = item.getImagePath();
                Integer pathA = (Integer) path;
                mList.add(pathA);
            }
        }

    // create a new ImageView for each item referenced by the Adapter
        public View getView(int position, View convertView, ViewGroup parent) {
            ImageView imageView;
            if (convertView == null) {  // if it's not recycled, initialize some attributes
                imageView = new ImageView(mContext);
                imageView.setLayoutParams(new GridView.LayoutParams(85, 85));
                imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
                imageView.setPadding(8, 8, 8, 8);
            } else {
                imageView = (ImageView) convertView;
            }

            imageView.setImageResource(mList.get(position));
            return imageView;
        }

A:

From first glance, it looks like you're not initializing mList, so a null pointer exception is correct. Try initializing it, like so:
public ImageAdapter(Context c, int menuId) {
    mListContents = new ArrayList<ClothingItem>();
    mList = new ArrayList<Integer>();  // <---  here

    mContext = c;
    mMenuId = menuId;
    db = new dbhelper(mContext);
    setList(mMenuId);
    setDrawableList();
}


Q:

MySQL trigger works on one field, not on second field, in the same table

I have a MySQL database with a table inventory with multiple triggers set up to capture changes in a second table inventory_history. I'm updating two of the fields (both in a single query, and in two separate queries), and the trigger consistently works on only one of the two fields (qty but not on last_sale).
Here is the troublesome query:
UPDATE inventory SET last_sale = 321, qty = 0 WHERE id = 123;

Alternately, these query combinations don't work either:
UPDATE inventory SET last_sale = 321 WHERE id = 123;
UPDATE inventory SET qty = 0 WHERE id = 123;

Here are the table constructs and triggers:
CREATE TABLE `inventory` (
  `serial_no` varchar(255) DEFAULT NULL,
  `qty` mediumint(9) DEFAULT NULL,
  `partid` mediumint(9) unsigned DEFAULT NULL,
  `last_sale` mediumint(9) unsigned DEFAULT NULL,
  `date_created` timestamp NULL DEFAULT CURRENT_TIMESTAMP,
  `id` mediumint(9) unsigned NOT NULL AUTO_INCREMENT,
  PRIMARY KEY (`id`),
  KEY `partid` (`partid`),
  KEY `date_created` (`date_created`),
  KEY `last_sale` (`last_sale`),
  KEY `last_rma` (`last_return`),
  KEY `last_purchase` (`last_purchase`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

CREATE TABLE `inventory_history` (
  `date` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  `inventory_id` mediumint(9) unsigned NOT NULL,
  `field_changed` enum('serial_no','qty','partid','last_sale','new') NOT NULL,
  `changed_from` varchar(255) NOT NULL,
  KEY `inventory_id` (`inventory_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

CREATE TRIGGER `inv_new` AFTER INSERT ON `inventory`
 FOR EACH ROW BEGIN
  SET
    @id = NEW.id,
    @userid = NEW.userid,
    @date = now();

  INSERT INTO inventory_history VALUES (@date,@userid, @id, 'new', 'new');
END
//
DELIMITER ;
DROP TRIGGER IF EXISTS `inv_update`;
DELIMITER //
CREATE TRIGGER `inv_update` AFTER UPDATE ON `inventory`
 FOR EACH ROW BEGIN
  SET @userid = OLD.userid;
  SET @inv_id = OLD.id;

  IF (OLD.serial_no <> NEW.serial_no) THEN
    INSERT INTO inventory_history VALUES (now(), @userid, @inv_id, 'serial_no', OLD.serial_no);
  END IF;

  IF (OLD.qty <> NEW.qty) THEN
    INSERT INTO inventory_history VALUES (now(), @userid, @inv_id, 'qty', OLD.qty);
  END IF;

  IF (OLD.partid <> NEW.partid) THEN
    INSERT INTO inventory_history VALUES (now(), @userid, @inv_id, 'partid', OLD.partid);
  END IF;

  IF (OLD.last_sale <> NEW.last_sale) THEN
    INSERT INTO inventory_history VALUES (now(), @userid, @inv_id, 'last_sale', OLD.last_sale);
  END IF;
END
//
DELIMITER ;

So again, the qty trigger works, but the last_sale does not.

A:

Days later, turns out to be a simple but profound explanation (isn't it always?).
The trigger statement I used above was:
  IF (OLD.last_sale <> NEW.last_sale) THEN
    INSERT INTO inventory_history VALUES (now(), @userid, @inv_id, 'last_sale', OLD.last_sale);
  END IF;

The problem with this statement is that it doesn't capture a value change from NULL to 0, for example. It only captures a value to another value. So I needed to ADD a second statement for the NULL scenarios:
  IF (OLD.last_sale IS NULL AND NEW.last_sale IS NOT NULL) THEN
    INSERT INTO inventory_history VALUES (now(), @userid, @inv_id, 'last_sale', OLD.last_sale);
  END IF;

And all the world is right. :)


Q:

How Do I 'Restore' MS Word's Document Window Using Automation

I would like to be able to 'restore' MS Word's document window using Automation.
I already have the application object and I have tried calling App.Activate. Activate will bring the window to the top of the Window stack but not if Word is minimized. I can set the WindowState to Maximized, Minimized and Normal but what I really need to do is restore the window to the state it was in before the user minimized it (this would be equivalent to the user clicking on the application's button in the taskbar).
Is this possible using Word automation?
I am actually using C++ to to the automation so I am able to call Win32 API functions if required.
If there is not direct way to restore the window then the question becomes, 'how can I get the window handle of the ActiveWindow?'

A:

The best way I have come up with so far is as follows.
Get the active window using Application.ActiveWindow
This window object has a property named Caption. The caption appears in the document window's title.
I then use the Win32 function EnumWindows() to search for the Win32 window. I get the window text for each window returned by EnumWindows() using the Win32 function GetWindowText(). I attempt to find the caption in the window text and as an extra check I make sure the window text also contains the string 'Microsoft Word'.
Once I find the window, I then have it's Win32 window handle which I can then pass to the Win32 function ShowWindow(hWnd, SW_RESTORE).
You also have to call Application.Activate.
This solution is not perfect, for example I don't really like to assume that the window title will always contain the text 'Microsoft Word' but I also don't want to pick the wrong window.


Q:

Trigger Question!

Greetings StackOverflow community!
For this new project I'm required to write a trigger which fires when a row is inserted into one of the tables.
I have a table called Questions which contains the following fields:

ID - int
Datecreated - smalldatetime
Category_ID - int
Value - ntext
Timelimit - smalldatetime
helper - ntext (nullable)

and another table User_Questions which contains the following fields:

ID - int
Question_ID - int
User_ID - int
Datecreated - smalldatetime
helper - ntext (nullable).

Now I think i can write a trigger which extracts the Datecreated and ID fields from Questions table and adds them to a new row in the Users_Questions table. Could you please advice me on how to get the value for the User_ID field?
That would be greatly appreciated.
Thank you very much in advance!

A:

One option that I would prefer in this case would be to create a stored procedure that takes the necessary input parameters, and then does your two inputs into the two tables in a transaction. That way you control what's going on:
(this assumes SQL Server 2005, and the ID fields are INT IDENTITY - correct??)
 CREATE PROCEDURE dbo.InsertQuestion
    @Datecreated SMALLDATETIME, @Category_ID INT,
    @Question NVARCHAR(MAX), @Timelimit SMALLDATETIME,
    @helper NVARCHAR(MAX)
 AS BEGIN
    -- start transaction and a TRY..CATCH block
    BEGIN TRANSACTION
    BEGIN TRY
        -- insert values into "Questions" table
        INSERT INTO
           dbo.Questions(DateCreated, Category_ID, Question, TimeLimit, Helper)
        VALUES
            (@DateCreated, @Category_ID, @Question, @TimeLimit, @Helper)

        -- retrieve the ID of the newly inserted row
        DECLARE @QuestionID INT
        SET @QuestionID = SCOPE_IDENTITY()

        -- determine the user ID from SQL Server
        DECLARE @UserID INT
        SET @UserID = SUSER_ID()

        -- insert values into "User_Questions" table
        INSERT INTO
           dbo.UserQuestions(QuestionID, UserID, DateCreated, Helper)
        VALUES
            (@QuestionID, @UserID, @DateCreated, @Helper)

        -- commit transaction, if everything went well
        COMMIT TRANSACTION
    END TRY
    BEGIN CATCH
       -- handle your error, e.g. by logging to a table or something.....
       ROLLBACK TRANSACTION
    END CATCH
 END

Triggers are notoriously hard to get right, they don't scale very well - I would try to avoid triggers if ever possible (not always possible, but often, it is) –


Q:

Будет ли равномерным распределение заданий в очереди?

Нужно что-то вроде RR.
Будет ли равномерным распределение заданий в очереди Queue.Queue() по тредам? Смущает то что задания появляться будут медленней чем выполнение команд по ним.
Запускаю несколько тредов (с разным кодом под разные устройства) и тред который принимает задания по http. Задание попадает в очередь, а до  этого воркеры висят заблокированном queue.get().
Я использовал в другом проекте multiprocessing.dummy.Pool - там все красиво и равномерно, но сейчас треды имеют разный код внутри и одной функцией не обойдешься.
Задача разгрузить исполнительные устройсва, а не процессор.

A:

Сперва почему-то хотелось ответить, что распределение неравномерное - то есть часть потоков будет простаивать, а тот, что был создан первее всех будет отдуваться за всех. Видимо такой поспешный вывод из-за наивного представления потоков в воображении. Но вот эксперимент (py3) - задания появляются в два раза медленнее, чем обрабатываются:
import queue
import threading
import time
import random

counter = {}
lock = threading.Lock()

def worker():
    while True:
        try:
            sleep = q.get()
            if sleep == "DIE":
                q.task_done()
                return
            print(threading.current_thread().name)
            with lock:
                counter[threading.current_thread().name] = counter.get(threading.current_thread().name, 0) + 1
            time.sleep(sleep)
            q.task_done()
        except queue.Empty:
            pass

q = queue.Queue()
pool = [threading.Thread(target=worker, name="Worker " + str(i)) for i in range(4)]
[t.start() for t in pool]
for i in range(100):
    rand_sleep = random.random() / 8
    q.put(rand_sleep)
    time.sleep(rand_sleep * 2)
for i in range(4):
    q.put("DIE")

q.join()

print("Report: ", counter)

Вот что скрипт выводит:
output: ('Report: ', {'Worker 2': 25, 'Worker 3': 25, 'Worker 0': 25, 'Worker 1': 25})

Как видно из результатов - для моего кода распределение равномерное.
Если задания поступают без задержек - то распределение неравномерное и зависит от того, как долго обрабатывает задание каждый поток.
Дополнение: данный скрипт был протестирован в Windows и Ubuntu, использовался Python3.4 и Python2.7. Во всех четырех случаях результаты одинаковы.


Q:

Destination file already exists and could not be deleted when upload

My web app is made on Spring MVC. I have a method where the user can upload PDFs
.
 The I am sending the file as mutlipart file to the server. Every time the user uploads.
All what I want is to send the files as attachments in that email.
My code
private File prepareAttachment(final MultipartFile mFile) {
        File file = new File(System.getProperty("java.io.tmpdir") + System.getProperty("file.separator") + mFile.getOriginalFilename());
        try {
            if(file.exists()) {
                file.delete();
            }
            mFile.transferTo(file);
        } catch (FileNotFoundException fnfE) {
            file.delete();
            LOG.error(" file was not found.", fnfE);
        } catch (IOException ioE) {
            file.delete();
            LOG.error("file has failed to upload.", ioE);
        }
        return file;
    }

calling the method to prepare the attachment:
MimeMessagePreparator preparator = new MimeMessagePreparator() {
            @Override
            public void prepare(final MimeMessage mimeMessage) throws Exception {

                File file = prepareAttachment(form.getFile());
                File file2 = prepareAttachment(form.getFile2());
                MimeMessageHelper message = new MimeMessageHelper(mimeMessage, true);

message.addAttachment(form.getFile().getOriginalFilename(), file);
message.addAttachment(form.getFile2().getOriginalFilename(), file2);

Getting exception:
    2017-08-28 15:10:59,549 ERROR com.menards.requestForms.business.service.EmailService - file has failed to upload.
java.io.IOException: Destination file [C:\opt\tcserver\main\temp] already exists and could not be deleted
    at org.springframework.web.multipart.commons.CommonsMultipartFile.transferTo(CommonsMultipartFile.java:160) ~[spring-web-4.3.6.RELEASE.jar:4.3.6.RELEASE]
    at com.menards.requestForms.business.service.EmailService.prepareAttachment(EmailService.java:552) ~[classes/:?]

this will work perfectly if I comment out adding the second file :(
message.addAttachment(form.getFile2().getOriginalFilename(), file2);

any advise?

A:

Generally, you shouldn't let your users determine the path of a file that you're creating on your server - it introduces a lot of security vulnerabilities. In this case, they may be attempting to create a temp file that has the same as some other file in your temp directory, potentially one that has nothing to do with your current application. File.createTempFile ensures that it creates a file with a unique name on each invocation.
It's also good practice to clean up temp files as soon as you're finished with them, so you don't have to worry about maintaining state on your server between method calls. This can sometimes create code that's a bit busy with catch/finally blocks, but it's worth it to avoid waking up at 3 AM to a hard disk that's full of garbage temp files.
I'd implement this roughly as:
private File prepareAttachment(final MultipartFile mFile) throws IOException {
    File tmp = null;
    try {
        tmp = File.createTempFile("upload", ".tmp");
        mFile.transferTo(tmp);
        return tmp;
    } catch (IOException ioE) {
        if (tmp != null) {
            tmp.delete();
        }
        LOG.error("file has failed to upload.", ioE);
        throw ioE;
    }
}

MimeMessagePreparator preparator = new MimeMessagePreparator() {
    @Override
    public void prepare(final MimeMessage mimeMessage) throws Exception {
        File file1 = null;
        File file2 = null;
        try {
            file1 = prepareAttachment(form.getFile());
            file2 = prepareAttachment(form.getFile2());
            MimeMessageHelper message = new MimeMessageHelper(mimeMessage, true);

            message.addAttachment(form.getFile().getOriginalFilename(), file1);
            message.addAttachment(form.getFile2().getOriginalFilename(), file2);
            // do your other stuff
        } catch (IOException e) {
            // some sort of error-handling, probably returning a message with an error status
        } finally {
            if (file1 != null) {
                file1.delete();
            }
            if (file2 != null) {
                file2.delete();
            }
        }
    }
};


Q:

Behaviour of createBackgroundSubtractorMOG2 function in opencv

I am trying to create a motion detecting alarm by using the cv2.createBackgroundSubtractorMOG2() function to check for moving objects and sound an alarm.
This is my code:
import cv2
import numpy as np
import winsound

kernel=np.ones((5,5),np.uint8)
cap=cv2.VideoCapture(0)
fgbg=cv2.createBackgroundSubtractorMOG2()
while True:
    ret,frame=cap.read()
    fgmask=fgbg.apply(frame)  #creates binary image of moving objects
    fgmask=cv2.erode(fgmask,kernel,iterations=1)  #erosion to remove noise
    counter=np.sum(fgmask==255)  # counts the number of white pixels in the mask
    cv2.imshow('img',fgmask)
    cv2.imshow('frame',frame)
    print(counter)
    if counter>50:  #sounds an alarm if the number of white pixels is greater than a certain limit
        winsound.Beep(1000,2000)
        print("beep")

    if (cv2.waitKey(1) & 0xFF)==ord('q'):
        break
cap.release()

The problem is caused as the program is paused for 2 seconds when the winsound.Beep function is called and after it resumes the program glitches and repeatedly starts beeping.
If I remove the winsound.Beep function the program works as expected.
Why does this happen?

A:

The reason you're experiencing such problem is because winsound.Beep(1000,2000) is a blocking operation and should be runned on a separate thread.
In order for you to accomplish what you're trying to do, here the working code:
import cv2
import numpy as np
import winsound
import threading

kernel=np.ones((5,5),np.uint8)
cap=cv2.VideoCapture(0)
fgbg=cv2.createBackgroundSubtractorMOG2()

def playSound():
    winsound.Beep(1000,2000)

while True:

    ret,frame=cap.read()
    fgmask=fgbg.apply(frame)
    fgmask=cv2.erode(fgmask,kernel,iterations=1)
    counter=np.sum(fgmask==255)

    cv2.imshow('img',fgmask)
    cv2.imshow('frame',frame)

    if counter>50:
        # Run the playSound function on a separate thread
        t = threading.Thread(target=playSound)
        t.start()

    if (cv2.waitKey(1) & 0xFF)==ord('q'):
        break

cap.release()

Hope this helps


Q:

Changing MySQL WHERE params

I have these where params, but it's not returning what is desired:
WHERE `Profiles`.`Departure1` >= '2012-04-01'
OR `Profiles`.`Departure2` >= '2012-04-01'
OR `Profiles`.`Departure3` >= '2012-04-01'
AND `Profiles`.`Departure1` <= '2012-04-04'
OR `Profiles`.`Departure2` <= '2012-04-04'
OR `Profiles`.`Departure3` <= '2012-04-04'

There are three departure date fields and I'm trying to only return entries where the date lands between the two dates.  What I have here is returning everything.  Is there a better way to do this that might actually work?

A:

Use mySQL's BETWEEN operator:
WHERE
    `Profiles`.`Departure1` BETWEEN CAST('2012-04-01' AS Date) AND CAST('2012-04-04' AS Date) OR
    `Profiles`.`Departure2` BETWEEN CAST('2012-04-01' AS Date) AND CAST('2012-04-04' AS Date) OR
    `Profiles`.`Departure3` BETWEEN CAST('2012-04-01' AS Date) AND CAST('2012-04-04' AS Date)

See the documentation:

BETWEEN - http://dev.mysql.com/doc/refman/5.0/en/comparison-operators.html#operator_between
CAST/CONVERT - http://dev.mysql.com/doc/refman/5.0/en/cast-functions.html#function_convert

A note: if this is the type of thing you're going to be doing a lot of, consider storing your dates as UNIX timestamps, using the BIGINT field type rather than a Date. That way you don't have to use CAST so much to do BETWEEN comparisons. You can use FROM_UNIXTIME (docs) to format on the way out of the db instead of monkeying around with converting every time you compare. See:

PHP's strtotime - http://php.net/manual/en/function.strtotime.php
PHP's date - http://php.net/manual/en/function.date.php
mySQL's FROM_UNIXTIME - http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_from-unixtime

A:

Use proper parenthesis:
WHERE ((`Profiles`.`Departure1` >= '2012-04-01'
OR `Profiles`.`Departure2` >= '2012-04-01'
OR `Profiles`.`Departure3` >= '2012-04-01' )
AND (`Profiles`.`Departure1` <= '2012-04-04'
OR `Profiles`.`Departure2` <= '2012-04-04'
OR `Profiles`.`Departure3` <= '2012-04-04'))


Q:

php include failing?

I have this code:
if (file_exists(CHAL_DIR . $row['filename'])) { // Check if the file exists or not.
                         if(!include('' . CHAL_DIR . $row['filename'])) { // Include the Challenge's class file.
                            echo "Include failed.";
                         } else {
                            echo "I win.";
                         }

                    } else {
                         echo "File " . CHAL_DIR . $row['filename'] . " does not exist.";
                    }

But it is not printing any errors? It seems like it just kills the php code after that include? It doesnt even print Include failed.

A:

It depends on the content of the included file: if it has an exit call or any other sort of termination, then PHP will stop there.


Q:

Which is better of the two: effects happening before rolling, or after rolling?

Plenty of systems use both types of abilities "before a participant A rolls, add bonus/effect to opposed number/roll of Participant B" or "If a participant A would succeed, add bonus/effect to opposed number/roll of participant B and re-evaluate the situation"
I have been wondering which type of ability is the better one for players to use, or are they equal when considering optimization, system mastery and probability.
I think both kinds are present in the latest 5e dnd. For example you can see within fighter's archetype, battle master superiority die maneuvers to have both kinds. This is just for referencing an example but I want to keep this system neutral.

A:

The latter is strictly better. In cases where you have limited resources involved, you can choose whether or not to use them based on the roll, i.e. how much you think you need the effect. For example, only using a bonus when the roll isn’t good enough but close, or only using a penalty when the roll succeeds but only barely—cases where the bonus or penalty actually changes the result.
Whether or not you know the target number is irrelevant—knowing it allows you to be precise in your judgment, but even if you don’t, you can usually tell when using the effect is worthwhile, or at least tell when it clearly won’t be. For example, when a natural-1 is an auto-fail or a natural-20 is an auto-success, clearly expending some resource to apply a bonus or penalty is a waste of time.
When there aren’t limited resources involved, it doesn’t matter (and should just be a passive bonus).


Q:

How do I load a java class (not a servlet) when the tomcat server starts

I need to continuously update and query a mysql database (and I don't think I need a servlet to do this, just a regular java class).  But I don't know how to call that class or run it when the servlet starts.

A:

Let that class implement ServletContextListener. Then you can do your thing in contextInitialized() method.
public class Config implements ServletContextListener {

    public void contextInitialized(ServletContextEvent event) {
        // Webapp startup.
    }

    public void contextDestroyed(ServletContextEvent event) {
        // Webapp shutdown.
    }

}

Register it in web.xml as follows to get it to run:
<listener>
    <listener-class>com.example.Config</listener-class>
</listener>

Or if you're already on Servlet 3.0, then just use @WebListener annotation on the class.


Q:

Change elements of activity_main by click from recyclerView in Kotlin

I need to change color of Button element from activity_main.xml by clicking the element in RecyclerView. The hex color value should be taken from selected item parameters.
Just because I'm new to Kotlin, do not understand how to perform it.

Here is MainActivity:
class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        doAsync {
            val json  = URL("https://api.jsonbin.io/b/5e299cea5eae2c3a26db9cdf/2").readText()
            d("daniel", "json? $json")
//            val dataList: ArrayList<String> = ArrayList()
            uiThread {
                val stations = Gson().fromJson(json, Array<Stations>::class.java).toList()
                ElementsList.apply{
                    layoutManager = LinearLayoutManager(this@MainActivity)
                    adapter = ElementsAdapter(stations)
                }
            }
        }
    }
}

Here is ElementsAdapter (recyclerView):
class ElementsAdapter(private val stations: List<Stations>) : RecyclerView.Adapter<ElementsAdapter.ViewHolder>() {

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val view = LayoutInflater.from(parent.context).inflate(R.layout.item_sample, parent, false)

        return ViewHolder(view)
    }

    override fun getItemCount() = stations.size

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        val stationItem = stations[position]
        val highlightColor = stationItem.properties.color
        val colorFilter = Color.parseColor(highlightColor)
        holder.nameStation.text = stationItem.properties.color
        holder.lineColor.setColorFilter(colorFilter, PorterDuff.Mode.SRC_ATOP)
        holder.view.setOnClickListener{
            val curValue = holder.adapterPosition
            val selectedValue = stations[curValue].name

//              something should be done here to change button's color

        }
    }

    class ViewHolder(val view: View): RecyclerView.ViewHolder(view){
        val nameStation: TextView = itemView.name_station
        val lineColor: ImageView = itemView.line_color
    }

}

A:

Follow below steps to achieve this
Step - 1: Change your ElementsAdapter's constructor to receive Activity instance like below:
class ElementsAdapter(private val context: Context, private val stations: List<Stations>) : RecyclerView.Adapter<ElementsAdapter.ViewHolder>() {

    ....

}

Step - 2: Create a callback function in MainActivity to change button's color
class MainActivity : AppCompatActivity() {

    ....

    fun updateButtonColor(hexColor: String) {

        // update button's color here
    }
}

And pass the activity instance during creation of adapter
adapter = ElementsAdapter(this@MainActivity, stations)

Step - 3: Inside onBindViewHolder's OnClickListener call the activity's updateButtonColor with appropriate HEX_COLOR
holder.view.setOnClickListener{
    val curValue = holder.adapterPosition
    val selectedValue = stations[curValue].name

    //something should be done here to change button's color

    (context as MainActivity).updateButtonColor(HEX_COLOR)
}


Q:

Change/Replace Href parameter with jquery

I have a URL parameter that I want to replace based on whether a checkbox has been checked:
<input id="acknowledge" type="checkbox" checked="checked" name="acknowledge" tabindex="">I accept

Add another institution

I want to replace p_acknowledge parameter to be p_acknowledge=N if the checkbox is not checked and p_acknowledge=Y if it is checked.
It always return p_add_institution?id=55&p_acknowledge=Y even if the checkbox is not checked.
Also, when I hover over the link, I want to have the proper URL showing up as well.
http://jsfiddle.net/u89usjnj/5
Any help would be appreciated and if anyone can explain why it the parameter is not switching to N
Thanks

A:

// Input with id acknowledge on change event
$("input#acknowledge").change(function(){

    // Fetch checkbox is checked or not
    var status = this.checked;

    // Decide what to set in href Y or N based on status
    var yorn = (status?"Y":"N");

    // Update the link using .attr
    $("#add-institution").attr("href", "p_add_institution?id=55&p_acknowledge="+yorn);
})

Play Here
FYI:

Rule of thumb is: .prop() method should be used for boolean attributes/properties and for properties which do not exist in html
  (such as window.location). All other attributes (ones you can see in
  the html) can and should continue to be manipulated with the .attr()
  method.
  (http://blog.jquery.com/2011/05/10/jquery-1-6-1-rc-1-released/)


Q:

String Var with int var

I want to have a string variable showing next to my int variable but it doesn't seem to work.
public class ThreeLittleNumbers {
    public static void main(String[] argts) {
        String as = "Number 1: ";
        String bs = "Number 2: ";
        String cs = "Number 3: ";
        int a = 1;
        int b = 3;
        int c = 5;
        String tot = "Total: ";
        System.out.println(as+a);
        System.out.println(bs+b);
        System.out.println(cs+c);
        System.out.println(tot);
        System.out.print(a+b+c);
    }
}

A:

If I understand your question, then this
System.out.println(tot);
System.out.print(a + b + c);

should be
System.out.print(tot);
System.out.println(a + b + c);

When I make the change above, I get output like you seem to be asking for -
Number 1: 1
Number 2: 3
Number 3: 5
Total: 9

Another option would be to use printf and something like
System.out.printf("%s %d%n", tot, a + b + c);


Q:

Why doesn't this block of code work?

I've mocked up some code here
var common = common || {};

(function(NAMESPACE) {

  NAMESPACE = {
    isIE: function() {
        return true;
    }
  };

  main();

})(common);

function main() {
    console.log(common.isIE());
  return 'Hello, World!';
}

I would like to understand a couple of things,
1) Why isn't this working, I guess it has something to do with how scoping is "decided" and IIFE, but not entirely sure.
2) How to make this code work?

A:

common which passed as argument named NAMESPACE needs to be extended instead of assigning new value.
So Object.assign can help here.
var common = common|| {};

(function(NAMESPACE) {

  Object.assign(NAMESPACE,{
    isIE: function() {
        return true;
    }
  });

  main();

})(common);

function main() {
    console.log(common.isIE());
  return 'Hello, World!';
}


Q:

Send event to Google Analytics using API server sided

I have a website where I send events to Google Analytics using javascript function:
ga('send', 'event', 'showphone', 'feedback', 'result');
However I also need to send some similar events from server-side using PHP. I tried this quick start tutorial: Hello Analytics API: PHP quickstart for service accounts and reporting works like a charm, but I have no idea how to send event.
Could you please show me step-by-step what I should code to send exactly same event like mentioned above.

A:

Hello Analytics API: PHP quickstart for service accounts  is not going to help you at all.    That code uses the core reporting API the core reporting API is for requesting data from Google Analytics not sending data to Google Analytics.
To send data to Google Analytics we use the Measurement Protocol. The measurement protocol is used to send information to Google analytics the JS snippet you posted also uses the measurement protocol.
You can use the measurement protocol from any language that supports HTTP post or Http Get.   That being said there is no PHP specific library for sending information to Google analytics you are going to have to format your post yourself.   A tip would be to use Validating hits to check it before you send it to Google while you are developing this.
It will probably look something like this
http://www.google-analytics.com/collect?v=1&tid=UA-XXX-Y&cid=35009a79-1a05-49d7-b876-2b884d0f825b&an=My%20Awesom%20APP&aid=com.daimto.awesom.app&av=1.0.0&aiid=come.daimto.awesom.installer &t=event&ec=list&ea=accounts&userclicked&ev=10

A:

There is a PHP library php-ga-measurement-protocol by theiconic on github which can be used to send data using Measurement Protocal.
use TheIconic\Tracking\GoogleAnalytics\Analytics;

// Instantiate the Analytics object
// optionally pass TRUE in the constructor if you want to connect using HTTPS
$analytics = new Analytics(true);

// Build the GA hit using the Analytics class methods
// they should Autocomplete if you use a PHP IDE
$analytics
    ->setProtocolVersion('1')
    ->setTrackingId('UA-26293728-11')
    ->setClientId('12345678')
    ->setDocumentPath('/mypage')
    ->setIpOverride("202.126.106.175");

// When you finish bulding the payload send a hit (such as an pageview or event)
$analytics->sendPageview();


Q:

Unable to find explicit activity class when started from fragment

I have a fragment that I'm trying to start another activity from in a button click like this:
Intent i = new Intent(getActivity(), RoundPagerActivity.class);
// put extras
startActivity(i);

The app crashes on the call to startActivity(i) with a Fatal Exception. Here's the logcat:
08-24 22:08:12.625: D/AndroidRuntime(9865): Shutting down VM
08-24 22:08:12.625: W/dalvikvm(9865): threadid=1: thread exiting with uncaught exception(group=0x40c231f8)
08-24 22:08:12.720: E/AndroidRuntime(9865): FATAL EXCEPTION: main
08-24 22:08:12.720: E/AndroidRuntime(9865): android.content.ActivityNotFoundException: Unable to find explicit activity class {com.wilk.android.tablink/com.wilk.android.tablink.RoundPagerActivity}; have you declared this activity in your AndroidManifest.xml?
08-24 22:08:12.720: E/AndroidRuntime(9865):     at android.app.Instrumentation.checkStartActivityResult(Instrumentation.java:1511)
08-24 22:08:12.720: E/AndroidRuntime(9865):     at android.app.Instrumentation.execStartActivity(Instrumentation.java:1387)
08-24 22:08:12.720: E/AndroidRuntime(9865):     at android.app.Activity.startActivityForResult(Activity.java:3190)
08-24 22:08:12.720: E/AndroidRuntime(9865):     at android.support.v4.app.FragmentActivity.startActivityFromFragment(FragmentActivity.java:826)
08-24 22:08:12.720: E/AndroidRuntime(9865):     at android.support.v4.app.Fragment.startActivity(Fragment.java:838)
08-24 22:08:12.720: E/AndroidRuntime(9865):     at com.wilk.android.tablink.RoundListFragment.onListItemClick(RoundListFragment.java:94)
08-24 22:08:12.720: E/AndroidRuntime(9865):     at android.support.v4.app.ListFragment$2.onItemClick(ListFragment.java:58)
08-24 22:08:12.720: E/AndroidRuntime(9865):     at android.widget.AdapterView.performItemClick(AdapterView.java:292)
08-24 22:08:12.720: E/AndroidRuntime(9865):     at android.widget.AbsListView.performItemClick(AbsListView.java:1175)
08-24 22:08:12.720: E/AndroidRuntime(9865):     at android.widget.AbsListView$PerformClick.run(AbsListView.java:2703)
08-24 22:08:12.720: E/AndroidRuntime(9865):     at android.widget.AbsListView$1.run(AbsListView.java:3456)
08-24 22:08:12.720: E/AndroidRuntime(9865):     at android.os.Handler.handleCallback(Handler.java:605)
08-24 22:08:12.720: E/AndroidRuntime(9865):     at android.os.Handler.dispatchMessage(Handler.java:92)
08-24 22:08:12.720: E/AndroidRuntime(9865):     at android.os.Looper.loop(Looper.java:137)
08-24 22:08:12.720: E/AndroidRuntime(9865):     at android.app.ActivityThread.main(ActivityThread.java:4507)
08-24 22:08:12.720: E/AndroidRuntime(9865):     at java.lang.reflect.Method.invokeNative(Native Method)
08-24 22:08:12.720: E/AndroidRuntime(9865):     at java.lang.reflect.Method.invoke(Method.java:511)
08-24 22:08:12.720: E/AndroidRuntime(9865):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:790)
    08-24 22:08:12.720: E/AndroidRuntime(9865):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:557)
    08-24 22:08:12.720: E/AndroidRuntime(9865):     at dalvik.system.NativeStart.main(Native Method)

Here's my manifest file:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.wilk.android.tablink"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="17" />

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@android:style/Theme.Holo" >

        <!-- other activities -->

        <!-- activity that calls the pager activity -->
        <activity
            android:name="com.wilk.android.tablink.RoundListActivity"
            android:label="@string/app_name" >

        </activity>

        <!-- activity that is called -->
        <activity
            android:name="com.wilk.android.tablink.RoundPagerAcivity"
            android:label="@string/app_name" >
            <meta-data
                android:name="android.support.PARENT_ACTIVITY"
                android:value="com.wilk.android.tablink.RoundListActivity" />

        </activity>

    </application>

</manifest>

The odd thing is I have another app that does this the same exact way w/o issue.
I've looked at other questions here and am pretty sure I've exhausted those choices, at least the ones that appeared to apply. I've tried to set breaks points in the new activity as well but none are hit. Can anyone see something I've newbly overlooked?

A:

It's misspelled in your manifest. You have: android:name="com.wilk.android.tablink.RoundPagerAcivity" It should be android:name="com.wilk.android.tablink.RoundPagerActivity".
Also, I don't know if it matters, but in my application I also have an attribute on the "detail" activity like this:
    <activity
        android:name="com.wilk.android.tablink.RoundPagerActivity"
        android:label="@string/app_name"
        android:parentActivityName="com.wilk.android.tablink.RoundListActivity">
        <meta-data
            android:name="android.support.PARENT_ACTIVITY"
            android:value="com.wilk.android.tablink.RoundListActivity" />
    </activity>


Q:

What should I check if my chainsaw fails to start?

My chainsaw stopped working and I've got a tree that fell and needs cut up.  Does anybody have any idea what I can do to get my chainsaw started? I've done a bit of stuff on cars so I'm willing to try to take it all apart, though part of me is tempted to just drop $200 for a new one.  Still, an afternoon tinkering isn't going to cost me much.  Here is what I tried:
So Far:

check gas in tank Add Star Tron or Stabil Fuel Additive
check for spark with screwdriver.
Check Air Filter / intake for clogs
Check Fuel Filter / to cylinder.
Check linkages for Start/Stop and choke levers are operating
Clean Magneto of Rust, ensure it holds a screwdriver up.
Clean carburetor and fuel lines, especially if it may contain old fuel.

It's a husqavarna about 5 years old.  I ran it hard 3 years ago when I had another tree topple but it made it through, though I may have vapor locked it once.  It's also not been running since I failed to start it last year and it's been sitting there.  With the spring I need to get on it before the weeds come.

A:

Most two cycle engines are sensitive to the newer gasoline blends that can contain up to 10% ethanol. Get a small bottle of fuel additive for small engines and add a small amount of that into your gas tank. It should run a lot better after that. I had a similar problem with my leaf blower last year and this did the trick.

Star Tron is a much better brand than Stabil by the way.
If you are still having trouble and you have already checked the spark plugs, sometimes the magneto can have a buildup of rust on the surface that prevents it from generating enough current to sustain repeated firing of the spark plug as the engine turns.  Take apart the pull start mechanism on the chainsaw until the magneto is exposed, and take a fine grit sandpaper to it to rub off all the rust that has formed on it by sitting all these years.  To clarify the magneto is the part that is magnetic, it should grab your screwdriver.


Q:

Click on the screen or any element to execute a function

How can I reverse a function so when I click on an input it transforms the y value to -100% and when i click elsewhere on the screen or another element it reverse so the value returns to 0%.
I want to do it in js not in css

let movingName = document.querySelectorAll('.span-name');
let input = document.getElementsByTagName('input')

input[0].onclick = function() {
  movingName[0].style.transform = "translateY(-100%)";
}
.span-name {
  position: relative;
  color: black;
  bottom: 34px;
  left: 10px;
  font-size: 18px;
  padding: 2px;
  z-index: 1;
  pointer-events: none;
  display: block;
  width: fit-content;
  transition: 500ms;
}
<input type="email" name="email_config" required>
Email Configuration

A:

Try using the body to get that click event and filter the events basis the target.

let movingName = document.querySelectorAll('.span-name');
let input = document.getElementsByTagName('input')

document.getElementsByTagName('body')[0].onclick = function(e) {
    var tagName = e.target.tagName;
    if (tagName !== 'INPUT') {
        movingName[0].style.transform = "translateY(100%)";
    }
}

input[0].onclick = function() {
  movingName[0].style.transform = "translateY(-100%)";
}
.span-name {
  position: relative;
  color: black;
  bottom: 34px;
  left: 10px;
  font-size: 18px;
  padding: 2px;
  z-index: 1;
  pointer-events: none;
  display: block;
  width: fit-content;
  transition: 500ms;
}

    <input type="email" name="email_config" required>
    Email Configuration


Q:

A field of type "String" does not appear in the result (json) serialization of the vraptor controller

A field of type "String" does not appear in the result of the serialization controller
result.use(Results.json()).indented().from(list).serialize();

Some fields appear, and another not appear when null, the field I want is to type "String" and implemented the "get" and "sets" and this always filled
PS: I am using vraptor framework

A:

I solved using the "include":
result.use(Results.json()).indented().from(list)
                .include("codigoComposto").serialize();


Q:

Additional Line Spacing Issue on Custom Font

I use a custom font / custom Typeface for a TextView on my app. The TextView displays a paragraph of a text, but with the additional line spacing from the font itself it's rather irritating. So there's like a quite gap between one line with another on the paragraph. Can anybody know how to reduce the spacing through XML or programmatically?

A:

You can use the lineSpacingMultiplier attribute of your TextView to reduce/increase the spacing. Like this:
<TextView
    android:lineSpacingMultiplier="0.6"
    ...
    />


Q:

HTML5 Canvas line draw between two clicks, live

You might see that this is my first post so excuse any beginner mistakes using stackoverflow.
I'm currently working on a floor plan web app where you can simply draw lines to create the floor plan of your housing.
The wanted effect is:
When clicking once the user draws a temporary line where the start point X is the clicked point and the target point Z is the mouse which the user can move around.
I'm currently using canvas for this effect but somehow the line is invisible or just not there. I've tried some debugging which brought me here.
This is the current code:
    function drawLineXY(fromXY, toXY) {
    if(!lineElem) {
        lineElem = document.createElement('canvas');
        lineElem.style.position = "absolute";
        lineElem.style.zIndex = 100;
        document.body.appendChild(lineElem);
        console.log("Added line element");

    }
    var leftpoint, rightpoint;
    if(fromXY.x < toXY.x) {
      leftpoint = fromXY;
      rightpoint = toXY;
    } else {
      leftpoint = toXY;
      rightpoint = fromXY;
    }

    var lineWidthPix = 4;
    var gutterPix = 0;
    var origin = {x:leftpoint.x-gutterPix,
                  y:Math.min(fromXY.y, toXY.y)-gutterPix};
    lineElem.width = "1000px";
    lineElem.height = "1000px";
    lineElem.style.left = "0px";
    lineElem.style.top = "0px";
    var ctx = lineElem.getContext('2d');
    // Use the identity matrix while clearing the canvas
    ctx.save();
    ctx.setTransform(1, 0, 0, 1, 0, 0);
    ctx.clearRect(0, 0, lineElem.width, lineElem.height);
    ctx.restore();
    ctx.lineWidth = 4;
    ctx.strokeStyle = '#09f';
    ctx.beginPath();
    ctx.moveTo(fromXY.x - origin.x, fromXY.y - origin.y);
    ctx.lineTo(toXY.x - origin.x, toXY.y - origin.y);
    ctx.stroke();
    console.log("drawing line..");
}

    function moveHandler(evt) {
    var startCentre, startBounds;
    var targets = [];

    if(clicked.length === 2) {
      targets = clicked;
    } else if(clicked.length === 1) {
      targets.push(clicked[0]);
      if(typeof hoverElement !== 'undefined') {
        targets.push(hoverElement);
      }
    }

    if(targets.length == 2) {
        var start = {x:targets[0], y:targets[0]};
        var end = {x:targets[1], y:targets[1]};
        drawLineXY(start, end);

    } else if(targets.length == 1) {
        var start = {x:targets[0], y:targets[0]};

        drawLineXY(start, {x:evt.clientX, y:evt.clientY});
    }
};

    function clickHandler(e) {
    if(clicked.length == 2) {
        clicked = [];
    }
    clicked.push(e.target);
};

document.onclick = clickHandler;
document.onmousemove = moveHandler;

As you can see in drawLineXY's last line I've made a debug console log "drawing line"
This works as I move the mouse around. Like it should.
But there is no line, does someone has help?
PS: #canvas is specified in style.css.

A:

I created a very basic example of probably what you are trying to achieve:

let c, ctx, fromXY, toXY;

window.onload = function(){
  document.onclick = clickHandler;
  document.onmousemove = moveHandler;
  c = document.getElementById("myCanvas");
  ctx = c.getContext("2d");
  reset();
}

function draw(){
  clear();
  ctx.beginPath();
  ctx.moveTo(fromXY.x, fromXY.y);
  ctx.lineTo(toXY.x, toXY.y);
  ctx.stroke();
  ctx.closePath();
}

function clear(){
  ctx.clearRect(0, 0, c.width, c.height);
}

function reset() {
  fromXY = {};
  toXY = {};
}

function moveHandler(e) {
  if(typeof fromXY.x !== "undefined"){
    toXY.x = e.clientX;
    toXY.y = e.clientY;
    draw();
  }
}

function clickHandler(e) {
  if(typeof fromXY.x === "undefined"){
    fromXY.x = e.clientX;
    fromXY.y = e.clientY;
  }else{
    reset();
  }
}
<canvas id="myCanvas" height="500" width="500"></canvas>

You can set line options in the draw() function, and if you want the lines to persist, you would save their fromXY and toXY in an array and redraw them as well.


Q:

Why wasn't Fiona in human form in Shrek: Forever After?

Why wasn't Fiona in human form? Rumpelstiltskin had the contract signed by Shrek costing his existence. Shrek didn't exist, which means that Fiona was always a human (unless at night when the curse took place) when she was imprisoned in the castle. However she is seen as a female warrior ogre in the tribe/clan.
Regarding that:

She escaped herself so she couldn't have a true love to kiss her (so as to become an ogre).
She did not turn human when it was daylight when Rumpelstiltskin was defeated.

A:

I believe that in Shrek: Forever After, Fiona wasn't ever seen during the day.  Shrek spent only a single day in that reality, starting at sunrise.  After the next sunrise, he would disappear.
He didn't encounter Fiona until after dusk, when the curse would transform her into an ogre.
At the end of the movie, he hadn't faded away (and thus the sun hadn't risen) completely before the contract was nullified.  Had the sun fully risen (and thus triggered her change to human) Shrek would have already faded entirely away.
More to the point, Rumplestiltskin, who adheres strictly to the letter of his word, promises to let "all ogres" go free in return for Shrek's surrender.  He specifically does not release Fiona, as she isn't "all ogre".  He points out that she's only half-ogre, being human during the day.
Ergo, the curse was still in place during this movie, and would have been broken at the climax, except that the entire world was invalidated simultaneously.


Q:

splitting up of xml file using java

< ?xml version="1.0" encoding="utf-8"? >
   < rss xmlns:media="http://search.yahoo.com/mrss/" xmlns:ynews="http://news.yahoo.com/rss/" version="2.0" >  < channel >
< title>Cricket News Headlines | Cricket News - Yahoo! News India< /title>
< link>http://in.news.yahoo.com/cricket/< /link>
< description>Check out the latest Cricket news headlines from Yahoo! News India. Find top Cricket stories and in-depth coverage of
  Cricket news from India and around the world.< /description>
< language>en-IN< /language>
< copyright>Copyright (c) 2011 Yahoo! Inc. All rights reserved< /copyright>
< pubDate>2011-04-06T15:30:02+05:30< /pubDate>
< ttl>5< /ttl>
< image>
< title>Cricket News Headlines | Cricket News - Yahoo! News India< /title>
< link>http://in.news.yahoo.com/cricket/< /link>
< url>http://l.yimg.com/os/mit/media/m/index/img/Yahoo_logo_en-
  IN.gif< /url>
< /image>
  < item>< title>Hectic schedule will drain players, says Dhoni< /title>
< description>Chennai, Apr 6 (PTI) ...< /description>
< link>http://in.news.yahoo.com/hectic-schedule-drain-players-says-dhoni-20110406-023100-889.html< /link>
< pubDate>2011-04-06T09:31:00Z< /pubDate>
< source>PTI< /source>
< guid isPermaLink="false">/hectic-schedule-drain-players-says-dhoni-20110406-023100-889.html< /guid>
< /item>
< item>
< title>India, Pakistan trade secretaries to meet on April 27-28< /title>
< description>New Delhi, Apr 6 (PTI)  ...< /description>
< link>http://in.news.yahoo.com/india-pakistan-trade-secretaries-meet-april-27-28-20110406-023100-140.html< /link>

I want only the HEADLINES  from this XML, that is only between < item>< title>MESSAGES< /title> tags.  Also have to print the message one after other continuously. how can i do this.

A:

I would use the javax.xml.xpath APIs that are included in Java SE 5 for this.
import java.io.FileReader;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathFactory;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;

public class Demo {

    public static void main(String[] args) throws Exception {
        XPath xPath = XPathFactory.newInstance().newXPath();

        FileReader reader = new FileReader("input.xml");
        InputSource xml = new InputSource(reader);
        NodeList titleNodes = (NodeList) xPath.evaluate("//item/title", xml, XPathConstants.NODESET);

        for(int x=0; x<titleNodes.getLength(); x++) {
            System.out.println(titleNodes.item(x).getTextContent());
        }
    }

}