text:
Q: empty view not display in listview I am trying to display empty view when no internet connection give me no internet connection  and display no book when no book is not found
This is my code
public class MainActivity extends AppCompatActivity {
private static final String BOOK_REQUEST_URL = "https://www.googleapis.com/books/v1/volumes?q=";
public static final String LOG_TAG = MainActivity.class.getName();
// search button
private Button search_button;
// edit text to use for search
private EditText editText;
// string used to get string from edit text.
private String queryWord = null;
private TextView emptyTextView;
private ListView bookListView;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    search_button = (Button) findViewById(R.id.next_button);
    editText = (EditText) findViewById(R.id.edit_text);
    emptyTextView = (TextView) findViewById(R.id.empty_view);

    bookListView = (ListView) findViewById(R.id.list_view);

    // Get a reference to the ConnectivityManager to check state of network connectivity
    ConnectivityManager connMgr = (ConnectivityManager)
            getSystemService(Context.CONNECTIVITY_SERVICE);

    // Get details on the currently active default data network
    final NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();

here I want when not connection give me no internet connection`
 search_button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (networkInfo != null && networkInfo.isConnected()) {

                new GetBook().execute(BOOK_REQUEST_URL);
            } else {

                emptyTextView.setText(R.string.NoConnect);
                bookListView.setEmptyView(emptyTextView);

            }
        }

    });
    new GetBook().execute(BOOK_REQUEST_URL);
}
//  method to get string from edit text.
public String getBook() {
    queryWord = editText.getText().toString();
    if (queryWord == null) {
        bookListView.setEmptyView(emptyTextView);
    }
    return queryWord;
}

/**
 * Update the UI with the given book information.
 */
private void updateUi(List<Book> books) {

    // Find a reference to the {@link ListView} in the layout

    // Create a new {@link ArrayAdapter} of book
    final BookAdapter adapter = new BookAdapter(this, books);

    // Set the adapter on the {@link ListView}
    // so the list can be populated in the user interface
    bookListView.setAdapter(adapter);

}
// inner class for to support methods do in the background.
private class GetBook extends AsyncTask<String, Void, List<Book>> {

    @Override
    protected List<Book> doInBackground(String... urls) {
        String word_search = getBook();
        // Don't perform the request if there are no URLs, or the first URL is null.
        if (urls.length < 1 || urls[0] == null) {
            return null;
        }
        List<Book> result = QueryUtils.fetchBookName(urls[0], word_search);
        return result;
    }

    /**
     * This method is invoked on the main UI thread after the background work has been
     * completed.
     * <p>
     * It IS okay to modify the UI within this method. We take the {@link Book} object
     * (which was returned from the doInBackground() method) and update the views on the screen.
     */

here I want to display no list book
    @Override
        protected void onPostExecute(List<Book> book) {

            emptyTextView.setText(R.string.nobook);
            bookListView.setEmptyView(emptyTextView);

            // Hide loading indicator because the data has been loaded
            View loadingIndicator = findViewById(R.id.loading_indicator);
            loadingIndicator.setVisibility(View.GONE);
            if ((book != null) && !book.isEmpty()) {
                updateUi(book);
            }

        }
    }
}

I try more steps nothing happen

A:
try this

View  emptyV = getActivity().getLayoutInflater().inflate(R.layout.empty_view, null);
                    TextView tvMSG = (TextView) emptyV.findViewById(R.id.tvMSG);
                    tvMSG.setText("No product available.");
                    ViewGroup viewGroup= (ViewGroup) listView.getParent();
                    viewGroup.addView(emptyV, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                            ViewGroup.LayoutParams.MATCH_PARENT));
                    listView.setEmptyView(emptyV);

A: You can add another layout for empty state and pragmatically show/hide depending on list size.
Here is an example:
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/container"
    android:layout_height="match_parent"
    android:layout_width="match_parent">

    <ListView
        android:id="@+id/list_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

    <RelativeLayout
        android:id="@+id/layout_empty"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerVertical="true"
        android:layout_centerHorizontal="true"
        android:visibility="gone"
        android:layout_margin="30dp">

        <ImageView
            android:id="@+id/image_empty"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerHorizontal="true"
            android:src="@mipmap/ic_launcher"/>

        <TextView
            android:id="@+id/text_empty"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerHorizontal="true"
            android:layout_below="@id/image_empty"
            android:layout_marginTop="16dp"
            android:gravity="center"
            android:textSize="20sp"
            android:textStyle="bold"
            android:textColor="@color/textColorPrimary"
            android:text="Oops!"/>

        <TextView
            android:id="@+id/text_empty_hints"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerHorizontal="true"
            android:layout_below="@id/text_empty"
            android:layout_marginTop="16dp"
            android:gravity="center"
            android:textSize="14sp"
            android:textStyle="bold"
            android:textColor="@color/textColorSecondary"
            android:text="No items found"/>
    </RelativeLayout>
</RelativeLayout>

MainActivity.java:
private ListView bookListView;
private RelativeLayout layoutEmpty;

.......
............

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

    bookListView = (ListView) findViewById(R.id.list_view);
    layoutEmpty = (RelativeLayout) findViewById(R.id.layout_empty);

    .......
    ...........
}

private void updateUi(List<Book> books) {

    if(books.size() > 0) {
        layoutEmpty.setVisibility(View.GONE);
        bookListView.setVisibility(View.VISIBLE);
    } else {
        layoutEmpty.setVisibility(View.VISIBLE);
        bookListView.setVisibility(View.GONE);
    }
}

OUTPUT:

Hope this will help~


text:
Q: Proportionality in RC circuits I know that the time constant $\tau= RC$, where $R$ is the resistance and $C$ is the capacitance.
But I'm confused, bear with me, when I double or increase the capacitance of the RC circuit.
If I double the capacitance of the RC circuit, will the time constant be also double, or half of its original value? Can the same be said if I also do it to the resistor?
Thank you for taking the time.

A: If you double the capacitance, then your new capacitance is
$$
C_{new} = 2C,
$$
whereas the new time constant is
$$
\tau_{new} = RC_{new}=2RC.
$$

A: As already stated, from the math, if you increase the capacitance or resistance you increase the time constant RC. However, it is equally important to understand what the time constant is and why increasing R or C increases the time constant, and vice versa.
The time constant is how long it takes to charge the capacitor,  through the resistor, from an initial charge voltage of zero to approximately 63.2% ($1-e^{-1}$) of an applied DC voltage, or to discharge the capacitor through the same resistor to 37.8% ($e^{-1}$) of its initial charge voltage.
The relationship between capacitance, voltage, and charge is
$$C=\frac{Q}{V}$$
So the greater the capacitance the greater the amount of charge it will have on its plates for a given voltage. That, in turn, means for a larger capacitor it takes longer to add or remove the charge in order to achieve the same increase or decrease in voltage, all else being equal.
For a given capacitance and voltage the greater the resistance the lower the current. Since current is the charge per unit time added to or removed from the capacitor, a lower current increases the time it takes to charge or discharge the capacitor, I.e., increases the time constant. Likewise a lower resistance and higher current decreases time constant.
Hope this helps.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Removal of colons in directory name Currently the directory getting automatically created for a program I am working with includes colons (:), creating issues when I try manipulate the directory. Could anyone help me first remove this colon, and then be able to cd into the renamed directory? (So I guess I would have to equal the new directory name to a variable?)
Example:

*

*current directory name: Lang-32b-Branch:Line

*desired directory name: Lang-32b-BranchLine

A: If you want a general command to rename several files and/or directories with one or more colons, you can use rename,
rename 's/://g' *

After that you can cd into any of the directories (that you modified) as usual (without any quotes).

Alternate command line according to the tips in comments by @DavidFoerster and @dessert,
rename 's/://g' *\:*/

*

*If you want to limit the rename actions to directories, you should add a slash after the wild-card star.

*You can also put a colon in the wild-card expression to limit the selection of files to those, that contain a colon in the file name, which might make the action faster, if a huge amount of directories are to be searched,

Edit:
@EliahKagan suggests to start with a 'dry run' with the option -n,
rename -n 's/://g' *

which just prints out what renaming operations would be performed.
  Then it can be run again with the -n option removed to actually rename
  the files. This helps avoid mistakes such as accidentally renaming a
  bunch of files one actually wanted to leave alone.

A: If it's only the one directory you can use mv and cd. To make use of the power of bash History Expansion and the special parameter $_:
mv Lang-32b-Branch:Line !#:$:s/:/ && cd $_

!#:$:s/:/ is replaced with the last word ($) of the current command line (!#), where the first : is substituted by nothing. If you want every colon to be removed, change it to !#:$:gs/:/ (globally). $_ is simply replaced with the last command's last argument.

A: To achieve this manually, an in a simple manner you could use the mv command with some strong quoting to ensure that the shell doesn't interpret the colon as a special character:
mv 'Lang-32b-Branch:Line' 'Lang-32b-BranchLine' && cd 'Lang-32b-BranchLine'

An alternate approach is to use a variable and the one of the features of Bash parameter expansion, which may be more useful if you wish to automate this directory name change into a script:
dir=Lang-32b-Branch:Line
mv "$dir" "${dir//:/}"

The expansion of "${dir//:/}" will replace any occurrence of the colon character with nothing, giving the expected result of Lang-32b-BranchLine. Using "${dir/:/}" would result in only the first occurrence of the colon being removed, though that would still work for your given example.
As a one-liner to move and cd into the directory:
dir=Lang-32b-Branch:Line ; mv "$dir" "${dir//:/}" && cd "${dir//:/}"

Or if you wished to capture the modified directory name into a variable named new_dir:
dir=Lang-32b-Branch:Line ; new_dir="${dir//:/}"; mv "$dir" "$new_dir" && cd "$new_dir"

A great guide to Bash parameter expansion is available here.


text:
Q: Testing Angular service depending on private functions I want to test an Angular service with Karma and Jasmine. Testing of the public function works as expected. But while testing not all lines of the service are covered because some lines within private functions are not reached. The reason is the private function depends on private states/variables.
Angular service:
// depends on something locally
var switch = false;

// private
function help() {
  if (switch) {
    return 0;
  } else {
    return 1;
  }
}

// public
this.func = function() {
  // ...
  help();
  // ...
}

With this sample only the false path of ther help function is covered.
Is there any way to test all paths of the service without making private functions public or to create setter?


text:
Q: Long cycle blocks application I hve following cycle in my app
var maxIterations: Int = 0

func calculatePoint(cn: Complex) -> Int {

    let threshold: Double = 2
    var z: Complex = .init(re: 0, im: 0)
    var z2: Complex = .init(re: 0, im: 0)
    var iteration: Int = 0

    repeat {
        z2 = self.pow2ForComplex(cn: z)
        z.re = z2.re + cn.re
        z.im = z2.im + cn.im
        iteration += 1
    } while self.absForComplex(cn: z) <= threshold && iteration < self.maxIterations

    return iteration
}

and rainbow wheel is showing during the cycle execution. How I can manage that app is still responding to UI actions?
Note I have NSProgressIndicator updated in different part of code which is not being updated (progress is not shown) while the cycle is running.
I have suspicion that it has something to do with dispatcing but I'm quite "green" with that. I do appreciate any help.
Thanks.

A: To dispatch something asynchronously, call async on the appropriate queue. For example, you might change this method to do the calculation on a global background queue, and then report the result back on the main queue. By the way, when you do that, you shift from returning the result immediately to using a completion handler closure which the asynchronous method will call when the calculation is done:
func calculatePoint(_ cn: Complex, completionHandler: @escaping (Int) -> Void) {
    DispatchQueue.global(qos: .userInitiated).async {
        // do your complicated calculation here which calculates `iteration`

        DispatchQueue.main.async {
            completionHandler(iteration)
        }
    }
}

And you'd call it like so:
// start NSProgressIndicator here

calculatePoint(point) { iterations in
    // use iterations here, noting that this is called asynchronously (i.e. later)

    // stop NSProgressIndicator here
}

// don't use iterations here, because the above closure is likely not yet done by the time we get here;
// we'll get here almost immediately, but the above completion handler is called when the asynchronous
// calculation is done.

Martin has surmised that you are calculating a Mandelbrot set. If so, dispatching the calculation of each point to a global queue is not a good idea (because these global queues dispatch their blocks to worker threads, but those worker threads are quite limited).
If you want to avoid using up all of these global queue worker threads, one simple choice is to take the async call out of your routine that calculates an individual point, and just dispatch the whole routine that iterates through all of the complex values to a background thread:
DispatchQueue.global(qos: .userInitiated).async {
    for row in 0 ..< height {
        for column in 0 ..< width {
            let c = ...
            let m = self.mandelbrotValue(c)
            pixelBuffer[row * width + column] = self.color(for: m)
        }
    }

    let outputCGImage = context.makeImage()!

    DispatchQueue.main.async {
        completionHandler(NSImage(cgImage: outputCGImage, size: NSSize(width: width, height: height)))
    }
}

That's solves the "get it off the main thread" and the "don't use up the worker threads" problems, but now we've swung from using too many worker threads, to only using one worker thread, not fully utilizing the device. We really want to do as many calculations in parallel (while not exhausting the worker threads).
One approach, when doing a for loop for complex calculations, is to use dispatch_apply (now called concurrentPerform in Swift 3). This is like a for loop, but it does the each of the loops concurrently with respect to each other (but, at the end, waits for all of those concurrent loops to finish). To do this, replace the outer for loop with concurrentPerform:
DispatchQueue.global(qos: .userInitiated).async {
    DispatchQueue.concurrentPerform(iterations: height) { row in
        for column in 0 ..< width {
            let c = ...
            let m = self.mandelbrotValue(c)
            pixelBuffer[row * width + column] = self.color(for: m)
        }
    }

    let outputCGImage = context.makeImage()!

    DispatchQueue.main.async {
        completionHandler(NSImage(cgImage: outputCGImage, size: NSSize(width: width, height: height)))
    }
}

The concurrentPerform (formerly known as dispatch_apply) will perform the various iterations of that loop concurrently, but it will automatically optimize the number of concurrent threads for the capabilities of your device. On my MacBook Pro, this made the calculation 4.8 times faster than the simple for loop. Note, I still dispatch the whole thing to a global queue (because concurrentPerform runs synchronously, and we never want to perform slow, synchronous calculations on the main thread), but concurrentPerform will run the calculations in parallel. It's a great way to enjoy concurrency in a for loop in such a way that you won't exhaust GCD worker threads.

By the way, you mentioned that you are updating a NSProgressIndicator. Ideally, you want to update it as every pixel is processed, but if you do that, the UI may get backlogged, unable to keep up with all of these updates. You'll end up slowing the final result to allow the UI to catch up to all of those progress indicator updates.
The solution is to decouple the UI update from the progress updates. You want the background calculations to inform you as each pixel is updated, but you want the progress indicator to be updated, each time effectively saying "ok, update the progress with however many pixels were calculated since the last time I checked". There are cumbersome manual techniques to do that, but GCD provides a really elegant solution, a dispatch source, or more specifically, a DispatchSourceUserDataAdd.
So define properties for the dispatch source and a counter to keep track of how many pixels have been processed thus far:
let source = DispatchSource.makeUserDataAddSource(queue: .main)
var pixelsProcessed: UInt = 0

And then set up an event handler for the dispatch source, which updates the progress indicator:
source.setEventHandler() { [unowned self] in
    self.pixelsProcessed += self.source.data
    self.progressIndicator.doubleValue = Double(self.pixelsProcessed) / Double(width * height)
}
source.resume()

And then, as you process the pixels, you can simply add to your source from the background thread:
DispatchQueue.concurrentPerform(iterations: height) { row in
    for column in 0 ..< width {
        let c = ...
        let m = self.mandelbrotValue(for: c)
        pixelBuffer[row * width + column] = self.color(for: m)
        self.source.add(data: 1)
    }
}

If you do this, it will update the UI with the greatest frequency possible, but it will never get backlogged with a queue of updates. The dispatch source will coalesce these add calls for you.


text:
Q: How to click a button in an webpage I'm using these code to download a file from the server.
The link of the server from where I need to download the file is:
http://www.mcxindia.com/sitepages/BhavCopyDateWise.aspx
        var forms = new NameValueCollection();

        forms["__EVENTARGUMENT"] = "";
        forms["__VIEWSTATE"] = ExtractVariable(s, "__VIEWSTATE");
        forms["mTbdate"] = "12/22/2011";
        forms["__EVENTVALIDATION"] = __EVENTVALIDATION;
        forms["mImgBtnGo"] = "?";
        forms["__EVENTTARGET"] = "btnLink_Excel";

        webClient.Headers.Set(HttpRequestHeader.ContentType, "application/x-www-form-urlencoded");

        var responseData = webClient.UploadValues(@"http://www.mcxindia.com/sitepages/BhavCopyDateWise.aspx", "POST", forms);
        System.IO.File.WriteAllBytes(@"c:\11152011.csv", responseData);

Its downloading the file of the given date in the textbox which is default in the website now.
I need to click a button called mImgBtnGo before, to download the file of the given date
in the mTbdate.
I don't know what I should do to click the button called mImgBtnGo .
What I should write here
              forms["mImgBtnGo"] = "?";

A: using fiddler I think this is what you want:
 class Program
    {

        static string Extract(string s, string tag)
        {
             var startTag = String.Format("id=\"{0}\" value=\"", tag);
            var eaPos = s.IndexOf(startTag) + startTag.Length ;
            var eaPosLast = s.IndexOf('"', eaPos);
            return s.Substring(eaPos, eaPosLast-eaPos);
        }

        static void Main(string[] args)
        {

            WebClient webClient = new WebClient();

            var firstResponse = webClient.DownloadString(@"http://www.mcxindia.com/sitepages/BhavCopyDateWise.aspx");

            var forms = new NameValueCollection();
            forms["__EVENTARGUMENT"] = "";
            forms["__VIEWSTATE"] = Extract(firstResponse, "__VIEWSTATE");
            forms["mTbdate"] = "12/22/2011";
            forms["__EVENTVALIDATION"] = Extract(firstResponse, "__EVENTVALIDATION");
            forms["mImgBtnGo.x"] = "10";
            forms["mImgBtnGo.y"] = "10";
            forms["ScriptManager1"] = "MupdPnl|mImgBtnGo";
            // forms["__EVENTTARGET"] = "btnLink_Excel";
            webClient.Headers.Set(HttpRequestHeader.ContentType, "application/x-www-form-urlencoded");

            String secondResponse = UTF8Encoding.UTF8.GetString(
                webClient.UploadValues(@"http://www.mcxindia.com/sitepages/BhavCopyDateWise.aspx", "POST", forms)
              );

            forms = new NameValueCollection();
            forms["__EVENTARGUMENT"] = "";
            forms["__VIEWSTATE"] = Extract(secondResponse, "__VIEWSTATE");
            forms["mTbdate"] = "12/22/2011";
            forms["__EVENTVALIDATION"] = Extract(secondResponse, "__EVENTVALIDATION");
            // forms["mImgBtnGo"] = "?";
            forms["__EVENTTARGET"] = "btnLink_Excel";
            webClient.Headers.Set(HttpRequestHeader.ContentType, "application/x-www-form-urlencoded");
            var responseData = webClient.UploadValues(@"http://www.mcxindia.com/sitepages/BhavCopyDateWise.aspx", "POST", forms);
            System.IO.File.WriteAllBytes(@"c:\prj\11152011.csv", responseData);
            }

     }


text:
Q: Animated Icon During Web page loading I am creating an iOS app that displays a web view. How can I show an animated busy icon that shows a webpage is still loading. The icon should of course disappear when the webpage is fully loaded. An example code would be nice to have.Thanks

A: OK, I figured out my own problem. For those of you who might want to know how to do this... UIWebView has a protocol called UIWebViewDelegate Protocol naming some methods that can be implemented optionally. To show an animated icon in the status bar while a web page is loading, simply implement the webViewDidStartLoad method. Something like this...
- (void)webViewDidStartLoad:(UIWebView *)webView {

    // starting the load, show the activity indicator in the status bar
    [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;

}


text:
Q: If $f(x)$ is a twice differentiable function and given that $f(1) = 2, f(2) = 5$ and $f(3) = 10$ then
Q. If $f(x)$ is a twice differentiable function and given that
   $f(1) = 2, f(2) = 5$ and $f(3) = 10$ then
(A) $f''(x) = 2$  for all $x\in (1,3)$
(B) $f''(x) = f'(x) = 2$  for some $x\in (2,3)$
(C) $f''(x) = 3$  for all $x\in (2,3)$
(D) $f''(x) = 2$  for some $x\in (1,3)$

I assumed $$f(x) = ax^2 + bx + c$$ and compared and found $a,b,c$. That way, I get $f''(x) = 2$ for all $x$. But, seems like that's not how it is done. I am aware that it could be a thrce differentiable function or a trigonometric one. But, I thought that a general case should satisfy it and hence I could atleast deduce the answer. Why is it wrong? What should I do?

A: Only (D) can possibly be correct, since $f(x) = 2^x + x-1$ violates (A), (B), (C).
Added: (D) must be correct. To see this, write any such $f$ as
$$
f(x) = x^2 + 1 + g(x) \, .
$$
Then $g(1) = g(2) = g(3) = 0$. Therefore $g$ cannot be convex or concave on $[1,3]$ and there must be a $c \in (1,3)$ where $g''(c) = 0$. Thus $f''(c) = 2$.

A: Hint:
If $ f$ is a continuous function on the closed interval $ [a,b]$, and differentiable on the open interval $(a,b)$, then there exists a point $c $ in $ (a,b)$ such that
$$ f'(c)=\frac {f(b)-f(a)}{b-a}$$

A: If $f''$ is a constant for all $x$ within an interval, then $f$ is a quadratic. Following your approach you would get that $f(x)=x^2+1$. The second derivative of this is $2$ which rules $(C)$ out.
However, there are functions that are more than just polynomials that satisfy the three conditions. In fact, there is a twice-differentiable function that does so of the form $f(x)=Ax^2+Bx+C\sin x+D\cos x$. It can clearly be seen that $f''(x)\ne 2$ for all $x\in(1,3)$. Thus rules $(A)$ out.
Finally, if you use that function, it is possible to show that between $(2,3)$, $f'(x)\ne f''(x)$ at any point*. This rules $(B)$ out.
*: since $f'(2)<f''(2)$ and $f'(3)<f''(3)$, if suffices to prove that between $(2,3)$, $f'$ is monotonically increasing.
$$\textsf{The answer is (D).}$$

A: The mistake you have made is: Assuming that the function is a polynomial function. Polynomial function is just a special case.
There could certainly be another strange function like a trigonometric function satisfying the given conditions.
Hence the answer should be D and not B


text:
Q: database design for checkout and order table I am designing a database for e-commerce. I am confused regarding the checkout and order table. I am not sure if I need to create separate order table when most of the things is already done on checkout table.
Here is the design as of now
class Product(ModelWithMetadata, PublishableModel):
    product_type = models.ForeignKey(
        ProductType, related_name="products", on_delete=models.CASCADE
    )
    category = models.ForeignKey(
        Category,
        related_name="products",
        on_delete=models.SET_NULL,
        null=True,
        blank=True,
    )

class ProductVariant(models.Model):
    product = models.ForeignKey(Product, on_delete=models.CASCADE, related_name="variants")
    variant_attributes = models.ManyToManyField(VariantAttribute, related_name="productvariants")

class Checkout(ModelWithMetadata):
    """A shopping checkout."""
    created = models.DateTimeField(auto_now_add=True)
    last_change = models.DateTimeField(auto_now=True)
    user = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        blank=True,
        null=True,
        related_name="checkouts",
        on_delete=models.CASCADE,
    )
    email = models.EmailField()
    token = models.UUIDField(primary_key=True, default=uuid4, editable=False)
    quantity = models.PositiveIntegerField(default=0)
    billing_address = models.ForeignKey(
        Address, related_name="+", editable=False, null=True, on_delete=models.SET_NULL
    )
    shipping_address = models.ForeignKey(
        Address, related_name="+", editable=False, null=True, on_delete=models.SET_NULL
    )
    shipping_method = models.ForeignKey(
        ShippingMethod,
        blank=True,
        null=True,
        related_name="checkouts",
        on_delete=models.SET_NULL,
    )
    note = models.TextField(blank=True, default="")

    currency = models.CharField(
        max_length=settings.DEFAULT_CURRENCY_CODE_LENGTH,
        default=settings.DEFAULT_CURRENCY,
    )
    country = CountryField(default=get_default_country)

    discount_amount = models.DecimalField(
        max_digits=settings.DEFAULT_MAX_DIGITS,
        decimal_places=settings.DEFAULT_DECIMAL_PLACES,
        default=0,
    )
    discount = MoneyField(amount_field="discount_amount", currency_field="currency")
    discount_name = models.CharField(max_length=255, blank=True, null=True)

    voucher_code = models.CharField(max_length=12, blank=True, null=True)
    # gift_cards = models.ManyToManyField(GiftCard, blank=True, related_name="checkouts")

    objects = CheckoutQueryset.as_manager()

    class Meta:
        ordering = ("-last_change", "pk")

class CheckoutLine(models.Model):
    """A single checkout line.
    """

    checkout = models.ForeignKey(
        Checkout, related_name="lines", on_delete=models.CASCADE
    )
    variant = models.ForeignKey(
        "product.ProductVariant", related_name="+", on_delete=models.CASCADE
    )
    quantity = models.PositiveIntegerField(validators=[MinValueValidator(1)])

The additional things that is not covered in checkout table is about order tracking and refund. It is because I am confused if it's better to use that also on checkout table or create new order table and deal refund and tracking policy accordingly.
If it is better to use separate order table then can anyone enlighten me the benefits and how it is possible, please?

A: You must not only create a separate Order model, but also a separate Product model and integrate secondary costs differently. The reason is this: Orders must be static information for legal/financial reasons. They record something that happened in the past. It must match the price of the product at that time, the shipping costs, payment fees etc. All this information cannot be changed and in the checkout they are linked to entities that are mutable or even deletable.
For a product you usually do something like this:
class PurchasedItem(models.Model):
     original_product = models.ForeignKey(Product, on_delete=models.SET_NULL, null=True)
     ...  # minimal set of product attributes that allow delivery of the order
          # with the correct item (color / size / etc) and fixed price
          # Basically flatten product variant and product attributes that are
          # relevant.

This way, you can still make repeat orders happening as long as the product is still available. There's a lot to consider, but basically every time you want to make a ForeignKey on an order item, you must think if changing the linked item changes the order.
So your OrderLine becomes something like this:
class OrderLine(models.Model):
    order = models.ForeignKey(Order, ...)
    item = models.ForeignKey(PurchasedItem, ...)
    quantity = models.PositiveIntegerField(...)

The Order model:

*

*If you allow deletion of user accounts, then Order.user must be nullable.

*Shipping and billing address should be OneToOneField and a new copy must be made each time an order is made -or (better)- flatten the address attributes into the order.

*Shipping method: flatten and record final price

*Currency: record exchange rate, make it possible to change exchange rate once bank statement comes in

*Country: record the country name, if you want to keep a link to country for statistical purposes, make it nullable. Just in my lifetime, USSR, East/West Germany, Yugoslavia to name a few, ceased existing.

Hopefully this helps you get started.


text:
Q: SimpleSAMLphp OpenID Consumer I'm using SimpleSAMLphp as an OpenID Consumer and no openID provider I tried seems to work.
I always get the following error:
Exception during login: SimpleSAML_Error_BadRequest: BADREQUEST('%REASON%' =>
             'Not a valid OpenID: \'https://www.google.com/accounts/o8/id\'')

or:
 Exception during login: SimpleSAML_Error_BadRequest: BADREQUEST('%REASON%' =>
             'Not a valid OpenID: \'https://me.yahoo.com\'')

I tried my ID's with other web pages and they work fine.
I'm Using apache 2.2 & php5.3 and a cert from valid CA. Any clues on how I should approach the problem ? anyone got the same problem? I also tried to understand why the authn_request returned by the library is null...

A: my authsources is just defult values plus yahoo :
'openid' => array(
    'openid:OpenIDConsumer',
    'attributes.required' => array('nickname'),
    'attributes.optional' => array('fullname', 'email',),
    // 'sreg.validate' => FALSE,
   'attributes.ax_required' => array('http://axschema.org/namePerson/friendly'),
   'attributes.ax_optional' => array('http://axschema.org/namePerson','http://axschema.org/contact/email'),
    // Prefer HTTP redirect over POST
    // 'prefer_http_redirect' => FALSE,
),

'yahoo' => array(
    'openid:OpenIDConsumer',
    'target' => 'https://me.yahoo.com',
    'attributes.ax_required' => array(
            'http://axschema.org/contact/email',
    ),
    'extension.args' => array(
    ),
),

'google' => array(
    'openid:OpenIDConsumer',
    // Googles OpenID endpoint.
    'target' => 'https://www.google.com/accounts/o8/id',
    // Custom realm
    // 'realm' => 'http://*.example.org',
    // Attributes that google can supply.
    'attributes.ax_required' => array(
        //'http://axschema.org/namePerson/first',
        //'http://axschema.org/namePerson/last',
        //'http://axschema.org/contact/email',
        //'http://axschema.org/contact/country/home',
        //'http://axschema.org/pref/language',
    ),
    // custom extension arguments
    'extension.args' => array(
        //'http://specs.openid.net/extensions/ui/1.0' => array(
        //  'mode' => 'popup',
        //  'icon' => 'true',
        //),
    ),
),


text:
Q: Write into another file's resources how do I write into another's file resources.
For example, if i have builder in which you can write email,username. And then builder transfers that information into another's file resources. How can i do that?
I did similar thing using End Of File. Its when you basically write information into file's end. But people said that this method is unreliable and bad, and I should use resources, so how do i do that?   (C++)
How my EOF method works:
stub:
int main(){
int filesize = 104448; // File size . (not file size on disk
Settings data;
long int size = MAX_PATH;
char *filename = new char[size];
GetModuleFileNameA(NULL,filename,size);

ifstream fin(filename,ios::binary);  // Gets information that was additionally written into this file
fin.seekg(filesize);
fin.read((char*)&data,sizeof(Settings));

fin.seekg(filesize+sizeof(Settings),ios::end);
size_t len = fin.tellg();
fin.seekg(filesize+sizeof(Settings));
char *bytes = new char[len];
fin.read(bytes,len);
fin.close();  }

builder:
Settings data;
data.bytesLength = file.getBytesLength();
data.owner = m_username;

char * bytes = file.getBytes();

ifstream stub("Stub.exe", ios::binary);
ofstream built("Built.exe",ios::binary);
built << stub.rdbuf();
stub.close();

built.write((char*)&data,sizeof(Settings));
built.write(crc4.Encrypt(file.getBytes(),file.getPassword().c_str()),file.getBytesLength());
built.close();


text:
Q: how do i add a partition key using Azure.ResourceManager.CosmosDB c# I can create a database and container without an issue on both gremlin and sql, ut I can't seem to set the partition key.
I would expect to do
///
var containerParams = new SqlContainerCreateUpdateParameters
(
new SqlContainerResource(databaseName)
{
                    PartitionKey = new ContainerPartitionKey()
                    {
                        Paths = new List<string>{partialKey}
                    }
                },
                new CreateUpdateOptions()
            )

///
I would expect to do something like this, but the Paths field is readonly, and I can't see any other option to set it.
[Update]
i got it working with creating an object then converting to json and back to ContainerPartitionKey

A: Here is the syntax for creating the partition key using Cosmos DB Azure Management SDK.
SqlContainerCreateUpdateParameters sqlContainerCreateUpdateParameters = new SqlContainerCreateUpdateParameters
{
    Resource = new SqlContainerResource
    {
        Id = containerName,
        DefaultTtl = -1, //-1 = off, 0 = on no default, >0 = ttl in seconds
        AnalyticalStorageTtl = -1,
        PartitionKey = new ContainerPartitionKey
        {
        Kind = "Hash",
        Paths = new List<string> { "/myPartitionKey" },
        Version = 1 //version 2 for large partition key
    }
}

You can find a complete SqlContainer create example here. You can also find a complete set of examples for how to use the Azure Management SDK for Cosmos DB in GitHub. Please note, it is out of date but should still work for illustrating how to use to manage Cosmos resources.


text:
Q: Updating array in reducer i am trying to update state in reducer with a array of objects. Following is what i am doing.
Action.js file
export const apiSuccess = (data, forCust) => {
    return {
        type: ACTIONS.validateSuccess,
        data: data,
        forCust
    };
};

export const apiFailed = (error, forCust) => {
    console.log('pandetail failed', error)
    return {
        type: ACTIONS.ValidateFailed,
        data: error?.details?.data,
        forCust
    };
};

here forCust can be customer or admin
Here is the reducer
const initialState = {
    otherDetails: {},
    individualDetails: [{ forCust: 'customer' }, { forCust: 'admin' }],
};

const reducer = (state = initialState, action = {}) => {
    switch (action.type) {
        case ACTIONS.validateSuccess:
            console.log('Action in reducer', action)
            debugger;
            return {
                ...state,
                otherDetails: action?.data,
                individualDetails: state.individualDetails.map((item) => {
                if(item.forCust === action.forCust){
                    item = action
                }
                return item
                }),
            }
        case ACTIONS.validateFailed:
            return {
                ...state,
                otherDetails: action?.data,
                individualDetails: state.individualDetails.map((item) => {
                    if (item.forCust === action.forCust) {
                        item = action
                    }
                    return item
                }),
            }
        default:
            return state;
    }
};

export default reducer;

Now, when action is dispatched it dispatches with success and other parameter which is forCust to check if the dispatched action is for admin or customer. Now i have two fields in the same component but different parameters which calls the action(admin/customer). If the validateSuccess with customer is called i am trying to update customer details in individualDetails array and if admin is called i am trying to update only the admin state array object.
Now, what happens is that i am not able to maintain the old state ie when customer changes and admin details is there, it updated the whole array, not only the customer.
Also if somehow one of them get failed, failed action is dispatched and then update the array corresponding to the forCust field.
any help will be appreciated.


text:
Q: Unable to produce enum from c# code to json string I am using JsonForm to produce dynamic forms in my MVC core web application. I am using System.Text.Json.JsonSerializer.Serialize in the following code in my view model to produce a simple one field form. My aim is to store this json in the database eventually and retrieve it from there.
 public TestsViewModel GetFormControls1()
        {
            var myJsonModel = new
            {
                schema = new
                {
                    client = new
                    {
                        type = "object",
                        title = "Client",
                        properties = new
                        {
                            forename = new
                            {
                                type = "string",
                                title = "Forename",
                                minLength = 3,
                                maxLength = 10,
                            }
                        }
                    }
                },
                form = new List<Object>
                {
                    new {
                        key = "client.forename",
                        title = "Forename"
                    }
                },
                value = new
                {
                    client = new
                    {
                        forename = "",
                    }
                }
            };

            TestsViewModel homeVm = new TestsViewModel();
            homeVm.FormControls = System.Text.Json.JsonSerializer.Serialize(myJsonModel);
            return homeVm;
        }

Above code works fine and produces following json schema which is then used to create a form.
{
  "schema": {
    "client": {
      "type": "object",
      "title": "Client",
      "properties": {
        "forename": {
          "type": "string",
          "title": "Forename",
          "minLength": 3,
          "maxLength": 10
        }
      }
    }
  },
  "form": [
    {
      "key": "client.forename",
      "title": "Forename"
    }
  ],
  "value": {
    "client": {
      "forename": ""
    }
  }
}

I now need to produce an enum for my json so that a drop down for selecting a gender can appear in the form. However, I am unable to do that via c# code. Can someone help? I would like my c# code to produce following json (note two entries for gender in schema and form).
{
  "schema": {
    "client": {
      "type": "object",
      "title": "Client",
      "properties": {
        "forename": {
          "type": "string",
          "title": "Forename",
          "minLength": 3,
          "maxLength": 10
        },
        "gender": {
          "type": "string",
          "title": "Gender",
          "enum": [
            "male",
            "female",
            "alien"
          ]
        }
      }
    }
  },
  "form": [
    {
      "key": "client.forename",
      "title": "Forename"
    },
    {
      "key": "client.gender",
      "titleMap": {
        "male": "Dude",
        "female": "Dudette",
        "alien": "I'm from outer space!"
      }
    }
  ],
  "value": {
    "client": {
      "forename": ""
    }
  }
}

I have tried using following code but enum is a keyword in c# so I get error.
gender = new
                            {
                                type = "string",
                                title = "Gender",
                                enum = "[male, female, alien]"
                            }

Also Enum = "[male, female, alien]" produces "Enum": "[male, female, alien]" instead of "enum": [ "male", "female", "alien" ]
I have a gender lookup table which I will be eventually using to produce above enum somehow so any idea regarding that would be helpful as well.
UPDATE
@dbc's comment provides solution to most of my problem. However, I am still struglling with producing titleMap json if I try to map string to an int.
var gender3 = new
            {
                type = "string",
                title = "Gender",
                titleMap = new List<string> { new string("1" + ":" + "Male"), new string("2" + ":" + "Female")}
            };

Above code produces
{
  "type": "string",
  "title": "Gender",
  "titleMap": [
    "1:Male",
    "2:Female"
  ]
}

However, I need both 1 and Male in their own double quotations inside { } instead of [ ] as shown below.
{
  "type": "string",
  "title": "Gender",
  "titleMap": {
    "1": "Male",
    "2": "Female"
  }
}

A: enum is a keyword in C# so you need to prepend @ to enum
gender = new
                            {
                                type = "string",
                                title = "Gender",
                                @enum = new string[3]{"male", "female", "alien"}
                            }

A: From what I understand, you are trying to serialize an array of enum values as their text names into JSON. The simplest solution for that is to add an array or list of enums property to your TestViewModel and use the JsonStringEnumConverter converter to serialize them as strings rather than numbers.
Here's an example of how you could achieve what you are looking for.
Let's say you have some enum with a set of values:
//This is an arbitrary enum, this could be 'Gender', in your case
public enum TestEnum
{
    value1,
    value2,
    value3,
    value4,
}

And you want to write down an array of those enum values. Add a list of enums property (or array of enums) to your model. If you want the property name within the JSON to be one of the reserved words (like enum) either override the name using the JsonPropertyName attribute (and keep the name whatever makes most sense programmatically):
public class TestsViewModel_Option1
{
    // In your case, this property could be called 'Genders' to be self-documenting
    [JsonPropertyName("enum")]
    public List<TestEnum> ListOfEnums { get; set; }
}

OR, use the @ symbol if you really want the property name to be the reserved keyword and don't want to/can't use the attribute for some reason.
public class TestsViewModel_Option2
{
    // Or use fixed-size array, TestEnum[], if needed
    public List<TestEnum> @enum { get; set; }
}

And now this is what your code looks like with the JsonSerializer:
private static void SerializeListOfEnums()
{
    var model1 = new TestsViewModel_Option1
    {
        ListOfEnums = { TestEnum.value1, TestEnum.value3 }
    };

    var options = new JsonSerializerOptions
    {
        Converters = { new JsonStringEnumConverter() }
    };

    // {"enum":["value1","value3"]}
    Console.WriteLine(JsonSerializer.Serialize(model1, options));

    var model2 = new TestsViewModel_Option2
    {
        @enum = { TestEnum.value1, TestEnum.value3 }
    };

    // {"enum":["value1","value3"]}
    Console.WriteLine(JsonSerializer.Serialize(model2, options));
}


text:
Q: foundation 5 reveal modal not working Good day to all,
I'm using foundation 5 for my mini project. I want to use the reveal/modal feature of the framework. But it seems it does not work.
index.html
<!DOCTYPE html>

    <title>Job Posting</title>
    <link rel="stylesheet" type="text/css" href="../css/normalize.css">
    <link rel="stylesheet" type="text/css" href="../css/foundation.min.css">

  click

      Modal
      x

I'm pretty sure that the browser loaded the js as it does not show any error in the debugger. And I know it's somewhere in the code that I left out but it's been a couple of hours since I ran into this. Any help would be much appreciated.

A: You might have forgot data-reveal :


text:
Q: How to read contents off a zip file from google cloud storage (GCS) in Postman javascript In postman response, the output is a URL that contains a https link to google cloud storage which contains a zip folder. This . zip folder contains an excel and a pdf file.
I am looking for one of these solutions.

*

*Either use javascript to download the zip folder, parse it and validate the contents in the folder. i.e assert to ensure the content of the zip folder contains an excel and a pdf file.

*Make a GET request directly to gcs API via encoded url to get the contents of the zip folder. At the moment I can get to gcs cloud API, it seems to provide me with metadata, not the contents of the zip folder
For the 2nd solution, I have tried using this URL to get to the GCS
    https://www.googleapis.com/storage/v1/b/gcs-bucket-service/o/361b6d18-3881-49ed-994b-442574%2Freport_1.zip
This provides the metadata
I would be happy for either of the solutions to work

A: You can't have an AJAX request open the download prompt since you physically have to navigate to the file to prompt for download. Instead, you could use a success function to navigate to download.php. This will open the download prompt but won't change the current page.
$.ajax({
url: 'download.php',
type: 'POST',
success: function() {
    window.location = 'download.php';
   }
});


text:
Q: Getting unknown characters while decoding string in c# I am working on a project where I am submitting my form data as xml and storing it in xml form to my db.
While decoding the xml data in c# I am getting unknown characters. Actually I am saving spanish text for eg  " Introduzca texto aquí ".
So in xml I get this 'í' character as %ED and while decoding it using HttpUtility.UrlDecode(formData) I am getting � instead of í.
XML Data before decoding
%3CArrayOfDiary%3E%3CDiary%3E%3CDate%3E03042015%3C/Date%3E%3CSituation%3EIntroduzca%20texto%20aqu%ED%3C/Situation%3E%3CSensation%3EIntroduzca%20texto%20aqu%ED%3C/Sensation%3E%3CConcern%3EIntroduzca%20texto%20aqu%ED%3C/Concern%3E%3CBeliefRating%3E0%3C/BeliefRating%3E%3CAnxietyRating%3E0%3C/AnxietyRating%3E%3C/Diary%3E%0A%20%20%3CArrayOfDiary%3E

Data after decoding
<ArrayOfDiary><Diary><Date>03042015</Date><Situation>Introduzca texto aqu�</Situation><Sensation>Introduzca texto aqu�</Sensation><Concern>Introduzca texto aqu�</Concern><BeliefRating>0</BeliefRating><AnxietyRating>0</AnxietyRating></Diary>
<Diary>
<Date>03042015</Date>
<Situation> Introduzca texto aqu�</Situation>
<Sensation> Introduzca texto aqu�</Sensation>
<Concern> Introduzca texto aqu�</Concern>
<BeliefRating>0</BeliefRating>
<AnxietyRating>0</AnxietyRating>
</Diary>
</ArrayOfDiary>

Please help me. Thanks

A: Without seeing where the data is coming from, I assume that it has been created with an encoding of ISO-8859-1.
You can get around the problem by using the appropriate Encoding in UrlDecode:
Option Infer On
' ....
Dim s = "%3CArrayOfDiary%3E%3CDiary%3E%3CDate%3E03042015%3C/Date%3E%3CSituation%3EIntroduzca%20texto%20aqu%ED%3C/Situation%3E%3CSensation%3EIntroduzca%20texto%20aqu%ED%3C/Sensation%3E%3CConcern%3EIntroduzca%20texto%20aqu%ED%3C/Concern%3E%3CBeliefRating%3E0%3C/BeliefRating%3E%3CAnxietyRating%3E0%3C/AnxietyRating%3E%3C/Diary%3E%0A%20%20%3CArrayOfDiary%3E"
Dim enc = Encoding.GetEncoding("ISO-8859-1")
Dim txt = Web.HttpUtility.UrlDecode(s, enc)

To avoid that hassle, you could use <meta charset="utf-8" /> in the <head> section of the web page. You can still have <html lang="es"> if you want to indicate that the page is in Spanish.

A: https://msdn.microsoft.com/en-us/library/ms246590.aspx
Check out this page it should help you, it sounds like you may not have the right LIP


text:
Q: How to create circular polygon in openlayers 3? So i would really like to modify this example:
http://openlayers.org/en/v3.0.0/examples/tissot.html?q=circle
Problem is that when I try to apply it to my map it doesn't work, probably because I use OSM style which is not spherical:
var map = new ol.Map({
  layers: [
    new ol.layer.Tile({
        source: new ol.source.OSM()
      }),
    new ol.layer.Vector({
      source: vectorSource
    })
  ],
  renderer: 'canvas',
  target: 'map',
  view: new ol.View({
    center: ol.proj.transform([2.1833, 41.3833], 'EPSG:4326', 'EPSG:3857'),
    zoom: 2
  })
});

And for the question: how to create circular polygon?
As I can see, there are two choices:

*

*Somehow convert geom.Circle in geom.Polygon, which I can't do, based on my noob level

*Create my own function to do that, something like openlayers 2:
OpenLayers.Geometry.Polygon.createRegularPolygon = function(origin, radius, sides, rotation) {
    var angle = Math.PI * ((1/sides) - (1/2));
    if(rotation) {
        angle += (rotation / 180) * Math.PI;
    }
    var rotatedAngle, x, y;
    var points = [];
    for(var i=0; i

Has anyone got to the same point in their GIS master life? Which one is better? or is there a hidden path, that only Wise and Strong ones can see? Help me please!

A: As others have correctly pointed out, the GeoJSON and WKT formats do not support circular geometries in any way.  Circles are not in the KML specification either. This makes it a pain when trying to write out a map frame to KML, GeoJSON or WKT.
OpenLayers v3 does have a way to approximate a circle with a polygon, but it isn't pretty as it involves converting to great circle distance.  See the API reference for the ol.geom.Polygon.circular method here: http://openlayers.org/en/v3.5.0/apidoc/ol.geom.Polygon.html#circular
An example of the ol.geom.Polygon.circular method is shown below, but can also be seen in this OpenLayers tissot indicatrix example.
 var lowpoly = ol.geom.Polygon.circular(
  /* WGS84 Sphere */
  new ol.Sphere(6378137),
  circle.getCenter(),
  circle.getRadius(),
  /* Number of verticies */
  12);

Alternatively, you can use fromCircle which, at the time of this post, is experimental.
var lowpoly = ol.geom.Polygon.fromCircle(
  circle,
  /* Number of verticies (optional) */
  12,
  /* Start angle (optional) */
  90
);

For something that you can play with, see my jsFiddle here: https://jsfiddle.net/a1syw4od/9/

A: If you are interested in creating a simple circular polygon then use:
new ol.geom.Circle(
            ol.proj.transform([longitude, latitude], 'EPSG:4326', 'EPSG:3857'),
            radius_meters),
            'XY'
        )

Source: http://openlayers.org/en/v3.0.0/apidoc/ol.geom.Circle.html
(remove the stable tick at the top of the page)


text:
Q: Failing core web vitals despite 90%+ PSI results Site : www.purelocal.com.au
Tested 1000's of URL's in Google PSI - all are Green 90%+.
However , in Google webmaster tools = 0 GOOD URLS.
Can someone please explain what Google requires and what we can do to pass core web vitals before JUNE ?
We've spent months optimising everything and cannot further optimise but Google says that NONE of our URL's pass core web vitals...it's just ridiculous.

A: Looking at your website's report in the CrUX Dashboard, there are a couple of things you could optimize more:

First, your site's LCP is right on the edge of having 75% good desktop experiences, and phone experiences are below that at 66% good. https://web.dev/optimize-lcp/ has some great tips for addressing LCP issues.
Second, while your site's desktop FID experiences are overwhelmingly good (98%), you do seem to have a significant issue for phone users (only 44% good). There are similarly great tips in the https://web.dev/optimize-fid/ article.

While the big green "98" score on PSI makes it look like the page is nearly perfect, what matters most in terms of the user experience is real field data. That information can be found in the "Field Data" and "Origin Summary" sections of the report.

You mentioned in the comments that your server response time is an issue. I can confirm this with lab testing:

https://webpagetest.org/graph_page_data.php?tests=210506_AiDcJ0_0283e8c51814788904bdf19cebe7a5c8&medianMetric=TTFB&fv=1&median_run=1&zero_start=true&control=NOSTAT#TTFB

https://webpagetest.org/result/210506_AiDcJ0_0283e8c51814788904bdf19cebe7a5c8/8/details/#waterfall_view_step1
The long light blue bar on line 1 of the chart above shows how long it takes your server to respond to the request. In this case the time to first byte (TTFB) is 1.132 seconds. This is going to be a huge problem for most users to achieve a fast LCP because in these tests it takes 1.9 seconds just to get the HTML to the client. No amount of frontend optimizations can make the HTML arrive sooner than that. You need to focus on backend optimizations to get the TTFB down.
I can't give you any specific hosting recommendations but it does seem like the shared hosting is adversely affecting your users' LCP performance.


text:
Q: Converting a birthdate to its lunar year equivalent Is it possible to figure out someones lunar birth day given that you know the regular (gregorian) day?
There is an example on the joda time website that shows:
// setup date object for midday on May Day 2004 (ISO year 2004)
DateTime dtISO = new DateTime(2004, 5, 1, 12, 0, 0, 0);

// find out what the same instant is using the Islamic Chronology
DateTime dtIslamic = dtISO.withChronology(IslamicChronology.getInstance());

Is this ISO year representing the gregorian representation?

A: The ISO chronology is an extended (proleptic) Gregorian calendar, meaning that strictly speaking, there was no Gregorian chronology before the Gregorian calendar was accepted in 1582, but the ISO chronology extends it before that. So yes, for all modern (post-1582) dates, the ISO year is the same as the Gregorian year.
As an alternative, there's the GJChronology, which automatically switches between Julian and Gregorian chronologies, depending on the actual date, and a DateTime constructor that accepts the desired chronology as a parameter.


text:
Q: Laravel 4 base/master view I've recently gotten some problems. There is an model from which I pull some data and things. There is a menu link that I want to be on every page I enter, so I've put it into the base/master view. But the problem is, I need to enter ->with blabla thing on every public function in every controller. How could I not do that? I mean is there anyway around it? I don't want to do that with thingy on every controller method/function. Here's my code:
                    @if ( Auth::guest() )

                          Register

                          Log in

              @else

                    {{ (Auth::user()->name) }}

                        Account Managment

                        Change Password

                        Log out

                @endif

A: You can define a View Composer :
View::composer(array('your.first.view','your.second.view'), function($view)
{
    $view->with('count', User::count());
});

Everytime you call your view, a user count will be bound to it automatically.
Edit:
About where to use it, it's up to you and it depends on your app, but you might use pp/start/global.php if you  don't have a better place to put it. It just have to be executed before your those views.

A: @Antonio's answer is a good way to do this. You can also use View::share(); to accomplish this with a shorter code.
View::share(array(
    'foo' => 'bar'
));


text:
Q: Loading large background images in cocos2d Im working on an iphone platforms game developed using cocos2d and box2d which has to use a very large image as a background, my question is this:
-which is the better way to load the image?? (I'm talking about an image which can be 14K pixels long), is it better to cut in smaller images an keep loading them as the player moves??
-Should I keep in memory as invisible or use the addChild method to load them as I need them and the removeChild to remove the previous one?
Thanks in advance, any answer will be welcome :)

A: You can't use textures larger then 1024x1024 or 2048x2048 for iphone/ipod 4 (maybe iPad too). So the only way to render such big image is rendering it's parts.
I would try to load the parts as the player moves (better in a separate thread).
Also maybe it is possible for you to use Parallax background. If so - use it.
If your image is made from a lot of identical parts then it's a good idea to use CCTMXTiledMap.


text:
Q: How to retrieve only containers running a specific image in go-dockerclient? I am using go-dockerclient library to retrieve list of containers I got all containers by using the ListContainers function
conts, err := client.ListContainers(docker.ListContainersOptions{All: true})

But I want to get only containers that are running a specific image
I tried running
conts, err := client.ListContainers(docker.ListContainersOptionsFilters: map[string][]string{"Image": {"<imagename>:<version>"}}})

but I got the error Invalid filter:'Image' meaning that there is no filter field called Image
So does anybody have a solution to get only containers that are running a specific image?
Thank you

A: instead of image field you should use ancestor so you can use
conts, err :=client.ListContainers(docker.ListContainersOptionsFilters: map[string][]string{"ancestor": {"<imagename>:<version>"}}}

A: Just see the docker ps filter options, the website below lists all filters supported currently.
https://github.com/docker/cli/blob/master/docs/reference/commandline/ps.md


text:
Q: r read json files incomplete final line found on I would like to read a json file where the sutructure is like below. I tried fromJson but it just read the first block.  Can you help me on specify the delimiter to read all the file?
Thank you so much
json_data <- fromJSON(paste(readLines("C:C:/Users/aa/Data-test.json"), collapse=""))

Warning message:
      In readLines("C:/Users/aa/Data-test.json") :
        incomplete final line found on 'C:/Users/jsalim/Desktop/Docapost_20160718/FILES/Extract-Morgane_1307/Data-device2.json'

{
  "id" : "aaa",
  "dateModification" : "2016-06-04T04:29:30Z",
  "active" : true,
.....
}
{
  "id" : "bbbb",
  "dateModification" : "2016-06-04T04:29:30Z",
  "active" : true,
.....
}
{
  "id" : "ccc",
  "dateModification" : "2016-06-04T04:29:30Z",
  "active" : true,
.....
}

A: I believe that as in the answer suggested in this question, you just need to enter a carriage return at the end of the line (that is, there should be a single empty line at the end of your file).  This worked for me in the same scenario.


text:
Q: Maximum continued solution of an initial value problem Consider the intervals $J=[0, \infty)$ and $D=(0,\infty)$ and the initial value problem $\begin{cases} u'(t)=f(t,u(t)) \,\,\,\,\,,\,\, t \in J \\u(0)=2\end{cases}$
where $f:J \times D \to \mathbb R$  , $f(t,v):=-\frac{t}{v} e^{t^2}.$
How can I determine a maximum continued solution of the IVP and check if it is unique?
Some hints are much appreciated.

A: The standard existence-uniqueness theorem applies to initial value problems where $f$ is such that $\partial f/\partial v$ is continuous. The given $f$ has continuous partial derivatives as long as $v$ does not turn into zero.
To find out how long we have until the solution hits zero, solve the equation. It's separable. To keep things rigorous, let's say that $w=u^2$, and then
$$w' = 2uu' = -2te^{t^2} \tag1$$
which leads to $w(t) = C - e^{t^2}$. Here $C=5$ from the initial condition.
Now you know that $u(t) = \sqrt{5-\exp(t^2)}$ for as long as the expression under the root is positive. This is the maximal interval of existence, because if a solution $u$ existed beyond it, the function $u^2$ would be a nonnegative solution of (1), but we know exactly what the solutions of (1) are.


text:
Q: Concurrent Remote Procedure Calls to C++ Object I would like to have a class written in C++ that acts as a remote procedure call server.
I have a large (over a gigabyte) file that I parse, reading in parameters to instantiate objects which I then store in a std::map.  I would like the RPC server to listen for calls from a client, take the parameters passed from the client, look up an appropriate value in the map, do a calculation, and return the calculated value back to the client, and I want it to serve concurrent requests -- so I'd like to have multiple threads listening.  BTW, after the map is populated, it does not change.  The requests will only read from it.
I'd like to write the client in Python.  Could the server just be an HTTP server that listens for POST requests, and the client can use urllib to send them?
I'm new to C++ so I have no idea how to write the server.  Can anyone point me to some examples?

A: Maybe factors can affect the selection.
One solution is to use fastcgi.
Client sends HTTP request to HTTP server that has fastCGI enabled.
HTP server dispatch the request to your RPC server via the fastcgi mechanism.
RPC server process and generates response, and sends back to http server.
http server sends the response back to your client.

A: If you must write the server in C++, and you have no idea how to do so, you definitely want to use a framework.
There are many choices out there, and StackOverflow is not a good place to ask for opinions about different choices. But to give you one example, JsonRpc-Cpp lets you implement a JSON-RPC (over either raw TCP or HTTP) server in about 10 lines of code, plus a line of boilerplate for each RPC you want to expose. Much easier than writing a server from scratch.
So, here's an example server:
#include <cstdlib>
#include <jsonrpc.h>

class Service {
public:
    bool echo(const Json::Value &root, Json::Value &response) {
        response["jsonrpc"] = "2.0";
        response["id"] = root["id"];
        Json::Value result;
        result["params"] = root["params"];
        response["result"] = result;
        return response;
    }
}

int main(int argc, char *argv[]) {
    int port = std::atoi(argv[1]); // add some error handling here...

    Json::Rpc::TcpServer server("127.0.0.1", port);
    Service service;
    server.AddMethod(new Json::Rpc::RpcMethod<Service>(service,
                     &Service::echo, "echo");
    server.Bind(); // add error handling again
    server.Listen();
    while(true) server.WaitMessage(1000);
}

However, it will probably be even easier if you write the server in Python, or use a WSGI web server and write a service in Python, and call the C++ code from Python (whether via ctypes, or by building a wrapper with something like Cython or SIP).
Here's the same server in Python using bjsonrpc:
import bjsonrpc

class Service(bjsonrpc.handlers.BaseHandler):
    def echo(self, *args):
        return {'params': args}

server = bjsonrpc.createserver(handler_factory = Service)
server.serve()


text:
Q: OpenCL reported device version different between clinfo / clGetDeviceInfo I'm just trying to dive into OpenCL 2.0. I'm using an AMD R7 260X GPU with AMD APP SDK 3.0 (final) with most current driver (Crimson-something, 2348.4) on Win10-64 with 16GB RAM. Compiler is Visual Studio 2015.
First thing I did was querying some information on my system with clInfo. Output was as expected, especially the device OpenCL C Version:
Platform Name:                                 AMD Accelerated Parallel Processing
Number of devices:                               2
Device Type:                                   CL_DEVICE_TYPE_GPU
Vendor ID:                                     1002h
Board name:                                    AMD Radeon R7 200 Series
Platform ID:                                   00007FFE91EF0188
Name:                                          Bonaire
Vendor:                                        Advanced Micro Devices, Inc.
Device OpenCL C version:                       OpenCL C 2.0
Driver version:                                2348.4
Profile:                                       FULL_PROFILE
Version:                                       OpenCL 2.0 AMD-APP (2348.4)

Next thing was playing around with some of the samples from AMD APP SDK. Quickly I noticed, an OpenCL 2.0 didn't execute properly. I stepped through the code and noticed a function, which is gathering device information with clGetDeviceInfo. At this point, the reported device OpenCL C version (see screenshot 1) differs from what I got from clInfo, and therefore, the samples, which requires OpenCL 2.0 don't execute.
What did I do wrong?
clGetDeviceInfo

A: Switching from target platform Win32 to x64 strangely resolved the problem for me. clGetDeviceInfo reports now OpenCL 2.0 capabilities for my GPU.


text:
Q: Gradle 7.3.3 run Junit unable to create TestEngine I am using Gradle 7.3.3, but require JUnit and PowerMock
I have configured settings.gradle as:
        version('spring', '5.3.15')
        alias('spring-test').to('org.springframework', 'spring-test').versionRef('spring')

        //https://mvnrepository.com/artifact/junit/junit
        version('junit', '4.13.2')
        alias('junit').to('junit', 'junit').versionRef('junit')

        //https://mvnrepository.com/artifact/org.mockito/mockito-core
        version('mockito', '3.12.4')
        alias('mockito').to('org.mockito', 'mockito-core').versionRef('mockito')

        //https://mvnrepository.com/artifact/org.powermock/powermock-api-mockito2
        version('powermock', '2.0.9')
        alias('powermock-api').to("org.powermock", "powermock-api-mockito2").versionRef('powermock')
        alias('powermock-api-support').to("org.powermock", "powermock-api-support").versionRef('powermock')
        alias('powermock-core').to("org.powermock", "powermock-core").versionRef('powermock')
        alias('powermock-module-junit4').to("org.powermock", "powermock-module-junit4").versionRef('powermock')
        alias('powermock-module-junit4-common').to("org.powermock", "powermock-module-junit4-common").versionRef('powermock')
        alias('powermock-reflect').to("org.powermock", "powermock-reflect").versionRef('powermock')

        bundle('test', ['junit', 'mockito', 'powermock-api', 'powermock-api-support', 'powermock-core', 'powermock-module-junit4', 'powermock-module-junit4-common', 'powermock-reflect', 'spring-test'])

And then in the module's build.gradle, I included this
dependencies {
    testImplementation libs.bundles.test
}

test {
    useJUnitPlatform()
}

Test class is as below
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.modules.junit4.PowerMockRunner;
@RunWith(PowerMockRunner.class)
public class MyTest {

    @Test
    public void test(){
        System.out.print("hello");
    }
}

After running the test, I get the report for the failing test with the following stacktrace
org.gradle.api.internal.tasks.testing.TestSuiteExecutionException: Could not complete execution for Gradle Test Executor 6.
    at org.gradle.api.internal.tasks.testing.SuiteTestClassProcessor.stop(SuiteTestClassProcessor.java:63)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:36)
    at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:24)
    at org.gradle.internal.dispatch.ContextClassLoaderDispatch.dispatch(ContextClassLoaderDispatch.java:33)
    at org.gradle.internal.dispatch.ProxyDispatchAdapter$DispatchingInvocationHandler.invoke(ProxyDispatchAdapter.java:94)
    at com.sun.proxy.$Proxy2.stop(Unknown Source)
    at org.gradle.api.internal.tasks.testing.worker.TestWorker$3.run(TestWorker.java:193)
    at org.gradle.api.internal.tasks.testing.worker.TestWorker.executeAndMaintainThreadName(TestWorker.java:129)
    at org.gradle.api.internal.tasks.testing.worker.TestWorker.execute(TestWorker.java:100)
    at org.gradle.api.internal.tasks.testing.worker.TestWorker.execute(TestWorker.java:60)
    at org.gradle.process.internal.worker.child.ActionExecutionWorker.execute(ActionExecutionWorker.java:56)
    at org.gradle.process.internal.worker.child.SystemApplicationClassLoaderWorker.call(SystemApplicationClassLoaderWorker.java:133)
    at org.gradle.process.internal.worker.child.SystemApplicationClassLoaderWorker.call(SystemApplicationClassLoaderWorker.java:71)
    at worker.org.gradle.process.internal.worker.GradleWorkerMain.run(GradleWorkerMain.java:69)
    at worker.org.gradle.process.internal.worker.GradleWorkerMain.main(GradleWorkerMain.java:74)
Caused by: org.junit.platform.commons.PreconditionViolationException: Cannot create Launcher without at least one TestEngine; consider adding an engine implementation JAR to the classpath
    at org.junit.platform.commons.util.Preconditions.condition(Preconditions.java:296)
    at org.junit.platform.launcher.core.DefaultLauncher.<init>(DefaultLauncher.java:48)
    at org.junit.platform.launcher.core.LauncherFactory.create(LauncherFactory.java:105)
    at org.junit.platform.launcher.core.LauncherFactory.create(LauncherFactory.java:75)
    at org.gradle.api.internal.tasks.testing.junitplatform.JUnitPlatformTestClassProcessor$CollectAllTestClassesExecutor.processAllTestClasses(JUnitPlatformTestClassProcessor.java:97)
    at org.gradle.api.internal.tasks.testing.junitplatform.JUnitPlatformTestClassProcessor$CollectAllTestClassesExecutor.access$000(JUnitPlatformTestClassProcessor.java:79)
    at org.gradle.api.internal.tasks.testing.junitplatform.JUnitPlatformTestClassProcessor.stop(JUnitPlatformTestClassProcessor.java:75)
    at org.gradle.api.internal.tasks.testing.SuiteTestClassProcessor.stop(SuiteTestClassProcessor.java:61)
    ... 18 more

So, what is wrong with my configuration and how do I make this thing work with this gradle version?

A: You have a mix of JUnit5 and JUnit4, which requires extra attention to configuration.
To explain:
test {
    useJUnitPlatform()
}

useJUnitPlatform instructs Gradle to use Junit5 execution engines.

*

*Jupiter engine for JUnit5 tests

*Vintage engine for JUnit4 tests

The engine must be present on runtime classpath for tests.
In particular, the following config is invalid:
// Invalid config
dependencies {
    testImplementation 'junit:junit:4.13.2'
}

test {
    useJUnitPlatform()
}

You enable JUnit5 engine usage, but don't include any as dependency. This is precisely what happened in your build config
This results in an exception you can see in your stack trace:
Caused by: org.junit.platform.commons.PreconditionViolationException: Cannot create Launcher without at least one TestEngine; consider adding an engine implementation JAR to the classpath
    at org.junit.platform.commons.util.Preconditions.condition(Preconditions.java:296)
    at org.junit.platform.launcher.core.DefaultLauncher.<init>(DefaultLauncher.java:48)
    at org.junit.platform.launcher.core.LauncherFactory.create(LauncherFactory.java:105)
    at org.junit.platform.launcher.core.LauncherFactory.create(LauncherFactory.java:75)
    at org.gradle.api.internal.tasks.testing.junitplatform.JUnitPlatformTestClassProcessor$CollectAllTestClassesExecutor.processAllTestClasses(JUnitPlatformTestClassProcessor.java:97)
    at org.gradle.api.internal.tasks.testing.junitplatform.JUnitPlatformTestClassProcessor$CollectAllTestClassesExecutor.access$000(JUnitPlatformTestClassProcessor.java:79)
    at org.gradle.api.internal.tasks.testing.junitplatform.JUnitPlatformTestClassProcessor.stop(JUnitPlatformTestClassProcessor.java:75)
    at org.gradle.api.internal.tasks.testing.SuiteTestClassProcessor.stop(SuiteTestClassProcessor.java:61)

Now you have two options:
Option 1: Use JUnit4 only

*

*remove useJUnitPlatform()

*only use JUnit4 tests

dependencies {
    testImplementation 'junit:junit:4.13.2'
}

Option 2: Use JUnit5 platform and vintage engine
dependencies {
    testImplementation "junit:junit:4.13.2"
    testRuntimeOnly "org.junit.vintage:junit-vintage-engine:5.7.0"
}

test {
    useJUnitPlatform()
}

In the long run, consider:

*

*Moving to JUnit5 (you can mix Junit4 and JUnit5 tests if you use Junit Platform and include both engines). See Migrating from JUnit 4

*dropping PowerMock - Mockito is getting more and more features, maybe you are in a position to drop this dependency.


text:
Q: Consume CommonJS Module Angular 2 I'm trying to write a simple Angular 2 application which consumes a CommonJS Node module (Node Yelp). Angular 2 by default uses SystemJS which has the ability to load different module formats.
I have tried several different SystemJS configurations and import statements, but all of them seem to end with

SyntaxError: Unexpected token <(…)

Currently, my SystemJS configuration looks like
System.config({
    packages: {
      app: {
        format: 'register',
        defaultExtension: 'js'
      }
    },
    map: {
        yelp: 'node_modules/yelp'
    }
});

System.import('app/main')
    .then(null, console.error.bind(console));

and my simple AppComponent.ts
import {Component} from 'angular2/core';
import Yelp from 'yelp';

@Component({
    selector: 'app',
    templateUrl: '/app/app.component.html'
})
export class AppComponent {
    constructor(yelp: Yelp) {
        console.log(yelp);
    }
}

I'm still trying to wrap my head around the whole module system, so I'm not exactly sure what to change here. Any results online seem to be out dated, or not direclty related to loading CommonJS node modules with SystemJS.

A: I think that you could try something like that:
System.config({
  packages: {
    app: {
      format: 'register',
      defaultExtension: 'js'
    },
    yeld: {
      main: index.js
    }
  },
  map: {
    yelp: 'node_modules/yelp'
  }
});

and
import * as Yelp from 'yelp';

A: The solution, as I expected, turned out to be an easy one.
Don't try roll your own System.config when using NPM packages in Angular 2
Instead, use jspm to install packages. By doing so, all of the System.config will be taken care of by jspm. In this particular case, it was as easy as

jspm install npm:yelp

Then just adding
import Yelp from 'npm:yelp@1.0.1';

to the top of my AppComponent.ts file


text:
Q: Failed to start Automation Anywhere Control Room: Bad Gateway After I installed Automation Anywhere 11 with SQL Server 2017 on windows server 2012, I could not launch the control room getting bad gateway message.
Could anyone help identifying the problem??

A: There are several possible reasons for this to happen, the one most easy to miss is your SQL login not having permissions to access your DB.
Open your SQL Management Studio and check that your have login logging enabled (Server Properties -> Security -> Login auditing). It is set to Failed only by default, you can change it to Both successful and failed if you wish.

Then attempt to login to Control Room and then check the logs.

You are most likely going to see an account trying and failing to connect to the DB. Give that account sufficient privileges and try again.

A: I was experiencing something similar after I restarted my Automation Anywhere Control Room Service from services.msc as adviced in AA forum for getting this error.

grid is invalid state...contact administrator

But, after I restarted the Automation Anywhere Enterprise Auto Login Service V11 service the control room worked fine.


text:
Q: How to get qty of a product using rest api I want to get product info including the product qty how can i achieve it.
Currently i am using
rest/default/V1/products?searchCriteria
To get all the product but it is missing qty attribute in it.
Here is the result
   [0] => stdClass Object
      (
        [id] => 346
        [sku] => WATCH
        [name] => WATCH
        [attribute_set_id] => 4
        [price] => 3
        [status] => 1
        [visibility] => 4
        [type_id] => simple
        [created_at] => 2018-06-03 05:36:33
        [updated_at] => 2018-06-03 05:36:33
        [weight] => 1
        [product_links] => Array
            (
            )

        [tier_prices] => Array
            (
            )

        [custom_attributes] => Array
            (
                [0] => stdClass Object
                    (
                        [attribute_code] => meta_title
                        [value] => WATCH
                    )

                [1] => stdClass Object
                    (
                        [attribute_code] => meta_keyword
                        [value] => WATCH
                    )

                [2] => stdClass Object
                    (
                        [attribute_code] => meta_description
                        [value] => WATCH
                    )

                [3] => stdClass Object
                    (
                        [attribute_code] => image
                        [value] => /p/i/pinking_swatch_sq_dia_beige_1.png
                    )

                [4] => stdClass Object
                    (
                        [attribute_code] => small_image
                        [value] => /p/i/pinking_swatch_sq_dia_beige_1.png
                    )

                [5] => stdClass Object
                    (
                        [attribute_code] => thumbnail
                        [value] => /p/i/pinking_swatch_sq_dia_beige_1.png
                    )

                [6] => stdClass Object
                    (
                        [attribute_code] => category_ids
                        [value] => Array
                            (
                                [0] => 4
                                [1] => 61
                            )

                    )

                [7] => stdClass Object
                    (
                        [attribute_code] => options_container
                        [value] => container2
                    )

                [8] => stdClass Object
                    (
                        [attribute_code] => required_options
                        [value] => 0
                    )

                [9] => stdClass Object
                    (
                        [attribute_code] => has_options
                        [value] => 0
                    )

                [10] => stdClass Object
                    (
                        [attribute_code] => url_key
                        [value] => watch
                    )

                [11] => stdClass Object
                    (
                        [attribute_code] => gift_message_available
                        [value] => 2
                    )

                [12] => stdClass Object
                    (
                        [attribute_code] => swatch_image
                        [value] => /p/i/pinking_swatch_sq_dia_beige_1.png
                    )

                [13] => stdClass Object
                    (
                        [attribute_code] => tax_class_id
                        [value] => 2
                    )

            )

    )

A: Try using /V1/stockItems/:productSku
For more details, you can go through https://devdocs.magento.com/guides/v2.0/rest/list.html#cataloginventory


text:
Q: About Using size_t Suppose I wanted to initialize an array of characters, with the 'x' character, using a loop, should I use an int or a size_t?
char *pch = (char *) malloc(100);
for (size_t s = 0; s < 100; s++)
    pch[s] = 'x';

Note: I know about memset and other 'tricks', my question is just about int VS size_t.

A: Since the variable is indexing an array, using size_t is more appropriate as an array index can't (normally) be negative.
Also, since array indexes are often compared against the result of a strlen call or sizeof operator, both of which yield a size_t, using an int could generate warnings for signed/unsigned comparisons.
However, if you're initializing all bytes of a buffer to a given value, you should instead use memset:
memset(pch, 'x', 100);

A: size_t is more appropriate for indexing arrays as it is guaranteed to have the correct range for all array sizes.  Yet there are some issues to consider:

*

*size_t is an unsigned type, so you must be careful to only compute positive values in tests.
For example iterating downwards this way will not work:
for (size_t i = size - 1; i >= 0; i--) {
     array[i] = 0;
}

This naive approach has 2 problems: it iterates even if size is 0 and it loops forever because i >= 0 is always true.
A better approach is this:
for (size_t i = size; i-- > 0;) {
     array[i] = 0;
}

*size_t may be larger than int, so the format %d in printf is inappropriate for index values of this type.  The standard conversion specifier is %zd, but it is not supported on many windows systems. You may need to cast the size_t value as (int) or use %llu and cast the size_t value as unsigned long long.

*Some people consider size_t inelegant, maybe because of the _ or just because they are not used to it.
For these and other reasons, it is quite common to see index variables defined as int.  While it is OK for small arrays and short loops, it will cause hard to find bugs in code where these assumptions end up failing.

A: The generated code is likely to be identical, especially for such a simple case. With more complex math, signed types (if you can safely use them) are somewhat more optimizable because the compiler is allowed to assume they never overflow. With signed types, you also won't get unpleasant surprises if you decide to compare against a negative index.
So if you sum it up:
        very_large_arrays negative_comparison_safe maybe_faster
int     no                yes                      yes
size_t  yes               no                       no

it looks like int could be preferable with definitely-small (<2^15 or perhaps 2^31 if your architecture targets guarantee that) ranges unless you can think of another criterion where size_t wins.
The advantage of size_t is that it will definitely work for any array no matter the size as long as you aren't comparing against negative indices. (This may be much more important than negative-comparison-safety and potential speed gains from undefined overflow).
ssize_t (== signed size_t) combines the best of both, unless you need every last bit of size_t (you definitely don't on a 64 bit machine).


text:
Q: Why do all browsers' user agents start with "Mozilla/"? All popular browsers' user agent strings, even Internet Explorer's, start with Mozilla/. Why is this the case?

A: Reason for this are the infamous browser wars.
In short - browsers started to pretend to be some other browser, because some websites served content based on which browser asked for it and they also wanted content meant for other browsers.
I find it surprising it still haven't been solved to this day. Since userAgent can't be safely removed for legacy reasons, why some new feature clearly identifying a browser wasn't introduced? Yes, most of the time you don't need browser detection, but rather a feature detection, but it is not built-in JS neither!

A: It is a long and sad story.
In summary:

*

*Mozilla browser gets released, with User-Agent Mozilla/1.0 (Win3.1). It is publicly renamed to Netscape, but in its User-Agent it keeps its original name .

*Internet Explorer is released. It spoofs Netscape by starting its User-Agent with Mozilla/ because web servers were routinely browser sniffing and serving pages with frames - a feature supported by both Netscape and IE, but not other browsers of the era - to Netscape only.

*Over time, Gecko, Konqueror, Opera, Safari and Chrome each decide to similarly spoof the User-Agent of some previous browser in order to manipulate browser-sniffing web pages into correctly understanding their browser's features. As part of this spoofing, all the browsers start their User-Agents with Mozilla/, like the browsers before them had done. Plenty of other nonsense also results, like modern Chrome's User-Agent simultaneously claiming to be Mozilla, Chrome, Safari, and 'like Gecko'.

A: I think it had to do with: http://en.wikipedia.org/wiki/User_agent#User_agent_spoofing
Back in the early days, Netscape (code named Mozilla) was the main rival of IE, and they wanted to prevent being rejected by sites rejecting browsers other than Netscape.

A: Because that's how Netscape identified itself, and Microsoft wanted to work with sites that would detect Netscape and reject anything else.

A: Mozilla/5.0 is the general token that says the browser is Mozilla compatible, and is common to almost every browser today.
for more detail click here

A: As mentioned by @Jason "Its a long story". Summing that story up "its just every browser pretends to be Mozilla"
After trying everything, I have finally used: http://www.useragentstring.com/
You can use the above website to get the formatted user agent and OS.
They have an API which you can use directly...


text:
Q: Thin + Nginx Production ready combination for RubyOnRails Application I have recently installed Nginx + Thin on my deployment server, but i am not sure how this will perform in last requests & responses situation. lets say 1000/req per sec.
so the speed on thin is good with 10-100 req /per sec
I wanted to know on higher volumes of data being processed on the request/response cluster.
Guide me on this :-)

A: Multiple thin processes and nginx are capable of providing lots of speed, depending on what your application is doing. So, the problem will be your application code, the speed of your application server, and your database server.
Scaling Rails has been recently covered in depth by the Scaling Rails Screencasts. I recommend you start there. My 5 step program to scaling Rails would be:

*

*First step is to have the tools to look at what is slow in your application. Do not spend time optimizing everything in your application when you don't know what the problem is.

*The easiest way to be able to handle lots of requests/second is with page caching.

*If you can't do that, cache everything possible (fragment caching, use memcached to cache data, etc), to speed up your application.

*After that, optimize your application as best as possible, make SQL queries fast, index everything, etc.

*If you still need more speed, throw more hardware at the problem. Get a big, powerful database server, a bunch of app servers, and proxy your requests across them. You can start here, too, but it will only delay the optimization process.

A: If you have a single server I think that the main key is, apart from everything already mentioned, is don't skimp on the specs of it. Trying to get too much to run on too little is just a recipe for disaster.
It is also a good idea to get monit or God monitoring your thin instances, I started out with God, but it leaked memory pretty bad on Ruby 1.8.6 so I stop using it in favour of monit. Monit is written in C I believe and has a tiny memory footprint so I'd recommend that one.
If all that seems like a bit much to keep nginx and thin playing nicely you may want to look into an all in one solution like Passenger or LiteSpeed. I have very little experience with these so can offer no substancial advice for them.


text:
Q: Recorrer Array JSON en PHP Necesito Recorrer un array JSON en PHP
me devuelve lo siguiente:
{
  "SU_Result": {
    "SU_BE": [
      {
        "proABREVIATURATITULO": "",
        "proAPELLIDOMATERNO": "",
        "proAPELLIDOPATERNO": "",
        "proNOMBRES": "",
        "proNRODOCUMENTO": "",
        "proPAIS": "",
        "proTIPODOCUMENTO": "",
        "proESPECIALIDAD": "",
        "proTITULOPROFESIONAL": "",
        "proUNIVERSIDAD": ""
      },
      {
        "proABREVIATURATITULO": "",
        "proAPELLIDOMATERNO": "",
        "proAPELLIDOPATERNO": "",
        "proNOMBRES": "",
        "proNRODOCUMENTO": "",
        "proPAIS": "",
        "proTIPODOCUMENTO": "",
        "proESPECIALIDAD": "",
        "proTITULOPROFESIONAL": "",
        "proUNIVERSIDAD": ""
      }
    ]
  }
}

A: Para iterar la matriz recomiendo usar un foreach
foreach($obj as $clave => $valor) {
    print "$clave => $valor\n";
}

Puedes anidarlos hasta llegar al detalle que necesitas
foreach($obj as $valor) {
    foreach($valor as $clave2 => $valor2) {
        print "$clave2 => $valor2\n";
    }
}

Más info: http://php.net/manual/es/function.json-decode.php


text:
Q: Tower Of Hanoi - JavaScript - THe Good Parts I have seen the other Questions on SO about the Recursive function and I have read the responses but I still can't get the algorithm to click in my head
var hanoi = function (disc, src, aux, dst) {

  if (disc > 0) {
    hanoi(disc - 1, src, dst, aux);
   document.write('Move disc ' + disc + ' from ' + src + ' to ' + dst);
    hanoi(disc - 1, aux, src, dst);
  }
}

hanoi(3, 'Src', 'Aux', 'Dst');

How does the document.write(...), ever run. My Logic is First time we run the function disc is > 3. then we recursively call the function again skipping everything below so how does the document.write get a chance to run?
I understand recursion (done the basic examples) but i still can't see how you get an output. If there is a way i can run it visually and see it in action, that would help alot.

A: You can think of what will happen as a call tree (time moves from top to bottom):
hanoi(3, ...) =>
 |-> hanoi(2, ...) =>
 |    |-> hanoi(1, ...) =>
 |    |    |-> hanoi(0, ...) =>
 |    |    |    \-> (does nothing)
 |    |    |-> document.write(...)
 |    |    |-> hanoi(0, ...) =>
 |    |    |    \-> (does nothing)
 |    |  <-/ [hanoi(1, ...) finished]
 |    |-> document.write(...)
 |    |-> hanoi(1, ...) =>
 |    |    |-> hanoi(0, ...) =>
 |    |    |    \-> (does nothing)
 |    |    |-> document.write(...)
 |    |    |-> hanoi(0, ...) =>
 |    |    |    \-> (does nothing)
 |    |  <-/ [hanoi(1, ...) finished]
 |  <-/ [hanoi(2, ...) finished]
 |-> document.write(...) [halfway done!]
 |-> hanoi(2, ...) =>
 |    \-> [same pattern as the first time, with different data]
 \-> [hanoi(3, ...) finished]


text:
Q: How to remove a specific column from a file using awk? Hello everyone I am working with a text that looks as follows:
& & Training &  &  &   & Early birds &  &   &  &  & Test &   \\\hline
& EN & ES & IT & DU &  EN & ES & IT & DU  & EN & ES & IT & DU  \\\hline
Users & 152 & 110 & 38   & 34& 42 & 30 & 12 & 10 & 142 & 88 & 36 & 32 \\\hline
18-24  & 58 & 22 &  & & 16 & 6 &  & & 56 & 18 & & \\
25-34  & 60 & 56 &  & &16 & 14 & &  & 58 & 44 & &\\
35-49   & 22   & 22  &  &  & 6& 6 & &  & 20 & 18 & &\\
50+  & 12 & 10 &  & & 4& 4 & &  & 8 &8 &  & \\\hline

I am using the & symbol as a column separator, I would like to remove the seven column of my text.txt using awk, I tried:
awk -F "&" '{print $7}' text.txt

and I get:
Early birds
 ES
 30
 6
 14
 6
 4

which is the column that I want to remove from my text.txt, I would like to achieve this using awk, I would like to appreciate any suggestion.

A: sed works well for this:
$ sed -E 's/(([^&]*&){6})[^&]*&/\1/' text.txt
& & Training &  &  &   &  &   &  &  & Test &   \\\hline
& EN & ES & IT & DU &  EN & IT & DU  & EN & ES & IT & DU  \\\hline
Users & 152 & 110 & 38   & 34& 42 & 12 & 10 & 142 & 88 & 36 & 32 \\\hline
18-24  & 58 & 22 &  & & 16 &  & & 56 & 18 & & \\
25-34  & 60 & 56 &  & &16 & &  & 58 & 44 & &\\
35-49   & 22   & 22  &  &  & 6& &  & 20 & 18 & &\\
50+  & 12 & 10 &  & & 4& &  & 8 &8 &  & \\\hline

(([^&]*&){6}) matches the first six columns and saves them in group \1. [^&]*& matches the seventh.  All of that gets replaced with just the first six columns, \1.

A: With GNU awk for gensub():
$ awk '{print gensub(/(([^&]*&){6})[^&]*&/,"\\1",1)}' file
& & Training &  &  &   &  &   &  &  & Test &   \\\hline
& EN & ES & IT & DU &  EN & IT & DU  & EN & ES & IT & DU  \\\hline
Users & 152 & 110 & 38   & 34& 42 & 12 & 10 & 142 & 88 & 36 & 32 \\\hline
18-24  & 58 & 22 &  & & 16 &  & & 56 & 18 & & \\
25-34  & 60 & 56 &  & &16 & &  & 58 & 44 & &\\
35-49   & 22   & 22  &  &  & 6& &  & 20 & 18 & &\\
50+  & 12 & 10 &  & & 4& &  & 8 &8 &  & \\\hline

With other awks it's a bit more work:
$ awk 'match($0,/([^&]*&){7}/) { tgt=substr($0,1,RLENGTH); sub(/[^&]*&$/,"",tgt); $0=tgt substr($0,RLENGTH+1) } 1' file
& & Training &  &  &   &  &   &  &  & Test &   \\\hline
& EN & ES & IT & DU &  EN & IT & DU  & EN & ES & IT & DU  \\\hline
Users & 152 & 110 & 38   & 34& 42 & 12 & 10 & 142 & 88 & 36 & 32 \\\hline
18-24  & 58 & 22 &  & & 16 &  & & 56 & 18 & & \\
25-34  & 60 & 56 &  & &16 & &  & 58 & 44 & &\\
35-49   & 22   & 22  &  &  & 6& &  & 20 & 18 & &\\
50+  & 12 & 10 &  & & 4& &  & 8 &8 &  & \\\hline

or since you have a string FS rather than a regexp:
$ awk 'BEGIN{FS=OFS="&"} { j=0; for (i=1;i<=NF;i++) if (i!=7) printf "%s%s",(++j>1?OFS:""),$i; print "" }' file
& & Training &  &  &   &  &   &  &  & Test &   \\\hline
& EN & ES & IT & DU &  EN & IT & DU  & EN & ES & IT & DU  \\\hline
Users & 152 & 110 & 38   & 34& 42 & 12 & 10 & 142 & 88 & 36 & 32 \\\hline
18-24  & 58 & 22 &  & & 16 &  & & 56 & 18 & & \\
25-34  & 60 & 56 &  & &16 & &  & 58 & 44 & &\\
35-49   & 22   & 22  &  &  & 6& &  & 20 & 18 & &\\
50+  & 12 & 10 &  & & 4& &  & 8 &8 &  & \\\hline


text:
Q: Waiting for beta App Review on Testflight I had uploaded my App successfully to TestFlight, 5 days ago(with new version and new build number). Which is already uploaded on App Store (But with its Older version).
Now i have added external user to test it and select the build to test and then click on save button, then it is showing "Waiting for beta App Review".
I don't know why user is not added directly rather app goes into "Waiting for beta App Review", and how much time it will take to approve?
Please help me if anyone has faces such issue.

A: Once you add another user (ie not your apple id), then it must be reviewed by Apple first to ensure the app is safe (contains no malicious intent) for the users testing it.
Normally takes a couple of days for apple to turn around and approve.

A: There is a distinction between iTunes Connect users and people in TestFlight.
When you upload build, and it shows up, then it becomes visible to your users. But there is an approval process (presumably automated) before TestFlight users see the announcement (assuming it is approved).


text:
Q: Get file content from multipart data sent via rest request in ZF2 I need to retrieve the content of two files which I send to my ZF2 rest application using a POST request created with the Postman chrome extension. I specify the two files in the form-data dialog in postman, which are encoded in the request as follows (request preview):
...

----WebKitFormBoundaryE19zNvXGzXaLvS5C
Content-Disposition: form-data; name="blackbox-data"; filename="blackbox-data.txt"
Content-Type: text/plain

----WebKitFormBoundaryE19zNvXGzXaLvS5C
Content-Disposition: form-data; name="assessment-configuration"; filename="assessment-configuration.xml"
Content-Type: text/xml

...

I have extended the ZF2 AbstractRestfulController to handle rest requests, which works fine. How can I get the file content of the two files sent from within MyRestController::create()?
I have tried the following, but all I get are empty arrays, empty strings:
$meta = $this->request->getMetadata();
$content = $this->request->getContent();
$blackboxData = $this->request->getPost('blackbox-data');
$assessmentConfiguration = $this->request->getPost('assessment-configuration');

A: You have to use the $request->getFiles(). I do it this way:
$validFiles = array();
$data = $request->getPost()->toArray();
$postFiles = $request->getFiles();

foreach ($postFiles as $key => $file) {
    if ($file['error'] == UPLOAD_ERR_NO_FILE) continue;

    $validFiles[$key] = $file;
}

if (count($validFiles)) $data['files'] = $validFiles;

And now I have an array called $validFiles, with the successfully uploaded files, in the $data array (where I store all the post data).