text:
Q: Restlet parsing json request I am trying to make a simple observatory app for books and stuff using restlet.
Currently, I've managed some simple GETs here and there but i have a problem with POST.
To be precise, I can't access the entity's body. Here is the sample request, through Postman
{
    "isbn": "12345678909876",
    "title": "test",
    "genre": "Encyclopedias",
    "publisher": "Tzoman",
    "release": "2011-01-01",
    "language": "Foreign",
    "pages": 666,
    "cover": "Hard",
    "withdrawn": true,
    "tags": "sapiente"
}

And here is the code:
@Override
protected Representation post(Representation entity) throws ResourceException {

    if (entity.getMediaType().isCompatible(MediaType.APPLICATION_JSON)) {
        //Create a new restlet form
        Form form = new Form(entity);
        System.out.println("Form start");
        System.out.println(form);
        System.out.println(form.getClass().getSimpleName());
        System.out.println("Form end");

        //Read the parameters
        String isbn = form.getFirstValue("isbn");
        System.out.println(isbn);

        try {
            System.out.println("The entity:" + entity);
            JSONObject json = new JSONObject(entity);
            String isbn2 = json.getString("isbn");
            System.out.println(isbn2);
        } catch (JSONException e){
            e.printStackTrace();
        }
    }

The output is varied: Using the first approach, I've managed to somewhat access the request with the following output:
[[
{
    <Object here>
}=null
]]

The second approach aims to parse the request as a JSON Object but the reply i get is [application/json].
I have configured Postman to send json in headers and after an exhausting amount of research, I'm stuck. If anyone can provide me with some hints or research material, I would be indebted!
Thanks for your time!
EDIT1: This is the entire class with the imported packages for reference
package org.mypackage;

import org.mypackage.config.Configuration;
import org.mypackage.data.DataAccess;
import org.mypackage.data.Limits;
import org.mypackage.data.model.Book;
import org.json.JSONException;
import org.json.JSONObject;
import org.restlet.data.Form;
import org.restlet.data.MediaType;
import org.restlet.representation.Representation;
import org.restlet.resource.ResourceException;
import org.restlet.resource.ServerResource;

public class BooksResource extends ServerResource {

    private final DataAccess dataAccess = Configuration.getInstance().getDataAccess();

    String start;
    String count;
    String sort;
    String status;

    @Override
    protected Representation get() throws ResourceException {
        start = getQueryValue("start") != null ? getQueryValue("start") : "0";
        count = getQueryValue("count") != null ? getQueryValue("count") : String.valueOf(Limits.DEFAULT_COUNT);

        if(getQueryValue("sort") != null && Limits.SORTING_OPTIONS_LIST.contains(getQueryValue("sort"))) {
            sort = getQueryValue("sort");
            System.out.println(sort);
        } else {
            sort = String.valueOf(Limits.SORTING_OPTIONS_LIST.get(0));
            System.out.println(sort);
        }

        if(getQueryValue("status") != null && Limits.BOOK_STATUS_LIST.contains(getQueryValue("status"))) {
            status = getQueryValue("status");
            System.out.println(status);
        } else {
            status = String.valueOf(Limits.BOOK_STATUS_LIST.get(0));
            System.out.println(status);
        }

        return new JsonMapRepresentation(dataAccess.getProducts(
                new Limits(
                        Integer.parseInt(start),
                        Integer.parseInt(count)
                ),
                sort,
                status
        ));
    }

    @Override
    protected Representation post(Representation entity) throws ResourceException {

        if (entity.getMediaType().isCompatible(MediaType.APPLICATION_JSON)) {
            //Create a new restlet form
            Form form = new Form(entity);
            System.out.println("Form start");
            System.out.println(form);
            System.out.println(form.getClass().getSimpleName());
            System.out.println("Form end");

            //Read the parameters
            String isbn = form.getFirstValue("isbn");
            System.out.println(isbn);

            try {
                System.out.println("The entity:" + entity);
                JSONObject json = new JSONObject(entity);
                String isbn2 = json.getString("isbn");
                System.out.println(isbn2);
            } catch (JSONException e){
                e.printStackTrace();
            }
        }

/*        String title = form.getFirstValue("title");
        String genre = form.getFirstValue("genre");
        String publisher = form.getFirstValue("publisher");
        String release = form.getFirstValue("release");
        String language = form.getFirstValue("language");
        Integer pages = Integer.parseInt(form.getFirstValue("pages"));
        String cover = form.getFirstValue("cover");

        boolean withdrawn = Boolean.valueOf(form.getFirstValue("withdrawn"));
        String tags = form.getFirstValue("tags");*/

        //validate the values (in the general case)
        //...

        /*Book book = dataAccess.addProduct(isbn, title, genre, publisher, release, language, pages, cover, withdrawn, tags);*/

        /*return new JsonBookRepresentation(book);*/
        return new JsonBookRepresentation(
                new Book(
                     "isbn": "12345678909876",
                     "title": "test",
                     "genre": "Encyclopedias",
                     "publisher": "Tzoman",
                     "release": "2011-01-01",
                     "language": "Foreign",
                     "pages": 666,
                     "cover": "Hard",
                     "withdrawn": true,
                     "tags": "sapiente"
                )
        );
    }
}

A: You can accept a JsonRepresentation entity (docs).
Than you'll simply have to call
final JSONObject yourObject = entity.getJsonObject();

Your endpoint should signal it accepts an application/json media type.
You can specify that via the annotation @Post("json")

You can also accept a Java class.
class MyObject {
    public String isbn;
    public String title;
    public String genre;
    public String publisher;
    public String release;
    public String language;
    public int pages;
    public String cover;
    public boolean withdrawn;
    public String tags;
}

And then
@Post
public void accept(final MyObject myObject) { ... }

Ok, you haven't got the Restlet JSON extension.
<dependency>
    <groupId>org.restlet.jee</groupId>
    <artifactId>org.restlet.ext.json</artifactId>
    <version>2.3.12</version>
</dependency>


text:
Q: LINQ to xml with nested tags I have an xml doc defined as
 <Body>Stuff stuff stuff <FormatStuff> alsdkfafkafkaf </FormatStuff>  </Body>

Now, this is apparently valid xml (which I wouldn't have guessed). I want to return just the information in Body, and a separate XElement for <FormatStuff>, so it would look like
Stuff, Stuff, Stuff
alsdkfafkafkaf
the .Value of the Body xelement obviously returns everything. Thanks for any help.

A: Why wouldn't you have guessed that this was valid XML? It's not really clear what you want, to be honest. If you just want to get the text nodes for the Body element, you can use:
var textNodes = body.DescendantNodes()
                    .OfType<XText>()

If you want to get the value of all those nodes concatenated together, you'd do something like:
var text = string.Join("", body.DescendantNodes()
                               .OfType<XText>()
                               .Select(x => x.Value)
                               .ToArray());

(You could use the node type, but then you just have an IEnumerable<XNode> which isn't as useful, as I found out when trying to compile the above :)
You can get the FormatStuff element with body.Element("FormatStuff").

redpajama_set_name: RedPajamaStackExchange


text:
Q: loading a brands -> categories -> products hiearchy efficiently I have a system which has 3 objects - Brands, Categories and Products. I am using Nhibernate as my ORM.
A product is assigned to one brand, and to multiple Categories.  For an ecommerce website we are building, we need to show the brands menu on the left.  For each brand, the idea is to show the categories which ONLY have a product, of that brand.
For example, if we have 3 categories - Camping, Hiking and Climbing, and 3 brands A,B,C.  If brand A has no products which are under the category 'Climbing', the category wouldn't show.
The problem is how to do this efficiently.  For each brand, it requires to go through each category, and check if there is at least one product under that category, of the current brand.  With 200 categories, and 20 brands, this would result in approximately 2000 database calls at the worst case.
The other option would be to load all products in memory, but if there are a lot of products (20,000 +), it would be slow also this way.
Any ideas / optimizations I could do, to make it load much faster?

A: you can use QueryOver to get, for each brand- its categories and the count of products in that category. something to the effect of (I currently don't have access to my references, so this may not be 100% accurate, but you'll be able to get my meaning):
QueryOver<Brand>()
   .JoinQueryOver(b => b.Categories)
   .Select(c => c.CategoryId) //or whatever else you want to select
    .SelectCount(c=> c.Products);

another option can be to define a formula property for the Category class that would return the count of products associated with that Category.


text:
Q: itextsharp set bookmarks to fit page I'm starting out with itextsharp and I've managed to answer all my questions but one:
How are bookmarks set to open to the fitpage zoom/view?
I apologize if this has already been answered elsewhere.
Here's my code if it helps.
//edit: Below is my working code. It has been modified using Bruno's example.
 Public Sub MergePDFFiles(FileList As System.Collections.Generic.List(Of ModifiedItemForList), pdfName As String, pageCount As Integer)

    Dim reader As PdfReader
    Dim mergedPdf As Byte() = Nothing
    Dim n As Integer
    Dim page As Integer
    Dim par As Paragraph
    Dim pageMode As Integer
    Dim pageLayout As Integer
    Dim pageZoom As PdfDestination
    Dim outlineZoom As PdfDestination
    Dim pdfAction As PdfAction
    Dim root As PdfOutline
    Dim pdfOutline As PdfOutline

    Using ms As New MemoryStream()

        Using document As New Document()

            Using copy As New PdfCopy(document, ms)
                'Dim copy As New PdfCopy(document, ms)
                document.Open()
                root = copy.RootOutline
                pageMode = copy.PageModeUseOutlines
                pageLayout = copy.PageLayoutSinglePage
                pageZoom = New PdfDestination(PdfDestination.FIT)
                copy.ViewerPreferences = pageMode
                pdfAction = pdfAction.GotoLocalPage(1, pageZoom, copy)
                copy.SetOpenAction(pdfAction)

                ' For Each FilePath As KeyValuePair(Of String, String) In FileList  ' .Count - 1
                For i As Integer = 0 To pageCount - 1
                    ' FilePath As KeyValuePair(Of String, String)
                    If File.Exists(FileList.Item(i).Value) Then
                        reader = New PdfReader(FileList.Item(i).Value)
                        ' loop over the pages in that document
                        n = reader.NumberOfPages
                        page = 0
                        par = New Paragraph(FileList.Item(i).Key)
                        Debug.Print("FileList.Item(i).Key = " & FileList.Item(i).Key)
                        outlineZoom = New PdfDestination(PdfDestination.FIT)
                        pdfOutline = New PdfOutline(root, outlineZoom, par)

                        While page < n
                            copy.AddPage(copy.GetImportedPage(reader, System.Threading.Interlocked.Increment(page)))
                        End While

                    End If

                Next

            End Using

        End Using

        mergedPdf = ms.ToArray()

    End Using

    File.WriteAllBytes(pdfName, mergedPdf)

End Sub

Your input will be greatly appreciated,
Corbin de Bruin

A: If you want custom bookmarks, please don't use Chapter and Section, use PdfOutline instead. This is (of course) documented in chapter 7 of my book. If you need the C# port of the examples, take a look at the code examples for chapter 7, specifically CreateOutlineTree.cs, where instead of using PdfDestination.FITH (for Fit Horizontally) and a Y position, you just create a destination with PdfDestination.FIT (and no extra parameter):
new PdfOutline(root, new PdfDestination(PdfDestination.FIT), title, true);


text:
Q: UI Elements and IBOutlet Variables in Storyboard when instantiated recursively? What I've done so far:
I am using xcode 4.2.  I created a UITableView which contains an ImageView.  The UITableView uses the class MyTableViewController which has the files MyTableViewController.m/.h. I created an IBOutlet variable called _bgimageview. Then in the storyboard, in the connections inspector, i connected the ImageView to this _bgimageview variable.  In my viewDidLoad function of MyTableviewController.m, I set a backgound image to the _bgimageview.    When I run the simulator, click on a few tabs to get to MyTableViewController, and hten I see the background image.  Things work great so far.
The problem
I've also successfully built a recursive tree, but the problem is that I lose the backgorund image after the root level of the tree.  I think i know why, but don't know how to fix.  I instantiate a new MyTableViewController on each row-click like so:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
        MyTableViewController *childView = [[MyTableViewController alloc] init];
        childView._menu = children; // an NSDictionary of children
        [self.navigationController pushViewController:childView animated:YES];
}

As mentioned previously, I populate the IBOutlet variable for the backgruond image in the viewDidLoad function.  But that IBOutlet variable is linked up to the ImageView via the Storyboard connection.  In tree levels below the root level, I programmatically instantiate new MyTableViewControllers and thus, I'm probably losing the relationship between the IBOutlet variable for the backgund image and the actual UIImageView mentioned in the Storyboard.
Can someone re-assure me this is the problem and how I might go about adding a backgorund image to MyTableViewController when used in a hierarchical manner?

A: MyTableViewController *childView = [[MyTableViewController alloc] init];

This line creates a new instance of your view controller without reference to the storyboard. It will therefore not be connecting any of your outlets - the table view will probably be OK, since that is created and connected by default, but anything else will not be connected.
You can confirm this by logging your image view outlet in viewDidLoad - it will be nil.
You should create a recursive stack by dragging a segue from the row of the table down to the view controller object of the same view controller:

As Lvsti points out in comments, you can pass any parameters across in prepareForSegue:sender:


text:
Q: CentOS and fontconfig: Cannot load default config file I'm getting following error when using imagick:
Fontconfig error: Cannot load default config file

My script is working but i would like to fix this (is filling up log file).
OS is:
# cat /etc/redhat-release
CentOS release 5.10 (Final)

I was looking trough internet little bit and this is causing problem:
access("/etc/fonts/fonts.conf", R_OK)   = -1 ENOENT (No such file or directory)

Folder exists:
# ls /etc/fonts/ -all
total 64
drwxr-xr-x  4 root root  4096 Jul  9  2010 ./
drwxr-xr-x 86 root root 12288 Jan 13 00:48 ../
drwxr-xr-x  2 root root  4096 Jan  3  2012 conf.avail/
drwxr-xr-x  2 root root  4096 Apr 14  2013 conf.d/
-rw-r--r--  1 root root  5239 Jan 12  2008 fonts.conf
-rw-r--r--  1 root root  6907 Jan 12  2008 fonts.dtd

But i see only this folder via root account, other account under with script is run doesn't see this folder. Permissions looks fine for me, but not so experienced with linux.
Account under with script is run is created with WHM.
Please help :)

A: I manage to solve my problem. chroot was making trouble.
I need to:

*

*log with root account

*find jailed environment of account on with i run script (in my case /home/virtfs/[username])

*to create folder where i will mount real stuff mkdir /home/virtfs/[username]/etc/fonts

*to mount /etc/fonts to this folder: mount --bind /etc/fonts /home/virtfs/[username]/etc/fonts

A: Posting an answer for CentOS 7 in 2021:
yum install fontconfig

More info here:
https://centos.pkgs.org/7/centos-x86_64/fontconfig-2.13.0-4.3.el7.x86_64.rpm.html


text:
Q: How To Set a Primary Key On a View Using ROW_NUMBER()? I use SQL Server 2008 and Entity Framework for an app I work on.
I've set primary keys on all tables in SQL Server, since EF requires it, but I have a problem with one view. Since it doesn't have primary key, I've used ROW_NUMBER() function to get unique row identifiers. I've expected for that column to be defined as NOT NULL, so I could use it as primary key in EF, but instead, the column is nullable.
Here is my  view:
CREATE VIEW [dbo].[vw_Action]
AS

SELECT *, ROW_NUMBER() OVER(ORDER BY ActionDate DESC) AS RowID
FROM
(
   SELECT User1ID AS UserID, NULL AS FriendID, Object1ID, Object2ID, ActionType,    ActionDate
   FROM vw_ActionBase
   WHERE ActionType = 1
   GROUP BY User1ID, Object1ID, Object2ID, ActionType, ActionDate

   UNION

   SELECT User1ID AS UserID, NULL AS FriendID, Object1ID, Object2ID, ActionType,   ActionDate
   FROM vw_ActionBase
   WHERE ActionType = 2
   GROUP BY User1ID, Object1ID, Object2ID, ActionType, ActionDate

   UNION

   SELECT User1ID AS UserID, NULL AS FriendID, Object1ID, Object2ID, ActionType, ActionDate
   FROM vw_ActionBase
   WHERE ActionType = 3
   GROUP BY User1ID, Object1ID, Object2ID, ActionType, Object1ID, ActionDate

   )x

So, my question is how to set ROWID column as NOT NULL, so I could use it as primary key in EF.
Thanks in advance!


text:
Q: The point $c$ from mean value theorem The mean value theorem says that

Let $a<b$ be real numbers. If $f:[a,b]\rightarrow\mathbb{R}$ is continuous on the closed interval $[a,b]$ and differentiable on open interval $(a,b)$, then
there exists $c\in (a,b)$ such that
\begin{align*}
         f(b)-f(a)=f'(c) (b-a)
       \end{align*}

My question/answer: Suppose now that $f$ is differentiable on $[a,b]$. Can the point $c$ be an endpoint of the interval $[a,b]$? Since the mean value theorem is a corollary of Rolle's theorem, it follows that $c$ cannot be an endpoint of the interval $[a,b]$. Otherwise, the function $f$ would be constant. Am I right? Does exist a nonconstant function such that $c$ be an endpoint of the interval $[a,b]$?

A: Well, you can consider the function $y=x$ restricted on $[0,1]$.


text:
Q: Java Generating numbers How would I generate a number between 0.00 and 100? Trying to find out how but I cant get it to work.
Prefer to have a function and then that I can call it like 'getRandom(0.00, 100)'

A: There's a Random class. Googling helps...
Googling "java random" spawns the best result as the first. The JavaDoc reference.
So try, int rand = new Random().nextInt(101). That will generate a random number from 0 to 101 EXCLUSIVE. So it will generate a random number from 0 to 100.
EDIT: as a comment pointed out, I was incorrect, it goes from 0 to 100 inclusive. An easy off-by-one mistake.

A: You can use below utility class and call getRandom(int, int) method using  GenerateRandomNumber.getRandom(0, 100)
Code Snippet:
package com.test;

import java.util.Random;

public class GenerateRandomNumber {
    public static void main(String[] args) {
        int randomNumberBetween1To100 = getRandom(0,  100);
        System.out.println("Random number between 1 to 100 is: " + randomNumberBetween1To100);
    }
    public static int getRandom(int minNumber, int maxNumber) {
        Random rand = new Random();
        int randomNum = rand.nextInt(maxNumber - minNumber);
        return randomNum;
    }
}


text:
Q: How to calculate image histogram without normalizing data in Matlab I have an image I which pixel intensities fall within the range of 0-1. I can calculate the image histogram by normalizing it but I found the curves is not exactly the same as the histogram of raw data. This will cause some issue for the later peaks finding process(See attached two images).

My question is in Matlab, is there any way I can plot the image histogram without normalization the data so that I can keep the curve shape unchanged? This will benefit for those raw images when their pixel intensities are not within 0-1 ranges. Currently, I cannot calculate their histogram if I don't normalize the data.
The Matlab code for normalization and histogram calculation is attached. Any suggestion will be appreciated!
h = imhist(mat2gray(I));

A: Documentation of imhist tells us that the function checks the data type of the input and scale the values accordingly. Therefore, without testing with your attached data, this may work:
h = imhist(uint8(I));

An alternatively you may scale the integer-representation to floating-representation, by either using argument of mat2gray
h = imhist(mat2gray(I, [0,255]));

or just divide it.
h = imhist(I/255);

A: The imhist answer in this thread describing normalizing or casting is completely correctly. Alternatively, you could use the histogram function in MATLAB which will work with unnormalized floating point data:
A = 255*rand(500,500);
histogram(A);


text:
Q: R: Generating dynamic plots from dynamically-generated input fields in Shiny I'm working on a shiny app where an arbitrary number of numericInput fields are dynamically generated any time a numericInput field that appears on page load is updated. The user then can assigns values to these fields and push a button to produce a plot that is a function of those values.
With the help from several posts, I've gotten part of the way there. See the below, where I try to let users specify a number of parameters (n_params), which should then create that number of numericInput fields (param_fields). Since the values from those fields should appear in input, I then try to extract the values users provide into a vector and summarize them with a histogram.
What is confusing me is why I am receiving an error that argument "value" is missing, with no default" when I run the app and why the plot is not appearing - it seems like the values aren't being saved in the input object, but I'm not sure why.
library(shiny)
library(shinyWidgets)
library(purrr)

ui <- fluidPage(

  titlePanel("Title"),
  fluidRow(

    column("",
           width = 10, offset = 1,
           tags$h3("Filler"),

           panel(
             numericInput("n_params","How many fields?", min = 2, max = 100, value = 3),
             uiOutput("param_fields"),
             numericInput("n_sims","How many simulations?", min = 0, max = 100000, value = 10000),
             actionButton("sampling", "Sample from this distribution!")
           ),

           tags$h3("Plotted results!"),
           plotOutput("plotted")
  )
)
)

# Define server logic
server <- function(input, output) {

  # Dynamically create a set of numeric input fields based on the
  # number of parameters specified (fancy math symbols needed, ignore mathjax)
  dynamic_list_of_numeric_fields <- reactive({
    n_params <- req(input$n_params)
    purrr::map(1:n_params,
               ~numericInput(paste0("alpha",.),
                             withMathJax(paste0("\\(\\alpha_{", . ,"}\\)"))))

  })

  # Render the parameter fields for user-input of values
  output$param_fields <- renderUI({
    div(
      req(dynamic_list_of_numeric_fields())
    )
  })

  # Create plot updated any time sampling button is pushed
  plots <- eventReactive(input$sampling, {

    # Get the user-input parameter values
    n_params <- req(input$n_params)
    param_ids <- paste0("alpha", 1:n_params)
    param_vals <- input[[param_ids]]

    # Histogram
    hist(param_vals)
  })

  output$plot <- renderPlot({
    plots()
  })
}

shinyApp(ui = ui, server = server)

A: As noted in the comments by @guasi the issue was that a numericInput was missing a default value. Upon supplying this value, it also became clear that I was trying to index reactive values using a vector of values when they can only be indexed by a single string. Accordingly, I use purrr::map to operate on the vector of values. Since this produces a list, I unlisted to provide a vector of values to hist.
The revised code below produces a histogram as expected.
library(shiny)
library(shinyWidgets)
library(purrr)

ui <- fluidPage(

  titlePanel("Title"),
  fluidRow(

    column("",
           width = 10, offset = 1,
           tags$h3("Filler"),

           panel(
             numericInput("n_params","How many fields?", min = 2, max = 100, value = 3),
             uiOutput("param_fields"),
             numericInput("n_sims","How many simulations?", min = 0, max = 100000, value = 10000),
             actionButton("sampling", "Sample from this distribution!")
           ),

           tags$h3("Plotted results!"),
           plotOutput("plotted")
  )
)
)

# Define server logic
server <- function(input, output) {

  # Dynamically create a set of numeric input fields based on the
  # number of parameters specified (fancy math symbols needed, ignore mathjax)
  dynamic_list_of_numeric_fields <- reactive({
    n_params <- req(input$n_params)
    purrr::map(1:n_params,
               ~numericInput(paste0("alpha",.),
                             withMathJax(paste0("\\(\\alpha_{", . ,"}\\)"))))

  })

  # Render the parameter fields for user-input of values
  output$param_fields <- renderUI({
    div(
      req(dynamic_list_of_numeric_fields())
    )
  })

  # Create plot updated any time sampling button is pushed
  plots <- eventReactive(input$sampling, {

    # Get the user-input parameter values
    n_params <- req(input$n_params)
    param_ids <- paste0("alpha", 1:n_params)
    param_vals <- input[[param_ids]]

    # Histogram
    hist(param_vals)
  })

  output$plot <- renderPlot({
    plots()
  })
}

shinyApp(ui = ui, server = server)


text:
Q: Why won't this PHP mail script work? I don't know PHP very well and am trying to get a very simple PHP script to send emails. When submit is clicked I get the Thank You message but no email.
<?php $name = $_POST['name'];
$email = $_POST['email'];
$web = $_POST['web'];
$message = $_POST['message'];
$formcontent="From: $name \n Website: $web \n Message: $message";
$recipient = "myemail@example.com"; // I do have my email here
$subject = "Contact Form";
$mailheader = "From: $email \r\n";
mail($recipient, $subject, $formcontent, $mailheader) or die("Error!");
echo "Thank You!";
    ?>

here is the form html:
<form action="mail.php" method="post" class="form">

      Name
        <input type="text" name="name" id="name" />

      E-mail
        <input type="text" name="email" id="email" />

      Website
        <input type="text" name="web" id="web" />

      Comments
        <textarea name="message"></textarea>

        <input type="submit" value="Send" />

</form>

A: Hmm... seems good. Try:
mail('youremail@hotmail.com', 'aSubject', 'aMessage');

all arguments NOT variables, but actual strings with single quotes.
Should appear in your normal/junk mail in the next 5 mins.

If that doesn't work, it means the script isn't executing, so change mail.php to just:
echo 'hi';

to ensure the script path is correct. that will find out whats wrong, cheers.

A: I'll suggest you simple make use of PHPMAILER class for this and you'll have some rest for yourself.
https://code.google.com/a/apache-extras.org/p/phpmailer/
This would be of good help so you don't need to start bothering about editing much codes that will drain your time for other works.
Check the files that came in the examples folder for the SMTP examples and use either SMTP advanced or basic. With SMTP advanced, you'll be able to throw and catch your errors. That helps you know where you have errors until all errors are resolved. See sample code for the SMTP basic codes.
require_once('../class.phpmailer.php');
//include("class.smtp.php"); // optional, gets called from within class.phpmailer.php if not already loaded

$mail             = new PHPMailer();

$body             = file_get_contents('contents.html');
$body             = preg_replace('/[\]/','',$body);

$mail->IsSMTP(); // telling the class to use SMTP
$mail->Host       = "mail.yourdomain.com"; // SMTP server
$mail->SMTPDebug  = 2;                     // enables SMTP debug information (for testing)
                                           // 1 = errors and messages
                                           // 2 = messages only
$mail->SMTPAuth   = true;                  // enable SMTP authentication
$mail->Host       = "mail.yourdomain.com"; // sets the SMTP server
$mail->Port       = 26;                    // set the SMTP port for the GMAIL server
$mail->Username   = "yourname@yourdomain"; // SMTP account username
$mail->Password   = "yourpassword";        // SMTP account password

$mail->SetFrom('name@yourdomain.com', 'First Last');

$mail->AddReplyTo("name@yourdomain.com","First Last");

$mail->Subject    = "PHPMailer Test Subject via smtp, basic with authentication";

$mail->AltBody    = "To view the message, please use an HTML compatible email viewer!"; // optional, comment out and test

$mail->MsgHTML($body);

$address = "whoto@otherdomain.com";
$mail->AddAddress($address, "John Doe");

$mail->AddAttachment("images/phpmailer.gif");      // attachment
$mail->AddAttachment("images/phpmailer_mini.gif"); // attachment

if(!$mail->Send()) {
  echo "Mailer Error: " . $mail->ErrorInfo;
} else {
  echo "Message sent!";
}

When you are done testing and want to now stop outputting the SMTP buffer messages, locate this line that says
$mail->SMTPDebug = 2;

and replace it with
$mail->SMTPDebug = false;
$mail->do_debug = 0;

Then you're good to go. Ask questions where necessary.

A: First of all, you should be aware that your code is subject to headers injection using POST.
You should use filter_var() (http://php.net/manual/fr/function.filter-var.php) to ensure that $email value is harmless.
Then, there are a few reasons which can prevent PHP to send your mails.
The mail() function uses your server's MTA (such as sendmail, postfix...) : you need to install/configure it properly to send mails.
Your ISP can be blocking the 25 port, too (to prevent spam).
Alternatively, you can use php pear's Mail and Net_SMTP classes to send an email via SMTP. Theses classes handle encoding, attached files, and so on, in a convenient way.

A: I am not a back end developer so I do not know a lot about php, but this code worked for me so give this a go.

Name<input class="contact" type="text" name="your_name" value="" />

Email Address<input class="contact" type="text" name="your_email" value="" />

Message<textarea class="contact textarea" rows="8" cols="50" name="your_message"></textarea>

 <input class="submit" type="submit" name="contact_submitted" value="Send" />

            <?php
            $your_name = $_POST['your_name'];
            $your_email = $_POST[your_email];
            $your_message = $_POST['your_message'];
            $recipient = "youremailhere@domain.com";
            $subject = "New Message About BikeExcel";

            mail($recipient , $subject, $your_message, "From " . $your_email);
            echo "Your Message Has Been Sent";
            ?>

So instead of putting your email in the mail string, you make a variable that will define your email. This will also make your code look nice which will make you look good in your portfolio. I hope this helped!!!!


text:
Q: Permutar un vector cuatro veces con restricciones utilizando R Tengo el siguiente vector :
FirstName <- c(11, 10, 4, 7, 1, 13, 14, 9, 8, 12, 5, 2, 6, 3)

Quiero obtener 4 vectores más, de tal forma que en la posición i-ésima no se repita el mismo número que en el vector FirstName y que tampoco se repitan entre los 4 vectores resultantes. Necesariamente cada vector tiene que contener todos los números sólo una vez.
Además, deseo añadir una restricción:
En la posición i-ésima de todos lo vectores, respecto a ellos y el vector FirstName sólo contenga, por ejemplo, el número 14 y no el 13 o a la inversa.
Aquí adjunto mi código :
sam_minusone <- function(v, z) {
   t <- sample(v[v != z],1)
   return(t)
}

v = FirstName
t = c()

for(i in 2:length(v)){
    z <- FirstName[i-1]
    number <- sam_minusone(v,z)
    t <- c(t,number)
    v <- setdiff(v,number)
}
t

Aunque el vector t posee una componente menos respecto al vector FirstName.
Gracias por la ayuda y por vuestro tiempo.

A: Realmente la función sample es de gran ayuda para mezclar o extraer datos sin reposición -o con reposición-, pero usarse desde un inicio en este caso concreto, creo que se estaría entrando a una empresa sin muchas garantías de éxito, es decir, el camino sería más largo.
La pregunta a mi entender, parece ser una variante de sudoku, con la salvedad que sólo las filas deben sumar lo mismo sum(1:14)==105 #TRUE
Una forma de evitar que los números pertenecientes a la misma columna se repitan, es generar un desfase de posición entre las filas de por lo menos una unidad -esto más adelante se le llamará factD: factor de desfase- y que los valores de dichas filas (vectores) sean cíclicas como un reloj.
Al hablar de ciclos existe una herramienta llamada aritmética modular. En R dicha herramienta se le usa mediante el operador %%, véase lo siguiente con un desfase de una unidad entre filas:
1:14%%14
2:15%%14
3:16%%14
4:17%%14

 [1]  1  2  3  4  5  6  7  8  9 10 11 12 13  0
 [1]  2  3  4  5  6  7  8  9 10 11 12 13  0  1
 [1]  3  4  5  6  7  8  9 10 11 12 13  0  1  2
 [1]  4  5  6  7  8  9 10 11 12 13  0  1  2  3

for (j in 5:8) print (((j):(j+13))%%14)
 [1]  5  6  7  8  9 10 11 12 13  0  1  2  3  4
 [1]  6  7  8  9 10 11 12 13  0  1  2  3  4  5
 [1]  7  8  9 10 11 12 13  0  1  2  3  4  5  6
 [1]  8  9 10 11 12 13  0  1  2  3  4  5  6  7

Nótese que las columnas no se repiten (son cíclicas), aquí está la clave, porque las filas siempre sumaran 105 como el sudoku, -el cero (0) es un detalle menor, puede cambiarse por 14 luego-.
Entonces generándase los "datos de partida o inicio":
set.seed(20190320) # una semilla para replicar las pruebas
m <- matrix(0, nrow=4, ncol=14)
desf <- sample(0:13,1) # esto viene
factD<-2 # cuando es uno (1), se tiene lo expuesto al inicio
         # ajustar de acuerdo a lo que se necesita
         # no he probado todo el intervalo [1,13]
for (j in 1:4) {
    d<-((j*factD+desf):(j*factD+desf+13))%%14
    d[d %in% 0]<-14
    m[j,]<-d
}
m
     [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [,11] [,12] [,13] [,14]
[1,]   13   14    1    2    3    4    5    6    7     8     9    10    11    12
[2,]    1    2    3    4    5    6    7    8    9    10    11    12    13    14
[3,]    3    4    5    6    7    8    9   10   11    12    13    14     1     2
[4,]    5    6    7    8    9   10   11   12   13    14     1     2     3     4

Nótese que el desfase entre los elementos de las filas es 2, asimismo el ciclo (desf) corresponde a 11 porque la celda[1,1] es 13... 11+2, es decir si se continuase con el ejemplo inicial (8:21%%14)... 11:24%%14 esta expresión luego de sumarle el factD=2, sería 13:26%%14, correspondiente a la primera fila de la matriz m.

Lo que viene a continuación es mezclar los datos sin que se pierda la integrar alcanzada en el paso previo.
# se mezcla, se baraja, se permutan o se extrae sin reposición
# las posiciones de las columnas y las filas
shuffleCol <- sample(1:14, 14, replace = FALSE)
shuffleRow <- sample(1:4 ,4, replace = FALSE)

shuffleCol   #  [1] 4 6 11 13  2  9 14  8 12  5  7  3 10  1
shuffleRow   #  [1] 2 4 1 3

Luego se crea una matriz que contendrá los resultados de acuerdo a los indices (filas y columnas) previamente generados de forma aleatoria.
mf<-matrix(0 ,nrow=4, ncol=14)
# se insertan las filas en este orden:
#     mf       m
# 2 4 1 3 <- 1 2 3 4
mf[shuffleRow,] <- m[1:4,]
mf
     [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [,11] [,12] [,13] [,14]
[1,]    3    4    5    6    7    8    9   10   11    12    13    14     1     2
[2,]   13   14    1    2    3    4    5    6    7     8     9    10    11    12
[3,]    5    6    7    8    9   10   11   12   13    14     1     2     3     4
[4,]    1    2    3    4    5    6    7    8    9    10    11    12    13    14

# lo mismo con las columnas pero solo con la matriz mf
# mf: 4 6 11 13 2 9 14 8 12 5  7  3  10 1
# mf: 1 2 3  4  5 6 7  8 9  10 11 12 13 14
mf[,1:14]<-mf[,shuffleCol]
mf
     [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [,11] [,12] [,13] [,14]
[1,]    6    8   13    1    4   11    2   10   14     7     9     5    12     3
[2,]    2    4    9   11   14    7   12    6   10     3     5     1     8    13
[3,]    8   10    1    3    6   13    4   12    2     9    11     7    14     5
[4,]    4    6   11   13    2    9   14    8   12     5     7     3    10     1

Finalmente quería añadir que el factor de desfase (factD) se ajustó a dos (2) en este caso, para allanar un poco la explicación de lo resuelto, no obstante también puede ser aleatorio factD<-sample(1:Tope,1) podría ser incluso hasta trece (13) -o el rango empezarlo desde 2, 3,...-, honestamente no he realizado las pruebas hasta ese número (13), sería cuestión que lo definan (Tope) de acuerdo a sus necesidades.

En todo caso, no perder de vista que debe existir siempre un desfase de al menos una unidad entre las valores de las filas que serán columnas, porque también se está agregando la variable desf.

Ampliación Respuesta
Una forma de verificar el comportamiento que tendrán los datos iniciales, es mediante la evaluación de las combinaciones que son generadas con las variables desf, factD, para este caso, los bucles for, ayudarían a tal fin:
for (desf in 0:13){
    for (factD in 1:13){
        print('------------------------------------------')
        print(paste("desf:",desf,"factD:",factD))
        print('------------------------------------------')
        for (j in 1:4) {
            d<-((j*factD+desf):(j*factD+desf+13))%%14
            d[d %in% 0]<-14
            print(d)
        }
        cat("\n")
    }
}


text:
Q: Select JSON value that match column id My data are of payments, amount, currency and a JSON object with the exchange rates for that particular date. This JSON contains ALL currencies and all exchange rates.

Amount
Currency
Exchange rates

666.00
USD
[{"BaseCurrency":"SEK","ExchangeCurrency":"GBP","Rate":0.07848,"Date":2018-10-21},{"BaseCurrency":"SEK","ExchangeCurrency":"USD","Rate":0.106593,"Date":2018-10-21]

123.00
GBP
[{"BaseCurrency":"SEK","ExchangeCurrency":"GBP","Rate":0.08239,"Date":2020-03-10},{"BaseCurrency":"SEK","ExchangeCurrency":"USD","Rate":0.117549,"Date":2020-03-10}]

How do I select just the correct rate in each object for each row?  The final goal is to have one column called "Amount in SEK".
I want a result that looks something like this:

Amount
Currency
Exchange rates
Rate
Amount in SEK

666.00
USD
[{"BaseCurrency":"SEK","ExchangeCurrency":"GBP","Rate":0.07848,"Date":2018-10-21},{"BaseCurrency":"SEK","ExchangeCurrency":"USD","Rate":0.106593,"Date":2018-10-21}]
0.106593
6248.07

123.00
GBP
[{"BaseCurrency":"SEK","ExchangeCurrency":"GBP","Rate":0.08239,"Date":2020-03-10},{"BaseCurrency":"SEK","ExchangeCurrency":"USD","Rate":0.117549,"Date":2020-03-10}]
0.08239
1492.90

A: If you use SQL Server 2016+, you may parse the JSON data with OPENJSON(). The following statement is a possible solution to your problem (without rounding):
Sample data:
SELECT *
INTO Data
FROM (VALUES
   (666.00, 'USD', '[{"BaseCurrency":"SEK","ExchangeCurrency":"GBP","Rate":0.07848,"Date":"2018-10-21"},{"BaseCurrency":"SEK","ExchangeCurrency":"USD","Rate":0.106593,"Date":"2018-10-21"}]'),
   (123.00, 'GBP', '[{"BaseCurrency":"SEK","ExchangeCurrency":"GBP","Rate":0.08239,"Date":"2020-03-10"},{"BaseCurrency":"SEK","ExchangeCurrency":"USD","Rate":0.117549,"Date":"2020-03-10"}]')
) v ([Amount], [Currency], [Exchange rates])

Statment:
SELECT
   d.[Amount], d.[Currency], d.[Exchange rates],
   j.[Rate],
   CASE WHEN j.[Rate] > 0.0 THEN d.[Amount] / j.[Rate] END AS [Amount in SEK]
FROM Data d
OUTER APPLY OPENJSON(d.[Exchange rates]) WITH (
   ExchangeCurrency varchar(3) '$.ExchangeCurrency',
   Rate numeric(20, 5) '$.Rate'
) j
WHERE d.Currency = j.ExchangeCurrency

Result:

Amount
Currency
Exchange rates
Rate
Amount in SEK

666.00
USD
[{"BaseCurrency":"SEK","ExchangeCurrency":"GBP","Rate":0.07848,"Date":"2018-10-21"},{"BaseCurrency":"SEK","ExchangeCurrency":"USD","Rate":0.106593,"Date":"2018-10-21"}]
0.10659
6248.24092316352378271882915

123.00
GBP
[{"BaseCurrency":"SEK","ExchangeCurrency":"GBP","Rate":0.08239,"Date":"2020-03-10"},{"BaseCurrency":"SEK","ExchangeCurrency":"USD","Rate":0.117549,"Date":"2020-03-10"}]
0.08239
1492.89962374074523607233887

A: Thanks, That seems to be what I'm looking for and I've done a bit of research and tried on my own code but it doesn't seem to work. I've also double-checked the server version. I'm running SQL Server 13.0.6300.2 which Google tells me is 2016.
I took my data and loaded it into a sample temp table.
SELECT top 100
s.STM_AMOUNT [Amount],
d.DIC_CODE [Currency],
REPLACE([CRR_CURRENCIES],'''','"') as [Exchange rates]
into #data
FROM database.SETTLEMENTS s
left join database.CURRENCIES c on c.crr_id = s.stm_crr_id
left join database.DICTIONARIES d on d.dic_id = s.stm_cur_dic_id

Result
select * from #data

I then do the code you suggested:
Select
d.[Amount], d.[Currency], d.[Exchange rates],
j.[Rate],
CASE WHEN j.[Rate] > 0.0 THEN d.[Amount] / j.[Rate] END AS [Amount in SEK]
from #data d

OUTER APPLY OPENJSON(d.[Exchange rates])
WITH(
ExchangeCurrency varchar(3) '$.ExchangeCurrency',
Rate numeric(20, 5) '$.Rate'
) j
WHERE d.Currency = j.ExchangeCurrency

I have also tried "CROSS APPLY" but I get this error code:
Incorrect syntax near the keyword 'with'. If this statement is a common table expression, an xmlnamespaces clause or a change tracking context clause, the previous statement must be terminated with a semicolon.
So I tried to add a semicolon ( ; ) in front of WITH but then everything after the colon gets error.


text:
Q: Avoid division by zero: 1 / 0 error in WITH clause I am using the following in a WITH clause to create a FULL JOIN in Big Query:
    WITH
    a AS(
        SELECT
        date AS Date,
        SUM(Val1 / (1 - (Val2 + Val3))) AS Calc1,
        FROM `project.dataset.table1`
        GROUP BY Date
        ),
    b as (SELECT
        date AS Date,
        FROM `project.dataset.table2`
        GROUP BY Date
        )

SELECT a.Date, SUM(Calc1)

FULL JOIN a on b.Date = a.Date

GROUP BY b.Date

Calc1 is creating a 'division by zero: 1 / 0' error, and I can't seem to work out how to restructure this so it doesn't occur. The query works fine outside of the WITH clause, as I can simply not include the GROUP BY so have no need to SUM Calc1?

A: Below is for BigQuery Standard SQL
Use
SUM(SAFE_DIVIDE(Val1, 1 - (Val2 + Val3))) AS Calc1

instead of
SUM(Val1 / (1 - (Val2 + Val3))) AS Calc1

A: Use NULLIF :
WITH
a AS(
SELECT
date AS Date,
SUM(Val1 / NULLIF((1 - (Val2 + Val3)),0)) AS Calc1,
FROM `project.dataset.table1`
GROUP BY Date, SUM(Calc1)
)

A: Have you analysed your data within "table1" to ensure that Val1, Val2 & Val3 are consistently populated, or do you have NULL values?
This could be the issue with your subtraction from 1.

WITH
    a AS(
        SELECT
        date AS Date,
        SUM(Val1 / (1 - (isnull(Val2,0.00) + isnull(Val3,0.00)))) AS Calc1
        FROM `project.dataset.table1`
        GROUP BY Date
        ),
    b as (
            SELECT
            date AS Date,
            FROM `project.dataset.table2`
            GROUP BY Date
        )

SELECT a.Date, SUM(a.Calc1)
FULL JOIN a on b.Date = a.Date`enter code here`
GROUP BY b.Date


text:
Q: Counting consecutive repeats in a string and returning a value in python Asked my friend to give me an assignment for me to practice. It is:

If a user enters a string "AAABNNNNNNDJSSSJENDDKEW" the program will return
  "3AB6NDJ2SJEN2DKEW" and vice versa.

This what I tried so far:
from collections import Counter
list_user_input =[]
list_converted_output=[]
current_char = 0 #specifies the char it is reading
next_char = 1
cycle = 0 # counts number of loops
char_repeat = 1
prev_char=""
count = 1
user_input = input("Enter your string: ")
user_input_strip = user_input.strip()
user_input_striped_replace = user_input_strip.replace(" ", "").lower()
list_user_input.append(user_input_striped_replace[0:len(user_input_striped_replace)])
print(list_user_input)
print(user_input_striped_replace)

I have "cleaned" the code so it removes white spaces and keeps it in low cap
Here is where I am stuck - the logics. I was thinking to go the through the string one index at a time and compare the next on to the other. Is this the wright way to go about it? And I'm not even sure about the loop construction.
#counter = Counter(list_user_input)
#print(counter)

#while cycle <= len(user_input_striped_replace):
for letter in user_input_striped_replace:
    cycle+=1
    print("index nr {}, letter: ".format(current_char)+letter +" and cycle : " + str(cycle))
    current_char+=1

    if letter[0:1] == letter[1:2]:
        print("match")

    print("index nr {}, letter: ".format(current_char)+letter +" and cycle : " + str(cycle))
    current_char+=1

A: Counter is a good choice for such task but about the rest you can use sorted to sort the items of Counter then use a list comprehension to create the desire list then concatenate with join :
>>> from collections import Counter
>>> c=Counter(s)
>>> sor=sorted(c.items(),key=lambda x:s.index(x[0]))
>>> ''.join([i if j==1 else '{}{}'.format(j,i) for i,j in sor])
'3AB7N3D2J3S2EKW'

A: I'd do it with regular expressions. Have a look at those.
Spoiler:
import re
def encode(s):
    return re.sub(r'(.)\1+', lambda m: str(len(m.group(0)))+m.group(1), s)
def decode(e):
    return re.sub('(\d+)(.)', lambda m: int(m.group(1))*m.group(2), e)

s = "AAABNNNNNNDJSSSJENDDKEW"
e = encode(s)
print(e, decode(e) == s)

Prints:
3AB6NDJ3SJEN2DKEW True

Your "and vice versa" sentence sounds like the program needs to detect itself whether to encode or to decode, so here's that (proof of correctness left as an exercise :-)
def switch(s):
    e = re.sub(r'(\D)\1+', lambda m: str(len(m.group(0)))+m.group(1), s)
    d = re.sub('(\d+)(.)', lambda m: int(m.group(1))*m.group(2), s)
    return e if e != s else d


text:
Q: How to dynamicaly set up unique id to objects in js? Writing a project in .Net and having trouble with js.
I need a method to trigger a click on the 'generate' button that takes data from the (dropdown menu) after the click.
I have a button 'btn', when I click on it the page loads an image with a 'dropdown' button. I need to take data from the dropdown menu(n, size, url) when I click on the button 'Dropdown' to use it later but the onclick method only reads the values of the first button. I tried to create a method to create unique button id but it doesn't work, all buttons have the same id.
var i = 0;
$('.dropdown').each(function () {
    i++;
    var newID = 'VarBtn' + i;
    $(this).attr('id', newID);
});

$(document).ready(() =>
{
    $('#btn').click(function ()
    {
        var input = {};
        input.n = parseInt($('#quantity').val());
        input.prompt = $('#txt').val();
        input.size = $('#sel').find(":selected").val();
        $.ajax({
            url: '/Home/GenerateImage',
            method: 'post',
            contentType: 'application/json',
            data: JSON.stringify(input)

        }).done(function (data) {
            $.each(data.data, function () {
                $('#display').append(
                    '
' +
                    '
' +
                    '<button class="btnV" id="idOne">Dropdown</button>' +
                    '
' +
                    '
Select size' +
                    '<select id="Vsel">' +
                    '<option selected>256x256</option>' +
                    '<option>512x512</option>' +
                    '<option>1024x1024</option>' +
                    '</select>' +
                    '
Enter quantity' +
                    '<input type="number" id="Vquantity" value="1" min="1" max="10" />' +
                    '
' +
                    '<button id="VarBtn_'+i+ '" >Generate</button>' +
                    '
' +
                    '
' +
                    '' +
                    '
');
            });
        });
    });

$(document.body).on('click', '#VarBtn', function () {
   //Code..
});

I tried to make unique id's for the buttons, so that clicking on the 'VarBtn' button will access the desired button and take the necessary data by unique id from the dropdown menu, but all id's remain the same.

A: Try this :
var i = 0;
$('.dropdown').each(function () {
    i++;
    var newID = 'VarBtn' + i;
    $(this).attr('id', newID);
});

$(document).ready(() =>
{
    $('#btn').click(function ()
    {
        var input = {};
        input.n = parseInt($('#quantity').val());
        input.prompt = $('#txt').val();
        input.size = $('#sel').find(":selected").val();
        $.ajax({
            url: '/Home/GenerateImage',
            method: 'post',
            contentType: 'application/json',
            data: JSON.stringify(input)

        }).done(function (data) {
            $.each(data.data, function () {
                var btnID = 'VarBtn_' + i;
                $('#display').append(
                    '
' +
                    '
' +
                    '<button class="btnV" id="idOne">Dropdown</button>' +
                    '
' +
                    '
Select size' +
                    '<select id="Vsel">' +
                    '<option selected>256x256</option>' +
                    '<option>512x512</option>' +
                    '<option>1024x1024</option>' +
                    '</select>' +
                    '
Enter quantity' +
                    '<input type="number" id="Vquantity" value="1" min="1" max="10" />' +
                    '
' +
                    '<button id="' + btnID + '" >Generate</button>' +
                    '
' +
                    '
' +
                    '' +
                    '
');
            });
        });
    });

$(document.body).on('click', '[id^=VarBtn]', function () {
    var dropdown = $(this).closest('.dropdown-content');
    var input = {};
    input.size = dropdown.find('#Vsel').val();
    input.quantity = parseInt(dropdown.find('#Vquantity').val());
    // do something with input
});


text:
Q: adding a click count to a react native So I am building an app that I want to implement basically a 'like' button on and I can't seem to get the right combination of things to make it work. Basically I want to press a like button and have a number on the page that shows how many times it has been liked. Anyone have any ideas? This is what I have so far:

import React from 'react';
import { StyleSheet,View, Image,TouchableOpacity,Text, StatusBar,
ScrollView } from 'react-native';

export default class SingleVeg extends React.Component {
  constructor(props){
      super(props)
console.log("Here", props);
      this.state = {
        data: {},
        count: 0
      }
      this.update = this.update.bind(this)
  }

  update() {
       this.setState({ count: this.state.data.count + 1 })
     }

async componentDidMount() {
  const response = await fetch(`https://just-
ripe.herokuapp.com/vegetable/$
{this.props.navigation.state.params.id}`)
  const json = await response.json()
    this.setState({data: json})

}

render(){
console.log(typeof this.state.data, this.state.data.id)
  return (
    <View style={styles.container}>
      <View style={styles.image}>
        <Image
        style ={{ width: 350, height: 200
        }}
        source={require("../../images/JustRipe.png")}/>
      </View>
      <Text style={styles.title}>{this.state.data.title}</Text>
      <TouchableOpacity style={styles.love} onPress ={this.update}>
<Text style= {styles.loveText}>Love: {this.state.data.count}</Text>
</TouchableOpacity>

A: You have a bug in your update function, it should be:
 update() {
   this.setState({ count: this.state.count + 1 })
 }

vs. this.state.data.count
You should also update your text to read from count. ie.
Love: {this.state.count}

and when you save state:
this.setState({data: json, count: json.count})

A: The problem here is you have 2 count storage.
Remove count in state:
this.state = {
  data: {},
  count: 0
}

And update correct count in data:
this.setState({ data: { ...data, count: this.state.data.count + 1 }})

A: import React from 'react'`enter code here`;

class Counter extends React.Component {
  state = { count: 0 }

  increment = () => {
    this.setState({
      count: this.state.count + 1
    });
  }

  decrement = () => {
    this.setState({
      count: this.state.count - 1
    });
  }

  render() {
    return (

Counter

          <button onClick={this.decrement}>-</button>
          {this.state.count}
          <button onClick={this.increment}>+</button>

    )
  }
}

export default Counter;


text:
Q: Color selected portion of an image in android I am a newbie and wanted to know
how to apply transparent color in selected portion of the image? I have coded like this but I am not getting the transparent color. Not able to see the below image.
       Paint p = new Paint(Paint.ANTI_ALIAS_FLAG);
       p.setColor(SettingsActivity.myColor);
       p.setStrokeWidth(20);
       p.setStyle(Paint.Style.STROKE);
       p.setAlpha(0xFF);

Please suggest a solution.
Thanks in advance
Prathima

A: See Color Picker Dialog


text:
Q: Drawing text onto an OpenGL surface using SDL I'm using SDL, I have OpenGL rendering setup, I want to draw some text to the screen.
I found this question: Using SDL_ttf with OpenGL which seems to address the same concern, but I think my GL-fu isn't good enough to understand what to do next.
Ie, I have the texture from that other post, which, if I understand everything correctly, is an integer ID representing a GL texture that contains the rendered text. How do I actually render this texture onto my screen (everything's 2D here so I just want to render it as flat text on the screen, not onto some fancy surface in a 3D scene or anything).
Alternatively, is there any easier way of getting this working? (ie, rendering some text via SDL while also being able to render GL shapes)
edit: Or, even more generally, is there an easier way of being able to render both text and shapes onto the screen via SDL?

A: *

*Use SDL_ttf to turn your string into a bitmap; this is just a single function call.

*Use the code in the link you posted to turn it into a texture.

*Draw a rectangle using said texture. That is, glBindTexture, glBegin, (glTexCoord, glVertex) x4, glEnd. If you have doubts about this step, you better go through some basic OpenGL tutorials (covering texture mapping, of course) first.

A: Try this snippet, it renders a SDL true type font extension library font starting from the bottom left side of the screen.
Note the arrangment of the texcords to the shape on the screen. The pixels from the text texture start 0,0 at the top left of the image. So I need to flip that around to make it show properly on a screen with x,y at the bottom left.
void RenderText(std::string message, SDL_Color color, int x, int y,
                TTF_Font* font)
{

  glMatrixMode(GL_MODELVIEW);
  glPushMatrix();
  glLoadIdentity();

  gluOrtho2D(0, gWindow->getWidth(),0,gWindow->getHeight());
  glMatrixMode(GL_PROJECTION);
  glPushMatrix();
  glLoadIdentity();

  glDisable(GL_DEPTH_TEST);
  glEnable(GL_TEXTURE_2D);
  glEnable(GL_BLEND);
  glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

  GLuint texture;
  glGenTextures(1, &texture);
  glBindTexture(GL_TEXTURE_2D, texture);

  SDL_Surface * sFont = TTF_RenderText_Blended(font, message.c_str(), color);

  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
  glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, sFont->w, sFont->h, 0, GL_BGRA,
                GL_UNSIGNED_BYTE, sFont->pixels);

  glBegin(GL_QUADS);
  {
    glTexCoord2f(0,1); glVertex2f(x, y);
    glTexCoord2f(1,1); glVertex2f(x + sFont->w, y);
    glTexCoord2f(1,0); glVertex2f(x + sFont->w, y + sFont->h);
    glTexCoord2f(0,0); glVertex2f(x, y + sFont->h);
  }
  glEnd();

  glDisable(GL_BLEND);
  glDisable(GL_TEXTURE_2D);
  glEnable(GL_DEPTH_TEST);

  glMatrixMode(GL_PROJECTION);
  glPopMatrix();
  glMatrixMode(GL_PROJECTION);
  glPopMatrix();

  glDeleteTextures(1, &texture);
  SDL_FreeSurface(sFont);
}


text:
Q: data frame, match two columns and remove repeated value from second columns if that exist in first columns, row number or id is not matter In a data, frame match two-column and if any value from the second column is available in the first column, remove value from the second columns
col1 col2
1
2     1
3     9
4
5     1
6     2

Output
col1 col2
1
2
3    9
4
5
6

Here, 1 and 2 from col2 are available in col1.
So, this repeated data should be removed

A: Using s.mask to value match and replace, we can do something along the likes of:
df['col2'] = df['col2'].mask(pd.to_numeric(df['col2']).isin(df['col1']), "")

col1    col2
0   1
1   2
2   3   9.0
3   4
4   5
5   6

A: import pandas as pd
col1= [1,2,3,4,5,6]
col2= [0,0,9.0,0,0,0]

df = pd.DataFrame({'col1':col1, 'col2':col2})
# add column with no of occurrence of Non None values in the column name starts with 'a'

# iterate over columns
for col in df.columns:
    # remove values that are in previous columns
    for prev_col in df.columns[:df.columns.get_loc(col)]:
        df[col] = df[col].where(~df[col].isin(df[prev_col]), None)

# OUTPUT
#    col1  col2
# 0     1   0.0
# 1     2   0.0
# 2     3   9.0
# 3     4   0.0
# 4     5   0.0
# 5     6   0.0


text:
Q: URLRewriteFilter blocks POST values I have written this rule
<rule>
    <condition type="request-uri" operator="notequal">^/admin/(.*)$</condition>
    <condition type="request-uri" operator="notequal">^/(.*)(ico|gif|jpg|jpeg|png|js|css)$</condition>
    <condition type="parameter" name="route" operator="notequal"></condition>
    <condition type="method" operator='notequal'>POST</condition>
    <from>^/(.*)$</from>
    <to>/index.php?_route_=$1</to>
</rule>

but for some reason when ever trying to access something with POST values never pass
ex. https://mydomain.com/index.php?route=checkout/cart/add (product_id=5 this value send it with POST) i well never get product_id=5 but product_id=0.
what am i missing from my rule. Thanks for your time

A: ok found the problem i also added DOCTYPE that was missing from my file
<!DOCTYPE urlrewrite PUBLIC "-//tuckey.org//DTD UrlRewrite 4.0//EN"
    "http://www.tuckey.org/res/dtds/urlrewrite4.0.dtd">

RULE
<rule match-type="regex">
    <condition type="request-uri" operator="notequal">^/admin/(.*)$</condition>
    <condition type="request-uri" operator="notequal">^/(.*)(ico|gif|jpg|jpeg|png|js|css)$</condition>
    <condition type="parameter" name="route" operator="notequal"></condition>
    <condition type="method" name="POST" operator="notequal">POST</condition>
    <from>^/([a-zA-Z-_/0-9]+)$</from>
    <to>/index.php?_route_=$1</to>
</rule>


text:
Q: Transalate .htaccess allow deny rules to IIS rewrite rules I have no access to IIS manager so I need to edit the Web.config files.
I had trouble translating this kinds of rules:
<Limit GET>
order deny,allow
deny from all
allow from .comodomain.com
</Limit>

Into IIS rewrite rules. Does anybody have some clue¿?

A: Use this instead.
http://www.iis.net/learn/extensions/url-rewrite-module/request-blocking-rule-template
if you can't find the URL rewrite, you can download it from iis.net


text:
Q: Comma usage after a direct quote?
Possible Duplicate:
Punctuation of direct speech, edge cases

Schwimmer promised Ciccaroni "nothing would happen to any teacher of mine under my watch," and told him not to bring any pepper spray onto school grounds.

I am having a real hard time trying to figure out if there should there be a comma in the above sentence. Can anyone please explain why there should or should not be a comma ?

A: There are bigger problems here than punctuation. The sentence is a mixture of direct and indirect speech, and you need to make it one or the other. Indirect speech might be preferable, in which case it becomes:

Schwimmer promised Ciccaroni that nothing would happen to any teacher
  of his under his watch, and told him not to bring any pepper spray
  onto school grounds.


text:
Q: Boxify feature for popup in openlayers Is it possible to give effect of boxify and animations for a popup in openlayer??
I have anchoredPopup .
var Popup = new OpenLayers.Popup.Anchored("popupId");

I know that display class of this is olPopup . But how to give those effects?

A: For this u can use gxp or ExtJs. gxp more simply that ExtJs but ExtJs give u more options.


text:
Q: Magento 2 - InstallSchema.php does not create table I have created a module that has a setup that creates a table for me. However, the table does not exist after installing the module. I don't know why.
Error:

SQLSTATE[42S02]: Base table or view not found: 1146 Table 'mag2new.formmodule_users' doesn't exist, query was: DESCRIBE formmodule_users

File is: Setup/InstallSchema.php
namespace Company\FormModule\Setup;

use Magento\Framework\Setup\InstallSchemaInterface;
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\Setup\SchemaSetupInterface;
use Magento\Framework\DB\Adapter\AdapterInterface;

class InstallSchema implements InstallSchemaInterface
{
    /**
     * {@inheritdoc}
     * @SuppressWarnings(PHPMD.ExcessiveMethodLength)
     */
    public function install(SchemaSetupInterface $setup, ModuleContextInterface $context)
    {
        $installer = $setup;
        $installer->startSetup();
        $table = $installer->getConnection()->newTable(
            $installer->getTable('formmodule_users')
        )->addColumn(
            'id',
            \Magento\Framework\DB\Ddl\Table::TYPE_INTEGER,
            null,
            ['identity' => true, 'nullable' => false, 'primary' => true],
            'ID'
        )->addColumn(
            'name',
            \Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
            255,
            ['nullable' => true],
            'Firstname'
        )->addColumn(
            'lastname',
            \Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
            255,
            ['nullable' => true],
            'Lastname'
        )->addColumn(
            'address',
            \Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
            255,
            ['nullable' => true],
            'Address'
        )->setComment(
            'FormModule User Table'
        );
        $installer->getConnection()->createTable($table);
        $installer->endSetup();
    }
}

I've tried setup:upgrade, setup:db-schema:upgrade, setup:db-data:upgrade, cache:clean and deleting the record in setup_module. Any tips?
I used this for my module: How do I make a module with the form component?

A: try this code checking version
namespace Company\FormModule\Setup;

use Magento\Framework\Setup\InstallSchemaInterface;
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\Setup\SchemaSetupInterface;
use Magento\Framework\DB\Adapter\AdapterInterface;

class InstallSchema implements InstallSchemaInterface
{
    /**
     * {@inheritdoc}
     * @SuppressWarnings(PHPMD.ExcessiveMethodLength)
     */
    public function install(SchemaSetupInterface $setup, ModuleContextInterface $context)
    {
        $installer = $setup;
        $installer->startSetup();
        if (version_compare($context->getVersion(), '2.0.1') < 0){
            $table = $installer->getConnection()->newTable(
                $installer->getTable('formmodule_users')
            )->addColumn(
                'id',
                \Magento\Framework\DB\Ddl\Table::TYPE_INTEGER,
                null,
                ['identity' => true, 'nullable' => false, 'primary' => true],
                'ID'
            )->addColumn(
                'name',
                \Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
                255,
                ['nullable' => true],
                'Firstname'
            )->addColumn(
                'lastname',
                \Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
                255,
                ['nullable' => true],
                'Lastname'
            )->addColumn(
                'address',
                \Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
                255,
                ['nullable' => true],
                'Address'
            )->setComment(
                'FormModule User Table'
            );
            $installer->getConnection()->createTable($table);
        }
        $installer->endSetup();
    }
}

compare your current module version. for example module.xml
<module name="Company_FormModule" setup_version="2.0.0"></module>

so your current version 2.0.0 you update your version edit setup_version = "2.0.1" and InstallSchema.php
if (version_compare($context->getVersion(), '2.0.1') < 0){
   // your table
}

then finally setup:upgrade and cache:clean

A: Give this code a try , it worked for me ( replace this code in your public function ):
$table = $setup->getConnection()
    ->newTable($setup->getTable('formmodule_users'))
    ->addColumn(
        'id',
        \Magento\Framework\DB\Ddl\Table::TYPE_INTEGER,
        null,
        ['identity' => true, 'nullable' => false, 'primary' => true],
        'ID'
    )->addColumn(
        'name',
        \Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
        255,
        ['nullable' => true],
        'Firstname'
    )->addColumn(
        'lastname',
        \Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
        255,
        ['nullable' => true],
        'Lastname'
    )->addColumn(
        'address',
        \Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
        255,
        ['nullable' => true],
        'Address'
    )->setComment("FormModule User Table");
$setup->getConnection()->createTable($table);
$setup->endSetup();


text:
Q: How to get image url of image clicked in react I am using React. I want my user to click on one of four images, then get the url of the image they clicked on. Right now, I am getting a url of the domain, path, and image together with e.target.src (http://localhost:3000/img/cat.png). How can I just get the image url (cat.png)?
Here is part of my code:
        this.setState({
            urlClicked: e.target.src
        });
        console.log(this.state.urlClicked)
      }

      <img
         src={this.state.urlClicked}>
      </img>

Thanks so much.

A: You can split the string by "/" and then pop (from the end) the first value:
this.setState({
  urlClick: e.target.src.split("/").pop()
});


text:
Q: Raphael- Detect overlapped elements when drag and drop I'm trying to get element by drag and drop another element.
I have for example 2 circles: c1 and c2.
What i want to do is :  if i drop c2 above c1 hence they are overlapped(not entirely necessary), i can get circle c1 (ex:id, title... etc).
http://jsfiddle.net/Tomen/LYjnV/1/
Is there a way to do it?

A: I'm not sure if you want the moving element that collides, or the static one that is collided with - so I'll give both. (it sounds like you want the static one, but it is this one which Element.onDragOver gives, as suggested in Oli's comment)
Here is a rudimentary jsfiddle which accesses both elements:

*

*For the static element that is collided with, it uses Raphael's Element.onDragOver

*For the moving element that is being dragged, it uses some basic code based loosely on how jQuery UI's Draggable and Droppable libraries do this, as described here - by placing the dragged object in the global namespace while it is being dragged, and then accessing it from there.

It's possible Raphael already has a feature like this for accessing the dragged element, but if it does I haven't managed to find it looking in the docs, code or DOM.
My implementation of the second point is an extremely basic demonstration which would need improvement. For something more complete, I'd recommend reading and taking inspiration from the code used by the heavily tested and refined jQuery UI to do the same thing


text:
Q: Rails app ArgumentError in RelationshipsController#create I'm having trouble between my relationships controller and shops model.  I'm using relationships to create a friending-like association between shops and users.  When trying to add a user as a shop, I get the following error:
ArgumentError in RelationshipsController#create
wrong number of arguments (0 for 1)

on the first line in add(user) in the shop model:
shop.rb
class Shop < ActiveRecord::Base
  has_many :relationships
  has_many :users, through: :relationships
.
.
.
def add(user)
  relationships.create(user_id: other_user.id)
end
.
.
end

This command is triggered by "create" in the relationships controller:
relationships_controller.rb
class RelationshipsController < ApplicationController
  before_action :logged_in_shop

  def create
    user = User.find(params[:user_id])
    current_shop.add.relationship(user)
    redirect_to user
  end

  def destroy
    user = Relationship.find(params[:user_id])
    current_shop.remove.relationship(user)
    redirect_to user
  end
end

after clicking this add button:
<%= form_for(current_shop.relationships.build) do |f| %>

<%= hidden_field_tag :user_id, @user.id %>

  <%= f.submit "Add", class: "btn btn-primary" %>
<% end %>

For some reason the argument (user) isn't being carried to the add(user) method.  How can I make this work?  (I understand there are several errors in my syntax, this is a working version.  Looking for help on this specific error, will deal with others after I get rid of this error).
Relationship Model
class Relationship < ActiveRecord::Base
  belongs_to :user
  belongs_to :shop
  validates :user_id, presence: true
  validates :shop_id, presence: true
end

A: Error is raised because you called add without any arguments:
current_shop.add.relationship(user)

Since you have implemented add taking one argument, you should pass it
def create
  user = User.find(params[:user_id])
  current_shop.add(user)
  redirect_to user
end


text:
Q: export mercurial repo to zip root (without prefix) When I use this command:
hg archive -t zip -p "" test.zip

it zips the file, but in a subdirectory named test.  So the files are in test.zip/test/(my_files).
I would like to export to test.zip directly, that's why I tried an empty prefix (-p ""), I also tried "." as prefix, but it always create a subdirectory.
In my particular case, I want to be able to run "python archive.zip" which requires the ____main__.py file to be directly in the zip's root; this is why I want to subdirectory.
Any idea how to do that?
Thanks!


text:
Q: Android: App can't be found from Tablets After application uploading to Google Market I've observe, that it can't be found from tablets.
I've googled about minsdk and xlarge screens, but app still not visible. What else can be done? Application was made on Qt 5.1 for Android - may be this affects me somehow?
Here is my updated manifest:
<?xml version='1.0' encoding='utf-8'?>
<manifest package="qqq.qqq" android:versionName="1.11" android:versionCode="11" xmlns:android="http://schemas.android.com/apk/res/android">
    <application android:name="org.qtproject.qt5.android.bindings.QtApplication" android:label="@string/app_name" android:icon="@drawable/icon">
        <activity android:configChanges="orientation|locale|fontScale|keyboard|keyboardHidden|screenSize" android:name="org.qtproject.qt5.android.bindings.QtActivity" android:label="@string/app_name" android:launchMode="singleTask" android:hardwareAccelerated="true">
            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>
                <category android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>
            <meta-data android:name="android.app.qt_sources_resource_id" android:resource="@array/qt_sources"/>
            <meta-data android:value="@string/repository" android:name="android.app.repository"/>
            <meta-data android:name="android.app.qt_libs_resource_id" android:resource="@array/qt_libs"/>
            <meta-data android:name="android.app.bundled_libs_resource_id" android:resource="@array/bundled_libs"/>
            <meta-data android:value="lasercad" android:name="android.app.lib_name"/>
            <!-- Deploy Qt libs as part of package -->
            <meta-data android:value="1" android:name="android.app.bundle_local_qt_libs"/>
            <meta-data android:name="android.app.bundled_in_lib_resource_id" android:resource="@array/bundled_in_lib"/>
            <meta-data android:name="android.app.bundled_in_assets_resource_id" android:resource="@array/bundled_in_assets"/>
            <!-- Run with local libs -->
            <meta-data android:value="1" android:name="android.app.use_local_qt_libs"/>
            <meta-data android:value="/data/local/tmp/qt/" android:name="android.app.libs_prefix"/>
            <meta-data android:value="plugins/platforms/android/libqtforandroid.so:libs/libgnustl_shared.so:" android:name="android.app.load_local_libs"/>
            <meta-data android:value="jar/QtAndroid-bundled.jar:" android:name="android.app.load_local_jars"/>
            <meta-data android:value=":" android:name="android.app.static_init_classes"/>
            <!--  Messages maps -->
            <meta-data android:value="@string/ministro_not_found_msg" android:name="android.app.ministro_not_found_msg"/>
            <meta-data android:value="@string/ministro_needed_msg" android:name="android.app.ministro_needed_msg"/>
            <meta-data android:value="@string/fatal_error_msg" android:name="android.app.fatal_error_msg"/>
            <!--  Messages maps -->
        </activity>
        <activity android:name="org.j2cpp.CameraTest" android:label="@string/app_name"/>
        <activity android:name="org.qtproject.qt5.android.bindings.StartJavaActivity" android:label="@string/app_name">
            <intent-filter>
                <category android:name="android.intent.category.DEFAULT"/>
            </intent-filter>
        </activity>
        <activity android:name="org.qtproject.qt5.android.bindings.PhotoIntentActivity" android:label="@string/app_name"/>
        <activity android:name="org.qtproject.qt5.android.bindings.SettingsActivity" android:label="@string/app_name">
            <intent-filter>
                <category android:name="android.intent.category.DEFAULT"/>
                <category android:name="android.intent.category.PREFERENCE"/>
            </intent-filter>
        </activity>
    </application>
    <uses-sdk android:minSdkVersion="10" android:targetSdkVersion="15"/>
    <supports-screens android:resizeable="true" android:smallScreens="true" android:largeScreens="true" android:normalScreens="true" android:xlargeScreens="true" android:anyDensity="true"/>
    <uses-permission android:name="android.permission.BLUETOOTH" android:required="false" />
    <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" android:required="false" />
    <uses-permission android:name="android.permission.CAMERA" android:required="false" />
    <uses-permission android:name="android.permission.INTERNET" android:required="false" />
    <uses-permission android:name="android.permission.RECORD_AUDIO" android:required="false" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" android:required="false" />
</manifest>

update:
here is result of aapt for my apk file:
C:\src\Android\sdk\build-tools\17.0.0>aapt.exe dump badging C:\p4\views\AndroidLaser\Src\android\bin\Lasercad-debug.apk
package: name='lasercad.mobile' versionCode='11' versionName='1.11'
application-label:'Lasercad'
application-label-fa:'Lasercad'
application-label-ja:'Lasercad'
application-label-nb:'Lasercad'
application-label-id:'Lasercad'
application-label-de:'Lasercad'
application-label-el:'Lasercad'
application-label-nl:'Lasercad'
application-label-pl:'Lasercad'
application-label-ro:'Lasercad'
application-label-fr:'Lasercad'
application-label-es:'Lasercad'
application-label-ms:'Lasercad'
application-label-rs:'Lasercad'
application-label-et:'Lasercad'
application-label-it:'Lasercad'
application-label-ru:'Lasercad'
application-label-zh_CN:'Lasercad'
application-label-pt_BR:'Lasercad'
application-label-zh_TW:'Lasercad'
application-icon-120:'res/drawable-ldpi/icon.png'
application-icon-160:'res/drawable-mdpi/icon.png'
application-icon-240:'res/drawable-hdpi/icon.png'
application: label='Lasercad' icon='res/drawable-mdpi/icon.png'
application-debuggable
launchable-activity: name='org.qtproject.qt5.android.bindings.QtActivity'  label='Lasercad' icon=''
sdkVersion:'10'
targetSdkVersion:'15'
uses-permission:'android.permission.BLUETOOTH'
uses-permission:'android.permission.BLUETOOTH_ADMIN'
uses-permission:'android.permission.CAMERA'
uses-permission:'android.permission.INTERNET'
uses-permission:'android.permission.RECORD_AUDIO'
uses-permission:'android.permission.WRITE_EXTERNAL_STORAGE'
uses-permission:'android.permission.READ_EXTERNAL_STORAGE'
uses-implied-permission:'android.permission.READ_EXTERNAL_STORAGE','requested WRITE_EXTERNAL_STORAGE'
uses-feature:'android.hardware.camera'
uses-feature:'android.hardware.camera.autofocus'
uses-implied-feature:'android.hardware.camera.autofocus','requested android.permission.CAMERA permission'
uses-feature:'android.hardware.bluetooth'
uses-implied-feature:'android.hardware.bluetooth','requested android.permission.BLUETOOTH or android.permission.BLUETOOTH_ADMIN permission and targetSdkVersion> 4'
uses-feature:'android.hardware.microphone'
uses-implied-feature:'android.hardware.microphone','requested android.permission.RECORD_AUDIO permission'
uses-feature:'android.hardware.touchscreen'
uses-implied-feature:'android.hardware.touchscreen','assumed you require a touch screen unless explicitly made optional'
main
other-activities
supports-screens: 'small' 'normal' 'large' 'xlarge'
supports-any-density: 'true'
locales: '--_--' 'fa' 'ja' 'nb' 'id' 'de' 'el' 'nl' 'pl' 'ro' 'fr' 'es' 'ms' 'rs' 'et' 'it' 'ru' 'zh_CN' 'pt_BR' 'zh_TW'
densities: '120' '160' '240'
native-code: 'armeabi' 'armeabi-v7a'

A: make sure you have added the Activity into your Manifest.xml with package name at manifest mode and activity node correctly

A: Make sure you are doing the correct things of
uses-feature
and
uses-permission
Sometimes you might request feature (or implicitly required some feature via permissions) like phone/gps etc. which are not normally armed on a tablet.
A best practice should be
<uses-feature
  android:name="android.hardware.location.gps"
  android:required="false" />


text:
Q: I have error when I run docker in daemon mode I try to run docker in daemon mode but get an error
#docker -d -b br0
flag provided but not defined: -d
See 'docker --help'.

#service docker status
docker stop/waiting

I need this because I use own bridge for docker instance.
Two weeks ago I did not got any problems  like this, but now I can't understand what happen
docker -v
Docker version 1.10.0, build 590d5108
uname -a
3.16.0-60-generic #80~14.04.1-Ubuntu SMP Wed Jan 20 13:37:48 UTC 2016 x86_64 x86_64 x86_64 GNU/Linux

A: I would suggest not starting the docker daemon by hand, because not least - the flags and options change.
My running 1.9 docker daemon has flags:
/usr/bin/docker daemon -H fd://

I would suggest what has happened here, is that the docker invocation has changed - it's no longer docker -d - it changed between my two installs (1.7.1 and 1.9.1).
If you look at the docker daemon manpage you'll see the -d flag is gone.
But actually, I'd suggest not running it by hand at all, and look at altering the service invocation. On my Centos6 box, that's /etc/sysconfig/docker (You can see where this is by reading /etc/init.d/docker which is what service invokes)


text:
Q: Vanilla JavaScript fetch request with Basic Auth and local .pem certificate (no node.js) I'm very new to JavaScript so I'm hoping this is not a stupid question.
I have searched this site and the internet but cannot find the answer. I am trying to replicate a Python request.get() (which is working) in a JavaScript request. The python is:
requests.get(url, auth=(username, password), cert="path/to/certificate.pem")

My JavaScript is as follows currently:
fetch(url, {
  headers: {
    Authorization: `Basic ${btoa(username + ":" + password)}`
  },
  method: GET
})

How do I load the .pem certificate into the request?
Many thanks.
EDIT:
My apologies @Random Davis I thought specifying I'd searched this site was enough of an indication I hadn't found anything I was looking for. Please see below and the edited title.
To clarify I am not using node.js. Or at least I am unaware that I am using it as I am just utilising local files (HTML/CSS/JavaScript). As far as I can tell every single other answer here is node.js related and requires importing(??requiring??) external libraries. I am trying to avoid this.
Obviously if it is not possible without node.js and the external libraries I will have to think about using them. Due to my lack of knowledge with the JS/Node stack I am unaware if these requests can be done with just vanilla JS.
Again may thanks for any help.


text:
Q: Which design pattern should we use for category of tenants / users? Existed Code -
We can perform CRUD on tenant and also we have business method for same in business layer.
Who can perform actions against tenant - Restricted to two users (Role_A & Role_B).
TenantController -> TenantService -> TenantDAO
New Scenario -
Now we are introducing tenantCategory so older tenants will be known as Tenant_A and new tenants will be known as Tenant_B.
What we did -
Used If else in same TenantService code and did what was required for new use case.

*

*Skip few fields

*Added few new fields

*Added new validations

*Did authorization in same method using if else as initially we were allowing two users (A & B).We used @PreAuthorization but for this new tenant only B can perform the actions.

What can be do better -
Can use design pattern to separate the flow. I did some research and get to know suitable design pattern are -

*

*Strategy

*Decorator

*Visitor

But still not sure which one is suitable pattern.
Techstack - Java 11 & Spring Boot


text:
Q: Wine vs Virtualbox? I have used Wine before. I recently heard of VirtualBox. Do they do the same thing? What are the differences and relative merits of these?

A: They are not the same, no.  VirtualBox is a "virtual machine", which means that it create a system where the software inside thinks it is on a real piece of hardware; VirtualBox can run Windows, MacOSX, Linux, SunOS (for x86), etc.  It would be a operating system once you start and then you would need to install the applications you desire to run.  With VirtualBox, a Windows app will look like a Windows app and a MacOSX app will look like a MacOSX app.
Wine is a MS-Windows interface emulator.  It mimics the windowing libraries so a MS-Windows GUI program can display in XWindows instead of WinXP/Vista/Win7.  It is not an environment, it can only run one program (but you can start multiple wine apps).  Because it is mimicing the standard MS libraries, not all Windows programs may run under it if they need additional libraries or if they bypass the standard libraries and try to access lower-level libraries/interfaces.  With Wine, it may not look like a Windows app once it is running.
VirtualBox takes a lot more room (creating a copy of the guest OS), but it is much more reliable than apps using Wine (usually not Wine's fault, but the apps fault).  And if you have an application that needs support programs (like Putty using Pageant), that won't work with Wine, but works very well in VirtualBox.


text:
Q: Quicksort index out of range exception I'm trying a different variant of QuickSort where I sort two ListBoxes.
here is my code:
class cS
{
    public static int[] mQS(int[] iar)
    {
        //divide and conquer
        if (iar.Length < 3)
        {
            if (iar.Length == 2)
            {
                if (iar[0] > iar[1])
                {
                    //wissel
                    int T = iar[1];
                    iar[1] = iar[0];
                    iar[0] = T;
                }
            }
        }
        else
        {
            int size = iar.Length;
            int sum = 0;
            int average = 0;
            for (int i = 0; i < size; i++)
            {
                sum += iar[i];
            }
            average = sum / size;

            int lk = 1, lg = 1;
            for (int i = 0; i < size; i++)
            {
                if(iar[i]<=average)
                {
                    lk++;
                }
            else
            {
                lg++;
            }
        }

        int[] ak = new int[lk];
        int[] ag = new int[lg];
        lk--; lg--;

        for (int i = 0; i < average; i++)
        {
            if (iar[i] <= average)
            {
                ak[lk]=iar[i];
                lk--;
            }
            else
            {
                ag[lg] = iar[i];
                lg--;
            }
        }

        if (!Allegelijk(ak)) {ak= mQS(ak);}
        if(!Allegelijk(ag)) {ag = mQS(ag);}
        // plak weer aan elkaar in iar
        for (int i = 0; i < ak.Length; i++)
        {
            iar[i] = ak[i];
        }
        for (int i = 0; i < ag.Length; i++)
        {
            iar[i + ak.Length] = ag[i];
        }
    }
    return iar;
}

private static  bool allEqual(int[] ar)
{
    bool bG = true;
    for (int i = 1; i < ar.Length; i++)
    {
        if (ar[i] != ar[0])
        {
            bG = false;
            break;
        }
     }
     return bG;
 }

}

}
But when running I get this error:
index out of range exception at the line :

  if (iar[i] <= average>

Can anyone explain what is happening and how to fix it?

A: From comments:
The line for (int i = 0; i < average; i++) should have size not average

A: At some point during execution the value of sum is becoming a large enough number that the value of average, which is equal to sum / size, becomes greater than iar.Length. Consequently the value of i in the for loop eventually reaches a value greater than or equal to iar.Length.


text:
Q: Taylor Series Maclaurin Series Interval Expansion I am currently woking on some clack online homework problem. I really have no idea how to approach this problem. If someone could help me solve this question I would greatly appreciate it!

From Rogawski ET 2e section 10.7, exercise 31.
Find the Taylor series for $f(x) = \dfrac{1}{1 - 3x}$ centered at $c=1$.
$$\frac{1}{1-3x} = \sum_{n=0}^{\infty} [\textrm{_________}]$$

A: $$\begin{array} \\
\frac{1}{1-3x} &= \frac{1}{1-3(x-1)-3} \\
 &= \frac{1}{-2-3(x-1)} \\
 &= -\frac{1}{2} \left( \frac{1}{1 + \frac{3}{2}(x-1)} \right) \\
 &= -\frac{1}{2} \left( \frac{1}{1 - (-\frac{3}{2}(x-1))} \right) \\
 &= -\frac{1}{2} \sum_{n=0}^\infty \left(-\frac{3}{2}(x-1)\right)^n \textrm{ for } \left|-\frac{3}{2}(x-1)\right|<1\\
 &= -\frac{1}{2} \sum_{n=0}^\infty \frac{(-1)^n 3^n}{2^n} (x-1)^n \textrm{ for } \left|x-1\right|<\frac{2}{3} \\
 &= \sum_{n=0}^\infty \frac{(-1)^{n+1} 3^n}{2^{n+1}} (x-1)^n \textrm{ for } x \in \left(\frac{1}{3},\frac{5}{3}\right)
\end{array}$$

A: Try writing out the expansion on a piece of paper. It should look like
$$\frac{1}{1-3x}=\sum_{n=0}^{\infty}\frac{(-1)^{n+1}(x-1)^n}{2^{n+1}}$$
Now, consider how the $k^{th}$ term and the $k+1^{th}$ term compare.
$$T_k=\frac{(-1)^{k+1}(x-1)^k}{2^{k+1}}$$
$$T_{k+1}=\frac{(-1)^{k+1+1}(x-1)^{k+1}}{2^{k+1+1}}=\frac{(-1)^{k+1}(x-1)^{k}}{2^{k+1}}\frac{(-1)(x-1)}{2}=\frac{(1-x)}{2}T_k=r(x)T_k$$
Obviously $|r(x)|<1$ must hold in order for the sum to converge, requiring $x$ to fall in the interval $(-1,3)$


text:
Q: Facebook Application without Popup and SSL I am developing facebook app using javascript SDK.
Is there any possibility to run facebook app without SSL with HTTPS URL but block popup window by browser.
My facebook app works fine in mozzila browser but in Google chrome its cant run because my google chrome browser block popup window.
so facebook authentication failed so its cant work ahead and stopped there. Is there any alternative way to solve it.
Your help appreciate me. Thanks in advance.

A: https://www.facebook.com/notes/facebook-engineering/secure-browsing-by-default/10151590414803920
It's no longer possible to not use HTTPS on Facebook (which is a good thing!).
You cannot do anything against blocked pop-ups except telling the user that there is a pop-up that might be blocked.


text:
Q: How to use AutoMapper to convert Child Object list to either list of strings or list of Guids I have tried using a custom converted
CreateMap<ChildB, string>().ConvertUsing(src => src.Name);
But I run into the scenario when I want to sometimes get the string like above or sometimes I want to just get the Guid:
CreateMap<ChildB, Guid>().ConvertUsing(src => src.Id);
It seems to throw and error as it always converts the Name.  The Objects are like this:
public class ParentA
{
 public Guid Id {get;set;}
 public string Name {get;set;}
 public ICollection<ChildB>? {get;set;}
 ...
}

public class ChildB
{
 public Guid Id {get;set;}
 public string Name {get;set;}
 ...
}
public class ParentADTO1
{
 public Guid Id {get;set;}
 public string Name {get;set;}
 public ICollection<string> ChildNames{get;set;}
 ...
}
public class ParentADTO2
{
 public Guid Id {get;set;}
 public string Name {get;set;}
 public ICollection<Guid> ChildIds {get;set;}
 ...
}

So the question is, can I use the CreateMap function like so:
CreateMap<ParentA,ParentADTO1>()
  ...
 .ForMember(ent => ent.ChildNames, opt => opt.MapFrom(???))

CreateMap<ParentA,ParentADTO2>()
  ...
 .ForMember(ent => ent.ChildIds, opt => opt.MapFrom(???))

Your help is greatly appreciated!!
Thanks
Jon

A: You can set up the mapping configuration like this (I suppose the property is named Children):
public class ParentA
{
 public Guid Id {get;set;}
 public string Name {get;set;}
 public ICollection<ChildB> Children {get;set;}
 // ...
}

CreateMap<ParentA,ParentADTO1>()
  // ...
 .ForMember(ent => ent.ChildNames, opt => opt.MapFrom(x => x.Children.Select(y => y.Name).ToArray()))

CreateMap<ParentA,ParentADTO2>()
  // ...
 .ForMember(ent => ent.ChildIds, opt => opt.MapFrom(x => x.Children.Select(y => y.Id).ToArray()))

A: @Markus answer is certainly valid and is an excellent solution.  FWIW, here is another approach you could by using the built-in AutoMapper's Flattening pattern.  Simply add a Get[PropertyName] method to the source class to combine the child objects in whatever way you want it.  Here is the complete example:
public class Parent
{
    public Guid Id { get; set; }
    public string Name { get; set; }
    public ICollection<Child> Children { get; set; }

    public ICollection<string> GetChildNames()
    {
        return Children.Select(x => x.Name).ToArray();
    }

    public ICollection<Guid> GetChildIds()
    {
        return Children.Select(x => x.Id).ToArray();
    }
}

public class Child
{
    public Guid Id { get; set; }
    public string Name { get; set; }
}

public class ParentWithChildNames
{
    public Guid Id { get; set; }
    public string Name { get; set; }
    public ICollection<string> ChildNames { get; set; }
}
public class ParentWithChildIds
{
    public Guid Id { get; set; }
    public string Name { get; set; }
    public ICollection<Guid> ChildIds { get; set; }
}

//No need to map the member, you could use Get[PropertyName] approach to automatically map it
var config = new MapperConfiguration(cfg =>
{
    cfg.CreateMap<Parent, ParentWithChildIds>();
    cfg.CreateMap<Parent, ParentWithChildNames>();
});
var mapper = config.CreateMapper();


text:
Q: How can this code make a new image appear on each click - Scala What I am looking to do is have a button click create and load a new image to the panel. The image should be draggable as well as for me able to find its position on screen etc. Im not sure how to do this. The idea being after multiple clicks I will have multiple new images all able to drag and move about.
The code looks something like this :-
val top = new MainFrame {

     //General code for menus

      val button = new Button {
        text = "Click for Image"
      }

      val panel = new Panel {
        override def paint(g:Graphics2D){

        }

        listenTo (button
                 mouse.clicks,
                 mouse.moves)

        reactions += {
            case ButtonClicked(`button`) => {
                new ImagePanel{ imagePath = ("bottoming.jpg")}

            }

            case e: MousePressed =>{}
            case e: MouseDragged =>{}
            case e: MouseReleased =>{}
        }

     }
     import BorderPanel.Position._
     contents =
        new BorderPanel {
            layout += new Label("label") -> North
            layout += panel -> Center
            layout += button -> West

        }

   }


text:
Q: How do I launch my Spring Batch application after this refactor: Previously, I had a batch job that used this Cron bean along with the following method to trigger the batch job:
public class CronBatchConfig {

    @Autowired
    private JobLauncher jobLauncher;

    @Autowired
    private Job batchJob;

    @Autowired
    private BatchType batchType;

    private final String ONETIME_BATCH_NAME = "ONETIME";
    private final String RECON_BATCH_NAME = "RECON";

    @Scheduled(cron = "00 00 17 ? * *", zone = "CST")
    public void executeDailyBatch() throws JobParametersInvalidException, JobExecutionAlreadyRunningException, JobRestartException, JobInstanceAlreadyCompleteException {

        batchType.setValue(RECON_BATCH_NAME);
        final JobParameters jobParameters = new JobParametersBuilder().addLong("startTime", System.nanoTime()).toJobParameters();
        final JobExecution execution = jobLauncher.run(batchJob, jobParameters);
        log.info("Daily batch job status: " + execution.getExitStatus().getExitCode());
    }

Now that I have removed the Cronbean class (we are using a different scheduling mechanism) I'm not sure how to trigger this job.
The scheduling mechanism requires no code like the cron bean with the @Schdeuled annoation so Im not sure where to launch the app from.
I tried adding the execute() method to my application class' main method but that is throwing a null pointer :
@SpringBootApplication
@Slf4j
@EnableBatchProcessing
public class ReconBatchApplication extends DefaultBatchConfigurer {
    @Autowired
    private static JobLauncher jobLauncher;
    @Autowired
    private static Job batchJob;
    @Autowired
    private static BatchType batchType;
    private static final String RECON_BATCH_NAME = "RECON";

    public static void main(String[] args) throws JobInstanceAlreadyCompleteException, JobExecutionAlreadyRunningException, JobParametersInvalidException, JobRestartException {
        ApplicationContext context = SpringApplication.run(ReconBatchApplication.class, args);
        executeDailyBatch();
        System.exit(SpringApplication.exit(context));

    }

    public static void executeDailyBatch() throws JobParametersInvalidException, JobExecutionAlreadyRunningException, JobRestartException, JobInstanceAlreadyCompleteException {

        batchType.setValue(RECON_BATCH_NAME);
        final JobParameters jobParameters = new JobParametersBuilder().addLong("startTime", System.nanoTime()).toJobParameters();
        final JobExecution execution = jobLauncher.run(batchJob, jobParameters);
        log.info("Daily batch job status: " + execution.getExitStatus().getExitCode());
    }
    ```

Any suggestions would be appreciated

A: Since you are using Spring Boot, you can let it launch the job for you, as described in the documentation. You only have to define your job as a bean in your application context. Your main method could be something like:
public static void main(String[] args) throws Exception {
   // add job parameters as key/value pairs to args if you want to do it programmatically and not from the command line
   System.exit(SpringApplication.exit(SpringApplication.run(ReconBatchApplication.class, args)));
}