text:
Q: A cartoon about football and saving the Earth I'm pretty sure it aired at MBC 3. It's a cartoon about playing football to save the planet. It's not Galactik Football or Team Galaxy. I remember one blond boy with poofy hair I think he wore something blue when playing.
When they would play it would look like they are in a round sphere, and maybe the ball was blue too and it had something special about it. I do remember something else. They had to keep it a secret from their parents, and also whenever someone scores, the ball disappears and comes back in the middle.

A: There's the anime Inazuma Eleven GO: Galaxy:

In order to save Earth from elimination, Earth Eleven must win through the [soccer] tournament against all kinds of aliens...

All the humans wear blue and white. I'm not sure if there's something special about the ball, but it does seem to be engulfed in blue fire at one point (near the start of episode 38).

A: This sounds like it might be Galactik Football, which did air on MBC 3.

Galactik Football is a 2006 French animated television series produced by Gaumont Alphanim that mixes conventional 2D animation with 3D computer graphics. Its third 26-episode season aired in Europe in June 2010.
In the universe of Galactik Football, the inhabited worlds of the Zaelion Galaxy compete in Galactik Football, a sport analogous to football, but played seven to a side. The game is complicated by the addition of the Flux, a magical energy which enhances a player's attributes such as speed, strength, and agility, or grants special powers such as teleportation. The story follows the fate of an inexperienced Galactik Football team, the Snow Kids, as they aim to compete in and win the Galactik Football Cup.

Watching some clips online, the stadium does seem to be in a sphere sort of shape. There isn't a boy with poofy blond hair, but Tia matches that description otherwise, and they all wear blue on their uniforms. The color of the ball varies, but there are episodes with partly blue balls to be certain.

Found with the search terms of cartoon space football

A: Maybe Next Gen I don't remember the blond boy (but there is a blond dog ...) There is soccer (football), but it is not the the primary plot, but used in the relationships with the bot and bullies.

It tells the story of Mai Su, a lonely rebellious teenage girl living in a world where sentient robot technology is commonplace, and 7723, a top-secret weaponized robot, who, through a chance encounter, meet each other and form an unlikely bond that they must use to stop a vicious threat.

A: This might be Sendokai Champions (2013-2014).

Zak, Cloe, Kiet and Fenzy are four unpopular kids from Earth who are not very good at sports. One day they find bracelets that have the power to transport them to another dimension. There they meet Tänpo, the master, who explains that the Zorn Empire is about to conquer the Multiverse. The Earth is in danger and, if they want to save it, there is only one way: they will have to overcome their weaknesses, learn the art of Sendokai to become warriors, and win the Great Sendokai Tournament of the Multiverse.

A group of four kids are transported to another dimension and drafted by a small, elderly alien, named Tänpo, to take part in a football-like tournament called Sendokai, which they need to win in order to prevent the Zorn Empire from conquering the Earth.
The main character, Zak, has spiky blond hair, and all four kids wear wristbands that allow them to transport back & forth between Earth and the other dimension/s, although Tänpo informs them that they must keep the tournament a secret from their parents.
Different balls are used in various episodes, but the ball they initially train with is a brown sphere surrounded by spherical teal enclosure. The kids gain powers in the other dimension/s, so all sorts of outlandish trick shots are possible.
Before any goals can be scored in the game though, the force field blocking the goal mouth must first be struck with the ball three times, at which point it vanishes. After that, a goal can be scored, and the first goal scored wins the game.


text:
Q: How can I get the least significant byte of a variable in C I'm trying to write a C function that will print a word consisting of the least significant
byte of x, and the remaining bytes of y. For example if x = 0x89ABCDEF and y =
0x76543210, this should give 0x765432EF, but how?

A: Have you tried this?
inline uint32_t combine(uint32_t x, uint32_t y) {
  return (y & 0xffffff00) | (x & 0xff);
}

Here's an example (see the result here).
#include <inttypes.h>
#include <stdio.h>

inline uint32_t combine(uint32_t x, uint32_t y) {
  return (y & 0xffffff00) | (x & 0xff);
}

main() {
  printf("%" PRIx32 "\n", combine(0x89abcdef, 0x76543210));
}

A: In order to manipulate specific bits (or bytes) within a data type, you should use the bit-wise operators.
The basic bit-wise operators are | (or), & (and), ^ (exclusive or), and ~ (NOT or complement), and they work very differently from the logical operators ||, &&, and !.
Using your variables x = 0x89ABCDEF and y = 0x76543210, let's step through a solution:
First, these are the values of x and y in binary:
    x = 1000 1001 1010 1011 1100 1101 1110 1111
    y = 0111 0110 0101 0100 0011 0010 0001 0000

I've split the 32 bits up into groups of 4 to see how hex translates to binary.
Now, we need to unset all but the last byte in x: the operation (x & 0xFF)
           x = 1000 1001 1010 1011 1100 1101 1110 1111
        0xFF = 0000 0000 0000 0000 0000 0000 1111 1111
    --------------------------------------------------
    x & 0xFF = 0000 0000 0000 0000 0000 0000 1110 1111

And we need to unset just the last byte of y: the operation (y & ~0xFF)
              y = 0111 0110 0101 0100 0011 0010 0001 0000
          ~0xFF = 1111 1111 1111 1111 1111 1111 0000 0000 (~ flips all bits)
    -----------------------------------------------------
    (y & ~0xFF) = 0111 0110 0101 0100 0011 0010 0000 0000

Now, combine our results using the "or" operation: (x & 0xFF) | (y & ~0xFF)
                  (x & 0xFF) = 0000 0000 0000 0000 0000 0000 1110 1111
                 (y & ~0xFF) = 0111 0110 0101 0100 0011 0010 0000 0000
    ------------------------------------------------------------------
    (x & 0xFF) | (y & ~0xFF) = 0111 0110 0101 0100 0011 0010 1110 1111
    Which in hex is------------7----6----5----4----3----2----E----F

Take some time to get familiar with these operations, and you shouldn't have any trouble. Also, make sure to learn other bitwise operators (<<, >>, &=, |=, etc.)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Exception of Texture2D.FromMemory() in SharpDX code I'm studying the DirectX and SharpDX(use ver.2.6.2).
Now, I try to create a texture from byte array by using Texture2D.FromMemory() method.
My sample code is as follows.
using System;
using System.Diagnostics;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;

using SharpDX;
using SharpDX.D3DCompiler;
using SharpDX.Direct3D;
using SharpDX.Direct3D11;
using SharpDX.DXGI;
using SharpDX.Windows;
using Buffer = SharpDX.Direct3D11.Buffer;
using Device = SharpDX.Direct3D11.Device;
using MapFlags = SharpDX.Direct3D11.MapFlags;

namespace HLSLTest
{
    static class Program
    {
        [STAThread]
        static void Main()
        {
            Form1 form = new Form1();
            form.Text = "D3DRendering - Test";
            form.Width = 640;
            form.Height = 480;

            Device device;
            SwapChain swapChain;

            var desc = new SwapChainDescription()
            {
                BufferCount = 1,
                ModeDescription = new ModeDescription(form.ClientSize.Width, form.ClientSize.Height, new Rational(60, 1), Format.R8G8B8A8_UNorm),
                IsWindowed = true,
                OutputHandle = form.Handle,
                SampleDescription = new SampleDescription(1, 0),
                SwapEffect = SwapEffect.Discard,
                Usage = Usage.RenderTargetOutput
            };

            Device.CreateWithSwapChain(
                SharpDX.Direct3D.DriverType.Hardware,
                DeviceCreationFlags.None,
                new[] {
                    SharpDX.Direct3D.FeatureLevel.Level_11_0,
                    SharpDX.Direct3D.FeatureLevel.Level_10_1,
                    SharpDX.Direct3D.FeatureLevel.Level_10_0,
                },
                desc,
                out device,
                out swapChain
            );

            // It's Ok, no error
            //var texture = Texture2D.FromFile<Texture2D>(device, "GeneticaMortarlessBlocks.jpg");

            // "An unhandled exception of type 'SharpDX.SharpDXException' occurred in SharpDX.dll"
            // "Additional information: HRESULT: [0x80004005], Module: [General], ApiCode: [E_FAIL/Unspecified error]"
            byte[] texArray = new byte[8];
            var texture = Texture2D.FromMemory(device, texArray);

            var textureView = new ShaderResourceView(device, texture);
        }
    }
}

However, my code occurrs the following exception.
An unhandled exception of type 'SharpDX.SharpDXException' occurred in SharpDX.dll
Additional information: HRESULT: [0x80004005], Module: [General], ApiCode:[E_FAIL/Unspecified error], Message: エラーを特定できません

I search same problem or a solution on the web but I cannot find anything.
Please give me any advices.
Thanks,

A: You can't create a texture from a memory block like this. The method Texture2D.FromMemory is expecting the same kind of texture supported by Texture2D.FromFile, the only difference is that instead of reading from the disk, it can read from memory.
Creating a texture from a raw memory block requires to create a new Texture2D() from a Texture2DDescription of the texture and a memory region of the data through the DataRectangle structure. This description includes the width, height, the pixel format, the number of mips, number of arrays...etc.  The equivalent native method is ID3D11Device::CreateTexture2D.
In the end, the D3DX functions like Texture2D.FromFile/FromMemory are using the same ID3D11Device::CreateTexture2D to create a texture.


text:
Q: He is good enough "on" or "in" English? Which is correct?

He is good enough on English.
He is good enough in English.

Intuitively I will use on, but second thought make me feel both the same, or is it bizarre to use "good enough" in this way in the first place?

A: The second sentence is the correct one.

"In" can be used to describe a belief, opinion, or object of interest.

For example:

*

*I'm interested in you.

*I believe in god.

"On" has its own use cases.
For denoting position:

I set a pencil on my desk.

For referring to device:

He is on the phone.

Or for talking about the state of something:

The house is on fire.


text:
Q: A lot of buttons that does the same thing to be more neat? I am making android application and I have the screen with text and under that I have 2 buttons. Like and Comment. I have many texts so I am thinking how can I make this with less lines of codes. Asking from guys who has more experience than me :)
Here is the picture how I have done it.

This is side thing: I want to update the buttons color and picture. I have done it in updateButtons method.

A: You can achieve this with less code using for loop with parent layout of buttons. Upload your xml layout code, so I can describe in a good way.


text:
Q: MySQL - Calculate percent of total by group State     ID     Value     Result1 (%)     Result2 (Rank)
MA        AAA    44        0.24            2
MA        BBB    12        0.07            4
MA        CCC    90        0.50            1
MA        DDD    34        0.19            3
CT        EEE    200       0.10            5
CT        FFF    300       0.15            4
CT        GGG    400       0.20            3
CT        HHH    500       0.25            2
CT        III    600       0.30            1

Is there a way to calculate percent of totals BY GROUP (in this case by "State") and then rank them in descending order?
I have the first 3 columns and I want to calculate the last 2 columns in MySQL.
I have seen plenty of examples of calculating percentages across a single group but I can't find an example where percentages are calculated across multiple groups AND are then ranked. Then I would like to limit the results to the top N (top 3 for example).

A: You can get result by:
SELECT *
FROM (
    SELECT tt.*
    ,@statewiserank := IF(@state_v = State, @statewiserank + 1, 1) AS statewiserank
    ,@state_v := State
    FROM (
        SELECT State,ID,Value, value/
            (SELECT sum(value)
            FROM yourtable it
            WHERE it.state=ot.state
            GROUP BY state) result1_perc
        FROM yourtable ot
        ORDER BY state, result1_perc DESC) tt
    )
WHERE statewiserank <= 3


text:
Q: Force new permissions on files after rsync from seedbox I have a seedbox-account which I use for torrenting. I have set up a cron job that uses rsync to download all files from the seedbox to my 14.04.1 ubuntu server. The download folder is a samba share, as I have previously used windows to organize the content into folders before moving it to a more permanent place on my server. Before upgrading to 14.04, I used 12.04 and everything worked OK.
The problem is that the files I get from the seedbox is owned by a user called "544" (this is the username generated by the seedbox, not some octal thing) and can not be deleted by my user on my server. After changing permissions on the download folder, I can delete them. Also, I have given all users permissions to read/write in the samba folder upon sharing it.
So my question is this: Is it possible through some elegant command executed to make rsync change user/permissions on the files when downloading it? Or is it possible to make the folder function in a way that all new files will automatically change user when copied/moved to it? I guess I could put the chmod command in sudo cron to run every once in a while to change the owner of the files, but since sometimes the amount of data to be downloaded can be rather large, it is difficult to know when to trigger it in relation to the rsync-job to make sure all files are downloaded.

A: rsync only preserves the owner if you ask it to with -o — otherwise files will be owned by the user running the rsync command, just like when any other files are created. -a includes -o, however, so lots of common rsync command lines include it. man rsync includes a passage on this explicitly:
For example: if you want to use -a (--archive) but don't want -o
(--owner),  instead  of  converting  -a  into -rlptgD, you could
specify -a --no-o (or -a --no-owner).

So instead of rsync -a source dest you can use rsync -a --no-o source dest to have files be owned by the user running the command.
On the other hand, you can usually only change the owner of a file if you're root, so this doesn't come up much. If it's necessary to run this job as root for some reason, and you want the files to be owned by your normal user rather than root, you can use the --chown option:
rsync -a --chown=youruser:yourgroup ...

There is also a --usermap option for more complicated mappings, if you do want to keep some users. It takes a comma-separated list of from:to pairs.
As a final option, since you're apparently running rsync from a cron job, you can just append the owner/permissions-changing operation to the cron job with && chown ....

A: I tested some ways but in my case the result of e.g. this script
rsync -a -v --progress --modify-window=1 -c -b -i -s -m --del -vv --ignore-errors --chmod=ugo=rwx --delete --delete-excluded  --exclude='*~'  --exclude='.*' --backup-dir=.rsync_bak /home/test /media/user/usb_ext4

was that the permission cannot be wider than the permission of the partition / target where the file should be written to. (Check those permissions after mounting the device)


text:
Q: BigQuery fails to save view that uses functions We're using BigQuery with their new dialect of "standard" SQL.
the new SQL supports inline functions written in SQL instead of JS, so we created a function to handle date conversion.
CREATE TEMPORARY FUNCTION
  STR_TO_TIMESTAMP(str STRING)
  RETURNS TIMESTAMP AS (PARSE_TIMESTAMP('%Y-%m-%dT%H:%M:%E*SZ', str));

It must be a temporary function as Google returns Error: Only temporary functions are currently supported; use CREATE TEMPORARY FUNCTION
 if you try a permanent function.
If you try to save a view with a query that uses the function inline - you get the following error: Failed to save view. No support for CREATE TEMPORARY FUNCTION statements inside views.
If you try to outsmart it, and remove the function (hoping to add it during query time), you'll receive this error Failed to save view. Function not found: STR_TO_TIMESTAMP at [4:7].
Any suggestions on how to address this? We have more complex functions than the example shown.

A: Since the issue was marked as resolved, BigQuery now supports permanents registration of UDFs.
In order to use your UDF in a view, you'll need to first create it.
CREATE OR REPLACE FUNCTION `ACCOUNT-NAME11111.test.STR_TO_TIMESTAMP`
    (str STRING)
    RETURNS TIMESTAMP AS (PARSE_TIMESTAMP('%Y-%m-%dT%H:%M:%E*SZ', str));

*

*Note that you must use a backtick for the function's name.

*There's no TEMPORARY in the statement, as the function will be globally registered and persisted.

*Due to the way BigQuery handles namespaces, you must include both the project name and the dataset name (test) in the function's name.

Once it's created and working successfully, you can use it a view.
create view test.test_view as
select `ACCOUNT-NAME11111.test.STR_TO_TIMESTAMP`('2015-02-10T13:00:00Z') as ts

You can then query you view directly without explicitly specifying the UDF anywhere.
select * from test.test_view

A: As per the documentation https://cloud.google.com/bigquery/docs/reference/standard-sql/data-definition-language#create_function_statement , the functionality is still in Beta phase but is doable. The functions can be viewed in the same dataset it was created and the view can be created.
Please share if that worked fine for you or if you have any findings which would be helpful for others.

A: Saving a view created with a temp function is still not supported, but what you can do is plan the SQL-query (already rolled out for the latest UI), and then save it as a table. This worked for me, but I guess it depends on the query parameters you want.
##standardSQL
## JS in SQL to extract multiple h.CDs at the same time.
CREATE TEMPORARY FUNCTION getCustomDimension(cd ARRAY<STRUCT< index INT64,
value STRING>>, index INT64)
RETURNS STRING
LANGUAGE js AS """
     for(var i = 0; i < cd.length; i++) {
     var item = cd[i];
     if(item.index == index) {
         return item.value
  }
}
return '';
""";

SELECT DISTINCT h.page.pagePath, getcustomDimension(h.customDimensions,20), fullVisitorId,h.page.pagePathLevel1, h.page.pagePathLevel2, h.page.pagePathLevel3, getcustomDimension(h.customDimensions,3)
FROM
`XXX.ga_sessions_*`,
UNNEST(hits) AS h
WHERE
    ### rolling timeframe
    _TABLE_SUFFIX = FORMAT_DATE('%Y%m%d',DATE_SUB(CURRENT_DATE(),INTERVAL YY DAY))
    AND h.type='PAGE'

Credit for the solution goes to https://medium.com/@JustinCarmony/strategies-for-easier-google-analytics-bigquery-analysis-custom-dimensions-cad8afe7a153


text:
Q: Calling function on parent element give 'super' keyword unexpected here I have a typical call hierarchy
class A
{
   mirm(){
     //stuff here
   }
}

class B extends A
{
   constructor(){
     //obtain a promise
     promise().then(this.setUp)
   }

   setUp(){
    super.mirm();
   }
}

Could it be that the promise might be doing something to the scope? I would actually expect for you to be able to do something like this.mirm() from the setUp function since it should just follow the prototype chain. What gives? I am compiling with babel and have es2015 as target.

A: Passing this.setUp detaches the current context object from the function reference when it gets invoked, therefore the this in the super's method is confused about where to look
Consider wrapping it instead
// arrow function preserves context
foo.then(() => this.setUp());
// OR
// binding it to explicitly give context
foo.then(this.setUp.bind(this));


text:
Q: Calling schedule () function on an RTOS application I am pretty naive to the concept of RTOS, so this question might also be naive :)
While reading about task scheduling in RTOS, i came across the concept that the a non preemptive task can be interrupted if it calls schedule() (On linux based RTOS).
I need to know how actually this function can be called from the c program\application\task? An example will help.


text:
Q: Find and replace regular expression (matching unicode character class Devanagari) in multiple files Say you have a file named test.txt with the following lines:
ಕದಂಬ
कदम्ब

Then, suppose you want to replace each devanagarI unicode character (ie in कदम्ब) with a D. Then, you might think that the following would work:
find . -name 'test.*' | xargs perl -w -i -p -e 's/(\p{Devanagari})/D/g'

But it doesn't. How to accomplish this?

A: As suggested by steeldriver, you can force both STDIN/STDOUT to be UTF-8:

-C on its own (not followed by any number or option list), or the empty string "" for the PERL_UNICODE environment variable, has the
  same effect as -CSDL. In other words, the standard I/O handles and the
  default open() layer are UTF-8-fied but only if the locale environment
  variables indicate a UTF-8 locale.

find . -name 'test.*' 2>/dev/null | xargs perl -w -C -i -p -e 's/(\p{Devanagari})/D/g'

Will transform your sample file like this:
ಕದಂಬ
DDDDD

Source: http://perldoc.perl.org/perlrun.html#Command-Switches


text:
Q: Kubernetes nvidia-gpu UnexpectedAdmissionError I have a k8s cluster with one master and one worker. Worker has GPUs, and I am able to schedule pods on it using GPUs.
I add the second worker, also with GPUs. Everything is properly installed on that second worker. When I try to schedule GPU busybox on that second worker I get status UnexpectedAdmissionError.
With kubectl describe pod busybox I see Warning  UnexpectedAdmissionError  7m    kubelet, wikiserver  Update plugin resources failed due to requested number of devices unavailable for nvidia.com/gpu. Requested: 1, Available: 0, which is unexpected. which is odd since with kubectl describe nodes second-worker I see that both Capacity and Allocatable are nvidia.com/gpu: 1
I was able to successfully schedule GPU busybox on first worker. Also, I was able to schedule CPU busybox on both workers.
This is yaml conf for GPU busybox:
apiVersion: v1
kind: Pod
metadata:
  name: busybox
  namespace: default
spec:
  containers:
  - image: busybox
    command:
      - sleep
      - "3600"
    imagePullPolicy: IfNotPresent
    name: busybox
    resources:
        limits:
          nvidia.com/gpu: 1
  restartPolicy: Always
  nodeName: secondworker

The second worker (and first worker and the master) is configured as described by nvidia-device-plugin.


text: Q: Notebook (.nb) → Jupyter (.ipynb) conversion without Mathematica? Is there a way to convert Mathematica Notebook files (.nb) to Jupyter files (.ipynb) without using Mathematica?Is there a free online utility or other piece of software that can do this?


text:
Q: Can I add a "Open in homekit app" button to my iOS app? I'm adding a functionality in my iOS app (Swift) that should open HomeKit with a prefilled pin for a new accessory.
Is there a way to deeplink to the Home app ?
Thanks

A: The code below should open HomeKit
let url = URL(string: "com.apple.home://launch")!
UIApplication.shared.open(url)


text:
Q: JAVA. I am getting an 'unreported exception' compiler error I am trying to compile this code, but it keeps having an error,
errThrower.java:37: error: unreported exception Exception; must be caught or declared to be thrown
throw new Exception();

This exception is thrown in the callmethodErr(), and I thought it has been caught in main, but I can't figure out what is happening.
Thanks all.
import java.util.IllegalFormatConversionException;

public class errThrower
{
  public static void main(String[] args)
  {
    try
    {
      callmethodErr();
    }
    catch (Exception e)
    {
      e.printStackTrace();
    }
  }

  public static void methodErr() throws Exception
  {
    System.out.println("error thrown from methodErr");
  }

  public static void callmethodErr()
  {
    try
    {
      methodErr();
    }
    catch (Exception e)
    {
      System.out.println("error thrown from callMethodErr");
      throw new Exception();
    }
  }
}

A: This method:
public static void callmethodErr()
{

Contains the line:
throw new Exception();

But does not declare that it throws Exception thus:
public static void callmethodErr() throws Exception
{

A: Exception is a checked exception, and that means you must catch it in the method in which it is thrown, or declare that your method might throw this exception. You can do that by changing the signature of your method callmethodErr like this:
public static void callmethodErr() throws Exception
{
    // ...
}

For a more details description of how this works, see: The Catch or Specify Requirement in Oracle's Java Tutorials.

A: As the compiler says, the method callmethodErr can throw an Exception. So you must catch that Exception in the method callmethodErr or declare the method callmethodErr to throw the Exception. Whether you catch it in the main method or not is not relevant, because you could also call the method callmethodErr from another method (not the main) and forget about catching it, and the compiler must prevent this.
Declare the method like this public static void callmethodErr() throws Exception


text:
Q: What is a solution to this integral? What is a solution to the following integral:
$$\int_0^\infty \, \frac{\cos{kt}}{\pi}\,\mathrm{d}k\,?$$
I have tried to evaluate this in the usual way:
$$\begin{align}\frac{1}{\pi}\int_0^\infty\,\cos{kt}\,\mathrm{d}k &= \frac{1}{\pi t} \left[\sin{k t}\right]\bigg|_{k\rightarrow 0}^{k\rightarrow \infty} \\ &=\frac{1}{\pi t} \left[\lim_{k\rightarrow \infty}\sin{k t} - \sin 0\right]  \\ &=\frac{1}{\pi t} \lim_{k\rightarrow \infty}\sin{k t},\end{align}$$
but $\lim_{k\rightarrow \infty}\sin{k t}$ doesn't converge within infinity.
What is the trick here? Note that this is a homework question, so I don't need the complete solution, just directions where to start.

A: The integral doesn't converge to any finite value. A graph of the function you're integrating would be a transformed version of $\cos k$, which oscillates back and forth. The area underneath would also oscillate back and forth, which is what your answer already tells you.

A: To answer your question, there is no finite value for the integral.
As you showed, the integral simplifies to the value:
$$\frac{1}{\pi t} \lim_{k\rightarrow \infty}\sin{k t}$$
Looking at the limit, as $k$ approaches infinity, the function $\sin{(kt)}$ will oscillate between the values $-1$ and $1$, and therefore won't converge to a finite value.
You could use taylor series of $\sin x$ to get a value through approximation, but the integral itself doesn't converge to any value.

A: I have found that a solution can can be inferred from equation 2.3.36 (pg. 137) in Dubin's Numerical and Analytical Methods for Scientists and Engineers using Mathematica, which finds that
$$\lim_{k\rightarrow\infty} \frac{\sin{kt}}{\pi t} = \delta(t),$$
meaning that
$$\int_0^\infty \frac{\sin{k t}}{\pi}\,\mathrm{d}k = \delta(t)$$
a result, admittedly, not satisfactory for mathematics stack exchange since the limit is not well defined (and is not finite) but it is noteworthy and useful nonetheless.


text:
Q: Increasing page performance in asp.net c# I have a GridView with 21000 record and I am fetching from DB using Stored Procedures. Initialy when I click on this page from my Web Application it takes too much time to load this page. Also I have a dropdown as filters in this page and when a dropdown value is selected it takes too much time to load the data. I use LINQ query to filter dropdown values.
How can I probably increase the performance of the page.

A: You are in luck.  There is probably so much wrong with this scenario that you have lots of opportunity to improve.
You need to break down the problem into manageable chunks.

*

*Analyze the stored procedure performance.  How long is it taking to return 21,000 records?

*Is your filtering happening on the web server instead of in the database query?  That will add some extra overhead.

*Even if the web browser receives the web page instantly, it cannot render 21,000 records in a reasonable timeframe.  Large grids add a lot of overhead to your page rendering time.

Probably your best bet for this page is convert it to use paging and only display somewhere between 10 and 100 records on the screen at once.  Your query should have your filters in it and then fetch the page of information that the user will see.

A: I recommend you to not to load all the records at a same time.
The simple reason is because,
you are not going to show all the records at same time

Use, Lazy loading and load only those records that are currently being displayed.
This would make your page load faster and a significant performance improvement can be seen.
The point to note here is that: It will take more time for you to render html for those records than fetching them from database.
If you implement lazy loading, make sure you do server side filtering.
Do get confused with Client side filtering, which can produce wrong results
Hope this helps

A: 21000 records is too many to display in a single page. Instead I recommend you paging support to limit the amount of data retrieved at a time. Here is how you can implement:
http://www.codeproject.com/Articles/67520/GridView-Paging-and-Sorting
The above link will address the dropdown issue as well.


text:
Q: Importing Stockfish into React App: Uncaught SyntaxError: Unexpected token '<' I am trying to import the javascript implementation of stockfish into my react app. I can replicate the above error by adding the following:
let stockfish = new Worker('stockfish.js');

I have already tried to clear my cache and I think that it has to do with how I am loading stockfish.js.  To replicate the error, all you have to do is create a new react app using create-react-app, install stockfish and add the above line.
This has been asked before (for example) but I can't find anything that applies to my situation.

A: I had similar problems, except in a vue app.  Here are some suggestions.

*

*Is stockfish.js in your public folder of your project?  I had to manually copy stockfish.js, stockfish.wasm and stockfish.asm.js from the stockfish module folding into the project's public folder.  Not very NPM friendly.

*Try adding '/' to the path.  That is,
let stockfish = new Worker('/stockfish.js');
For me this solved a bug where if I called where the if I tried to make a new worker from a component with a route of say "localhost:8080/game/12341234", the request for stockfish would be sent to "localhost:8080/game/stockfish.js" instead of "localhost:8080/stockfish.js".


text:
Q: Do we have pool of objects for wrapper classes too? I would like to clarify few of queries. As i know Wrapper classes are final too and immutable. So do they have pool of objects just like String class did? and also are there mutable versions for Wrapper classes? String class has mutable versions like StringBuilder and StringBuffer.

A: Some wrapper classes (for example Long and Integer) have a cache for some values (for Integer and Long, the cache is for values between -128 and 127), which behaves similarly to the String pool, but unlike the String pool it is constant, so adding new objects to it is not possible.
As for your second question, I'm assuming it's a typo and you meant to ask if the wrapper classes have mutable versions like String has StringBuilder. The answer is no.

A: I would like to elaborate on cache part that Eran has mentioned in his answer. This will also answer op's question that he has asked in comments.

*

*Cached instances exist for the wrapper Boolean, Byte, Short,
Integer, Long, Character class.

*In the case of the Boolean class, the cached instances are
accessible directly because only two exist: static constants Boolean.TRUE
and Boolean.FALSE.

*The Character class caches instances with values from 0 to 127.

*The Byte, Short, Integer, and Long cache instances for value -127 to
128.

*No cached instances exist for the Float and Double wrapper classes.
If you request an object of any of these classes, from this range, the valueOf() method returns a reference to a predefined object: otherwise, it creates a new object and returns its reference.
Example :-

Integer i1 = new Integer(10);
Integer i2 = new Integer(10);

Integer i3 = Integer.valueOf(10);
Integer i4 = Integer.valueOf(10);

Integer i5 = 10; // Autoboxing, internally autoboxing uses valueOf() method.
Integer i6 = 10;

System.out.println(i1 == i2);
System.out.println(i3 == i4);
System.out.println(i4 == i5);
System.out.println(i5 == i6);

O/P :-
false
true - result is true because valueOf() returns a cached copy.
true
true


text:
Q: Equivalent control in Android to WPF Grid I feel so dumb asking this, but I couldn't find the answer nowhere. I'm used to C# and XAML, but I'm getting started with Android Developement, so I'm new with Java and XML and I feel so lost.
What is the control that's closest to the WPF Grid?
How can I define it via code and XML?

A: Well, another possible solution is to use LinearLayout and then set layout_weight of child elements as required, but make sure to set layout_height of child elements to 0dp.
For Example:
<LinearLayout
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <Space
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight=".5" />

    <TextView
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:text="SomeText"
            android:layout_weight=".5"/>

</LinearLayout>

A: You are probably looking for GridLayout, which is explained in full with implementation examples in this blog post.
Note that GridLayout was first introduced in API 14, Ice Cream Sandwich. If you need to support older devices, you can use the Support Library equivalent, android.support.v7.widget.GridLayout which as its package name implies, supports back to API 7. You'll need to add the support GridLayout to your project by following these instructions.


text:
Q: How to find specific data from a Volley Api string response I am new to APIs and finally figured out how to successfully retrieve a request response from a website.  The thing is I am completely lost on how I should handle the response. I don't know how to access certain values within the response
here is my API Volley code
  RequestQueue requestQueue = Volley.newRequestQueue(this);
    String uri = Uri.parse("https://chicken-coop.p.rapidapi.com/games/Fortnite?platform=pc")
            .buildUpon()
            .build().toString();

    StringRequest stringRequest = new StringRequest(
            Request.Method.GET, uri, new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {
            displayResults.setText("Response: " + response.substring(0,500));

        }

    }, new Response.ErrorListener() {

        @Override
        public void onErrorResponse(VolleyError error) {
             displayResults.setText( "" + error.toString());
        }

    }) {

        @Override
        public Map<String, String> getHeaders() throws AuthFailureError {
            Map<String, String> params = new HashMap<>();
            params.put("X-RapidAPI-Key", "5cdb2bbe57mshd9242c8d3177cb3p16f2fbjsnd7c5829eb4ad");
            params.put("X-RapidAPI-Host", "chicken-coop.p.rapidapi.com");
            return params;
        }
    };
    requestQueue.add(stringRequest);

Here is the response query that I received

"result":{10 items
  "title":"Fortnite"
  "releaseDate":"Jul 25, 2017"
  "description":"Epic Games next project has you building forts and stopping a zombie invasion."
  "genre":[...
  ]6 items
  "image":"https://static.metacritic.com/images/products/games/5/c7eb46ceb7da9c72c5a95193e8621faf-98.jpg"
  "score":81
  "developer":"Epic Games"
  "publisher":[...
  ]1 item
  "rating":"T"
  "alsoAvailableOn":[6 items
  0:
  "iPhone/iPad"
  1:
  "PlayStation 3"
  2:
  "PlayStation 4"
  3:
  "Switch"
  4:
  "Xbox 360"
  5:
  "Xbox One"

How would I go about finding an explicit value from the response query? I have been searching for how to do this online and there are so many different ways to go about and I have no clue what to do. For example, how would I be able to put the Release Date into its own text box? Most of the examples I see online use JsonObjects when I m using a string response

A: in your onResponse method you need to parse your result so you can extract any data you want
public void onResponse(String response) {
        try {
            JSONObject jsonObject = new JSONObject(response);
            JSONArray jsonArray = jsonObject.getJSONArray("result");
             // toaccess to your json data
                String title = jsonArray.getString("title");
                // your code

        } catch (JSONException e) {
            e.printStackTrace();
        }
    }


text:
Q: What is the reason behind having only one return value in C++ and Java? Normally I glance over this fact and just accept it as "this is how the wheel spins" but today I wonder where this comes from: Why does a function only have one return (reference)value?
Why can't, would it be hard, or not wise for a function to return multiple values? Is it because of objects and how you should expect that a package of data should always be returned in the form of a reference to an object?
If you see a declared function as a contract which states how a function can be called, which parameters it should take, and which return value type it has, then I don't see the logic behind having only one return value since you could apply the same logic the other way around (thus creating a contract for more than one return value).
The only reason based on logic I can see is that if a function returns more than 1 thing, it should also manipulate more than 1 thing for more than 1 reason which is against the philosophy that a function should do only one thing. If that one thing is manipulating an object and returning an other object it would make sense and you can return a reference value with the manipulated object..
So why exactly does this limitation exist?

A: This is purely historical. This is how usually mathematical functions work. Moreover, some languages (quite a lot actually) allow to return more than one value - usually using a tuple object.
The idea that it would be nice to return more than one object came late. Why was it chosen to be done via objects, and not language syntax? Because OO programming was in wild use and generally accepted.
Semantically both ways have the same meaning - "return more than one thing". So adding such functionality would be an equivalent to supporting another syntax for the same meaning. Having two ways to do one thing is not very welcomed in programming. Programmers wonder which way to chose, some only know one method, and compiler developers would have to maintain two mechanisms that do not differ in their functionality. It's a pretty good rationale. Okham's razor is appreciated tool. And objects are more useful.
Another thing is that, your argument: "a declared function as a contract which states how a function can be called, which parameters it should take, and which return value type it has", is not really good at the bold part.
Return type is often not considered a part of function signature. You can't have overloads that differ only in return value. That being said, of course compiler needs to know how many bytes it should take of the stack, after function finished, as the return value. So it's not totally irrelevant, though usually languages do not consider this.

A: When a function returns multiple things, the things are related to each other, at the very least by virtue of being returned by a single function. This consideration alone is sufficient to require the authors of functions that return multiple things to group these multiple things together by creating an appropriate data structure, which is already possible with functions returning a single item.
For example, in C++ std::set::insert needs to return two values - an iterator, and a bool to indicate whether the iterator is some old element or the element that we have just inserted. The solution was to return an std::pair:
pair<iterator,bool> insert (const value_type& val);

The second consideration is purely practical: dealing with multiple returned value in expressions like that
int x = f(y);

is simple and intuitive when there is only one return value. Trying to return multiple values, as in
int x, y = f(w, z);

would become hard to parse, because the reader must check the return type of f and see if it returns an int or two ints.
I am not even touching the situation when the data types of the returned items are not the same! The syntax would quickly become a nightmare, without a comparable gain in expressive power of the language.

A: Your question doesn't make it clear which exactly feature you're looking for: syntactic sugar which makes it "look" like you're returning several values, or the essential ability of a function to return several values.
If it is the former, then there's no big answer to give: languages just differ in the level of syntactical support they provide for this. For example, LISP has full support for multiple value return and many languages (Scala, Clojure) support the destructuring bind idiom which quite closely resembles what you're looking for, but work against reference-typed tuples. Java happens to be poor on syntax in general so its lack of support for the destructuring bind is no surprise.
As for the latter — in C, returning a struct type is exactly the functionality you are looking for. The struct will be placed on the stack frame and will contain an arbitrary number of values. Other languages, which don't let you control stack/heap placement at such a level of detail, still allow you to return a pointer to such a struct.

A: I wish people stopped interpreting "I can't do X in language Y" as "language Y has a limitation that prevents me from doing X". Sometimes this is in fact just true – for instance C++' const modifiers basically just forbid you from mutating values in a way that, syntax-wise, could be expressed perfectly well, but just isn't deemed wise if you want to ensure your program behaves in a certain predictable way.
OTOH, for most features X you could come up with it just doesn't make any sense to want them in a language. How about if I asked, "what is the reason I can't just differentiate all C++ functions?" For a physicist or engineer who knows nothing about programming this wouldn't seem a far-fetched thing to want, as these guys traditionally only deal with1 a particular kind of functions in the maths sense, which can always be differentiated as often as you like.
But for most functions in programming languages, it absolutely doesn't make any sense, conceptually, to take the derivative. To a programmer, the analytic functions can be but a tiny subset of all functions, simply because the idea of derivatives only applies to continuous domains (in practice, basically to vector spaces)2, and of course it is completely incompatible with the side-effects that "functions" in procedural and OO languages are allowed to have.
Now, allowing to return multiple values sure appears a much more mundane thing than allowing to differentiate functions, but it still changes in quite a fundamental way what's meant by "function". You can't just refer to the return type of a function anymore, you need to clarify what it means to compose functions with multiple return values, you need to come up with some new syntax for function pointers, etc. etc.
Unlike the differentiation example, all of this this would probably be possible, but it should be clear that it would change pretty much all of the language. It would very much not be just "stop preventing me from returning multiple things!"
Some languages, e.g. Fortran and Matlab, have hard-wired support for multiple return values into the language. Oh boy, I can tell you this does not make programming in these languages nicer: many things you can easily do with C++ functions are just blocked because they would get messed up by the multiple returns!
Other languages, e.g. Python, have a lightwight alternative: it looks like you're returning multiple things, but really you're just returning a single tuple and get some syntactic sugar for pattern-matching the components back into individual variables.
Returning tuples or something similar is of course, as said by the other answers, the sensible solution to your problem, though it can sometimes get a bit clumsy in languages that don't have very good syntactic support for tuples. (But that's just a bit of harmless boilerplate.)

1Well, at least they pretend they're dealing with analytic functions. Often, this is barely acceptable mathematically. Really, they're just approximating everything by analytic functions.
2Interestingly, in a language with proper algebraic data types, a remarkable analogue to the classical idea of differentiation turns up in quite a surprising way, without actually needing continuous domains. That's still something quite different from e.g. "take the derivative of x2 / (1+ex)".

Going further: it can be argued that functions should also have only a single argument. That, too, can be a composite type, but you don't even need tuples here: there's a thing called Currying – any function of two arguments can also be expressed as a function of a single argument, returning a function of the second argument. This may seem a bit of a strange way of thinking, but actually it works out quite nicely. Haskell does this consequently, and many people consider it one of the crazy things about the language, but it allows you to express some operations more consisely than possible in most other languages, while at the same time the syntax is actually kept very simple.

A: Back in the day certain CPU registers had particular conventions, and CPU registers were limited. So assembly code typically returned exactly one value, for example, in AX on the 8086.
Writing assembly code is laborious, and 'C' came along to relieve some of the burden while still allowing the developer to achieve similar performance of assembly code.
To emphasize the point, consider this 'C' code:
int foo(void)
{
    // no return statement; default register used
}

In this case the function foo will return the value in the "return value" register for the CPU type, for example, EAX on a 32-bit x86 processor.
'C++' is inter-operable with 'C' and does not introduce a second form of the return statement.

A: I have never worked on compiler internals before, but the term function generally refers to  a binary relation, that has a unique mapping for every item in it's domain(set of inputs) to it's codomain(set of outputs).
Now, those set elements could themselves be aggregate.
Maybe someone who is more well versed with compiler theory could elaborate on this.

A: In Mathematics, a function has a domain and a codomain. f:S->T denotes a function with domain S and codomain T.
A method with two parameters and one return value more or less corresponds to a function f:SxT->U, where x denotes the Cartesian product. So, for example, a method with parameters of type double and int that returns a boolean corresponds roughly to a function f:DxI->B where D is the set of all double values etc. This is done without bundling the two parameters together into a tuple.
There is no reason why we couldn't similarly have a method corresponding to a function of the form f:X->YxZ without the two returned values being bundled together into a tuple.
For example, the Java method
BigInteger[] divideAndRemainder(BigInteger divisor)

could easily have the signature
BigInteger q, BigInteger r divideAndRemainder(BigInteger divisor)

Somewhere in the body of the method there would be a return statement that could look like return q, r;. There would be no reason for the array at all.
In fact this would be better as you could call the method by writing
BigInteger q, BigInteger r = bigInt1.divideAndRemainder(bigInt2);

instead of
BigInteger[] arr = bigInt1.divideAndRemainder(bigInt2);
BigInteger q = arr[0];
BigInteger r = arr[1];

I guess the reason this is not allowed is that it would complicate the language without there being a great demand for it. If you look in standard libraries in many languages and compare the number of methods that bundle many return values into a single object, compared to the number of methods that have more than one argument, you would probably find that the latter is much more common.

A: Whenever you have multiple values x1 ... xN, you trivially have the tuple (x1, ..., xN) which is a single (albeit composite) value. If you don't have tuples in your language, use any aggregate type (struct, class, arrays, other collections) at will. So from this perspective, returning "multiple" values and returning a single value is completely equivalent.
That just means that you only need one, but why omit the other?
First, you need aggregate types anyway, so the choice is between having both or only having aggregate types. Second, if a function can return "multiple values", you face a semantic conundrum: Suddenly an expression does not evaluate to value (which we have previously defined very specifically), it's this new, different category of thing called "multiple values". Now what is the static type of this result? What can the program do and not do with it? What does it mean in implementation terms?
You can of course artificially answer these questions, but any sensible approach will just amount to tuple types. Ignoring that makes you blind to a very useful perspective, and refusing to make them first-class values is probably more complicated than saying "these are tuple types, they can be constructed like this and deconstructed like this".

A: Functions are just subroutines that leave something in the stack.  If what is left in the stack isn't predictable you now have to have some method predicting what all is left on the stack.  That creates overhead.  We decided to just point at one thing that might be a data structure of many things or might just be an int.
A mathematician will tell you a function is about relating each argument (input value) to the corresponding output value but to a computer scientist a function is contract about the state the stack will be left in when it returns.

A: I recognize the problem. Let's say you cycle through a collection of data and you need to filter the data on some aspect. As a side effect of that traversing data you will find out another interesting feature that you would like to have as well, but that result is not inline with the requested outcome of the function.
An example: you traverse all your code to find out which functions are called by which functions. While traversing you might find as a side effect functions that are never used/called upon. You will only find those functions when traversing all functions, it is not a result of the call, it is strictly spoken not related to the outcome, yet it is very interesting information to retrieve.
What should you do? Write another function performing the same functionality, but now with a different outcome? Creating a separate object storing both results? Store the outcome in a new variable to the object? Or have a function with multiple outcomes?
Those side effects are unpredictable from the perspective of designing a programming language. You really can't design a language on unpredictable requirements. And how should the next functions respond to it? In order to keep functions as loosely coupled from each other as possible, is it a good practice to keep the outcome of functions as simple as possible. Function design should apply the Law of Demeter. Letting functions have an output of unrelated results makes it impossible to write loosely coupled code. It can become a real nightmare if you have to change a chain of functions, because the first function with multiple output drops one of the results - or adds a new one to it.
My solution to the forementioned problem was to 'write' the code twice. One time to find all relations between functions and the other one to find all functions that were never called upon. This way there is a clean separation between content of the function and the rest of the application. I just pretended that I did not know that I wrote that function before.
I think that it is a good design to let a function only produce one coherent result. It makes the design of the whole process a lot more structured, which helps to build bigger and more complex applications.


text:
Q: Is it possible to use Spark SQL with relational databases when the tables are big? I want to know how can we use spark SQL to process structured big data stored in relational DB? I have tables that contain more than 4 billion lines (GPS coordinates). On using Merge operation, Spark tries to process the whole tables in the memory which is impossible. I know that Spark is "in-memory" processing, but in my case the memory can't fit for the whole tables. So is it possible to use spark with relational databases when the tables are big?

A: In case the data to be read is more than the memory size, Spark does not cache the whole dataset into the memory all at once. The Spark documents states :
Spark RDD Persistence

One of the most important capabilities in Spark is persisting (or caching) a dataset in memory across operations. When you persist an RDD, each node stores any partitions of it that it computes in memory and reuses them in other actions on that dataset

Also, one can provide Storage Level as MEMORY_AND_DISK

MEMORY_AND_DISK : Store RDD as deserialized Java objects in the JVM. If the RDD does not fit in memory, store the partitions that don't fit on disk, and read them from there when they're needed.

Any of the Spark Data Structure you use, internally uses RDD.
Also assuming you are using JDBC to connect to external Database, you can specify the property fetchsize and batchsize

fetchsize :The JDBC fetch size, which determines how many rows to fetch per round trip. This can help performance on JDBC drivers which default to low fetch size (eg. Oracle with 10 rows). This option applies only to reading.
batchsize : The JDBC batch size, which determines how many rows to insert per round trip. This can help performance on JDBC drivers. This option applies only to writing. It defaults to 1000.

JDBC To Other Databases
val jdbcDF = spark.read
  .format("jdbc")
  .option("url", "jdbc:postgresql:dbserver")
  .option("dbtable", "schema.tablename")
  .option("user", "username")
  .option("password", "password")
  .option("fetchsize", "100")
  .load()


text:
Q: Space-like and time-like: where do the names come from? Space-like separated events are events that, in a well-chosen reference frame, can take place at the same time but never happen at the same location.
On the other hand for time-like events, one can chose a reference frame such that they happen at the same place but never simultaneously.
I can't help thinking that the labels are therefore very ill-chosen... Is there another motivation for these names?

A: I admit that the terminology is not as self-explanatory as it should, however a source of confusion is the fact that  you are actually looking at consequences of the definitions, instead of at the original  definitions that hold in every connected time oriented spacetime. The terminology turns out to be more clear if you use the original definitions which are referring to the nature of the curves connecting the events.
For a pair of events in a generic spacetime, time-like related means, by definition, that there is a future directed time-like curve joining the points. In Minkowski spacetime, it is equivalent to say that there is a time-like geodesic joining the events and it implies (it is equivalent in that spacetime) that there is a Minkowski reference frame where the events have the same location at different times.
For a pair of events in a generic spacetime, causally related  means, by definition, that there is a future directed causal curve joining the events. Causal curve means that its tangent vector is not space-like.  Causal curves are those curves describing the stories of physical points transmitting interactions.
Finally, for a pair of events in a generic spacetime, space-like separated (or also, equivalently,  causally separated) means, by definition that there is no future directed causal curve joining the events. In Minkowski spacetime, it is equivalent to say (and it justifies the name) that there is a space-like geodesic joining the events and, in turns, it implies (it is equivalent in Minkowski spacetime) that there is a Minkowski reference frame where both events occur at the same time in the rest frame of the reference frame.

A: Think about it this way: Any event outside of another event's light cones is called "space-like separated" from that event because spatial separation dominates the difference.
For example, imagine two events that lie on what the wiki-link picture calls the "hypersurface of the present": these two events are causally disconnected because they are too far apart for light to reach one from the other (despite appearing to occur at the same time).
On the other hand, events which lie inside each other's light cones are "time-like separated" because temporal separation dominates the difference (i.e. one will always be in the other's past regardless of reference frame). Moreover, if two events are time-like separated they are well-ordered (one always comes before the other), but if they are space-like separated, there exist reference frames in which either one you choose happens first.

A: The terminology makes perfect sense if you include the word interval after space-like and time-like. If two events can never occur in the same place, regardless of which reference frame you choose to view them in, it seems reasonable to assert that they are separated by a space-like interval. Similarly, if one event must always occur after the other, it makes sense to say that they are separated by a time-like interval.
The important point is that the space-time interval is invariant under transformations between reference frames (Lorentz transformations). Therefore, we can meaningfully talk about different classes of intervals (space-like, time-like, and light-like). Humans are not great at visualizing distances in four-dimensional space-time, so these names are valuable in developing intuition.

A: Suppose you draw a spacetime diagram and measure the angle of your trajectory to the spatial and time axes. You'll find time like trajectories are more nearly parallel to the time axis - i.e. the angle the trajectory makes to the time axis is smaller than the angle it makes to the spatial axis. Conversely space like trajectories are more nearly parallel to the spatial axis. This seems to me a plausible origin for the terms.


text:
Q: There is a sentence which I find difficult in a set theory book! I am reading a book called 'A book of Set Theory by Charles C.Pinter'.
There is a sentence which I find confusing. It goes like this.
" We will use letters P,Q,R,S to denote sentences(a sentence is a statement which is unambiguously true or false); used in this sense, P, for instance, is to be understood as asserting that "P is true." "
Does this mean that we always assume that P is true or does this mean that we argue that P is true and we will show that such argument(that P is true) is true or false?

A: This sentence simply says that whenever we say "P", then it is a shorthand for saying that P is true.
For example: if we have the statement "exists a white sheep", then whenever we say "exists a white sheep" we actually mean "the statement that says that 'exists a white sheep' is true".
This is actually how we use statements when talking: we don't say, "the statement that 'most cows have four legs' is true", we say "most cows have four legs". In set theory, this is not how sentences are necessarily used, so the author just pointed out that that is how he will use sentences in this case.


text:
Q: Functional O(1) append and O(n) iteration from first element list data structure I'm looking for a functional data structure that supports the following operations:

*

*Append, O(1)

*In order iteration, O(n)

A normal functional linked list only supports O(n) append, while I could use a normal LL and then reverse it, the reverse operation would be O(n) also which (partially) negates the O(1) cons operation.

A: You can use John Hughes's constant-time append lists, which seem nowadays to be called DList.  The representation is a function from lists to lists: the empty list is the identity function; append is composition, and singleton is cons (partially applied).  In this representation every enumeration will cost you n allocations, so that may not be so good.
The alternative is to make the same algebra as a data structure:
type 'a seq = Empty | Single of 'a | Append of 'a seq * 'a seq

Enumeration is a tree walk, which will either cost some stack space or will require some kind of zipper representation.  Here's a tree walk that converts to list but uses stack space:
let to_list t =
  let rec walk t xs = match t with
  | Empty -> xs
  | Single x -> x :: xs
  | Append (t1, t2) -> walk t1 (walk t2 xs) in
  walk t []

Here's the same, but using constant stack space:
let to_list' t =
  let rec walk lefts t xs = match t with
  | Empty -> finish lefts xs
  | Single x -> finish lefts (x :: xs)
  | Append (t1, t2) -> walk (t1 :: lefts) t2 xs
  and finish lefts xs = match lefts with
  | [] -> xs
  | t::ts -> walk ts t xs in
  walk [] t []

You can write a fold function that visits the same elements but doesn't actually reify the list; just replace cons and nil with something more general:
val fold : ('a * 'b -> 'b) -> 'b -> 'a seq -> 'b

let fold f z t =
  let rec walk lefts t xs = match t with
  | Empty -> finish lefts xs
  | Single x -> finish lefts (f (x, xs))
  | Append (t1, t2) -> walk (t1 :: lefts) t2 xs
  and finish lefts xs = match lefts with
  | [] -> xs
  | t::ts -> walk ts t xs in
  walk [] t z

That's your linear-time, constant-stack enumeration.  Have fun!

A: I believe you can just use standard functional linked list:

*

*To append element, you can use cons (which is O(1))

*To iterate elements in the order in which they were inserted, you can first reverse the list,
(which is O(N)) and then traverse it, which is also O(N) (and 2xO(N) is still just O(N)).

A: How about a difference list?
type 'a DList = DList of ('a list -> 'a list)

module DList =
  let append (DList f) (DList g) = (DList (f << g))
  let cons x (DList f) = (DList (fun l -> x::(f l)))
  let snoc (DList f) x = (DList (fun l -> f(x::l)))
  let empty = DList id
  let ofList = List.fold snoc empty
  let toList (DList f) = f []

A: What about a circularly-linked list? It supports O(1) appends and O(n) iteration.

A: You could create a functional Deque, which provides O(1) adding to either end, and O(N) for iteration in either direction. Eric Lippert wrote about an interesting version of an immutable Deque on his blog note that if you look around you will find the other parts of the series, but that is the explanation of the final product. Note also that with a bit of tweaking it can be modified to utilize F# discriminated unions and pattern matching (although that is up to you).
Another interesting property of this version, O(1) peek, removal, and add, from either end (i.e. dequeueLeft, dequeueRight, dequeueLeft, dequeueRight, etc. is still O(N), versus O(N*N) with a double list method).


text:
Q: Accessing input type file at server side in asp.net I am using the <input type="file" /> tag to upload a file to the server. How do I access the file at the server side and store it at the server? (The file is an image file)
The client side code is :
<form id="form1" action="PhotoStore.aspx" enctype="multipart/form-data">
    <div>
    <input type="file" id="file" onchange="preview(this)" />
    <input type="submit" />
    </div>
</form>

Photostore.aspx.cs has
protected void Page_Load(object sender, EventArgs e)
        {
            int index = 1;
            foreach (HttpPostedFile postedFile in Request.Files)
            {
                int contentLength = postedFile.ContentLength;
                string contentType = postedFile.ContentType;
                string fileName = postedFile.FileName;

                postedFile.SaveAs(@"c:\test\file" + index + ".tmp");

                index++;
            }

        }

I tried uploading a jpg file. Not able to see a saved file. What is going wrong?

A: You'll need to add id and runat="server" attributes like this:
<input type="file" id="MyFileUpload" runat="server" />

Then, on the server-side you'll have access to the control's PostedFile property, which will give you ContentLength, ContentType, FileName, InputStream properties and a SaveAs method etc:
int contentLength = MyFileUpload.PostedFile.ContentLength;
string contentType = MyFileUpload.PostedFile.ContentType;
string fileName = MyFileUpload.PostedFile.FileName;

MyFileUpload.PostedFile.Save(@"c:\test.tmp");

Alternatively, you could use Request.Files which gives you a collection of all uploaded files:
int index = 1;
foreach (HttpPostedFile postedFile in Request.Files)
{
    int contentLength = postedFile.ContentLength;
    string contentType = postedFile.ContentType;
    string fileName = postedFile.FileName;

    postedFile.Save(@"c:\test" + index + ".tmp");

    index++;
}

A: I think the name tag is required on the file input:
<input type="file" name="file" />

Without this, I don't get anything back.

Further problems that I had which might be specific to my machine:
I get a
Unable to cast object of type 'System.String' to type 'System.Web.HttpPostedFile'.

error at the line
foreach (HttpPostedFile postedFile in Request.Files)

so my final code looks like this:
for (var i = 0; i < Request.Files.Count; i++)
{
    var postedFile = Request.Files[i];

    // do something with file here
}

A: Look into the asp:FileUpload control provided by ASP.NET.

A: If you dont want to use the FileUpload control in the toolbox, Give your input an ID then use form[id] to access the input field and cast it to HtmlInputFile.
example here: http://www.codeproject.com/KB/aspnet/fileupload.aspx

A: If you give the input-tag an id and add the runat="server" attribute then you can access it easily.
First change your input tag: <input type="file" id="FileUpload" runat="server" />
Then add the following to your Page_Load method:
if (FileUpload.PostedFile != null)
{
  FileUpload.PostedFile.SaveAs(@"some path here");
}

This will write your file to a folder of your choice. You can access the PostedFile object if you need to determine the file type or original file name.


text:
Q: p4 print command help need in perl hi i have written a code
#!/tools/baton/perl/5.12.1/bin/perl

use strict;

use YAML;

use YAML 'LoadFile';

use Data::Dumper;

my $file_yml;

my $path = "//IP2/D21EV/2hw/semi_axi_10g_ethernet/info.yml";

 my %hash = open(READ, p4 print -q $path|") or die "could not open ";

print Dumper (\%hash);

it is giving me :
$VAR1 = {

          '39807' => undef

        };

A: You have some syntax errors in your code (missing double quote), but it's probably just copy'n'paste problem.
The main problem seems to be you used the value returned by open to populate the hash, but open doesn't return the contents of the file. In fact, as documented, it returns the PID of the child process if you use it to open a pipe.
You need to actually read from the file handle to get its contents.
E.g.
my %hash;
open my $PIPE, '-|', qw( ls -s );
while (<$PIPE>) {
    my ($size, $file) = split;
    $hash{$file} = $size;
}


text:
Q: MSBuild Publish Profile .pubxml.user file not found I have this solution (Project1) and that has 2x web app projects and 3x dependent library projects. The primary web app project builds and deploys using publish profiles just fine, however, the second web app project is an API (noted below) with publish profiles named the same as the main project, but of course, are going to different locations. Unfortunately, the project will build and deploy using the publish profiles just fine in VS2019, however, when using the MSBuild command (TeamCity server):
MSBuild.exe /m /p:DeployOnBuild=True /p:PublishProfile=Test /t:Rebuild

I get the following error:
CopyAllFilesToSingleFolderForAspNetCompileMerge:
    Creating directory "obj\Debug\AspnetCompileMerge\Source".
    Copying all files to temporary location below for package/publish:
    obj\Debug\AspnetCompileMerge\Source.
    Copying bin\KuderCore.API.dll to obj\Debug\AspnetCompileMerge\Source\bin\Project1.API.dll.
    Copying bin\KuderCore.API.pdb to obj\Debug\AspnetCompileMerge\Source\bin\Project1.API.pdb.
    Copying Areas\HelpPage\HelpPage.css to obj\Debug\AspnetCompileMerge\Source\Areas\HelpPage\HelpPage.css.
    Copying Content\bootstrap-theme.css to obj\Debug\AspnetCompileMerge\Source\Content\bootstrap-theme.css.
    Copying Content\bootstrap-theme.min.css to obj\Debug\AspnetCompileMerge\Source\Content\bootstrap-theme.min.css.
    Copying Content\bootstrap.css to obj\Debug\AspnetCompileMerge\Source\Content\bootstrap.css.
    Copying Content\bootstrap.min.css to obj\Debug\AspnetCompileMerge\Source\Content\bootstrap.min.css.
    Copying favicon.ico to obj\Debug\AspnetCompileMerge\Source\favicon.ico.
    Copying fonts\glyphicons-halflings-regular.svg to obj\Debug\AspnetCompileMerge\Source\fonts\glyphicons-halflings-regular.svg.
    Copying Global.asax to obj\Debug\AspnetCompileMerge\Source\Global.asax.
    Copying Properties\PublishProfiles\Test.pubxml.user to obj\Debug\AspnetCompileMerge\Source\Properties\PublishProfiles\Test.pubxml.user.
    C:\Program Files (x86)\Microsoft Visual Studio\2019\BuildTools\MSBuild\Microsoft\VisualStudio\v16.0\Web\Transform\
        Microsoft.Web.Publishing.AspNetCompileMerge.targets(615,5): error : Copying file Properties\PublishProfiles\
        Test.pubxml.user to obj\Debug\AspnetCompileMerge\Source\Properties\PublishProfiles\
        Test.pubxml.user failed. Could not find file 'Properties\PublishProfiles\Test.pubxml.user'
    Done Building Project "Project1\Project1.API\Project1.API.csproj" (Rebuild target(s)) -- FAILED.

Build FAILED.

For some reason, MSBuild isn't generating a .user file and it is bombing instead. Any idea what is going on?

A: I ran into this problem today. The problem is that the pubxml.user file is added to the .gitignore but is also included in the solution. This means the file has a build action in the .csproj, and so when the publish step happens, msbuild is looking for the file, which may not exist.
Since the file is supposed to be ignored, it probably should not be in the .csproj. Two solutions I found that both worked:

*

*Remove the file from the solution, and thus the .csproj.

*Set the build action to "None". This is configurable in the properties for a file.

Either way, msbuild will no longer look for the file when executing the publish step, and the build should work.


text:
Q: If textField is empty, do not filter my array to nothing This works fine if the textField is containing any text. But if the textField is empty, no objects are added.
How to tell this piece of code that if the textField is empty, all objects should be added to resultObjectsArray?
resultObjectsArray = [NSMutableArray array];
for(NSDictionary *object in allObjectsArray)
{

    NSString *nameString = [NSString stringWithFormat:@"%@", [textField text]];
    NSString *wineName = [wine objectForKey:@"Name"];
    NSRange range = [wineName rangeOfString:nameString options:NSCaseInsensitiveSearch];

    if ((range.location != NSNotFound))
        [resultObjectsArray addObject:object];
}

A: resultObjectsArray = [NSMutableArray array];
NSString *nameString = [textField text];
for(NSDictionary *object in allObjectsArray)
{
    if ([nameString length] > 0)
    {
        NSString *wineName = [wine objectForKey:@"Name"];
        NSRange range = [wineName rangeOfString:nameString options:NSCaseInsensitiveSearch];
        if ((range.location != NSNotFound))
            [resultObjectsArray addObject:object];
    }
    else
    {
        [resultObjectsArray addObject:object];
    }
}

Note that you don't need:
NSString *nameString = [NSString stringWithFormat:@"%@", [textField text]];

as
NSString *nameString = [textField text];

is sufficient.  Also it won't change inside the for loop so can be initialised outside of it.

A: That's how the code ended up looking like using the answer from @trojanfoe. (I've excluded my other search criterias).
-(IBAction)searchButtonPressed:(id)sender{

BOOL textFieldIsEdited = NO;
if ([[textField text] length] > 0)
{
textFieldIsEdited = YES;
}

resultObjectsArray = [NSMutableArray array];
for(NSDictionary *wine in allObjectsArray)
{

    BOOL nameMatch = YES;
    if (textFieldIsEdited) {
        NSString *wineName = [wine objectForKey:@"Name"];
        NSString *nameString = [textField text];
        NSRange range = [wineName rangeOfString:nameString options:NSCaseInsensitiveSearch];
        if (range.location == NSNotFound) {
            nameMatch = NO;
        }
    }

    if ((nameMatch != NO))
        [resultObjectsArray addObject:wine];
}


text:
Q: How can I attach a file to a message? I want my bot to forward a file to the mentioned user when using the command, the problem is that I don't know how to do it.
if (command === "file") {
    if (message.channel.id != "700038969253167125") return;
    message.delete();
    message.channel.send(`> <@${message.author.id}> ✅`)

    let filejoin = args.join(" ");
    if (!filejoin)

        client.channels.cache.get('700052786909282344').send(`:information_source: **|** Ha llegado un nuevo archivo (<@${message.author.id}>)\n\n"${filejoin}"`);
    if (message.author.bot) return;

    client.channels.cache.get('700052786909282344').send(`:information_source: **|** Ha llegado un nuevo archivo (<@${message.author.id}>)\n\n"${filejoin}"`).then(async m => {

    });

}

A: You can send files using the .send() method.
As you stated in the comments of this answer, you want the file attached to the message containing the command to be sent to you. You can do that like so:
const user = client.users.cache.get("YOUR_ID")
if (message.attachments.array().length) {
   message.attachments.forEach((attachment) => user.send({ files: [ attachment ] }))
   user.send(`These files were sent by ${message.author.tag}`)
}


text:
Q: Which is the best method to redirect after login in FOSUserBundle Which is the best method to implement role based redirect after login in FOSUserBundle ?
Should I use a success handler and write the redirection logic in onAuthenticationSuccess
or Should I use a security listener and write the redirection logic in onSecurityInteractiveLogin

A: I think security listeners are used by other bundles to do some post-login operations like table update, setting cookie etc. While same can be done by success_handler, it is called once for each firewall configuration in app/config/security.yml. So you have full control over it. So I think it is better to implement redirection logic in onAuthenticationSuccess method of your success_handler service class.


text:
Q: Can RAII efficiently share immutable objects between threads without synchronization In the countless arguments about the superiority of C++-style deterministic destruction (RAII) versus garbage-collection, proponents of the former often suggest that it can do everything garbage-collection can do.  There is, however, a pattern which is used frequently in Java and .NET languages, but for which I know no nice pattern in C++.  Consider the class [could be Java or C#; using public fields for brevity}
public class MaxItemIdentifier
{
  public String maxItemName = null;
  public long maxItemValue = -0x7FFFFFFFFFFFFFFF-1;
  public void checkItem(String name, long value)
  {
    if (value > maxItemValue)
    {
      maxItemName = name;
      maxItemValue = value;
    }
  }
}

In both Java and C#, the above method may safely be passed a string that was created on any thread.  Further, while the method is not thread-safe, even improper threading usage will not jeopardize memory safety; maxItemName would still be guaranteed to either be null or identify one of the strings passed to checkItem.  Additionally, the method never actually has to copy (or even look at) the contents of any string; all it acts upon are string references.  Since no string object whose reference has been exposed to the outside world will ever be modified, a reference to a string may be considered synonymous with the sequence of characters identified thereby, and copying the reference is equivalent to copying the text.
Would there any way to write an equivalent class in C++ or similar RAII-based language which would guarantee memory safety regardless of threading usage, but would be not be needless inefficient when run from a single thread?  The only approaches I'm aware of that such a method could be workable in C++ would be if either:

*

*Whenever encountering an item whose "value" is larger than the previous maximum, the method copies the contents of the string; this would be slower than simply copying a reference.  Further, I don't know how well this could maintain memory safety in the presence of improper threading usage.

*Have the method receive a reference to a reference-counted pointer, and hold a variable of that type; when receiving a value which is larger than the previous maximum, atomically increment the reference count on the received pointer and atomically decrement the reference count on the previous maximum-item name; if the latter yields zero, release that name.  This approach would seem safe, but on many platforms atomically increments and decrements would be excessively expensive for single-threaded usage, but would be necessary for memory safety in multi-threading scenarios.
Personally, I believe a good language/framework should support both RAII and GC, since each can handle very easily and efficiently some things which the other really can't handle at all.  It's possible, though, that there would be some other approaches to handling such things in RAII that I'm unfamiliar with.  Is there any way when using RAII to make a method like the above work efficiently when used in single-threading scenarios but also be usable in scenarios where a reference to a string created on one thread might then be exposed to other threads?
Note that unlike some other multi-threading RAII scenarios in which objects have a predictable lifetime, being consistently created in a producer thread and destroyed in a consumer thread (the subject of a related post), references to immutable objects like Strings are often shared without any reference-holder being identifiable as an "owner", and without any way of knowing if or when whether any particular reference-holder might overwrite the last surviving reference to a string.

A: This is certainly a known concern.
You can't get deterministic destruction of shared objects without some overhead.  The reason that destruction comes out on top of finalization in so many cases is that:

*

*Most objects are not shared.

*Many shared objects require deterministic destruction, and the costs of providing that on top of finalization are even higher than the costs of using RAII to implement reference counting.

And clearly RAII does a great job of managing destruction.
It's really only objects that are shared among multiple unsynchronized users and will be abandoned and never used again where finalization outshines destruction.  An example would be zero-copy multicast sockets (or at least O(1) copy).
The tradeoff is still between determinism (with some counting overhead) and non-determinism.  Because C and C++ don't enforce a single resource management method, it's actually easier to mix destructor-based deterministic cleanup with efficient non-deterministic cleanup than it would be on top of the .NET or Java runtimes where everything undergoes non-deterministic deallocation.
An example of non-deterministic cleanup in the native world is the RCU method used in the Linux kernel.  It's C code, but applies equally well to C++.
So even here, the advantage goes to RAII, you just use a different set of smart pointers for non-deterministic RCU than the ones for local scope deterministic release or reference counting, thread synchronization, and deterministic release.
Really, that's where your thinking went wrong.  RAII is able to provide deterministic lifetime, but it is not limited to deterministic lifetime.


text:
Q: Mapping half-plane to unit disk? Say you have the half-plane $\{z\in\mathbb{C}:\Re(z)>0\}$. Is there a rigorous explanation why the transformation $w=\dfrac{z-1}{z+1}$ maps the half plane onto $|w|<1$?

A: There is, but I'm not sure what you do or don't know. But we'll see what we can do.
So you know that it's a fractional linear transformation. It's continuous, bijective, open, and ultimately beautiful. It can be shown that it preserves circilinearity - i.e. it takes lines and circles to lines and circles (not respectively - a line in the extended complex plane is a circle through infinity). You can then check that this transformation does in fact send the imaginary line to the boundary of the unit disk. (In fact, the modulus on imaginary numbers is 1 - that's all you need to check).
So we have a continuous linear map that sends the boundary where we want to send it. So take some point in the half plane and make sure it gets sent to the interior and not the exterior. $1$, for instance, is sent to $0$, and so the right half plane is on the interior of the disk (and in particular not the boundary, which is the image of the imaginary line).
That's why, in a nutshell.

A: You can also check it explicitly:
$$
\left| \frac{z-1}{z+1} \right|^2 = \frac{z-1}{z+1}\cdot\frac{\overline{z}-1}{\overline{z}+1} = \frac{|z|^2-2 \Re(z) +1}{|z|^2+2 \Re(z)+1} < 1.
$$
The last inequality follows simply because $\Re(z) > 0$ and so the numerator is smaller than the denominator.
The other way around: the inverse is given by
$$
z \mapsto \frac{1+z}{1-z}
$$
and we can check the real part for $|z| < 1$:
$$
\Re\left(\frac{1+z}{1-z}\right) = \frac{1}{2} \left( \frac{1+z}{1-z} + \frac{1+\overline{z}}{1-\overline{z}}\right) = \frac{1-|z|^2}{|1-z|^2} > 0.
$$

A: ( This is more comment then answer but I can't add images in comment )

Her is image and src code

A: I wrote a simple demo with Mathematica to demonstrate it.
f[z_] := (z - 1)/(z + 1);
Manipulate[
 ComplexListPlot[Table[f[re + I*im], {im, -50, 50, 0.1}],
  PlotRange -> {{-5, 5}, {-5, 5}}], {{re, 0}, -3, 3}]


text:
Q: What does 'typeof' operator tells here? The code is:
 var someVariable;    // this variable is declared but not initialised...

 alert(typeof someVariable);   // alerts 'undefined'
 alert(typeof notDeclared);    // also alerts 'undefined' irrespective
                               //  of the fact it has not been declared..

It seems a bit confusing. Now, if I do
alert(someVariable);    // again alerts 'undefined'
alert(notDeclared);     // causes an error

jsFiddle link: http://jsfiddle.net/gjYZt/2/
If 'typeof notDeclared' is undefined, then when I alert 'notDeclared', it should also alert 'undefined' instead of giving an error.

A: Short answer:
typeof has a special case for unresolvable references; it explicitly returns undefined if the reference is unresolvable.
Long answer:
The typeof operator has a special case for unresolvable references:

11.4.3 The typeof Operator
The production UnaryExpression : typeof UnaryExpression is evaluated as follows:

*

*Let val be the result of evaluating UnaryExpression.

*If Type(val) is Reference, then

*

*If IsUnresolvableReference(val) is true, return "undefined".

*Let val be GetValue(val).

*Return a String determined by Type(val) according to Table 20.

On the other hand, the internal GetValue(V) function, which is used everywhere in javascript, including for retrieving the value of a varialbe, throws a ReferenceError if the reference is unresolvable:

8.7.1 GetValue (V)

*

*If Type(V) is not Reference, return V.

*Let base be the result of calling GetBase(V).

*If IsUnresolvableReference(V), throw a ReferenceError exception.

*If IsPropertyReference(V), then
  [...]

See the spec.

A: someVariable is declared not initialized.But  notDeclared is not declared..
someVariable does not contain any default value .But notDeclared is not avialable.

A:
When I do 'alert(typeof notDeclared);', that should also give an
  error. Isn't it?

No, because the specification is clear that if the operand to typeof is not resolvable, the result of typeof must be undefined (look at 2a).
When you try to evaluate an expression that is not resolvable such as notDeclared in your example, you get a ReferenceError -- this is also according to the spec.

A: the  operator typeof returns the type of the operand.
This list summarizes the possible return values of typeof
Type    Result
Undefined   "undefined"
Null    "object"
Boolean "boolean"
Number  "number"
String  "string"
Host object (provided by the JS environment)    Implementation-dependent
Function object (implements [[Call]] in ECMA-262 terms) "function"
E4X XML object  "xml"
E4X XMLList object  "xml"
Any other object    "object"

if yout alert return undefined that's because your variable type is undifined.
Regards


text:
Q: Plot with x-axis contains the day I load a dataframe (named stock) with this data:
day               value
2000-12-01 00:00:00 11.809242
2000-12-01 06:00:00 10.919792
2000-12-01 12:00:00 13.265208
2000-12-01 18:00:00 13.005139
2000-12-02 00:00:00 10.592222
2000-12-02 06:00:00 8.873160
2000-12-02 12:00:00 12.292847
2000-12-02 18:00:00 12.609722
2000-12-03 00:00:00 11.378299
2000-12-03 06:00:00 10.510972
2000-12-03 12:00:00 8.297222
2000-12-03 18:00:00 8.110486
2000-12-04 00:00:00 8.066154

I try to implement forecasting using arima() model with this:
requires(forecast)
fit <- Arima(stock$value,c(3,1,2))
fcast <- forecast(fit, h = 5)

After that I want to take the plot from forecasting process. However I try to make the x-axis to have the days. Until now I have this:
x = as.POSIXct( stock$day , format = "%Y-%m-%d %H:%M:%S" )

plot(fcast, xaxt="n")
a = seq(x[1], by="min", length=nrow(stock))
axis(1, at = a, labels = format(a, "%Y-%m-%d %H:%M:%S"), cex.axis=0.6)

A: Since , you manipulate time series objects it is better to use ts-packages like zoo or xts, It  seems that forecast package  was designed to work with such objects.
## read the zoo object
## I add a virtual colname aaa here
## for some reason index=0:1 don't work
library(zoo)
stock <- read.zoo(text='aaa day value
2000-12-01 00:00:00 11.809242
2000-12-01 06:00:00 10.919792
2000-12-01 12:00:00 13.265208
2000-12-01 18:00:00 13.005139
2000-12-02 00:00:00 10.592222
2000-12-02 06:00:00 8.873160
2000-12-02 12:00:00 12.292847
2000-12-02 18:00:00 12.609722
2000-12-03 00:00:00 11.378299
2000-12-03 06:00:00 10.510972
2000-12-03 12:00:00 8.297222
2000-12-03 18:00:00 8.110486
2000-12-04 00:00:00 8.066154',header=TRUE,
                tz='',
                index=1:2)

##  arima works well with zoo objects
fit <- Arima(stock,c(3,1,2))
fcast <- forecast(fit, h = 20)
plot(fcast, xaxt="n")

To plot dates axis , you should use axis.POSIXct or axis.Date. There are equivalent of axis for dates objects. But you should first create date indexes. Here I aggregate the original dates and the forecated dates generated by forecast function.
  a <- c(as.POSIXct(index(stock)),
         as.POSIXct(index(fcast$mean),origin='1970-01-01 00:00.00 UTC'))

Then I plot my axis using something like this:
## Note the use of las to rotate the axis
## you can play with format here
axis.POSIXct(1,at=a,format="%a %H",las=2,cex=0.5)


text:
Q: Freshclam error After installing clamav and clamtk, when doing freshclam I receive this message:
freshclam
ERROR: Can't create temporary directory /var/lib/clamav/clamav-f52645d8e80b9b727228734e339d231d
Hint: The database directory must be writable for UID 1000 or GID 1000

Could somebody help?

A: I seem to remember getting this issue when I first started using clamav, going back through my notes I found I had written this:
First find out my uid and gid by typing at the command prompt: id your_username
Should give you a long line of text with a uid and gid in it somewhere, then type:
sudo chown UID.GID /var/lib/clamav
then
sudo chmod 755 /var/lib/clamav
Change UID and GID with the values you got from the id Command above.
hope that helps

A: Yes, run freshclam with sudo:
sudo freshclam

A: http://www.iasptk.com/ubuntu/19931-ubuntu-1204-clamav-problem-with-updating
In Terminal:
Stop the updater:
sudo /etc/init.d/clamav-freshclam stop

Update:
sudo freshclam -v

Start the updater:
sudo /etc/init.d/clamav-freshclam start

A: I got the same error in a docker container and could resolve it by adding:
AllowSupplementaryGroups true

to /etc/clamav/clamd.conf
Hope that helps.


text:
Q: using a String variable outside loop inside a StAX parsing example, I am setting a String dataread = se.getElementText();.
I am successfully printing that string (dataread) immediately.
However, everywhere else in my code, it won't work, it reports that it cannot find the symbol dataread. You will see it being attempted 5 other spots going down into the code - all report the same. The first line within the if statement works.
How can I use the string "dataread" elsewhere in my program?
Thanks
public static void main(String[] args) throws FileNotFoundException, XMLStreamException
{
    // TODO code application logic here
    //System.out.println("Here");
    //String filename = null;
    String filename = "BookCatalog2.xml";
    XMLInputFactory factory = XMLInputFactory.newInstance();
    XMLEventReader reader = factory.createXMLEventReader(new FileReader(filename));
    while(reader.hasNext())
            {
                XMLEvent event = reader.nextEvent();
                XMLEvent nextEvent = reader.peek();
                switch (event.getEventType())
                        {
                    case XMLEvent.START_ELEMENT:

                        StartElement se = event.asStartElement();
                        //System.out.println("Here");
                        //System.out.print("<" + se.getName());

                        //System.out.print(" " + se.getName());
                        //System.out.printf("\n");
                        String elem = se.getName().toString();
                        //String elem = "1";
                        //System.out.printf("elem = %s\n",elem);
                        //String ele = event.getAttributeName();

                        System.out.printf("event = %s\n",se.getName());

                        //if( se.getName().toString() == "{http://www.publishing.org}Date")
                       if( se.getName().toString().equals("Date"))
                       //if( elem == "1")
                        {
                            System.out.println("Here !!!!!!!!!!!!!!!!!");
                            String dataread = reader.getElementText();
                            //System.out.printf("data = %s\n",reader.getElementText());
                            System.out.printf("data = %s\n",dataread);
                        }
                        Iterator attributes = se.getNamespaces();
                        System.out.printf("DATA READ = %s\n",dataread);
                        while(attributes.hasNext())
                        {
                            Attribute attr= (Attribute)attributes.next();
                            System.out.print(" " + attr.getName() + "=\"" +attr.getValue() +"\"");
                            System.out.printf("\n");
                        }//end while loop
                    System.out.print(">");
                        if(nextEvent.isCharacters())
                        {
                            Characters c = reader.nextEvent().asCharacters();
                            if(!c.isWhiteSpace())
                            System.out.print(c.getData());
                            System.out.printf("\n");

                        }// end if
                        System.out.printf("DATA READ = %s\n",dataread);
                    /*case XMLEvent.END_ELEMENT>
                        EndElement ee = event.asEndElement();
                        System.out.print("</"+ee.getName()+">");
                        break;
                        * */
                        System.out.printf("DATA READ = %s\n",dataread);
                        }// end witch
                System.out.printf("DATA READ = %s\n",dataread);
            }// end while
    System.out.printf("DATA READ = %s\n",dataread);
    reader.close();
}//end Main
}// public claSS

A: Your string is within the scope of your first IF, you must declare it at the beginning of the method.
Try to declare after String filename = "BookCatalog2.xml";
Ex:
String filename = "BookCatalog2.xml";
String dataread = "";

A: Your String variable dataread is a local variable that has a scope within the if clause ONLY.
For that reason, you will not be able to access this variable outside the if block. To allow access to this variable when you print it, you must declare it before the if statement. e.g.:
String dataread = null;
if (test) {
    dataread = ...;
}

System.out.println(dataread); // etc

A: What you have to do is declare the local variable at a level where every method is at the same level or below it. As it is now you're declaring the variable in a if-clause, then you will only be able to reach it from that if-clause.


text:
Q: Global property filter in Jackson Is there a way to register a global property filter in ObjectMapper?
Global means that it will be applied to all serialized beans. I can't use annotations (I can't modify serialized beans) and don't know what properties the beans have.
The filtering should be name based.
My first idea was to write a custom serializer, but I don't know what should I pass to the constructor.

A: I'd make use of a FilterProvider.  It's a little involved, but not too unwieldy.
import org.codehaus.jackson.annotate.JsonAutoDetect.Visibility;
import org.codehaus.jackson.annotate.JsonMethod;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.ObjectWriter;
import org.codehaus.jackson.map.annotate.JsonFilter;
import org.codehaus.jackson.map.ser.FilterProvider;
import org.codehaus.jackson.map.ser.impl.SimpleBeanPropertyFilter;
import org.codehaus.jackson.map.ser.impl.SimpleFilterProvider;

public class JacksonFoo
{
  public static void main(String[] args) throws Exception
  {
    Bar bar = new Bar();
    bar.id = "42";
    bar.name = "James";
    bar.color = "blue";
    bar.foo = new Foo();
    bar.foo.id = "7";
    bar.foo.size = "big";
    bar.foo.height = "tall";

    ObjectMapper mapper = new ObjectMapper().setVisibility(JsonMethod.FIELD, Visibility.ANY);
    System.out.println(mapper.writeValueAsString(bar));
    // output:
    // {"id":"42","name":"James","color":"blue","foo":{"id":"7","size":"big","height":"tall"}}

    String[] ignorableFieldNames = { "id", "color" };

    FilterProvider filters = new SimpleFilterProvider().addFilter("filter properties by name", SimpleBeanPropertyFilter.serializeAllExcept(ignorableFieldNames));

    mapper = new ObjectMapper().setVisibility(JsonMethod.FIELD, Visibility.ANY);
    mapper.getSerializationConfig().addMixInAnnotations(Object.class, PropertyFilterMixIn.class);
    ObjectWriter writer = mapper.writer(filters);

    System.out.println(writer.writeValueAsString(bar));
    // output:
    // {"name":"James","foo":{"size":"big","height":"tall"}}
  }
}

@JsonFilter("filter properties by name")
class PropertyFilterMixIn
{

}

class Bar
{
  String id;
  String name;
  String color;
  Foo foo;
}

class Foo
{
  String id;
  String size;
  String height;
}

For other approaches and more information, I recommend the following resources.

*

*http://wiki.fasterxml.com/JacksonJsonViews

*http://www.cowtowncoder.com/blog/archives/2011/02/entry_443.html

*http://wiki.fasterxml.com/JacksonFeatureJsonFilter

*http://www.cowtowncoder.com/blog/archives/2011/09/entry_461.html


text:
Q: Why is there a comma after the variable in this sqlite query? I have the following code and it works, but I need to understand why there is a comma after the variable id_to_remove, can someone explain to me why that has to be there? (I bolded the part I don't understand)
def delete_user(id_to_remove):
    sql = "DELETE FROM USERS WHERE ID = ?"
    conn = create_connection()
    cursor = conn.cursor()
    **cursor.execute(sql, (id_to_remove, ))**
    conn.commit()
    conn.close()

So I don't know why its id_to_remove,  and not just cursor.execute(sql,(id_to_remove))

A: Because it will replace all the ? values with the ones in the tuple. If you don't put a comma then it is a single value, you need to add it to construct a single value tuple.


text:
Q: change text of tableviews delete button titanium how can I change the text of the red delete button of a tableview?
this is my tableview:
    var tableView = Ti.UI.createTableView({
        editable : true,
        backgroundColor : 'transparent',
        separatorColor : 'transparent',
        height : Ti.UI.SIZE,
    });

then i have the event listener for the 'DELET' event. but i need to change the text of the button from 'DELET' to 'X'
how can i du that?
I'm not using the alloy folder

A: You can set deleteButtonTitle property of the TableView :  http://docs.appcelerator.com/platform/latest/#!/api/Titanium.UI.TableViewRow-property-deleteButtonTitle