text:
Q: Time series weekly data I am very new to R and trying to manipulate my data in excel before moving it into R as a csv file.  I would like to use ts() for weekly data.  Can you do something as simple as Month 1-12, week 1-4, year?  MWY.  I was thinking if I use day 1-7 as week one and so on that would be uniform and work easy for my purpose but I don't know how to write it.  Using this site and another for a tutorial I came up with this:
myts <- ts(Time2012, start = c(8/3/2013,1), end = c(9/2/2013,4), frequency = 52)

is there any easy way to denote the date to show I want to count weeks?

A: i would recommend a slightly different workflow, one which you will likely find has broader utility:
> end = Sys.Date()
> start = end - 365

> class

> # create the index array comprised of date objects
> ndx = seq(start, end, by='weeks')
> class(ndx)
  [1] "Date"
> length(ndx)
  [1] 53

> # create a fake data array
> x = 1:length(ndx)
> mydata = sin(x/2)

> # import a time series library
> require(xts)

> # create the time series
> myts = xts(mydata, order.by=ndx)

> myts[1:5]
               [,1]
  2012-09-19 3.479426
  2012-09-26 3.841471
  2012-10-03 3.997495
  2012-10-10 3.909297
  2012-10-17 3.598472

> class(myts)
  [1] "xts" "zoo"

> periodicity(myts)
  Weekly periodicity from 2012-09-19 to 2013-09-18

Alternatively, if your data is not by week, then you can create a time series having a higher resolution (eg, days) then roll it up to weeks:
> ndx = seq(start, end, by='days')

> x = 1:length(ndx)
> mydata = sin(x/2) + 3
> myts = xts(mydata, order.by=ndx)

> myts[1:5]
             [,1]
2012-09-19 3.479426
2012-09-20 3.841471
2012-09-21 3.997495
2012-09-22 3.909297
2012-09-23 3.598472

> periodicity(myts)
    Daily periodicity from 2012-09-19 to 2013-09-19

> # now roll-up this daily series to weeks

> require(xts)

> # first create the endpoints
> np = endpoints(myts, on='weeks')

> myts_weeks = period.apply(x=myts, INDEX=np, FUN=sum, na.rm=TRUE)
> myts_weeks[1:5]
               [,1]
  2012-09-23 18.82616
  2012-09-30 17.11212
  2012-10-07 24.93492
  2012-10-14 17.51811
  2012-10-21 23.58635

> periodicity(myts_weeks)
  Weekly periodicity from 2012-09-23 to 2013-09-19

A: A simpler way to create a set of Year, Month, Week (of month) is with lubridate.
require(lubridate)

# Your starting date, plus 52 more dates at weekly intervals
xDates <- dmy("8/3/2013") + weeks(0:52)

# A data frame of the dates, the month of the year, and the week of the month
xYMW <- data.frame(date=(xDates), month=month(xDates), week=mday(xDates) %/% 7 + 1)
xYMW[1:5, ]
        date month week
1 2013-03-08     3    2
2 2013-03-15     3    3
3 2013-03-22     3    4
4 2013-03-29     3    5
5 2013-04-05     4    1


text:
Q: Unknown exception has been occured when running an android application in AVD I have created a small android application based on random number guessing. When I will click on the button "generate random number" it will generate one random number between 1-100 and the number will be shown in the TextView. But at the initial time the TextView will be invisible because I don't want to show that the random number to the user before guessing. After generating the random number, The user have to guess the correct number generated by the system and have to write on the EditText portion. Now when I will click on the check button, it will check whether the user guessed it correct or not. If the guess number is lower than the generated number, it will show "too low try again". If user guessed it higher than the generated number, it will show "Too high try again". Now if the user guessed it correct, it will show that the user guessed it correctly and also it will show that in how many guesses they got the correct answer. Also that time the TextView where the random number generated will get visible.(I have used do-while loop for the checking part)
Now, when I'm running the app, when I was clicking on the button "generate the random number", it was generating the number. But when I was mentioning the guessed number and clicking on the check button, neither the app was responding nor it was showing any kind of exceptions in the logcat. And each and every time the avd is restarting. I will be thankful, if anybody can assist me to solve this problem. Thank you.
The code is given below:
MainActivity.java
public class MainActivity extends AppCompatActivity {

Button btn_random, btn_check;
TextView txt_random_num;
EditText edt_guess;
int guess;
int random;
int count = 0;

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

    declareView();
    randomNumberGenerate();
    guessingTheValue();

}

private void guessingTheValue() {

    btn_check.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            while (guess != random){
                guess = Integer.valueOf(edt_guess.getText().toString().trim());
                count++;
                validation();
            }

        }
    });
}

private void randomNumberGenerate() {

    btn_random.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            txt_random_num.setVisibility(View.GONE);
            random = (int) (Math.random() * 100) + 1;
            txt_random_num.setText(String.valueOf(random));
            Toast.makeText(MainActivity.this,"Random number Generated!! Now guess Below",Toast.LENGTH_LONG).show();

        }
    });
}

private void declareView() {

    txt_random_num = findViewById(R.id.btn_random);
    btn_random = findViewById(R.id.btn_random);
    btn_check = findViewById(R.id.btn_check);
    edt_guess = findViewById(R.id.edt_guess);
}

public boolean validation(){

    if (guess > random)
    {
        Toast.makeText(MainActivity.this,"Too high! Try Again",Toast.LENGTH_LONG).show();
        return false;
    }
    else if (guess < random)
    {
        Toast.makeText(MainActivity.this,"Too low! Try Again",Toast.LENGTH_LONG).show();
        return false;
    }
    else {
        btn_random.setVisibility(View.GONE);
        txt_random_num.setVisibility(View.VISIBLE);
        Toast.makeText(MainActivity.this,"Correct! You got it in" + count + "guesses!",Toast.LENGTH_LONG).show();
        return true;
    }

}

}
Images are given below
Number Guessing app front-end
Logcat of number guessing app

A: Okay here is the problem same id for Button and TextView btn_random
txt_random_num = findViewById(R.id.btn_random);
btn_random = findViewById(R.id.btn_random);

A: The issue is declaring the while loop inside the Button OnClickListener, there is no need for it. Instead you can restructure your code as follows:
 btn_check.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            guess = Integer.valueOf(edt_guess.getText().toString().trim());
            validation();
            if (guess != random){
                count++;

            }

        }
    });

redpajama_set_name: RedPajamaStackExchange


text:
Q: Forks and PIDs in C I'm finding some difficulties with this C exercise: I'm asked to create a server socket which reads (through an infinite loop) a string from the input stream. If the string reads "self", the server prints on the output stream the server's own pid. If it reads "fork", it calls the fork() function and prints the child's pid.
I was thinking of including these lines inside the while loop
if (strcmp(val,"self")==0) sprintf(result,"%d\n",getpid());
else if (strcmp(val,"fork")==0){
    pid = fork();
    if (pid == 0) sprintf(result, "%d\n", getpid());

I tested it and it actually works fine when I write "self" or "fork" just once. If I try to issue the "fork" command more than once it gets "stuck", meaning that I have to repeat the command two or three times before I can actually get the result I need.
Here is an example of what I do (I use telnet to test the server):
 Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
self
4313
fork
4324
fork
fork
self
4313
fork
fork
fork
4327
fork
fork
fork
4328

Any ideas?

A: You need to manage the child after you've forked. The first thing to do after forking is to check whether you're the parent or the child process, then do different things based on where you are.
In the child:

*

*Do whatever you need to do, then exit. From your description the child may not need to do anything, in which case it can exit immediately.
If you don't exit then the child will continue on doing the same thing as the parent. It will step on its parent's toes, reading the parent's input and messing up its output and causing other sorts of minor havoc.
It's recommended to exit child processes with _Exit(), not exit(). exit() will run cleanup code like flushing stdio buffers that you really only want the parent to run.
In the parent:

*

*Get the child's PID and print it.

*Wait for the child to exit with wait().
The child is supposed to exit immediately, so the wait shouldn't block for long. Waiting for the child ensures the child process is cleaned up and doesn't become a zombie process.


text:
Q: Video are not updaing on vzaar Hi I am using Rails, vzaar gem to upload the video.
title, description are updating but video file is not updating in vzaar. Any help would be appreciated.
video_controller:
def edit
  @course = Course.find(params[:course_id])
  @video = @course.videos.find(params[:id])
end

def update
@course = Course.find(params[:course_id])
@video = @course.videos.find(params[:id])

api = Vzaar::Api.new(:application_token => "my token", :login => "myloginname")
api.edit_video(@video.vzaar_id, :path => params[:video][:video].tempfile.path, :title => params[:video][:title])
if @video.update_attributes(:title => params[:video][:title])
  redirect_to :back
 end
end

title is updating but video with path is not updating. However with same technique i successfully created video in vzaar.
Thanks

A: It looks like you're trying to replace the actual video content here - is that correct?
If that's the case, it's not the edit_video method that you need to use in this case. As our documentation states, you can only change title, description, private and seo_url that way.
To replace a video, you'll need to use the upload_video method again, but supply a replace_id in the options that marks the video id you want to overwrite. In your case, it'll look something like this:
api.upload_video(path: params[:video][:video].tempfile.path, title: params[:video][:title], replace_id: @video.vzaar_id)

You'd also need to set the other options to match your previous uploads.
I hope this helps, and please let me know if you have any questions, or alternatively contact us on support@vzaar.com. And don't forget to check out the documentation, as that lists all the arguments available for each method.
All the best,
Dan


text:
Q: Generate permutations based on provided template. Any better idea than this, to do the same? What do you think about code below? Any better idea, to do the same? Input should be some numbers and char "x", example: 12xx00.
from itertools import product

signs = input("signs: ")
template = signs.replace('x', '{}')
wildcard_count = signs.count('x')

results = [
    list(template.format(*digits))
    for digits in product(*(
        range(10)
        for _ in range(wildcard_count)
    ))
]

print(results)

A: You could simplify your code a lot using a generator expression and coding directly the wildcard replacement value:
from itertools import product

signs = '12xx00'

out = list(product(*('0123456789' if c == 'x' else c for c in signs)))

Output:
[('1', '2', '0', '0', '0', '0'),
 ('1', '2', '0', '1', '0', '0'),
 ('1', '2', '0', '2', '0', '0'),
 ('1', '2', '0', '3', '0', '0'),
 ('1', '2', '0', '4', '0', '0'),
 ('1', '2', '0', '5', '0', '0'),
 ('1', '2', '0', '6', '0', '0'),
 ('1', '2', '0', '7', '0', '0'),
 ('1', '2', '0', '8', '0', '0'),
 ('1', '2', '0', '9', '0', '0'),
 ...
]


text:
Q: Must I specify unique Loading booleans when fetching data via multiple async functions within useEffects in React hooks to avoid concurrency problems? My concern is if using the same isLoading boolean state can cause concurrency issues. Here's an example of what I'm talking about:
  const [isLoading, setIsLoading] = useState<boolean>(false);

  useEffect(() => {
    async function getWaitlistDetailsOnLoad() {
      setIsLoading(true)
      try {
        const details = await getWaitlistDetailsForUser(
          apiInstance,
          product.id
        );
        if (details.status === 200) {
          setWaitlistDetails(details.data);
        }
      } catch (e) {
        console.log("Error getting waitlist details: ", e);
      }
      setIsLoading(false)
    }
    getWaitlistDetailsOnLoad();
  }, [apiInstance, product.id]);

  useEffect(() => {
    async function getNextAvailableTimeOnLoad() {
      setIsLoading(true)
      try {
        const time = await getNextAvailableTime(apiInstance, product.id);
        if (time.status === 200) {
          setNextAvailableTime(time.data);
        }
        setIsLoading(false);
      } catch (e) {
        console.log("Error getting next available time: ", e);
      }
      setIsLoading(false)
    }
    getNextAvailableTimeOnLoad();
  }, [apiInstance, product.id]);

Of course I can just track two independent loading states like this:
  const [firstLoader, setFirstLoader] = useState<boolean>(false);
  const [secondLoader, setSecondLoader] = useState<boolean>(false);

...but if I don't have to, I'd rather not. It would make the code simpler and conditional rendering simpler as well for my use-case.

A: As @alexander-nied already pointed out there might by a bug in your code. useEffect callbacks can't be async. To use async/await nontheless you can wrap the three lines as follows and add an await statement.
// Version 1, closer to the original example
useEffect(() => {
    async doSomething() {
        await someAsyncMethod();
    }

    (async () => {
        setIsLoading(true);
        await doSomething();
        setIsLoading(false);
    })();
})

// Version 2, closer to the current example
useEffect(() => {
    async doSomething() {
        setIsLoading(true);
        await someAsyncMethod();
        setIsLoading(false);
    }

    doSomething();
})

To answer your question:
It certainly depends on you usecase, but I would recommend against just using one single boolean, since it allows for weired scenarios to occur.
What if one request is way faster than the other? Your loading indicator would be set to false, instead of informing the user that there is still work being done in the background.

A: If you are guaranteed that the two asynchronous effects will not run at the same time (for instance, if OperationTwo, if one is called at the completion of OperationOne) then  you could get away with using a single isLoading boolean, set as true at the start of OperationOne, and set as false at the completion of OperationTwo.
However, if you have two operations that might at any point run at the same time, then you should split them into two separate loaders, and use a single value that ORs them to determine the ultimate loading state of the view.
Let's consider a component that makes two asynchronous fetches on load:
const MyPretendComponent = () => {
    const [isLoading, setIsLoading] = useState(false);

    useEffect(() => {
      setIsLoading(true);
      MyService.fetchThatCompletesInOneSecond()
        .then(() => setIsLoading(false));
      MyService.fetchThatCompletesInTwentySeconds()
        .then(() => setIsLoading(false));
    }, [])

    return (
{`isLoading ? "Loading" : "Finished!"`}
);
}

This should illustrate the problem nicely-- we have two asynchronous operations on component load-- one that completes in one second, and one that completes in twenty seconds.  Both set isLoading as false when they complete.  In this case, the first operation completes in one second and sets isLoading to false, and the UI erroneously reports that it is not in a loading state even though the second operation still has nineteen seconds left until it completes.
The cleaner version, using two booleans, is this:

const MyPretendComponent = () => {
    const [isFirstOperationLoading, setIsFirstOperationLoading] = useState(false);
    const [isSecondOperationLoading, setIsSecondOperationLoading] = useState(false);

    useEffect(() => {
      setIsFirstOperationLoading(true);
      setIsSecondOperationLoading(true)
      MyService.fetchThatCompletesInOneSecond()
        .then(() => setIsFirstOperationLoading(false));
      MyService.fetchThatCompletesInTwentySeconds()
        .then(() => setIsSecondOperationLoading(false));
    }, [])

    const isLoading = isFirstOperationLoading || isSecondOperationLoading;

    return (
{`isLoading ? "Loading" : "Finished!"`}
);
}

Here we've split the two loading states into their own discrete booleans.  We still maintain a single isLoading boolean that simply ORs both the discrete booleans to determine if the overall loading state of the component is loading or not loading.  Note that, in a real-life example, we would want to use much more semantically descriptive variable names than isFirstOperationLoading and isSecondOperationLoading.
In regards to splitting the two calls into separate useEffects: at a glance one might think that in splitting the two calls across two different useEffects you could mitigate or sidestep the issue of asynchronicity.  However, if we walk through the component lifecycle, and think we will learn that this is not actually effective.  Let's update our first example:
const MyPretendComponent = () => {
    const [isFirstOperationLoading, setIsFirstOperationLoading] = useState(false);
    const [isSecondOperationLoading, setIsSecondOperationLoading] = useState(false);

    useEffect(() => {
      setIsFirstOperationLoading(true);
      setIsSecondOperationLoading(true)
      MyService.fetchThatCompletesInOneSecond()
        .then(() => setIsFirstOperationLoading(false));
      MyService.fetchThatCompletesInTwentySeconds()
        .then(() => setIsSecondOperationLoading(false));
    }, [])

    const isLoading = isFirstOperationLoading || isSecondOperationLoading;

    return (
{`isLoading ? "Loading" : "Finished!"`}
);
}

The problem here is that the component does not run in this manner:

*

*Run the first useEffect

*When the first useEffect completes, run the second useEffect

*When the second useEffect completes, render the UI

If it ran in that manner, we would be sitting and waiting for it to show the UI while it loaded.
Instead, the way it runs is like this:

*

*Run the component render-- call any useEffects if applicable, then render the UI

*Should any state updates occur (for instance, a state hook being called from the .then of a previous useEffect asynchronous call) then render again

*Repeat step two every time a state or prop update occurs

Keeping this in mind, at every component render React will evaluate and run any and all applicable useEffect callbacks.  It is not running them serially and tracking if one has completed-- such a thing would be difficult if not impossible.  Instead, it is the developer's responsibility to track loading states and organize useEffect dependency arrays in such a way that your component state is logical and consistent.
So you see, separating the async calls by useEffect does not save us from dealing with potential concurrent async calls.  In fact, if it did, it would mean that the UI load would be slower overall, because you would be serially calling two calls that could be called simultaneously.  For instance, if both async calls took ten seconds each, calling them one after the other would mean it would take 20 seconds before loading would be completes, as opposed to running them at the same time and finishing loading after only ten seconds.  It makes sense from a lifecycle perspective for the component to behave this way; we simply must code accordingly.


text:
Q: Why is a WPF DataGridCell.Content a TextBlock instead of a TextBox after adding a new item programmatically? I want to copy-paste data from a Excel table into a WPF DataGrid. For this I have the following function, which gets called on the KeyDown event:
private void OnDataGridPasteData(object sender, KeyEventArgs e)
{
    if ((Keyboard.Modifiers != ModifierKeys.Control) || e.Key != Key.V)
        return;

    DataGrid dg = (DataGrid)sender;

    var pastedData = Clipboard.GetText();
    List<string> rowDataCombined = pastedData.Split(new string[] { Environment.NewLine }, StringSplitOptions.None).ToList();
    List<string[]> rowData = new List<string[]>();
    foreach (var row in rowDataCombined)
    {
        rowData.Add(row.Split(new string[] { "\t" }, StringSplitOptions.None));
    }

    int initialRowIdx = Math.Max(dg.Items.IndexOf(dg.SelectedItem), 0);
    int initialColIdx = dg.CurrentCell.Column.DisplayIndex;
    int maxColIdx = dg.Columns.Count;
    int maxRowIdx = initialRowIdx + rowData.Count;

    Type sourceType = dg.ItemsSource.GetType().GetGenericArguments()[0];
    var sourceList = (IList)dg.ItemsSource;

    for (int r = initialRowIdx; r < maxRowIdx; r++)
    {
        if(r > dg.Items.Count - 1)
        {
            var newRowObject = Activator.CreateInstance(sourceType);
            sourceList.Add(newRowObject);
        }

        DataGridRow dgRow = GetRowFromDataGrid(dg, r);
        if (dgRow == null)
            continue;

        for (int c = initialColIdx; c < maxColIdx; c++)
        {
            var presenter = FindVisualChild<DataGridCellsPresenter>(dgRow);
            // try to get the cell but it may possibly be virtualized
            var cell = (DataGridCell)presenter.ItemContainerGenerator.ContainerFromIndex(c);
            if (cell == null)
            {
                // now try to bring into view and retreive the cell
                dg.ScrollIntoView(dgRow, dg.Columns[c]);
                cell = (DataGridCell)presenter.ItemContainerGenerator.ContainerFromIndex(c);
            }

            if(cell != null)
            {
                cell.Focus();
                if (!dg.BeginEdit()) //abort pasting if editing fails
                {
                    dg.CancelEdit();
                    return;
                }

                if(cell.Content is TextBox tb)
                {
                    tb.Text = rowData[r - initialRowIdx][c - initialColIdx];
                }
                if(!dg.CommitEdit()) // abort pasting if commit fails (e.g. wrong entry type)
                {
                    dg.CancelEdit();
                    return;
                }
            }
        }
    }
}

Notice the line if(cell.Content is TextBox tb):

*

*For existing DataGridCells this will be true

*For newly added items (line sourceList.Add(newRowObject);) this will be false. The content type then is a TextBlock

*If I add all the needed rows in a while loop in the same manner as above before entering the for loops, it will also result to true. However, I want to abort the whole operation, if the pasting fails without having the extra rows afterwards.

The DataGrid has AutoGenerateColumns set to true. Generated cells seem to get a TextBlock initially as content, which is later changed to a TextBox. Question is, what triggers this change, and can I do it manually? Would I break anything, if I simply change the content to a TextBox in case it is a TextBlock?

A: After searching a while I think I have found the issue. I have set the property DataGrid.CanUserAddRows to true by default. After editing the last row, it seems the DataGrid is therefore adding an empty row consisting of TextBlocks (until the user starts editing in the GUI) after the programmatic edits.
Setting the flag to false at the beginning of my paste function and back to true before returning fixes the problem.


text:
Q: Camel app on Liberty - JAXB Marshalling I'm running a Camel application on Liberty Profile server. I'm taking a message from a queue, unmarshalling, mapping then marshalling. This was working fine but now I'm getting an error that JAXBDataBinding method getContextualNamespaceMap is not found.
I think this is because there is an older version of the jar in the server libs but I don't know why it started using it.
IBM Jar: com.ibm.ws.org.apache.cxf-rt-databinding-jaxb.2.6.2_1.0.12

The issue is resolved if I switch to parent last class loading but its a very hacky way to fix it and is not a great option. Any other ideas? I'm thinking some feature or other dependency in my build may have pulled this jar in.

A: So it does look like getContextualNamespaceMap is only available in newer versions of the org.apache.cxf-rt-databinding-jaxb JAR than what is available in Liberty.
It might be that parentLast is the best option then.  (You already know how to do this but it's documented (here). If it leads to some other issues then do follow-up with another question.
I suppose it's conceivable you might be able to look at whatever is packaged within your application and try removing a set of things and picking them up from the Liberty runtime, to avoid running in parentLast mode.  E.g. if you are only referencing getContextualNamespaceMap because you have other code in your app but there is some alternative path you could have gone down entirely in the Liberty-provided modules, then in theory you could be OK.
I'm not familiar enough with the code paths in the modules in the CXF or Camel "stack" to guess whether that's a real-world likelihood though.

A: The javaee7 feature contained a jaxsw version that clashed with the server version. Removing the javaee7 feature has resolved this issue. Remains to be seen whether or not I will to add it back in.


text:
Q: How can I count frequency by data in dataframe? I have an issue with groupby in pandsa. My DF looks like below:
time    ID
01-13   1
01-13   2
01-14   3
01-15   4
01-15   5

I need result like below:
time   ID
01-13  2
01-14  1
01-15  2

So basically I need to count frequency ID by data. I treid with this but I am not sure of result (df is huge). Any idea? Thanks for help
df = df.groupby("Time").Id.value_counts()

Best regards

A: One way is:
df.time.value_counts()

Output:
01-15    2
01-13    2
01-14    1
Name: time, dtype: int64

Other way, as suggested by reviewer above:
df.groupby(['time']).size().reset_index(name='Frequency')

Output:
    time    Frequency
0   01-13   2
1   01-14   1
2   01-15   2

Note you can group by several variables if needed:
df.groupby(['col1', 'col2', 'etc.'])...


text:
Q: How to get Flutter WebSocket working with spring-boot backend? I have tried many combinations of the values below, I have no idea why it isn't working. I don't even know if the problem is with frontend or backend setup. I pasted the relevant code parts below.
FLutter says the following when I try to connect (MYIPADDRESS is a valid IP address, the IP address of the pc):
WebSocketChannelException: WebSocketChannelException: WebSocketException: Connection to 'http://MYIPADDRESS:8080/topic/greetings#' was not upgraded to websocket

Here is the backend/spring-boot controller part:
@MessageMapping("/hello")
@SendTo("/topic/greetings")
public String send(final String message) throws Exception {
    return message;
}

Here is the backend/spring-boot configuration part:
@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {

    @Override
    public void configureMessageBroker(MessageBrokerRegistry config) {
        config.enableSimpleBroker("/topic");
        config.setApplicationDestinationPrefixes("/app");
    }

    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
         registry.addEndpoint("/websocket").withSockJS();
    }
}

Here is the frontend/flutter part:
final channel = IOWebSocketChannel.connect(
  Uri(
    scheme: "ws",
    host: "MYIPADDRESS",
    port: 8080,
    path: "/topic/greetings",
  ),
);


text:
Q: Sort bibliography in order of appearance I'm trying to use \bibliographystyle{unsrt} to sort my bibliography in order of appearance. From here I know that I can't mix the biblatex package with \bibliographystyle. However, when I remove biblatex another compile error arises on a different line.
Here's what I have tried...
% BEGIN -- SETUP DOCUMENT (OVERLEAF) --
\documentclass[a4paper,12pt]{article}
\usepackage[utf8]{inputenc}
\usepackage[british]{babel}
\usepackage{csquotes}
\bibliographystyle{unsrt}
\DeclareLanguageMapping{british}{british-apa}
\usepackage[pdftex]{graphicx}
\addbibresource{ref.bib}

\let\cite\parencite
\begin{document}
% END -- SETUP DOCUMENT (OVERLEAF) --

\title{ Machine Learning for 3D Segmentation }
\author{Kendall Weihe}
\date{October 27, 2016}
\maketitle

\printbibliography[title=References]
\nocite{*}

\end{document}

It throws an error at the line \DeclareLanguageMapping{british}{british-apa}

A: You cannot mix BibTeX and biblatex.
In your code remove \bibliographystyle{unsrt} (which is BibTeX language) and load biblatex with sorting=none
\usepackage[backend=biber,style=numeric,sorting=none]{biblatex}

You will probably not need \DeclareLanguageMapping{british}{british-apa}, which is only necessary if you use the biblatex-apa style.


text:
Q: How to update column data in sharpoint with power automate from excel I have written a flow using power automate that checks an Excel spreadsheet for name and time since last modified (Last 10 mins) and if both are true it attempts to find a file in the Sharepoint folder using the file name taken from the table in the spreadsheet. This all works - please see the screen shots below:

I initialize the variable which contains my own email address for testing purposes.

I get the email to say the file has been found and is ok in time etc.
I then load the directory where the files detailed in the Excel spreadsheet are located and iterate through them.

This works and I get an email to say the file has been found and it returns the data etc.
No my problem is when I add the step below:

I have manually added in the information at the moment to prove it works and will then link back to the information in the spreadsheet.
When I test the flow, I get the error below:

ResponseSwaggerSchemaValidationFailure. The API 'sharepointonline' returned an invalid response for workflow operation 'Get_files_(properties_only)' of type 'OpenApiConnection'. Error details: 'The API operation 'GetFileItems' is missing required property 'body/value/0/WorkDate'.'

This is at the get files properties stage which worked until I added the new step?
I believe it is to do with the SharePoint Column Work Date because if I delete the step and then add work date into the email as a found value I get the error again.
Why would looking for a column which is available in SharePoint cause the issue?


text:
Q: Help on interaction terms Briefly, I am analysing how competitions and games run and what can affect performance in those competitions. Each individual plays in multiple competitions one after each other and receives an overall rating that signals how well they are doing based on how many competitions they have played in so far and won.
I want to analyse the effects of winning and losing streak but don't know how to model them with the following variables I have.
(1) Dummy variable = 1, if the individual is currently on a winning streak, and =0 if the individual is currently on a losing streak. (A streak can be made up of just one competition, so if I play for the first time and win, that is classed as I am on a "winning streak").
(2) Variable that tells you how long you're current streak has lasted. However, it doesn't distinguish between winning and losing streaks. So a value of "5" here could mean a winning streak of 5 or a losing streak of 5, essentially it is how long you're current streak has lasted.
I want to interact these terms to best analyse the impact on performance of such streaks, but I am having trouble interpreting the interaction term and especially the main effects term of (2) if it doesn't distinguish between good or bad streaks. I would like to ideally know how the length of a good streak affects performance and how the length of a bad streak affects performance.
Please, can someone offer any advice and interpretation?

A: Unfortunately, I cannot comment and ask for the model summary you received but I'll try to answer it fully regardless, and you let me know if I understood you correctly and whether it answers your question.
When you run a model with a dummy variable, your model assumes that always 1 of the groups of the categorical must be "true" and treats one of them as the reference group. Therefore the main effect of your continuous variable is not fully independent but gives you the coefficient given reference group.
When you treat categories as 0 and 1, what you call your main effect's coefficient is only true for group 0, the losing streak. The interaction that appears later gives you the coefficient given group 1 (winning)
You can find an elaboration of this here https://www.r-bloggers.com/interpreting-interaction-coefficient-in-r-part1-lm/
and here: http://imaging.mrc-cbu.cam.ac.uk/statswiki/FAQ/contint?action=AttachFile&do=get&target=int.pdf

A: To really understand linear models and interaction terms it is best to go back to algebra and factoring (yes, that topic that many ask: "when will I ever use this?").
Your model will be something like:
$y = \beta_0 + \beta_1 x_1 + \beta_2 x_2 + \beta_3 x_1 x_2 + \epsilon$
where $x_1$ and $x_2$ are your variables as described above and the $\beta$s are the model coefficients.  Here are a couple of ways that we can factor the above equation (dropping $\epsilon$ for simplicity):
$y = (\beta_0 + \beta_1 x_1) + (\beta_2 + \beta_3 x_1) x_2 $
$y = (\beta_0 + \beta_2 x_2) + (\beta_1 + \beta_3 x_2) x_1 $
Looking at the top model we can think of it as an equation of $x_2$ that depends on $x_1$.  The intercept is $(\beta_0 + \beta_1 x_1)$ and the slope (on $x_2$) is $(\beta_2 + \beta_3 x_1)$.  So the intercept and slope for $x_2$ depend on the value of $x_1$.  We can also see that $\beta_2$ is the "baseline" slope for $x_2$ when $x_1$ is 0 and $\beta_3$ is the adjustment to that slope when $x_1$ is not 0.  The second factoring can be interpreted similarly.
You say that you are having a hard time interpreting the main effect term.  That is because you should not be interpreting main effect terms when there are interactions.  Remember one definition of the coefficient on $x_2$ is "the effect of a 1 unit increase in $x_2$ holding all other predictors constant", but with an interaction term you cannot change $x_2$ relative to $\beta_2$ wile holding $x_2$ constant relative to $\beta_3$ (and $x_1$).  It is better to think of $\beta_2$ as the slope for $x_2$ when $x_1 = 0$ and $\beta_2 + \beta_3$ as the slope for $x_2$ when $x_1 = 1$.
With interactions, coefficients need to be interpreted in combination (with other coefficients and variables) not individually.  As things become more complicated it may be easier to interpret predictions from the model rather that the individual coefficients.


text:
Q: Maximum DB of lm386 What is the maximum Decibels that an LM386 chip, with its best wiring can go?
I have recently wired the LM386 to a breadboard and have found the audio output to be only about 55 dBA SPL.
Is that the highest the volume can go, or am i doing something wrong?

A: *

*Sound pressure level (SPL) depends on the loudness of the sound and the distance between the sound and the microphone in the meter.  Further away = lower SPL.

*The volume depends on the power supply.  To get the loudest output, you need to use the highest power supply voltage the chip is rated for.

*The volume depends on the speaker.  A tiny little speaker won't be as loud as a somewhat bigger one.  Too big is bad as well, though.  You won't want to try to drive a 100 watt sub-woofer with an LM386.  The speaker efficiency plays a part as well.  A low efficiency speaker won't be as loud as a more efficient speaker.

*The volume depends on the enclosure.  A speaker in free air has a sort of "acoustic short circuit" - the sound waves generated by the front and the back of the speaker cancel each other to some extent and reduce the volume.

*The volume depends on the input signal. The higher the input level, the louder the output volume - up to a point.  If the input is too high, then it would take more than the available voltage to produce the output signal.  The amplifier clips, and sounds horrible - and doesn't get any louder.

56dBA might be a reasonable volume for your setup.  There's no way to tell from here without details you didn't provide.
The LM386 is not a high power amplifier.  Wikipedia says that depending on exactly which version of the LM386 you use (and the powersupply voltage and speaker impedance) the maximum power output ranges from 0.3 watts to 1 watt of power output.  No matter how good (or bad) your speaker is, you aren't going to get window rattling, bone jarring bass out of the LM386.


text:
Q: Android Studio- Display one string if a button is pressed with no text in the textbox and another when text is inputted I am incredibly new to Android Studio and was hoping to get some assistance.
For some reason, this code is only displaying the ("Hi, " +name) portion. I am not sure what I am doing wrong or how to get the ("You must enter a name") portion to show when there is no text that has been inputted. We are needing to incorporate a SayHello() function into this and I am not sure if I am doing it properly...
enter image description here
package com.example.assignment5_2;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {
    EditText nameText;
    TextView textGreeting;
    Button buttonSayHello;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        nameText = (EditText) findViewById(R.id.nameText);
        textGreeting = (TextView) findViewById(R.id.textGreeting);
        buttonSayHello = (Button) findViewById(R.id.buttonSayHello);

        buttonSayHello.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                SayHello();
            }

            public void SayHello() {
                String name = nameText.getText().toString();
                if (name != null) {
                    textGreeting.setText("Hi, " + name);
                } else {
                    textGreeting.setText("You must enter a name");
                    buttonSayHello.setEnabled(name.isEmpty());
                }

            }
        });
    }
}

A: Hey I've tried your code and I guess I found the issue, please alter your condition as follows:
 public void SayHello() {
                String name = nameText.getText().toString();
                if (!name.isEmpty()) {
                    textGreeting.setText("Hi, " + name);
                } else {
                    textGreeting.setText("You must enter a name");
                }

It is preferred to use .isEmpty() method to check if the string is empty or not instead of using != null or == null, by altering your condition like I mentioned above your empty EditText check will work too. Check screenshots below for both cases:

try this and do let me know if it works !!

A: I think I got your problem, in the SayHello you have to change if(name != null) to
if(!name.trim().equals("")) or if(name.trim().length > 0)
Hope this helps


text:
Q: Read file in Python I am new to Python and trying to learn the language structure.
I understand how for statement and open function work. But cannot explain how this piece of code works, which dumps the content of file sample_log.txt to screen:
for line in open("sample_log.txt"):
    print line

These are my questions:

*

*Does open return a list?

*When the file actually gets read to memory?

*Does the file gets read line by line or all at once?

A: The open function returns a file object, they are iterable, so you can loop over it using a for expression.


text:
Q: Energy of the electron-muon reaction Lets see the reaction:
$e^- \mu^- \to e^- \pi^- \nu_\mu \;\;\;\;\;\;\;\;\;\;\; {(1)}$
I suppose, that this reaction occurs as follows
$e^- \mu^- \to e^- \mu^- \pi^+ \pi^- \to e^- \pi^- \nu_\mu$
Is it possible at energy less than 2*140 MeV?
The same is for the analogous proton-muon reaction
$p^+ \mu^+ \to p^+ \pi^+ \bar{\nu}_\mu \;\;\;\;\;\;\;\;\;\;\;{(2)}$
Once more reaction:
$p^+ p^+ \to p^+ p^+ \pi^- \pi^+ \to p^+ n \pi^+ \;\;\;\;\;\;\;\;\;\;\;{(3)}$
What are the experimental data?

P.S. This question is important enough. The main solar reaction is
$p^+ p^+ \to d^+ e^+ \nu_e $
If this reaction occurs as follows
$p^+ p^+ \to p^+ p^+ e^- e^+ \to p^+ n \nu_e e^+ \to d^+ e^+ \nu_e$
then  it would require the energy of more than 2*0.511 MeV to take place.
Cross section of this reaction will be much less, so the main solar reaction should be
$p^+ p^+ e^- \to d^+ \nu_e $

Update 20.02.11
Why I think so?
I suppose that new particles are created in pairs particle-antiparticle.
So the reaction
$e^- e^- \to e^- e^- \pi^- \pi^+ $
requires the energy of more than 2*140 MeV to take place
As well as the reaction
$e^- e^- \to e^- e^- \pi^- e^+ \nu_e $
from symmetry considerations, since there is a decay
$\pi^+ \to  e^+ \nu_e$
And the result is
$e^- e^- \to e^- e^- \pi^- e^+ \nu_e \to e^- \pi^- \nu_e $
contrary to
$e^- e^- \to e^- \nu_e W^- \to e^- \pi^-  \nu_e$
with the minimum reaction energy of 140 MeV
The same is valid for the reactions (1) (2) (3)
So what is the experimental data on minimum energy of these reactions?

A: There is no need for any intermediate state involving multiple pions. The leading Feynman diagram has a photon exchanged between the electron and muon, and the muon radiating a (very off-shell) W that decays into quarks that hadronize to a pion. The only constraint is that the initial energy is larger than the sum of the masses of the final state particles. (The pion in the final state, of course, is unstable and will soon decay back to a muon and antineutrino.)
(If you don't want to think in terms of the W and quarks, you can just consider that there's an effective pion–muon–neutrino vertex which is what allows the pion to decay, and the muon is using this interaction to turn into a pion and neutrino.)
More generally, for any process you can consider, the minimum energy needed is just the sum of the masses of the final-state particles.

A: The "main solar reaction" you are talking about,  $p^+ p^+ \to d^+ e^+ \nu_e $ is the first step of the pp-chain allowing the fusion of 4 protons to form Helium. This "pp-chain" has different "branches" (possible reactions) but all of them start with the process you mentioned.
This process is exoenergetic and releases 0.420 MeV even if deuton has a very low binding energy the reaction is possible because of the small difference in mass between the proton and the neutron.
It is a process involving the weak interaction: one of the proton "decay" ($\beta^+$ process) into a neutron, a positron and a neutrino.

Now about your second equation with an intermediate state where an electron-positron pair appear: you are making a mistake because you take the difference between the two sides, but you artificially introduced this electron-positron pair: this has to be taken into account:
You wrote
$p^+ + p^+ \rightarrow p + p + e^- + e^+$
but that's wrong, it should be
$p + p + \textrm{"some kinetic energy allowing the production of the pair = 0.511 MeV"} \rightarrow p + p + e^- + e^+$
and now, it should be right.

A: To complement Matt's answer, we just compare the total energy in both sides:
$M_e$ = 0.5 MeV, $M_\mu = 106 MeV$, $M_\pi = 140 MeV, the mass of the neutrino can be neglected so we obtain that kinematically this process is possible only if we give 34 MeV in the form of kinetic energy.


text:
Q: Android alarm clock app going off when its not supposed to I am currently struggling to find why my alarm sometimes works as intended and other times does not.
It normally works when i set the alarm for a few minutes but when i set the alarm from say 10pm to 6am that's when it normally starts going off within about 10 seconds. Whenever i set the alarm from pm to am or vice versa the error occurs and the alarm just goes off.
I know its a lot of code but I'm pretty much desperate at this point.
Any help will be appreciated.
Manifest
    <?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.insomniafinal">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".Register" android:label="@string/app_name" android:theme="@style/AppTheme.NoActionBar"></activity>

        <activity android:name=".MainActivity" android:theme="@style/AppTheme.NoActionBar">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <meta-data
            android:name="preloaded_fonts"
            android:resource="@array/preloaded_fonts" />
        <receiver android:name=".Alarm_Receiver" />

        <service android:name=".RingtonePlayingService"
            android:enabled="true">
        </service>
    </application>

</manifest>

Alarm Receiver
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;

public class Alarm_Receiver  extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {

        // fetch extra strings from the intent
        // tells the app whether the user pressed the alarm on button or the alarm off button
        String get_your_string = intent.getExtras().getString("extra");

        // fetch the extra longs from the intent
        // tells the app which value the user picked from the drop down menu/spinner
        Integer get_your_whale_choice = intent.getExtras().getInt("whale_choice");

        // create an intent to the ringtone service
        Intent service_intent = new Intent(context, RingtonePlayingService.class);

        // pass the extra string from Receiver to the Ringtone Playing Service
        service_intent.putExtra("extra", get_your_string);
        // pass the extra integer from the Receiver to the Ringtone Playing Service
        service_intent.putExtra("whale_choice", get_your_whale_choice);

        // start the ringtone service
        context.startService(service_intent);

    }

}

RingtonePlayingService
import android.annotation.TargetApi;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Build;
import android.os.IBinder;
import android.util.Log;

import java.util.Random;

public class RingtonePlayingService extends Service {

    MediaPlayer media_song;
    int startId;
    boolean isRunning;

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        // fetch the extra string from the alarm on/alarm off values
        String state = intent.getExtras().getString("extra");
        // fetch the whale choice integer values
        Integer whale_sound_choice = intent.getExtras().getInt("whale_choice");

        // notification
        // set up the notification service
        NotificationManager notify_manager = (NotificationManager)
                getSystemService(NOTIFICATION_SERVICE);
        // set up an intent that goes to the Main Activity
        Intent intent_main_activity = new Intent(this.getApplicationContext(), MainActivity.class);
        // set up a pending intent
        PendingIntent pending_intent_main_activity = PendingIntent.getActivity(this, 0,
                intent_main_activity, 0);

        // make the notification parameters
        Notification notification_popup = new Notification.Builder(this)
                .setContentTitle("An alarm is going off!")
                .setContentText("Click me!")
                .setSmallIcon(R.drawable.ic_action_call)
                .setContentIntent(pending_intent_main_activity)
                .setAutoCancel(true)
                .build();

        // this converts the extra strings from the intent
        // to start IDs, values 0 or 1
        assert state != null;
        switch (state) {
            case "alarm on":
                startId = 1;
                break;
            case "alarm off":
                startId = 0;
                Log.e("Start ID is ", state);
                break;
            default:
                startId = 0;
                break;
        }

        // if else statements

        // if there is no music playing, and the user pressed "alarm on"
        // music should start playing
        if (!this.isRunning && startId == 1) {
            Log.e("there is no music, ", "and you want start");

            this.isRunning = true;
            this.startId = 0;

            // set up the start command for the notification
            notify_manager.notify(0, notification_popup);

else if (this.isRunning && startId == 0) {
            Log.e("there is music, ", "and you want end");

            // stop the ringtone
            media_song.stop();
            media_song.reset();

            this.isRunning = false;
            this.startId = 0;
        }

        // these are if the user presses random buttons
        // just to bug-proof the app
        // if there is no music playing, and the user pressed "alarm off"
        // do nothing
        else if (!this.isRunning && startId == 0) {
            Log.e("there is no music, ", "and you want end");

            this.isRunning = false;
            this.startId = 0;

        }

        // if there is music playing and the user pressed "alarm on"
        // do nothing
        else if (this.isRunning && startId == 1) {
            Log.e("there is music, ", "and you want start");

            this.isRunning = true;
            this.startId = 1;

        }

        // can't think of anything else, just to catch the odd event
        else {
            Log.e("else ", "somehow you reached this");

        }

        return START_NOT_STICKY;
    }

    @Override
    public void onDestroy() {
        // Tell the user we stopped.
        Log.e("on Destroy called", "ta da");

        super.onDestroy();
        this.isRunning = false;
    }

Main Activity
public class MainActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener {

AlarmManager alarm_manager;
TimePicker alarm_timepicker;
TextView update_text;
Context context;
PendingIntent pending_intent;
int choose_whale_sound;
long startTime = 0;
long start = 0;
float numberOfHours = 0;

 @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        this.context = this;

}alarm_manager = (AlarmManager) getSystemService(ALARM_SERVICE);

        //initialize our timepicker
        alarm_timepicker = (TimePicker) findViewById(R.id.timePicker);

        //initialize our text update box
        update_text = (TextView) findViewById(R.id.update_text);

        // create an instance of a calendar
        final Calendar calendar = Calendar.getInstance();

        // create an intent to the Alarm Receiver class
        final Intent my_intent = new Intent(this.context, Alarm_Receiver.class);

        // create the spinner in the main UI
        Spinner spinner = (Spinner) findViewById(R.id.richard_spinner);
        // Create an ArrayAdapter using the string array and a default spinner layout
        ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
                R.array.whale_array, android.R.layout.simple_spinner_item);
        // Specify the layout to use when the list of choices appears
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        // Apply the adapter to the spinner
        spinner.setAdapter(adapter);
        // Set an onclick listener to the onItemSelected method
        spinner.setOnItemSelectedListener(this);

        // initialize start button
        Button alarm_on = (Button) findViewById(R.id.alarm_on);

        // create an onClick listener to start the alarm
        alarm_on.setOnClickListener(new View.OnClickListener() {
            //@TargetApi(Build.VERSION_CODES.M)
            @Override
            public void onClick(View v) {

                // setting calendar instance with the hour and minute that we picked
                // on the time picker
                calendar.set(Calendar.HOUR_OF_DAY, alarm_timepicker.getHour());
                calendar.set(Calendar.MINUTE, alarm_timepicker.getMinute());

                // get the int values of the hour and minute
                int hour = alarm_timepicker.getHour();
                int minute = alarm_timepicker.getMinute();

                // convert the int values to strings
                String hour_string = String.valueOf(hour);
                String minute_string = String.valueOf(minute);

                // convert 24-hour time to 12-hour time
                if (hour > 12) {
                    hour_string = String.valueOf(hour - 12);
                }

                if (minute < 10) {
                    //10:7 --> 10:07
                    minute_string = "0" + String.valueOf(minute);
                }

                // method that changes the update text Textbox
                set_alarm_text("Alarm set to: " + hour_string + ":" + minute_string);

                // put in extra string into my_intent
                // tells the clock that you pressed the "alarm on" button
                my_intent.putExtra("extra", "alarm on");

                // put in an extra int into my_intent
                // tells the clock that you want a certain value from the drop-down menu/spinner
                my_intent.putExtra("whale_choice", choose_whale_sound);
                Log.e("The whale id is" , String.valueOf(choose_whale_sound));

                // create a pending intent that delays the intent
                // until the specified calendar time
                pending_intent = PendingIntent.getBroadcast(MainActivity.this, 0,
                        my_intent, PendingIntent.FLAG_UPDATE_CURRENT);

                // set the alarm manager
                alarm_manager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),
                        pending_intent);

                start = System.currentTimeMillis();

            }

        });

        // initialize the stop button
        Button alarm_off = (Button) findViewById(R.id.alarm_off);
        // create an onClick listener to stop the alarm or undo an alarm set

        alarm_off.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                // method that changes the update text Textbox
                set_alarm_text("Alarm off!");

                // cancel the alarm
                alarm_manager.cancel(pending_intent);

                // put extra string into my_intent
                // tells the clock that you pressed the "alarm off" button
                my_intent.putExtra("extra", "alarm off");
                // also put an extra int into the alarm off section
                // to prevent crashes in a Null Pointer Exception
                my_intent.putExtra("whale_choice", choose_whale_sound);

                //Get duration of the alarm.
                long end = System.currentTimeMillis();
                long delta = end - start;
                int elapsedSeconds = (int)delta / 1000;
                int mins = elapsedSeconds/60;
                float hours = mins/60;

                documentReference.update("sleep", FieldValue.arrayUnion(hours));

                // stop the ringtone
                sendBroadcast(my_intent);

            }
        });

    }

    private void set_alarm_text(String output) {
        update_text.setText(output);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
        // An item was selected. You can retrieve the selected item using
        // parent.getItemAtPosition(pos)

        // outputting whatever id the user has selected
        //Toast.makeText(parent.getContext(), "the spinner item is "
        //        + id, Toast.LENGTH_SHORT).show();
        choose_whale_sound = (int) id;

    }

    @Override
    public void onNothingSelected(AdapterView<?> parent) {
        // Another interface callback

    }


text:
Q: Converting text file to constant char pointer I wanted to write a simple function that will take a file name as an argument and then return a constant char pointer that contains the characters in the text file.
#include <fstream>
#include <vector>
#include <iostream>
#include "text.h"

//function to get the size of a file
unsigned int Get_Size(const char * FileName){
    std::ifstream filesize(FileName, std::ios::in|std::ios::ate);

    unsigned int SIZE = filesize.tellg();

    filesize.close();

    return SIZE;
}

//Takes a file name then turns it into a c-style character array
const char * Get_Text(const char * FileName){

    //get size of the file
    unsigned int SIZE = Get_Size(FileName);

    std::ifstream file(FileName, std::ios::in);

    //I used a vector here so I could initialize it with a variable
    std::vector<char> text(SIZE);

    //here is where I loop through the file and get each character
    //and then put it into the corresponding spot in the vector
    std::streampos pos;
    for(int i = 0; i<SIZE; i++){
            pos=i;
        file.seekg(pos);
        text[i] = file.get();
    }

    //I manually added the terminating Null character
    text.push_back('\0');

    //I set the pointer equal to the address of the first element in the vector
    const char * finalText = &text[0];

    file.close();

    //this works
    std::cout<<finalText<<std::endl;

    return finalText;
};

int main(){

    //this does not work
    std::cout<<Get_Text("Text.txt")<<std::endl;

    return 0;
}

When I print the the text with the *char pointer inside of my function it works. But when the pointer is passed outside of the function and I try to use it, the output is a white box for each character in the console. I have tried a bunch of different things and nothing gets it to work. I don't understand why it works inside of the function but it doesn't work outside.

A: You could do something fancy and use mmap() (Linux assumed) to map the file into virtual memory. That would postpone the point at which the file was actually read from disk and would save memory. It would also work on arbitrary length files.

A: You're returning a pointer to the vector's underlying element array. However, since the vector is a local variable it goes out of scope when the function Get_Text returns. Automatic variables get destroyed when they go out of scope, whatever is associated with them also get thereby destroyed. Returning the vector itself or even better a string is a better option.
If you absolutely have to do this by returning a char*, then use std::unique_ptr<char[]> text(new char[SIZE]). When returning return text.get() AND in main you have the responsibility of calling delete [] ptr.


text:
Q: How to prevent multiple consecutive 'Enter' key press on a button I have a button, When I press 'Enter' Key through Keyboard, the button command executes. When I consecutively press the 'Enter' key, the command also executes multiple times which I don't want.
I want to restrict the behaviour to single execution of command even during multiple 'Enter' key press. Can somebody help ?
View.xaml
<Button x:Name="btnSearch" IsDefault="True"  Content="Search"  Command="{Binding SearchButtonCommand}">
      <Button.InputBindings>
          <KeyBinding Command="{Binding Path=SearchButtonCommand}" Key="Return" />
      </Button.InputBindings>
</Button>

ViewModel.cs
public ICommand SearchButtonCommand
{
 get { return new DelegateCommand(SearchButtonExecutionLogic); }
}

A: The easiest way to reach your goal is to introduce and check some flag isSearchRunning in your command implementation in ViewModel:
private bool isSearchRunning = false;
private void SearchButtonCommandImpl()
{
    if (isSearchRunning)
    {
        return;
    }
    try
    {
        isSearchRunning = true;
        //Do stuff
    }
    finally
    {
        isSearchRunning = false;
    }
}


text:
Q: Access 2007: What does "@" represent for a textbox format? On a form in Access 2007, there is a Text Box that has:
@

in the "Format" field under the Format tab.
What does this represent and what does it do? I did not see it mentioned on http://msdn.microsoft.com/en-us/library/ff823190.aspx
If it does not represent anything, what would it be doing to a textbox?

A: A required text character.
http://msdn.microsoft.com/en-us/library/aa159684(v=office.10).aspx


text:
Q: How can I pass useState value from one component to another component I have 2 components editor.js and toolbar.js, I want to pass activeTool value from Toolbar.js  to editor.js. I am expecting it to be updated after each click.
Editor.js
import Toolbar from './Toolbar.js'

export default function Editor() {

 const [canvas, setCanvas] = useState()

// I want current activeTool from Toolbar.js to use here -------------------

  useEffect(() => {
    if (!canvas) return

    if (activeTool !== 'select') canvas.discardActiveObject().requestRenderAll()

    handleDrawingModes(canvas, activeTool)
  }, [canvas, activeTool])

//-------------------------------------------------------------------------

return (
    <>
    <Toolbar />
    <Canvas canvas={canvas}/>
    </>
  )
}

Toolbar.js
const tools = [
  { name: 'Select',    func: 'select',     icon: BsCursor         },
  { name: 'Pencil',    func: 'draw',       icon: BsPencil         },
  { name: 'Eraser',    func: 'erase',      icon: BiEraser         },
]

export default function Toolbar() {

  const [activeTool, setActiveTool] = useState('select')

return (

 <Menu defaultSelectedKeys={['Select']}  >
  {tools.map((item) => (
    <Menu.Item key={item.name} onClick={ () => setActiveTool(`${item.func}`) }>
         <item.icon />
    </Menu.Item>
  ))}
  </Menu>
   )
}

Any help would be appreciated.

A: There are various methods to achieve it, from which you can pick the approach best fits your project.
Lift the state
// Refactor the Toolbar,
//  so it will only take care about display,
//  while state management will be the job of Editor.

export default function Toolbar(props) {

return (

 <Menu defaultSelectedKeys={['Select']}  >
  {tools.map((item) => (
    <Menu.Item key={item.name} onClick={ () => props.onSelectedItemChange(item.func) }>
         <item.icon />
    </Menu.Item>
  ))}
  </Menu>
   )
}

State store
You can use react context or state management libraries to build a global or local state store to handle this.

A: Above answer is the best. But you can in addition to that also use "useRef"
<Toolbar ref={myRef} />

Then access the state via myRef.current.state.
But the answer from @Yan is the way to go :)


text:
Q: Function returning info to console log, but doesn't actually do what it's supposed to I have a question regarding a image slider script I'm using called Slippry. I currently have it integrated into a site I'm working on and I've run into an issue. I'm using the following code to stop the slider when one of the images within the slider is clicked:
Javascript Code:
// Stop the slider and log click
$('.stop').click(function () {
    slider.stopAuto();
    console.log('stopped');
});

HTML Code:

If I let the slider play through to the slide and click the slide, it will add stopped to the JS console, but it won't stop the slider. If I click the pagination, then click the slide, it adds stopped to the JS console and stops the slider.
Why is the function attached to .stop only working when I click the pagination first? Any thoughts?

A: Thanks to @J.Cheong I found a solution to this problem.
There is a timing issue with the slider.stopAuto function, and the function that transitions the slides. It appears both functions were being called at the same time or close enough that they were conflicting with one another. I added the following:
setTimeout(function(){
    slider.stopAuto();
    console.log('50ms - Paused');
}, 50);

I repeated calling the script every 50ms for an entire second, thus resulting in 21 calls for slider.stopAuto. This seems to have fixed the issue I was having. Hopefully this offers a solution for others using the Slippry script that might encounter this issue in the future.
NOTE: I just receive a email from one of the developers, and this 'bug' has been reported.


text:
Q: Query by example images after training in a SVM on Scikit learn python module When I execute a SVM with a training set and a validation set i check results with a confusion matrix, and all is good.
After that, how can i implement a system "query by example": i give a picture and return most similar image in an image set ( based on a threshold)?
There are example in python (with scikit-learn module)?

A: Retrieving similar images does not need a classifier. It is usually a Nearest Neighbor Problem, most likely have features with high-dimensions. The keys are to find:

*

*What character of image you care most? shape? colors? color distribution? object?

*What are the best features to describe the character of image? If it's color, then you might want R/G/B values or histograms.

*How do you want to measure the similarity? i.e., the distance function.

*Which algorithm you want to use in such a NearestNeighbor problem setup? Options include and not limited to: kd-tree, locality-sensitive-hashing, etc. Here has some good discussions.


text:
Q: How can I recover partitioned data of windows 7 after formatting with Ubuntu 16 and how can I get past grub rescue mode? I need help regarding recovery of partion files and data.
I have installed Ubuntu 16 from a pendrive but it deleted all the files and folders as well as partitions data. To recover that partition data, I installed TestDisk and analyzed. I selected the partition to be written and it said to restart the system.
After I restarted there is an error like No such partition. Entering Grub mode and I couldn't open anything.
How can I fix this?
please need help Urgently..


text:
Q: Okhttp asking to approve connection via dialog box want to make silent I am using latest okhttp and when using at home it connects just fine. Inside a company it displays dialog box for approval to connect to a server. I do not want the user to see that dialog box just connect silently like it does for me at home. How do I get it to do that? I used httpclient from Apache and it does not do that. I wrote my own code to determine proxy and added that to Apache client code and it does not ask for connection approval.
Thanks for the help,
-Tony

A: Disable the software firewall that is showing the dialog. The dialog isn't OkHttp; it's just a side effect from OkHttp using your network.

A: Seems the issue might have nothing to do with firewalls as I expected. I read there were issues with earlier versions of Java and even 8u25. I am using 32-bit 8u45 a security patch release. I installed 32-bit 8u60 EA and it seemed to have fixed the problem. So I am sure 32-bit 8u45 has the issue. Hopefully when 8u60 is released (soon I hope) it will still have the fix. I will check another laptop I have that works to see what version of java it is running.
Regards,
-Tony


text:
Q: Localization_settings.bundle Just wanted to ask, how to localize Xibs via settings.bundle? Actually, I need to make my Xib arabic through settings.bundle. I have searched a lot for this. Please give me proper suggestions otherwise i need to recode my application and remove all contents of Xibs and do it via coding which would take a lot of time.
Thanx in advance.

A: This helped me for localizing apps in general. See post for localizing the settings bundle.
See too, this - good advice.
Hope it helps, and glad to see you're localizing apps, not enough apps are!


text:
Q: Linear combinations of two numbers can only be multiples of their gcd? If we are on a number line starting at 0 and we can only take steps x or y long in either direction where x and y are integers, we can only reach points that are (integer) multiples of gcd(x, y).
Apparently this is true, but I am having a hard time visualizing why we cannot reach multiples of smaller shared factors of x and y that are not multiples of the gcd.
Also, can anyone offer an intuitive explanation for why all shared factors of x and y must also be factors of their gcd? Thanks!

A: Since $d:=\gcd(x,y)$ divides both $x$ and $y$, then there are integers $m,n$ such that $md=x$ and $nd=y$. Thus every step of distance $x$ is $m$ steps of the gcd and similarly every step of distance $y$ is $n$ steps of the gcd. Hence, for every integers $s,t$, we have that
$$ sx + ty = s(md) + t(nd) = (sm+tn)d. $$
This shows that the total distance covered is a multiple of their gcd.

A: I think you can understand that a linear combinaton of multiples of units is itself a multiple of the unit whatever the unit is. A divisor of a number is like a unit and the number is itself a multiple of the unit. If numbers have a common divisor, then they have a common unit and so any linear combination is also a multiple of that unit. The GCD is a common divisor and thus the previous reasoning applies to it.
Note that the GCD of numbers is a linear combination of those numbers using the extended Euclid algorithm. Thus a a shared factor of the numbers is also a factor of the GCD.


text:
Q: Passing Data back to First Form from Second Form and a class using delegates in C# From FormA I call FormB using frmB.Show();
In FormB, I have two textboxes. Assume User enters some data in those two textboxes.
I need to add this to a ListBox on FormA.
To achieve this I have created a delegate instance and called it in FormA after creation of frmB object - which works fine.
In FormB, Class1 object is created and one of its method is called which also needs to access/update the ListBox in FormA.
I can't create an instance for Class1 in FormA as Class1 instance is created in FormB. I tried to assign Class1 delegate instance to FormB instance but it is not working.
How can I achieve this ?

A: I would expose an event in FormB that you invoke when you need to update FormA. Before FormA calls formBInstance.Show() you can hook up a delegate to the event handler to handle what you need to do in FormA: formBInstance.UpdateEvent += myDelegateEventHandler.
So, when FormB needs to update FormA, you simply fire off that event, and the delegate will run as expected under FormA.
Edit to show some more code!
FormB.cs:
    // You can add more parameters to this to pass any data you need
    // in addition to the object sender you pass back
    public delegate void UpdateEventHandler(object sender, EventArgs e)

    public class FormB : Form
    {

        public event UpdateEventHandler Update;

        private void update()
        {
            // do your updates to formB here
            InvokeUpdateEvent(objectThatContainsUsefulData);
        }

        protected void InvokeUpdateEvent(object sender)
        {
            var handler = UpdateEvent;
            if (handler != null)
                handler(sender, null);
        }
    }

FormA.cs:
    public class FormA : Form
    {

        private void myUpdateDelegate(object sender, EventArgs e)
        {
            // Do your updates that formA will require here
        }

        public void methodCallingFormB()
        {
            // Do whatever you need to set up for creating form B
            var formB = new FormB();
            formB.UpdateEvent += myUpdateDelegate;
            formB.Show();
        }
    }

I hope that all makes sense to you. Check out the MSDN Events Tutorial for more help!


text:
Q: Trying to determine screen views by region I'm new to BigQuery and have limited experience with SQL, but have been making a few queries successfully.
One complicated one which I am a bit stuck on is breaking down the number of screen views by a user's region.
My SQL query looks like this
SELECT
  geo.region, COUNT(params.value.string_value) as count
FROM
  `xxx`,
  UNNEST(event_params) as params
WHERE
  geo.country = "Australia" AND geo.region > "" AND event_name = "screen_view" AND params.key = "firebase_screen"
GROUP BY
  geo.region
ORDER BY
  count DESC

I get some output which is quite a significant amount less than what the Firebase console reports for total screen views in Australia.
Row   region              count
1     Victoria            25613
2     South Australia     3557
...

Is there something wrong with my query?


text:
Q: node.js serverside 2d search performance I plan to store and update user locations (lat, lon, userid) via websocket on a nodejs server.
my goal is to broadcast the user locations to every user, as fast as possible.
(like the mytaxi position of each taxi in the app)
my concerns / problems

*

*server side performance on lots of simultanious users

*pushing the data back (i only need to know about users in my region)
-> 2d search (get users which lat / lon is in boundingbox )

questions:

*

*whats the best storage solution (mongodb vs js array / object storage)

*is read/write on db faster than array searching?

*is there a 2d optimized javascript search solution?

my way
i would go for two arrays (arr1 sorted by lat, arr2 sorted by lon)
-> search via divide and conquer -> check on similar ids -> output
is there a better way to do this?
thanks in advance
alex

A: you can use Redis's pub/sub channels, create a channel for each bounding box and subscribe users to the relevant channels according to their location report, then push messages to entire channels.
this strategy may be naive for big data..


text:
Q: Delphi: frozen form There are 2 forms.
Form2 isn't auto-created.
 Form2:=TForm2.Create(Application);
 Form2.Show;

If to do Sleep(10000); inside any forms then another one will be frozen. How to prevent this behavior?
My problem: a big text file (3 Mb) is continuously  assigned (Lines.Assign) into a text editor, so a form is frozen.
Can I use another unfrozen form (not modal) to show a progress bar (a style is pbstMarquee)?

A: All GUI code should be run from the main thread, and it looks like you are following that rule.
If you call Sleep then the calling thread will not execute code until the timeout elapses. If you call Sleep from the main thread, then the message queue will not be pumped until the timeout elapses.  Hence the entire app appears frozen.
Why does calling Sleep from one form affect another form? Because all GUI components are served from the single message queue of the main thread.  Once you stop pumping that queue, all GUI components stop receiving queued messages like WM_PAINT, WM_KEYDOWN etc.
As I understand it your problem is that your application appears hung when you are loading a 3MB text file into an edit control.  That size of file doesn't sound very large to me and one obvious solution would be to find an edit control that performs the load better.  For example I'm pretty sure that Notepad, Notepad++ etc. do not take steps like showing progress when loading such files. I rather suspect that those apps don't pump the queue when loading files but you just don't notice because of the short time taken.
What you don't want to happen is for you to pump your queue to keep your GUI responsive and in turn allow the user to start loading another file whilst the first one is still loading. You need to disable your UI whilst processing a load operation. A modal progress dialog is one way to do that.
If you can't switch to a better performing control, you could show a modal progress dialog and use a background thread like this. The background thread would have load the file in small chunks, say into a string list. After each chunk of the file was ready it would then call Synchronize and get the main thread to add the contents of the string list to the edit control, and then clear the string list. The thread would then continue and load the next chunk. Adding to the edit control in small chunks would allow you to keep the message queue serviced.
You could show progress in a status bar rather than a modal dialog which would be less intrusive.  But just remember to disable any UI that would cause re-entrant execution.

A: Better load your file in a separate thread. Or you will have to create your second form in a plain WinAPI, because VCL doesn't support multithreading.


text:
Q: ASP.Net UrlReferrer Error I have the following code:
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Request.UrlReferrer.Host != "www.test.com")
            {
                Response.Redirect("~/redirect.aspx");
            }
        }

My goal is, that page cannot be accessible if it is visited from a URL other than the one in the if statement however when I run my project I am getting the following error:
An exception of type 'System.NullReferenceException' occurred
Why there is a NUll exception? if it is null it should just execute my code that  Ihave inside Page_Load... Please advise if there is another way to do what I am attempting, or if there is a way I can handle the Null Exception Error. Thank you.

A: Request.UrlReferrer can be null when there is no referrer, for example when you open this page directly in browser (as first page), or do request manually from fiddler etc. So, you should check if Request.UrlReferrer != null first or handle case when Request.UrlReferrer is null.
In your case you may try:
protected void Page_Load(object sender, EventArgs e)
        {
            if (Request.UrlReferrer == null || Request.UrlReferrer.Host != "www.test.com")
            {
                Response.Redirect("~/redirect.aspx");
            }
        }

This code will check if your page was requested from www.test.com and was not accessed directly as first page without referrer.


text:
Q: What are the objects/entities that are NOT allowed in an inner join SOQL query? I've tried to do an inner join SOQL query using Events/Tasks:
SELECT Id FROM Attachment WHERE ParentId IN (SELECT Id FROM Event) LIMIT 1000
But I failed with the error:
"Entity 'Event' is not supported for semi join inner selects"
I was wondering which are the not supported entities; I tried to figure out at Salesforce documentation but I wasn't lucky at all.
Does anyone of you have this valuable information or knows where to find out?

A: At the bottom of Comparison Operators in the SOSL/SOQL reference, it gives you the information you're looking for

*

*The following objects aren't currently supported in subqueries:

*

*ActivityHistory

*Attachments

*Event

*Note

*OpenActivity

*Tags (AccountTag, ContactTag, and all other tag objects)

*Task

My best guess at why these aren't currently supported is because these SObjects have polymorphic relationships. I imagine that makes it difficult for the query engine to determine how to proceed (how do we know if this row is related to the same object we're being told to filter against? is it possible to do that without looking deeper into the Id? how do we optimize this? etc...)


text:
Q: Xamarin Form Sqlite Connection : Method not found: int SQLite.SQLiteConnection.CreateTable<!0>(SQLite.CreateFlags) The build is success but when it comes to this method, it throws exception. This happened when I updated new packages at NuGet Packages.
public static string checkToken()
        {
            string token1 = "";
            try
            {
                SQLiteConnection db = DependencyService.Get<SQLiteInterface>().GetConnection();
                db.CreateTable<Token>();
            Token t = db.Table<Token>().FirstOrDefault();
            if (t != null)
            {
                DateTime dt = t.timeCreated;
                DateTime tmp = DateTime.Now;

                double diff = (tmp - dt).TotalMinutes;
                if (diff > 60.0 || App.IsUserLoggedIn == false)
                {
                    token1 = "expired";
                    db.Delete(t);
                }
                else
                {
                    token1 = t.token;
                }
            }
        }
        catch (Exception e)
        {
            e.ToString();
        }
        return token1;
    }

Here is the image.

UPDATED:
This packages from .Droid

This package from Portable

A: It's annoying, but there's a very good chance you're going to have to delete all of those packages and reinstall them. Try to remove them and add the following packages
SQLitePCLRaw.bundle_green Version 1.1.2 in your native projects (Not in PCL)
SQLitePCLRaw.core Version 1.1.2 in your native projects (Not in PCL)
SQLitePCLRaw.lib.e_sqlite3.android Version 1.1.2
SQLitePCLRaw.provider.e_sqlite3.android Version 1.1.2
SQLitePCLRaw.provider.sqlite3.ios_unified Version 1.1.2
and then when you create the database, initialise it using the following code as the path:
string path = System.IO.Path.Combine(System.Environment
            .GetFolderPath(System.Environment.SpecialFolder.Personal), "localstore.db");

OR
If that doesn't work, remove all of them and only add the following one all of your projects
https://www.nuget.org/packages/sqlite-net-pcl/
I hope this helps

A: As Janwilx72 said that you need to install sqlite-net-pcl package by Nuget for Pcl and Platforms. Don't need the package that you provided.

Then you can use SQLiteConnection.CreateTable() and have no issue.
I do one sample for Android at github, that you can take a look:
https://github.com/CherryBu/sqliteapp
If you want to do this in ios or other platform, you can take a look this article:
https://dzone.com/articles/register-and-login-using-sqlite-in-xamarinforms
https://learn.microsoft.com/en-us/archive/msdn-magazine/2016/july/xamarin-working-with-local-databases-in-xamarin-forms-using-sqlite


text:
Q: Serializable ObjecOutputStream object I want to make server client aplication and use ObjecOutputStream to send Object to client, but in object which I want to send is ObjectOutputStream object and I need to serializable it somehow but I dont know how... any advice?
I need to send object Player:
public class Player implements Serializable{
    ObjectOutputStream out;
    public Player(ObjectOutputStream out){
        this.out = out;
    }
    public send(){
        this.out.writeObject(this);
    }
}

after launch similar code like this an exeption show this:
java.io.NotSerializableException: java.io.ObjectOutputStream

A: Since ObjectOutputStream doesn't implement Serializable, so your Player class cannot be serialized. To fix it:
class Player implements Serializable {
    private transient ObjectOutputStream out;

    // the rest
}

In my opinion, the Player should not know how to send itself. You can introduce a new class PlayerSender:
class PlayerSender {

    private ObjectOutputStream outputStream;

    public PlayerSender(OutputStream out) {
        this.outputStream = new ObjectOutputStream(out);
    }

    public void send(Player player) {
        this.outputStream.writeObject(player);
    }

}

//---- Usage ----

List<Player> players = // make a bunch of players;

PlayerSender playerSender = new PlayerSender(getNetworkStream());
//PlayerSender playerSender = new PlayerSender(new FileOutputStream("/players/list.txt");
//PlayerSender playerSender = new PlayerSender(socketConnection.getOutputStream());
for (Player player : players) {
    playerSender.send(player);
}

A: Here is a code that could help
public void toTXT(String fileName)
{
    try
    {
        // Serialize data object to a file
        ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(fileName));
        out.writeObject(player); // player is an instance of Player class
        out.close();

    }
    catch (Exception e)
    {

    }
}

This is the correct way to write your code:
public class Player implements Serializable{

    public Player(){

    }
    public ObjectOutputStream send(){
        ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("filename.txt"));
        this.out.writeObject(this);
        return out;
    }
}

And here is your main() function:
public static void main(String args[])
{

    Player player = new Player();
    player.send();

}


text:
Q: R check if values in row are equal I have data in the following format:

what I want to do is check in each row whether the value in pred is = to the one in obs
so in the example above 3 out of 5 are equal and the accuracy would be 60% ?
How can I do that?
Screenshot of code:

A: It looks like your data frame is called "prediction".
The == operation takes each element if the vectors are of equal lengths and compares them, returning a TRUE or FALSE. When performing arithmetic on TRUEs and FALSEs they're treated like 1s and 0s respectively. As such the mean of this == comparison will give you what you want.
mean(prediction[["pred"]]==prediction[["obs"]])


text:
Q: How to use a class I have an app that needs to extract some information about various entities (vendor, worker, etc.) for each row of an input source. I thought this was the definition of a class, but I'm struggling now.
class Vendor
{
    public int ID { get; set; }
    public string Name { get; set; }

    public Vendor(int vendorID)
    {
        using (CPASEntities ctx = new CPASEntities())
        {

            tblVendor v = (from vndr in ctx.tblVendors
                           where vndr.ID == vendorID
                           select vndr).FirstOrDefault();
            if (v == null)
            {
                ID = 0;
                Name = null;
            }
            else
            {
                ID = v.ID;
                Name = v.Vendor_Name;
            }
        }
    }

It's in the same namespace of the main program. Now I want to instantiate that class and feed it a vendor ID so it will make the two properties available to me (black box, sort of...)
So, I tried:
vendor v= vendor(VendorID);
Then, I tried:
vendor v = new vendor(VendorID);
I even made it a static class and tried both of the above. I'm thinking about this incorrectly, I'm sure.
Can someone point me in the right direction?

Code (early stages...):
using CPAS_EM;
using Excel = Microsoft.Office.Interop.Excel;
using SpreadsheetGear;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;

namespace ProcTimesheets
{
    public static class Vendor

{
    public int ID { get; set; }
    public string Name { get; set; }

    public Vendor(int vendorID)
    {
        using (CPASEntities ctx = new CPASEntities())
        {

            tblVendor v = (from vndr in ctx.tblVendors
                           where vndr.ID == vendorID
                           select vndr).FirstOrDefault();
            if (v == null)
            {
                ID = 0;
                Name = null;
            }
            else
            {
                ID = v.ID;
                Name = v.Vendor_Name;
            }
        }
    }
}
public static class Worker
{....}
static class LaborRate
{....}
class Program
{
    static void Main(string[] args)
    {
        XmlNodeList timesheets = TSList();
        foreach (XmlNode doc in timesheets)
        {
            string link = @"http://moss.mava.xxx.com/" + doc.Attributes["ows_FileRef"].InnerText.Split('#')[1];             // Leaves out the "//" at the beginning
            Timesheet tsheet = new Timesheet(link);
            tsheet.TimesheetID = Convert.ToInt32(doc.Attributes["ows_ID"].InnerText);
            tsheet.WeekStartDate = Convert.ToDateTime(doc.Attributes["ows_WeekStart"].InnerText);
            tsheet.CurrentStatus = doc.Attributes["ows_TimesheetStatus"].InnerText;
            tsheet.ApproverName = doc.Attributes["ows_Approver"].InnerText;
            tsheet.VendorFullName = doc.Attributes["ows_Vendor"].InnerText.Split('#')[1];               // strips some crap at the beginnining
            tsheet.Creator = doc.Attributes["ows_Author"].InnerText.Split('(')[1].Split(')')[0];         // Strips out only the NT user name
            tsheet.CreateDate = doc.Attributes["ows_Created"].InnerText;                                 // Leaves it in string format...never used as a date
            tsheet.Modifier = doc.Attributes["ows_Editor"].InnerText.Split('(')[1].Split(')')[0];       // Strips out only the NT user name
            tsheet.ModDate = doc.Attributes["ows_Modified"].InnerText.Split('(')[1].Split(')')[0];      // Leaves it in string format...never used as a date
            tsheet.OverrideStatus = doc.Attributes["ows_OverrideStatus"].InnerText;
        }
    }
    static XmlNodeList TSList()
    {
        //  This function returns an XML list of all Documents in the library with a status that needs to be audited.
        //  It uses the URL and Library Name found in the project property settings
       ....
    }
}
public class Timesheet
{
    private enum NotifyType
    {
        General,
        Approver,
        OverrideApprover,
        BadWO
    }

    private Excel.Worksheet xlSH;                               // Local variables
    private Excel.Range xlRange;                                //
    private Excel.Application xlApp;                            //
    private Excel.Workbooks xlWBS;                              //
    private Excel.Workbook xlWB;                                //

    public int RowCount { get; set; }                           // Row count in the "Used Range" (including the header row)
    public int ColCount { get; set; }                           // Column count in the "UsedRange"
    public int TimesheetID { get; set; }                        // Set from the SP Document Property
    public int VendorID                                         // "Read-only" property derived from the VendorFullName Document Property
    {
        get
        {
            return Convert.ToInt32(VendorFullName.Split('(')[1].Split(')')[0]); // Retrieves the parenthesized Vendor ID
        }
    }

    public DateTime WeekStartDate { get; set; }                 // Set from the SP Document Property
    public DateTime WeekEndDate                                 // "Read-only" property
    {
        get
        {
            return WeekStartDate.AddDays(6);                    //(always returns WeekStartDate+6)
        }
    }

    public string CurrentStatus { get; set; }                   // Set from the SP Property unchanged
    public string ApproverName { get; set; }                    // Set from the SP Property unchanged
    public string ApproverEmailAddress
    {
        get
        {
            return ApproverName + "@xxx.com";
        }
    }
    public string VendorFullName { get; set; }                  // Set from the SP Property unchanged
    public string link { get; set; }                            // Derived from the SP Property
    public string Creator { get; set; }                         // NT user name of the SP Document creator
    public string CreatorEmailAddress
    {
        get
        {
            return Creator + "@xxx.com";
        }

    }
    public string CreateDate { get; set; }                      // straight from ows_Created -- left as a string
    public string Modifier { get; set; }                        // NT user name of the SP Document ows_Modifier
    public string ModDate { get; set; }                         // straight from ows_Modified -- left as a string
    public string OverrideStatus { get; set; }
    public string VendorShortName
    {
        get
        {
            return VendorFullName.Split('(')[0].Trim();        // Strips off trailing (), and trims it up
        }
    }

    List<string> WorkbookErrors = new List<string>();

    public bool IsValid
    {
        get                                   // This property is set by "validating" the worksheet
        {
            vendor v = new Vendor(VendorID);
            bool returnvalue = true;
             // Don't forget spreadsheetgear is zero based.....
            for (int row = 0; row < RowCount; row++)
            {

            }
            return returnvalue;
        }
    }                                // "Read-only" property
    private void NotifyWorkbookError(List<string> MsgLst)
    {  ....  }
    private void Notify(NotifyType nType, List<string> MsgLst)
    {....}
    private string GetHTML(int MessageID)
    {....}
    public Timesheet(string wbPath)
    {
        link = wbPath;
        bool validDocument = OpenWorkbook();
        // Vendor curVndr = new Vendor(VendorID);
        //  Test the headings to make sure the workbook is valid
        if (validDocument)
        {

        }
        else
        {

        }

        xlWB.Close();
        xlWBS.Close();
        xlApp.Quit();

        System.Runtime.InteropServices.Marshal.ReleaseComObject(xlRange);
        System.Runtime.InteropServices.Marshal.ReleaseComObject(xlSH);
        System.Runtime.InteropServices.Marshal.ReleaseComObject(xlWB);
        System.Runtime.InteropServices.Marshal.ReleaseComObject(xlWBS);
        System.Runtime.InteropServices.Marshal.ReleaseComObject(xlApp);
        GC.Collect();
        GC.WaitForPendingFinalizers();

    }
    bool OpenWorkbook()
    {
        xlApp = new Excel.Application();
        xlApp.Visible = false;
        xlWBS = xlApp.Workbooks;
        xlWB = xlWBS.Open(link);

        if ((xlWB.ReadOnly == true) || (ValidHeadings(xlRange) == false))
        {
            WorkbookErrors.Add("This workbook is read-only. Someone has it open for writing. No processing can be completed");
            return false;                                           // Read-only Workbooks or WBs with bad heading row are not auditable
        }
        xlSH = xlWB.Worksheets[Properties.Settings.Default.Timesheet_WorkSheetName];
        xlRange = xlSH.UsedRange;
        RowCount = xlRange.Rows.Count;
        ColCount = xlRange.Columns.Count;
        return true;
    }
    bool ValidHeadings(Excel.Range range, int headingrow = 1)
    {....}
    static bool ValidRow(Excel.Range row, int vendorID)
    {
        bool returnvalue = false;

        return returnvalue;
    }
}

}

A: I suspect that either your class is not really in the same namespace, or it is in another project, and your main project doesn't have a reference to that project.
If the Vendor class is really in the same namespace as your main entry point for your program, all you have to do there is just:
Vendor v = new Vendor(VendorID);

A: C# is case-sensitive. If your class is Vendor (with a capital V) then you can create an object with
int id = ...; // your vendor Id goes here
Vendor v = new Vendor(id);


text:
Q: javascript validation I have two radio buttons. Each one has one associated text box. If I click one radio button and then submit an alert box should be shown if the associated text box is empty. How can I achieve this?
<form action="#" name="form1" id="form1" method="post" onsubmit="return check_workorder()">
     <input type="radio" name="click" id="click1" checked="checked" value="date"/>
            Start Date
              <input type="text" id="my_date_field" name="my_date_field" class="datepicker" style="width:80px;"/>

            <input type="radio" name="click" id="click2" value="order" />
            Work order no
            <input type="text" name="workno" id="workno" style="width:100px;"/>

            <input type="submit" name="submit" value="submit" onclick="return check_workorder()"/>

the javascript is
function check_workorder() {
    if (document.forms.form1.elements.click.value == "date") {
        var dat = (form1.my_date_field.value);
        if (dat == "") {
            alert("please select date");
            return false;
        }
    } else if (document.forms.form1.elements.click.value == "order") {
        var wor = (form1.workno.value);
        if (wor == "") {
            alert("please enter work order no");
            return false;
        }
    }
}

A: if (document.forms.form1.elements.click.value == "date") {
    if (document.forms.form1.elements.click.checked) {
    //the radio button is checked
    }
}