text:
Q: Does all c++ code(exactly the same) will compile and work the same on Windows system as well as Linux Based system? and Why?[in c++] [RBIx] Till now, i have been successfully compiling a same code in both windows and Linux Based system using code-blocks! And got no errors till now but i am just c++ beginner and my program are simple so i couldn't figure it !so i thought maybe I could get it cleared from you, guys!
Does all c++ code(exactly the same) will compile and work the same on Windows system as well as Linux Based system? and Why?
If your answer is:YES,they do

*

*Why are same c++ programs in different versions (Windows version and
Linux version)?

If your answer is:No,they dont

*

*Why? and What code work in windows and not in Linux and vice versa?

*Is there any c++ code to find whether it is running in windows based
system or Linux based system?

*Does all c++ code(exactly the same) will compile and work the same on
MAC system as well as Linux Based system?
Thanks for reading

A: There are many requirements for C++ code that must be met, if you want it to compile on two different OS:

*

*Does your code use OS-specific libraries? Such code won't compile on different platforms.

*Does your compiler provide appropriate extensions on OS A to support OS B libraries?

The best way would be to avoid both of these situations. Another question is:

*

*Does compiler on OS A use the same C++ standard version as compiler on OS B?

If you use features from C++14 with C++14-supporting compiler on OS A, but compiler on OS B does not support it, it simply won't compile.

Why are same c++ programs in different versions (Windows version and
  Linux version)?

Because C++ standard doesn't provide information about OS without some additional libraries or compiler extensions. There might be also some differences in string parsing that you use in your code, for example when opening files or writing to files.

Why? and What code work in windows and not in Linux and vice versa?

Why is that, see above. Only code that uses exacly the same C++ standard without any OS specific aspects will compile of different OS. You can hax this with conditionally compiled code,
see this.

Is there any c++ code to find whether it is running in windows based
  system or Linux based system?

Compilers should provide prefedined macros to check the target OS (see link above)

Does all c++ code(exactly the same) will compile and work the same on
  MAC system as well as Linux Based system?

No, definitely not all, reason given above.

A: There are already some answers, however there are more subtle differences than the system libraries. The first one that comes to my mind is line endings. Windows uses \r\n while linux uses just \n. If you use e.g. std::endl you will get the right line ending. However, once you want to read a file in linux that was written in windows, or vice versa, this might be an issue. Similarly windows uses \ as seperator for folders while linux uses /.
I am not claiming that this would be major obstacles when porting code from linux to windows or vice versa. The point is: the code might compile and maybe even run without errors but it might not work as expected when it was tested on linux but running on windows (or vice versa). The good thing is that C++ gives you all you need to write code that in principle should be able to run both on windows and linux.

A: Not necessarily. They are two different operating systems and hence both of them have system specific libraries which they work with. If your code is a simple code with libraries that are both present in linux and Windows, well and great, the code will run on both systems.
On the other hand, for instance, if your code contains libraries that play with the operating system itself, the system calls the libraries make are different. Windows uses the windows API which will not work when run on Linux systems.

A: Answer: it depends!
If your code contains references to system files (ex: windows dlls), then it will not compile on a different system (ex: linux system). If your code does not reference system files, then it will compile on any system.


text:
Q: Automatically updating a tkinter label that isn't directly accessible I want to create a simple GUI for a constant data that comes through Serial. I decided to use tkinter. The value reading is updated and should be shown in a label. I created separate classes for the container and the other pages. I defined the container as such:
class Gui(Tk):
def __init__(self, *args, **kwargs):
    Tk.__init__(self, *args, **kwargs)
    container = Frame(self)
    container.pack(side="top", fill = "both", expand = TRUE)
    container.grid_rowconfigure(0, weight = 1)

    self.frames={}

    for F in (StartPage, PageOne):
        frame = F(container, self)
        self.frames[F] = frame
        frame.grid(row = 0, column = 0, sticky = "nsew")
        frame.UpdateMe()

    self.show_frame(StartPage)

def show_frame(self, cont):
    frame = self.frames[cont]
    frame.tkraise()

And the page showing the label:
class PageOne(Frame):
def __init__(self, parent, controller):
    Frame.__init__(self,parent)
    global reading
    self.label1text = StringVar()
    self.label1 = Label(self, textvariable = label1text)
    self.label1.pack()
    button1 = Button (self, text = "Show Start Page", command = lambda: controller.show_frame(StartPage))
    button1.pack()
    self.label1text.set(reading)

def UpdateMe(self):
    global reading
    self.lable1text.set(reading)

Now, to initialize the GUI:
root = Gui()
root.mainloop()

However, since mainloop() is blocking, any argument coming after that wouldn't be executed; I could get around that with update and update_idletasks. However, I still don't know how I could call the function UpdateMe() inside PageOne()when I only created an instantiation of the Gui(). Is there a way for me to solve this or remediate my understanding of classes and object programming?

A: Since you cannot create StringVar without initializing Tk() (for your case, it is Gui()), so you need to create the reading variable inside Gui() and PageOne.label1 uses it as its textvariable.  Below is an example based on your code:
from tkinter import *
from random import randint

class Gui(Tk):
    def __init__(self, *args, **kwargs):
        Tk.__init__(self, *args, **kwargs)
        container = Frame(self)
        container.pack(side="top", fill="both", expand=True)
        container.grid_rowconfigure(0, weight=1)
        container.grid_columnconfigure(0, weight=1)

        self.reading = StringVar() # create the StringVar for PageOne

        self.frames = {}
        for F in (StartPage, PageOne):
            frame = F(container, self)
            frame.grid(row=0, column=0, sticky="nsew")
            self.frames[F] = frame
        self.show_frame(StartPage)

    def show_frame(self, cont):
        self.frames[cont].tkraise()

class StartPage(Frame):
    def __init__(self, parent, controller):
        Frame.__init__(self, parent)
        button1 = Button (self, text="Show Page 1", command=lambda: controller.show_frame(PageOne))
        button1.pack(fill="both", expand=True)

class PageOne(Frame):
    def __init__(self, parent, controller):
        Frame.__init__(self, parent)
        self.label1 = Label(self, textvariable=controller.reading) # refer to Gui.reading StringVar
        self.label1.pack(fill='x')
        button1 = Button (self, text="Show Start Page", command=lambda: controller.show_frame(StartPage))
        button1.pack(fill='x')

# use .after() to simulate the update of reading variable periodically
def update_reading():
    app.reading.set(randint(0, 10000))
    print('reading:', app.reading.get())
    app.after(1000, update_reading)

app = Gui()
update_reading() # start the simulation task of updating reading variable
app.mainloop()

Note that I have created a function update_reading() to simulate the update of reading variable periodically using after() function.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Lax entropy condition and uniqueness for shallow water equations Why is the Lax entropy condition $${\lambda _i}({{\mathbf{u}}_R}) \leqslant {\sigma _i} \leqslant {\lambda _i}({{\mathbf{u}}_L}),$$ where $i = 1,2$, a sufficient condition for uniqueness of the solution of the shallow water equations
$$\begin{split}
  {h_t} + {\left( {hu} \right)_x} = 0, \hfill \\
  {\left( {hu} \right)_t} + {\left( {h{u^2} + \tfrac{1}{2}g{h^2}} \right)_x} = 0 \hfill \\
\end{split} $$
?
Here $\sigma_i$ is the i-th shock speed and $\lambda_i$ is the i-th characteristic speed of the shallow water equations.
Furthermore, ${{\mathbf{u}}_L}$ and ${{\mathbf{u}}_R}$ are the states to the left and right of the shocks respectively, so ${\lambda _1}({{\mathbf{u}}_L}) = {u_L} - \sqrt {g{h_L}} ,\;\;\;{\lambda _2}({{\mathbf{u}}_L}) = {u_L} + \sqrt {g{h_L}} ,\;\;\;{\lambda _1}({{\mathbf{u}}_R}) = {u_R} - \sqrt {g{h_R}} ,\;\;\;{\lambda _2}({{\mathbf{u}}_R}) = {u_R} + \sqrt {g{h_R}} $ where $u_L, u_R$ are the fluid speeds to the left and right of the shocks, and $h_L, h_R$ are the heights of the fluid columns to the left and right of the shocks. Also, ${\sigma _i} = {u_L} \pm {h_R}\sqrt {\frac{g}{2}\left( {\frac{1}{{{h_R}}} + \frac{1}{{{h_L}}}} \right)}  = {u_R} \pm {h_L}\sqrt {\frac{g}{2}\left( {\frac{1}{{{h_R}}} + \frac{1}{{{h_L}}}} \right)}$ where $-$ corresponds to $i=1$ and $+$ corresponds to $i=2$ are the shock speeds.
I'm reading some lecture notes (not in English, so there's no point in uploading them here) where it just says that it's easy to show that the Lax entropy conditions are sufficient for uniqueness of solution of the shallow water equations (no proof), but I don't see why this is true.
Are there any books where I can read more about this?

A: From (1) p. 274

For the shallow water equations, the characteristic speed $\lambda_p(\tilde q(\xi))$ varies monotonically as we move along an integral curve. [...] If $\lambda_p(\tilde q(\xi))$ varies monotonically with $ξ$ along every integral curve, then we say that the $p$th field is genuinely nonlinear.

Existence and uniqueness results need specifications. Are we speaking of classical solutions or weak solutions? Are we speaking of the Cauchy problem (general IVP) or of the Riemann problem (particular IVP)? In the latter case, there is the following result ((2) p. 84):

Assume that for all $k \in 1, ... , p$, the $k$th characteristic field is either genuinely nonlinear or linearly degenerate. Then for all ${\bf u}_L \in \Omega$ there exists
  a neighborhood $\vartheta$ of ${\bf u}_L$ in $\Omega$ with the following property: If ${\bf u}_R$ belongs to $\vartheta$, the Riemann problem (6.1) has a weak solution that consists of at most $(p + 1)$ constant states separated by rarefaction waves, admissible shock waves, or contact discontinuities. Moreover, a weak solution of this kind is unique.

Here, "admissible" means satisfying the Lax entropy condition.
More results of this king can be found in (3).

(1) R.J. LeVeque, Finite Volume Methods for Hyperbolic Problems, Cambridge University Press, 2002 doi:10.1017/CBO9780511791253
(2) E. Godlewski, P.-A. Raviart, Numerical Approximation of Hyperbolic Systems of Conservation Laws, Springer, 1996 doi:10.1007/978-1-4612-0713-9
(3) C.M. Dafermos, Hyperbolic Conservation Laws in Continuum Physics, 4th ed., Springer, 2016 doi:10.1007/978-3-662-49451-6


text:
Q: Display a list of all PDF files on HDD in a Cocoa application I am trying to make a simple OS x PDF reader in Xcode 4.2. I would like to have a drawer that displays all the PDF files on the users computer with the ability to click on a select PDF and have my PDFView display it. I currently have everything set up, I have my main window and drawer with a Browser View as its content view. How can I populate the Browser View with a list of all PDF files on the HDD and have the list selectable to open that PDF file? This is where i am stuck and am tired of searching so I broke down and decided to ask for help. I am fairly new to Objective-C and am using Xcode 4.2 on Snow Leopard 10.6.8. Any help/suggestions will be greatly appreciated!

A: NSFileManager contains methods to enumerate the items in a directory tree, e.g. see enumeratorAtURL:includingPropertiesForKeys:options:errorHandler:. Using such an enumerator you check each found item against your criteria, in this case being a PDF, and process the ones which match.
If you'd like a lower-level way of doing this look at fts(3) in the manual pages.


text:
Q: Accessing events in "Events Found in Mail" calendar I'm trying to access events that are created automatically from emails with the new proactive assistant feature found in iOS 9. The events are displayed in the "Events Found in Mail" Calendar.
To access these I am doing the following
self.eventStore.requestAccessToEntityType(.Event, completion: { (granted, error) -> Void in

    let predicate = eventStore.predicateForEventsWithStartDate(NSDate(timeIntervalSince1970: timestamp1), endDate: NSDate(timeIntervalSince1970: timestamp2), calendars: nil)
    let events = eventStore.eventsMatchingPredicate(predicate)

}

However the events in this calendar are not listed. Is this a limitation from Apple or can I access them in any other way?

A: I was able to ask this question to an apple engineer and their answer is that they do not expose this calendar for privacy reasons. They want an user to add an event parsed from mail to one of their normal calendars to confirm they want to expose it to other apps and that is why this calendar is not visible when doing usual
 let calendars = store.calendarsForEntityType(EKEntityTypeEvent)

A: I am unsure if this is a limitation by Apple but in general if you know the name of a calendar you can access it like this :)
func yourFunc(store: EKEventStore) {

    let calendars = store.calendarsForEntityType(EKEntityTypeEvent)
        as! [EKCalendar]

    for calendar in calendars {

        if calendar.title == "Events Found in Mail" {
       //Do something!}}}

Try something along these lines!


text:
Q: How can i use async move closure in a unasync call back? this's a click call back function for a fltk button,I want to execute a database query on the click of a button.
    //button click even
    ui.but.set_callback(async move |_| {
        let txt = "Some long text!Some long text!Some long text!Some long text!Some long text!\n";
        log.buffer().unwrap().append(txt);
        my_db::sqlserver_mod2::sql2().await.unwrap();
    });

I got an error:
[E0308] mismatched types.
[Note] expected `()`, found opaque type

How can i use  async move closure in a unasync call back?

A: The signature of set_callback() is:
fn set_callback<F: FnMut(&mut Self) + 'static>(&mut self, cb: F)

In other words, the callback must not return anything. But your callback
async move |_| {
  //skipped
});

has a return type of:
impl Future<Output=()>

which is an anonymous future that returns nothing. So you cannot use an async closure as your callback.
Instead, you should pass a closure of the expected type and do your processing inside it:
ui.but.set_callback(move |_| {
        let txt = "Some long text!Some long text!Some long text!Some long text!Some long text!\n";
        log.buffer().unwrap().append(txt);

         //acquire a runtime somehow, see the docs of your preferred runtime
        runtime.spawn(async {
            my_db::sqlserver_mod2::sql2().await.unwrap();
        });

    });

And last , but not least - you should avoid doing slow operations inside the UI, as it will appear unresponsive. Consider offloading the the work to another thread. For instance you can start tokio and pre-spawn your handlers which should work in a producer-consumer model and just pass commands via channels from the UI (the producer).


text:
Q: npm -v Is Different from npm list npm -g This probably comes from lack of understanding on my part but I'm having some weird issues on build machines related to npm.  I ran npm install npm -g in an attempt to fix this problem.  However, when I run "npm -v", I still get the old version 1.3.2.  If I run "npm list npm -g", I get 1.4.4.
What do I need to do to ensure 1.3.2 doesn't actually exist any more?

A: npm list -g will show you the npm modules you have installed, so if npm is listed in there, then you have downloaded npm with npm (yay).
npm -v will show you the version of the npm executable you are currently using.
If those two versions are different, then obviously, the npm in your PATH does not point to the npm you have installed with npm. On Unix, you can find out with which npm where the npm command is located; it's probably not at the same location as where your installed npm modules go (and as such where the newer npm is located).


text:
Q: Error: "You may need an additional loader to handle the result of these loaders." I'm developing a web page with Vue.js and webpack. When I write a style in a single file component Curry.vue, the build fails.
<template>
    <div>

    </div>
</template>
<script>
export default {

}
</script>
<style scoped>
.tomato {
    color: red;
}
</style>

The error message is:
ERROR in ./src/components/Curry.vue?vue&type=style&index=0&id=4d934a99&scoped=true&lang=css& (./node_modules/vuetify-loader/lib/loader.js??ref--7-0!./node_modules/vue-loader/lib??vue-loader-options!./src/components/Curry.vue?vue&type=style&index=0&id=4d934a99&scoped=true&lang=css&) 12:0
Module parse failed: Unexpected token (12:0)
File was processed with these loaders:
 * ./node_modules/vuetify-loader/lib/loader.js
 * ./node_modules/vue-loader/lib/index.js
You may need an additional loader to handle the result of these loaders.
|
|
> .tomato {
|     color: red;
| }
 @ ./src/components/Curry.vue?vue&type=style&index=0&id=4d934a99&scoped=true&lang=css& 1:0-209 1:225-228 1:230-436 1:230-436
 @ ./src/components/Curry.vue
 @ ./src/index.js

webpack.config.js is:
const path = require('path');

const HtmlWebpackPlugin = require('html-webpack-plugin')
const VueLoaderPlugin = require('vue-loader/lib/plugin')
const VuetifyLoaderPlugin = require('vuetify-loader/lib/plugin')

module.exports = {
  mode: 'development',
  entry: path.join(__dirname, 'src', 'index'),
  watch: true,
  output: {
    path: path.join(__dirname, 'dist'),
    publicPath: '/dist/',
    filename: "bundle.js",
    chunkFilename: '[name].js'
  },
  plugins:[
    new HtmlWebpackPlugin({
      template: './src/index.html'
    }),
    new VueLoaderPlugin(),
    new VuetifyLoaderPlugin()
  ],
  module: {
    rules: [
      {
        test:/\.vue$/,
        use:['vue-loader']
      },
      {
        test: /.jsx?$/,
        include: [
          path.resolve(__dirname, 'src')
        ],
        exclude: [
          path.resolve(__dirname, 'node_modules')
        ],
        loader: 'babel-loader',
        query: {
          presets: [
            ["@babel/env", {
              "targets": {
                "browsers": "last 2 chrome versions"
              }
            }]
          ]
        }
      },
      {
        test: /\.s(c|a)ss$/,
        use: [
          'vue-style-loader',
          'css-loader',
          {
            loader: 'sass-loader',
            // Requires sass-loader@^7.0.0
            options: {
              implementation: require('sass'),
              fiber: require('fibers'),
              indentedSyntax: true // optional
            },
            // Requires sass-loader@^8.0.0
            options: {
              implementation: require('sass'),
              sassOptions: {
                fiber: require('fibers'),
                indentedSyntax: true // optional
              },
            },
          },
        ],
      },
    ]
  },
  resolve: {
    extensions: ['.json', '.js', '.jsx', '.vue'],
    alias:{
      '@': path.resolve('src'),
    }
  },
  devtool: 'source-map',
  devServer: {
    contentBase: path.join(__dirname, '/dist/'),
    inline: true,
    host: 'localhost',
    port: 8080,
  }
};

A: You need to add a rule for css, your current scss rule doesn't apply for css.
Add additional rule for css:
// webpack.config.js

module.exports = {
...
  module: {
    rules: [
      ...
      {
        test: /\.css$/,
        use: [
          'vue-style-loader',
          'css-loader',
        ]
      }
      ...
   ]
...
};

Updated on 3/31/2022


text:
Q: intellij idea 13.1.4 update scala plugin to v0.41 cause permission denied After I update the scala plugin to v0.41 of intellij idea 13.1.4 on Ubuntu 14.04, I get following error when open a sbt project:
Error:Cannot run program "/home/abc/bin/java/jdk1.7.0_51" (in directory "/home/abc/workspace/myproject"): error=13, Permission denied error=13, Permission denied

If I reinstall scala plugin with a lower version, everything works fine. Is it a bug or more configuration need to be applied?

A: File -> Settings -> IDE Settings -> SBT
change the JVM from "Custom" to "Default".
http://youtrack.jetbrains.com/issue/SCL-7481


text:
Q: How to make sqllite database call and store return value to variable I need to covert C# code to JavaScript and I've got stuck with async database calls.
I'm pretty new to JavaScript and I don't know how to solve this problem. I know it must be done with callback function but I just don't know how to write it. I've tried some few examples I've found on this site but without success.
If someone can help me with this please help.
I have 2 tables in project. Lets say Table1 and Table2. Table1 is parent table and Table2 is child that contains items for Table1.
They are connected with id.
Table1 (Id, userid, Col1, Col2)
Table2 (Id, Col1, Col2, Col3)
Data is stored in SQL LITE database, I need to make a call to read that data and send it in JSON format.
I have next code.
var Table1row = {};
var Table1Array = [];
var Table2row = {};
var Table2Array = [];

function GetTable1()
{
     try
     {
    db.transaction(
             function(transaction)
             {
                 transaction.executeSql('SELECT * FROM Table1 WHERE userid  = ?',
         [userid],  DataHandlerTable1, txError);
             });
     }
     catch(e)
     {
         console.log(e.message);
     }
}

function DataHandlerTable1 (tx,results)
{
    var len = results.rows.length;
    if(len > 0)
    {
         for(var i=0; i<len; i++)
         {
             row = results.rows.item(i);

             Table1row ["id"] = row.id;
             Table1row ["userid"] = row.userid;
             Table1row ["Col1"] = row.Col1;
             Table1row ["Col2"] = row.Col2;
             Table1row ["Table2Array"] = GetTable2(row.id);

            Table1Array.push(Table1row);
         }

         var jsonObject = { prod: Table1Array }

            Type = "POST";
            Url = "http://192.168.136.27:54076/Service1.svc/SaveResult";
            ContentType = "application/json";
            DataType = "json";

            $.ajax({
                type: Type,
                url: Url,
                contentType: ContentType,
                data: JSON.stringify(jsonObject),
                dataType: DataType,
                success: function (json) {
                },
                error: function (jqXHR,exception) {
                },
            });
     }
}

Problem is in this line:
Table1row ["Table2Array"] = GetTable2(row.id);

This does not work and i don't know how to write this other way in JavaScript.
I need to store in Table1row ["Table2Array"] return value of GetTable2() function.
function GetTable2(id)
{
        db.transaction(function(transaction) {
             transaction.executeSql('SELECT * FROM Table2 WHERE id  = ?', [id],   function (tx, results) {
                 var len = results.rows.length;
                 if(len > 0)
                 {
                     for(var i=0; i<len; i++)
                     {
                         row = results.rows.item(i);
                         Table2row ["id"] = row.id;
                         Table2row ["Col1"] = row.Col1;
                         Table2row ["Col2"] = row.Col2;
                         Table2row ["Col3"] = row.Col3;

                         Table2Array.push(Table2row);
                         }

                     return Table2Array;
                     }
             });
     });
}

Any ideas about this ?
Thank you.

A: You are approaching the problem incorrectly, it sounds like you do not understand how to write good javascript code. I suggest you read up on it starting with the book "Javascript The Good Parts". If you are using async code, you will need to make all of your code async.
A rough idea is as follows.
function GetTable1(callback) {
  [...]
  transaction.executeSql('SELECT * FROM Table1 WHERE userid  = ?',
     [userid], function(tx, results) { DataHandlerTable1(tx, results, callback); }, txError);
  [...]
}
function DataHandlerTable1 (tx,results,callback) {
  [...]
  GetTable2(row.id, function(value) {
    Table1row ["Table2Array"] = value
  });
[...]
callback(jsonObject);
}
function GetTable2(id, callback) {
  [...]
  callback(Table2Array);
  return;
}

Again, it is a bad idea to assume you can port c# over to javascript without having a fundamental understanding of the javascript language.


text:
Q: k-th smallest number of standard normal distribution There are $n$ random variables obey the standard normal distribution $N(0 ,1)$.
What is the expectation of the k-th smallest number?
My attempt
I tried to use conditional probability to solve the problem, but the situation of $n=4$ is too complex to handle.
for n = 2
$$p_1(x) = \frac{e^{-\frac{x^2}{2}} }{\sqrt{2 \pi }}\text{erfc}\left(\frac{x}{\sqrt{2}}\right)$$
$$p_2(x) = \frac{e^{-\frac{x^2}{2}} }{\sqrt{2 \pi }}\left(\text{erf}\left(\frac{x}{\sqrt{2}}\right)+1\right)$$
$E_1 = -\dfrac{1}{\sqrt{\pi }}, E_2 = \dfrac{1}{\sqrt{\pi }}$
for n = 3
$$p_1(x) = \frac{3 e^{-\frac{x^2}{2}} }{4 \sqrt{2 \pi }}\text{erfc}\left(\frac{x}{\sqrt{2}}\right)^2$$
$$p_2(x) = -\frac{3 e^{-\frac{x^2}{2}} }{2 \sqrt{2 \pi }}\left(\text{erf}\left(\frac{x}{\sqrt{2}}\right)^2-1\right)$$
$$p_3(x) = \frac{3 e^{-\frac{x^2}{2}} }{4 \sqrt{2 \pi }}\left(\text{erf}\left(\frac{x}{\sqrt{2}}\right)+1\right)^2$$
$E_1 = -\dfrac{3}{2 \sqrt{\pi }}, E_2 = 0, E_3 = \dfrac{3}{2 \sqrt{\pi }}$
Is there any good way to deal with this problem?

A: The density of the $k$-th smallest number among $n$ i.i.d standard normal random variables is given by
$$
f_{X_{(k)}}(x) = \frac{n!}{(r-1)!(n-r)!} \phi(x) \left[\Phi(x)\right]^{k-1}
\left[1-\Phi(x)\right]^{n-k},$$
where $\phi(x)$ and $\Phi(x)$ are PDF and CDF of standard normal distribution respectively. Then the task is to compute$\int x f_{X_{(k)}}(x) \,dx$. Thr approximation of this integral is done here.


text:
Q: Nested routes error in Rails In my rails application I have this routes
resources :jobs do
  resources :job_applications, :path =>  'applications' do
    member do
      put :change_stage
    end
  end
end

And I have a method called change_stage in my job_application controller
Actually I'm trying to change one params of the job_application in an modal so for this I have this in the modal body
<%=form_for :job_application, :url => change_stage_job_job_application.(params[:application_status]), :html => {:method => :post, :class => 'form-horizontal' } do |f| %>

<%= label :status, 'reject' %>
<%= f.radio_button :application_status, 'reject' %>

<%= label :status, 'interview' %>
<%= f.radio_button :application_statuss, 'interview' %>

<%= label :status, 'hired' %>
<%= f.radio_button :application_status, 'hired' %>

<% end %>

but I'm getting this error

undefined local variable or method `change_stage_job_application' for #<#<Class:0xb463b49c>:0xb463ac04>

What is wrong in my form

A: 1) Remove the dot between url's name and params
2) Concatenate _path after url's name.
3) As it is a member method for nested routes, pass both parameters job and job_application.
<%=form_for :job_application, :url => change_stage_job_job_application_path(@job, @job_application), :html => {:method => :post, :class => 'form-    horizontal' } do |f| %>

A: You should use change_stage_job_job_application_path (without dot at the end).
FYI: Will be better to check Rails URL helper name use rake routes for any case.

A: I have to mention that the idea behind creating resources in your routes is to use RESTful routes and let Rails infer the URL rather than forcing a URL in your form statement. From the APIdock: http://apidock.com/rails/ActionView/Helpers/FormHelper/form_for

However, further simplification is possible if the record passed to form_for is a resource, i.e. it corresponds to a set of RESTful routes, e.g. defined using the resources method in config/routes.rb. In this case Rails will simply infer the appropriate URL from the record itself.

Why not try removing the URL statement entirely and trust your routes?
About the nil error mentioned, I think this parameter
params[:application_status]

is stripping the rest of your hash vars so they're missing when it gets to the controller.


text:
Q: Get media_type to fetch correct insights in a single request The metadata can be fetched using the following endpoint, {post-id}?metadata=1 and it can have type either shadowigcomment or shadowigmedia. If the type if the later, is there a way to know the media_type so the correct insights could be fetched in a single request to minimize the api calls?
To clarify more, the image post and vide post insights are engagement, impressions, reach, saved. In case of video, there is another metric which is video_views. If I send the video_views metric in the request and it turned out to be an image post, I would get an error. If I don't and I get a vide post, I would have to send another request to just fetch the video views. Any chance this issue could be done in a single request.
I have also tried to get the media_type along with the metadata as follow: {post_id}?metadata=1&fields=media_type but there is also an issue. If the happens to be a comment, an error is thrown stating "Tried accessing nonexisting field (media_type) on node type (ShadowIGComment)".
What I am asking for is a way to get the metadata of an object in one request and then fetch all fields and insights in just another single so as not to cause an overhead on the api call count.


text:
Q: Insert nested object via JSON using web api with NHibernate I'm writing an application that consist of a ReadAPI and a WriteAPI. The read API contains the domain classes, and uses EF CORE code first to generate the SQL DB, and to read from it.
The write API uses NHibernate to write to the database that is generated by EF Core. So far I have inserted 'simple' object via the write API, which has worked fine.
I'm encountering a problem now. I have a domain class, Driver, that has a nested object, Address, inside. At DB level a driver can have one address and an address can belong to multiple drivers. I'm trying to POST a JSON object, a driver object, via the write API. As to now, I've solved inserting the address by creating an address record in DB in advance, and giving the address ID in the JSON.
What I want to do now is giving the complete nested JSON object and have NHibernate generate the inserts for me. I have tried so many things but I feel like I am getting nowhere. Any advice would be much appreciated.
I'm using .Net Core with NHiberate 5.3.5, which has the mapping by code functionality already. If someone can solve it using Fluent NH instead, that is fine as well since I will convert it to NH 5.3.5 notation myself then.
My code:
Domain classes:
Driver:
namespace Models
{
    public class Chauffeur : IIdentifiable
    {
        public virtual long Id { get; set; }
        public virtual string Naam { get; set; }
        public virtual string Voornaam { get; set; }
        public virtual DateTime GeboorteDatum { get; set; }
        //todo validatie
        public virtual string RijksRegisterNummer { get; set; }
        public virtual RijbewijsTypes TypeRijbewijs { get; set; }
        public virtual bool Actief { get; set; }

        //rel adres
        public virtual long AdresId { get; set; }
        public virtual Adres Adres { get; set; }

        //rel tankkaart
        public virtual long TankkaartId { get; set; }
        public virtual Tankkaart Tankkaart { get; set; }

    }
}

Address:
namespace Models
{
    public class Adres : IIdentifiable
    {
        public virtual long Id { get; set; }
        public virtual string Straat { get; set; }
        public virtual int Nummer { get; set; }
        public virtual string Stad { get; set; }
        public virtual int Postcode { get; set; }
        public virtual ICollection<Chauffeur> Chauffeurs { get; set; }
    }
}

My DriverMap so far:
namespace WriteAPI
{
    public class ChauffeurMap : ClassMapping<Chauffeur>
    {
        public ChauffeurMap()
        {
            this.Table("Chauffeurs");

            this.Id(c => c.Id, c =>
            {
                c.Generator(Generators.Native);
                c.Type(NHibernateUtil.Int64);
                c.Column("Id");
                c.UnsavedValue(0);
            });

            this.Property(c => c.Naam);
            this.Property(c => c.Voornaam);
            this.Property(c => c.GeboorteDatum);
            this.Property(c => c.RijksRegisterNummer);
            this.Property(c => c.TypeRijbewijs);
            this.Property(c => c.Actief);

            this.Property(c => c.AdresId);

            this.Property(c => c.TankkaartId);
        }
    }
}

Using this mapping i could insert the nested object, by using an existing child address ID.
How I inserted this via a post:
{
                "Naam" : "Bart",
                "Voornaam" : "Jannsses",
                "AdresId" : 4,
                "GeboorteDatum" : "1979-04-25",
                "RijksRegisterNummer" : "999-888-7777",
                "TypeRijbewijs" : 1,
                "Actief" : true
}

How I would like to insert it in the future:
{
                "Naam" : "Bart",
                "Voornaam" : "Jannsses",
                "Adres" : {
                    "Straat": "Boomstraat",
                    "Nummer": 1,
                    "Stad": "Gent",
                    "Postcode": 9000
                          },
                "GeboorteDatum" : "1979-04-25",
                "RijksRegisterNummer" : "999-888-7777",
                "TypeRijbewijs" : 1,
                "Actief" : true
}

Note that the ID of an address is auto generated at DB level.
Any help would be much appreciated.
Kind regards

A: You would need to add ManyToOne mapping in your ChauffeurMap class
 this.ManyToOne(x => x.Adres , m =>
        {
            m.Column("AdresId");
            // AdresId can be insert and update
            m.Update(true);
            m.Insert(true);
            m.Cascade(Cascade.None);
            m.Fetch(FetchKind.Join);
            m.NotFound(NotFoundMode.Exception);
            m.Lazy(LazyRelation.Proxy);
            m.ForeignKey("AdresId");
        });

And you would also need additional mapping class for Adres as AdresMap. I hope you already have it. If not, please add it as below -
public class AdresMap : ClassMapping<Adres>
{
    public AdresMap()
    {
    this.Table("Adres"); //Your table name
    this.Id(c => c.Id, c =>
        {
            c.Generator(Generators.Native);
            c.Type(NHibernateUtil.Int64);
            c.Column("Id");
            c.UnsavedValue(0);
        });

    Set(x => x.Chauffeurs, c =>
        {
            c.Key(k =>
                {
                    k.Column("Id");
                    k.ForeignKey("AdresId");
                });
            c.Inverse(true);
            c.Cascade(Cascade.None);
        },
        r => r.OneToMany(o => { }));

    this.Property(x => x.Straat );
    // ... other properties
   }
}


text:
Q: No monochromatic arithmetic progression Given $n\in\mathbb{N}$, what is the minimum value of $m$ for which we can color $1,2,\dots,n$ in $m$ colors such that no three numbers of the same color form an arithmetic progression?
Let $f(n)$ denote the specified value. For small values of $n$, we have $f(1)=f(2)=1$, $f(n)=2$ for $3\leq n\leq 8$, and I believe $f(9)=3$. Might the answer be $\lfloor\log_3n\rfloor+1$?


text:
Q: Incorrect Date Format In R I try to change the format of "20FEB12:00:00:00" to Date and R gives me "NA"
Don´t know what I am doing wrong:
strptime("20FEB12:00:00:00", "%d%b%y:%H:%M:%S")

Thanks!

A: Sys.setlocale(category = "LC_TIME",locale = "C")


text:
Q: Kie uses substring to extract its module name. But calls it wrongly? So I am doing a project that involves a Java implementation of Drools client running up against a KIE service with Drools-WorkBench.
I've started building the final project, though I'm running into some troubles, as the URL of the KIE jar path, seems to have some issues.
So in the meat of the ServiceDiscoveryImpl the application tries to get its module name.
This it does with the following commands:
    private static String getModuleName(URL url) {
        String s = url.toString();
        int moduleStart = s.indexOf("META-INF/kie") + "META-INF/kie".length() + 1;
        return s.substring(moduleStart, s.length() - ("kie.conf".length() + 1));
    }

Now in my case the value of s is jar:file:/C:/SLP/Drools/target/war.jar!/META-INF/kie.conf.
resulting in the value of moduleStart to be 53
and thus we make a call to String.substring with the value (53, 48). Causing the exception
java.lang.StringIndexOutOfBoundsException: begin 53, end 48, length 57
Stacktrace:
java.lang.StringIndexOutOfBoundsException: begin 53, end 48, length 57
    java.base/java.lang.String.checkBoundsBeginEnd(String.java:3319)
    java.base/java.lang.String.substring(String.java:1874)
    org.kie.api.internal.utils.ServiceDiscoveryImpl.getModuleName(ServiceDiscoveryImpl.java:346)
    java.base/java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:195)
    java.base/java.util.ArrayList$ArrayListSpliterator.forEachRemaining(ArrayList.java:1655)
    java.base/java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:484)
    java.base/java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:474)
    java.base/java.util.stream.ReduceOps$ReduceOp.evaluateSequential(ReduceOps.java:913)
    java.base/java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234)
    java.base/java.util.stream.ReferencePipeline.collect(ReferencePipeline.java:578)
    org.kie.api.internal.utils.ServiceDiscoveryImpl.findKieConfUrls(ServiceDiscoveryImpl.java:290)
    org.kie.api.internal.utils.ServiceDiscoveryImpl.loadKieConfs(ServiceDiscoveryImpl.java:212)
    java.base/java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:195)
    java.base/java.util.Spliterators$ArraySpliterator.tryAdvance(Spliterators.java:958)
    java.base/java.util.stream.ReferencePipeline.forEachWithCancel(ReferencePipeline.java:127)
    java.base/java.util.stream.AbstractPipeline.copyIntoWithCancel(AbstractPipeline.java:502)
    java.base/java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:488)
    java.base/java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:474)
    java.base/java.util.stream.FindOps$FindOp.evaluateSequential(FindOps.java:150)
    java.base/java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234)
    java.base/java.util.stream.ReferencePipeline.findFirst(ReferencePipeline.java:543)
    org.kie.api.internal.utils.ServiceDiscoveryImpl.getKieConfs(ServiceDiscoveryImpl.java:204)
    org.kie.api.internal.utils.ServiceDiscoveryImpl.getServices(ServiceDiscoveryImpl.java:103)
    org.kie.api.internal.utils.ServiceRegistry$Impl.<init>(ServiceRegistry.java:62)
    org.drools.dynamic.DynamicServiceRegistrySupplier$LazyHolder.<clinit>(DynamicServiceRegistrySupplier.java:27)
    org.drools.dynamic.DynamicServiceRegistrySupplier.get(DynamicServiceRegistrySupplier.java:32)
    org.drools.dynamic.DynamicServiceRegistrySupplier.get(DynamicServiceRegistrySupplier.java:23)
    org.kie.api.internal.utils.ServiceRegistry$Impl.getServiceRegistry(ServiceRegistry.java:90)
    org.kie.api.internal.utils.ServiceRegistry$ServiceRegistryHolder.<clinit>(ServiceRegistry.java:49)
    org.kie.api.internal.utils.ServiceRegistry.getInstance(ServiceRegistry.java:41)
    org.kie.api.internal.utils.ServiceRegistry.getService(ServiceRegistry.java:37)
    org.kie.api.KieServices$Factory$LazyHolder.<clinit>(KieServices.java:358)
    org.kie.api.KieServices$Factory.get(KieServices.java:365)
    utils.KieServerAccessor.validate(KieServerAccessor.java:73) // I call it here
    module.RabbitMQConsumer.handleDrools(RabbitMQConsumer.java:112)
    module.RabbitMQConsumer.access$000(RabbitMQConsumer.java:18)
    module.RabbitMQConsumer$1.lambda$handleDelivery$0(RabbitMQConsumer.java:79)
    java.base/java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:515)
    java.base/java.util.concurrent.FutureTask.run$$$capture(FutureTask.java:264)
    java.base/java.util.concurrent.FutureTask.run(FutureTask.java)
    java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
    java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
    java.base/java.lang.Thread.run(Thread.java:829)

This seems like an oversight from the KIE team, and I would submit it as an issue, if not for the fact that this exception only occurs when running the .jar file, after building.
I have no ide as to how IDEA compiles / runs a java application, but whenever I use that feature, this exception does not occur. So I'm a bit confused whether this is actually a bug in the KIE java client, or just me who did something wrong with my building.
I hope some of you might be able to help explain why KIE does what they do, and how it is me building the jar wrongly that causes the exception.
My pom.xml file is atrocious, but here it is;
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">

  <modelVersion>4.0.0</modelVersion>

  <groupId>dk.slp</groupId>
  <artifactId>DroolsWrapper</artifactId>
  <version>1.0.0-SNAPSHOT</version>
  <packaging>jar</packaging>

  <name>Drools :: Wrapper</name>
  <description>
    The Wrapper Program which handel validations on received objects from RabbitMQ, and send the result to the output queue.
  </description>
  <dependencyManagement>
    <dependencies>
      <dependency>
        <groupId>org.junit</groupId>
        <artifactId>junit-bom</artifactId>
        <version>5.8.2</version>
        <type>pom</type>
        <scope>import</scope>
      </dependency>
    </dependencies>
  </dependencyManagement>
  <properties>
    <runtime.version>7.59.0.Final</runtime.version>
    <java.version>8</java.version>
    <maven.compiler.source>${java.version}</maven.compiler.source>
    <maven.compiler.target>${java.version}</maven.compiler.target>

  </properties>
  <build>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.8.0</version>
      </plugin>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-surefire-plugin</artifactId>
        <version>2.22.2</version>
        <configuration>
          <skipTests>true</skipTests>
        </configuration>
      </plugin>
    <plugin>
      <groupId>org.apache.maven.plugins</groupId>
      <artifactId>maven-assembly-plugin</artifactId>
      <executions>
        <execution>
          <phase>package</phase>
          <goals>
            <goal>single</goal>
          </goals>
          <configuration>
            <finalName>war</finalName>
            <archive>
              <manifest>
                <mainClass>
                  SLPDrools
                </mainClass>
              </manifest>
            </archive>
            <descriptorRefs>
              <descriptorRef>jar-with-dependencies</descriptorRef>
            </descriptorRefs>
            <appendAssemblyId>false</appendAssemblyId>
          </configuration>
        </execution>
      </executions>
    </plugin>
    </plugins>
  </build>
  <repositories>
    <repository>
      <id>jboss-public-repository-group</id>
      <name>JBoss Public Repository Group</name>
      <url>http://repository.jboss.org/nexus/content/groups/public/</url>
      <releases>
        <enabled>true</enabled>
        <updatePolicy>never</updatePolicy>
      </releases>
      <snapshots>
        <enabled>true</enabled>
        <updatePolicy>daily</updatePolicy>
      </snapshots>
    </repository>
  </repositories>

  <dependencies>
    <dependency>
      <groupId>org.drools</groupId>
      <artifactId>drools-core</artifactId>
      <version>${runtime.version}</version>
    </dependency>
    <dependency>
      <groupId>org.drools</groupId>
      <artifactId>drools-decisiontables</artifactId>
      <version>${runtime.version}</version>
    </dependency>
    <dependency>
      <groupId>org.jbpm</groupId>
      <artifactId>jbpm-test</artifactId>
      <version>${runtime.version}</version>
    </dependency>
    <dependency>
      <groupId>org.kie.server</groupId>
      <artifactId>kie-server-client</artifactId>
      <version>${runtime.version}</version>
      <scope>compile</scope>
    </dependency>
    <dependency>
      <groupId>ch.qos.logback</groupId>
      <artifactId>logback-classic</artifactId>
      <version>1.2.10</version>
    </dependency>
    <dependency>
      <groupId>com.rabbitmq</groupId>
      <artifactId>amqp-client</artifactId>
      <version>5.13.1</version>
    </dependency>
    <dependency>
      <groupId>org.mockito</groupId>
      <artifactId>mockito-all</artifactId>
      <version>1.10.19</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.droolsassert</groupId>
      <artifactId>droolsassert</artifactId>
      <version>3.0.8</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.junit.jupiter</groupId>
      <artifactId>junit-jupiter</artifactId>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>com.google.guava</groupId>
      <artifactId>failureaccess</artifactId>
      <version>1.0.1</version>
    </dependency>
  </dependencies>

</project>

EDIT:
So I narrowed down the problem a bit further, by trying to build with gradle instead using this process
jar {
    manifest {
        attributes "Main-Class": "$mainClassName"
    }

    from {
        configurations.runtimeClasspath.collect { it.isDirectory() ? it : zipTree(it) }
    }
}

and it displays this error message;
Caused by: org.gradle.api.GradleException: Could not expand ZIP 'C:\Users\asger.weirsoe\.m2\repository\org\kie\kie-ci\7.59.0.Final\kie-ci-7.59.0.Final.jar'.

Now I'm no expert, and getting a bit frustrated in the JAVA building mechanism. But I think this might be my issue, that some library that I need, which is fetched in the background is not baked into the .jar file. Resulting in my issues.
I googled this and found this in the documentation for KIE. But tbh it just made me more confused than gave me answers.

A: The problem was in regards to how KIE manages its dependencies.
The solution was to instead not build everything into the same jar, as some of the dependencies that KIE has packaged some dependencies with the same name but different functionalities, which were overwriting each other.


text:
Q: How to figure out if a query result contains exactly some items I want to figure out if a query result contains exactly some items. I explain:
I have a profile_stores table that contains the managed stores of each profile
Let's say i have 5 profiles P1-> P5 and 4 stores s1 -> s4
and my table contains
profie  |  store
------------------
    P1  |  S1
    P2  |  S2
    P3  |  S3
    P2  |  S2
    P1  |  S2
    P1  |  S3
    P4  |  S1
    P5  |  S2

Now, we have the following profile 1 P1 is managing the stores S1 and S2 and S3
=>
    P1(S1,S2,S3)
    P2(S1,S2)
    P3(S4)
    P4(S1)
    P5(S2)

What i need to know now is how can i set my query to get the profiles that are managing simultanously and only the stores S1 and S2 ?
Ps: In my case the query should return only P2
Any Help will be appreciated

A: SELECT DISTINCT profile FROM profile_stores
WHERE profile IN (SELECT profile FROM profile_stores WHERE store = 'S1')
  AND profile IN (SELECT profile FROM profile_stores WHERE store = 'S2')
  AND profile NOT IN (SELECT profile FROM profile_stores WHERE store NOT IN ('S1','S2'))

Alternatively, use the lesser-known set operators (which give a more easily readable SQL code in my opinion):
SELECT profile FROM profile_stores WHERE store = 'S1'
INTERSECT
SELECT profile FROM profile_stores WHERE store = 'S2'
EXCEPT
SELECT profile FROM profile_stores WHERE store NOT IN ('S1', 'S2')

In both cases, we start by filtering out only those profiles that are linked to stores 'S1' and 'S2' simultaneously. From this set, we then remove profiles that are also linked to other stores.
Both these set-oriented methods can be easily expanded to a variety of search conditions. For example to find profiles that are linked to any number of stores while not being linked to others (in general, or specific), etc.

A: GROUP BY-solution:
select profile
from tablename
group by profile
having count(distinct store) = 2
   and min(store) = 'S1'
   and max(store) = 'S2'

Alternative solution:
select profile
from tablename t1
where not exists (select 1 from tablename t2
                  where t1.profile = t2.profile
                    and t2.store not in ('S1', 'S2', ...))
group by profile
having count(distinct store) = 2 (or 3 or 4...)

A: another approach
select profile from table where store = 's1'
intersection
select profile from table where store = 's2'
except
select profile from table where store not in ('s1', 's2')


text:
Q: Show that $n!e^n/n^{n+1/2} \leq e^{1/(4n)}C$ Consider the sequence $r_n = n!e^n/n^{n+1/2}$ for positive integers $n$. It's straightforward to show that $r_n$ converges to some finite limit (applying the monotone convergence theorem to this decreasing sequence). Call the limit value $C$ and show that for all $n$:
$$r_n \leq e^{1/(4n)}C$$
I'm working on a proof by induction, but I'm having trouble with the induction step.
Note, this is used in a proof of Stirling's approximation.

A: As mentioned in the comments above, consider $\log C/r_n$ and note that $C = \sum^\infty_{i=1} \log r_{i+1}/r_i$. So we have:
$$\log C/r_n = \sum^\infty_{i=n} \log r_{i+1}/r_i$$
Now we will bound this sum term-wise: Use Jensen's inequality to show $\frac{2x}{2+x} < \log(1+x) < \frac{2x+x^2}{2+2x}$ for $x>0$
$$\frac{2x}{2+x} < \log(1+x) < \frac{2x+x^2}{2+2x}$$
And substituting $x = 1/n$ we get:
$$(n+1/2)\log(1+1/n) - 1 < \frac{1}{4n(n+1)}$$
We also have: $\log r_{n+1}/r_n=1-(n+1/2)\log(1+1/n)$
So now:
$$\log C/r_n = \sum^\infty_{i=n} \log r_{i+1}/r_i > -\sum^\infty_{i=n} \frac{1}{4i(i+1)}=-\frac{1}{4n}$$
Exponentiating each side and rearranging gives the desired result.


text:
Q: MultiValueDictKeyError - Passing GET parameter I'm using django allauth.
All my users should have access to an url that is generated dynamically. Ex: www.example.com/uuid/
From this page they should be able to login with Soundcloud and should be redirected to this page after connecting.
I am using the following to get the previous link but I am receiving a good url in html but is empty on django.
#Html
Download

#adapter.py
class AccountAdapter(DefaultAccountAdapter):

def get_login_redirect_url(self, request):
    #assert request.user.is_authenticated()
    #pass
    return request.GET['next']

A: You have a typo in your url - it should be:
href="/accounts/soundcloud/login?process=login&next={{request.path}}"

Notice the & instead of the second ?.


text:
Q: How do you use Countif with two matching criterias in Excel? The current formula is =COUNTIF(Sheet2!C[-1],Sheet1!RC[-1])
Fruit   Color   Sold
Apple   Red     Yes
Shoe    Red     Yes

Fruit   Color   Count
Apple   Green   0
Apple   Red     2

The count should be "1" for red apples. How does the formula get fixed so the column "Fruit" also matches?

A: With that notation you can use:
=COUNTIFS(Sheet2!C[-1],Sheet1!RC[-1],Sheet2!C[-2],Sheet1!RC[-2])


text:
Q: How to get value of input field from a form in a script I am trying to display a value from a form in a script using console.log() for troubleshooting purposes but it seems to not be working. Here is my script.
Is there something I am missing?
jQuery(document).ready(function() {
    var user = jQuery('#id').val;
    var file = jQuery('#custom-file-input').val;
    console.log(file);
});

echo "<form method='post' enctype='multipart/form-data' id='test_ajax'>";
echo "<select name='id' id='form-option' class='test-only'>";
echo '<option selected="selected">' .'Choose a User'. '</option>';

foreach ($registeredUsers as $key => $value) {
    $registered = JFactory::getUser($value);
    echo '<option value="'.$registered->id.'">'.$registered->name.'</option>';a
}
echo "</select>";

echo "<input name='uploadedfile' type='file' id='custom-file-input' class='test-only' /> <br/>";
echo '<input type="submit" name="submit" value="Upload" id="custom-submit-input">';
echo "</form>";

A: Use val() to get the value of an element.
var user = jQuery('#id').val

Should be
var user = jQuery('#form-option').val();

*

*Notice () of val

*The id of element is form-option, id is the name of the dropdown.


text:
Q: Kaspersky 2012 Firewall - prompt on new connection attempts How can I get Kaspersky 2012 Firewall to ask me everytime if I want to allow or deny an application to connect to the internet the first time it asks and have it remember that until the application changes.
Thank you.

A: Maybe Here is your solution.
Maybe it will help you to disable/enable all  important notifications: go settings, service, on notifications settings.
Kaspersky Forum has this article for the firewall check out there for more. Or you can be a member there to ask this question there if it doesn't help you.
Kaspersky Settings Is the place where can you get your appropriate help hope it will work for you. Best Of luck.


text:
Q: Create Eclipse java project with a java programm I would like to generate Eclipse Java Project with my Java program. When I click a button: it will generate an eclipse project with the parameters I specified (source path, library, ...)
My questions are:

*

*is there a way to do that ? and how ? (api).

*it is possible to generate Net-beans project too ?
Best regards,
Florent

A: Maven enables this and many more things around creating, bulding, testing and developing Java projects.
Create a Java project from command line. Then, using Maven create NetBeans, Eclipse or IntelliJ IDEA specific project files. Or even easier, just import already created Maven project directly from these IDEs.

A: Create Java Project in Eclipse first. Then look into directory created. You should find there two files: .project and .classpath. These are the files you should create in your app to get what you want.

A: Also for eclipse available M2Eclipse plugin to provide some Maven feature from Eclipse IDE.
http://m2eclipse.sonatype.org/

A: While Maven is the way to go in the long term, the best way to start a project in Eclipse is:

*

*Hit Ctrl+N and choose Java project

*Fill in the project name fields

*Copy your files from wherever they are to the newly created project (ensuring to preserve package hierarchy)

*Refresh project from File menu

*Create a Run / Debug profile to run your app.

It should be fairly simple to get up and running this way.
The reason people recommend Maven is because Eclipse is an IDE. It's great for development but its no good for resolving external dependencies or for command line / automated builds. Maven is an IDE neutral way of building and becomes essential the more dependencies a project pulls in.
Unfortunately Eclipse integration with Maven is pretty clumsy and can be summarized with these very broad steps:

*

*Install Eclipse Helios

*Install m2eclipse from the Help | Eclipse Marketplace

*Mess around with eclipse.ini to make Eclipse start from a JDK.

*Configure m2eclipse to use any existing Maven local repository

*Hit Ctrl+N and create a new Maven project and skip archetype selection

*Copy all the source files from the old project into the new ensuring to use Maven's conventions for file locations. (e.g. source goes in src/main/java)

*Create a Run / Debug maven target to clean / install the app

I say broad steps because there are a lot of gotchas. For example if the source is Java 5+ you might have to tweak the pom to set the compiler level. Best to get Eclipse working and then worry about Maven.
Netbeans has vastly better out of the box support for Maven although IMO Eclipse is still the better IDE for other reasons.


text:
Q: Awkward implementation of add function I am struggling to see why this:
addItem = item => {
    this.setState({ grudges: [grudge, ...this.state.grudges] });
}

rather awkward implementation exists. Wouldn't
this.state.grudges.push(grudge)

suffice?

A: This wouldn't be suffice because React state is expected to be immutable:

Never mutate this.state directly, as calling setState() afterwards may replace the mutation you made. Treat this.state as if it were immutable.

This 'awkward implementation' is also incorrect, this.state shouldn't be used together with this.setState because setState is asynchronous and may result in race conditions:

Think of setState() as a request rather than an immediate command to update the component. For better perceived performance, React may delay it, and then update several components in a single pass. React does not guarantee that the state changes are applied immediately.
<...>
setState() does not always immediately update the component. It may batch or defer the update until later. This makes reading this.state right after calling setState() a potential pitfall.

A correct way is to use updater function:
addItem = item => {
    this.setState(({ grudges }) => ({ grudges: [grudge, ...grudges] }));
}

It additionally benefits from destructuring syntax.

A: This is necessary because React doesn't track changes in the state like, for example, Vue. You have to explicitly tell react that the state changes. If you change state by modifying directly this.state, the state will be updated but the UI won't be updated since React won't know about the change.

A: In react, you should only change state using setState:

Never mutate this.state directly, as calling setState() afterwards may
  replace the mutation you made. Treat this.state as if it were
  immutable.

See https://reactjs.org/docs/react-component.html (bottom of page)


text:
Q: How can a Git tag be aligned with the formatted PDF using gitinfo2? I think I do not understand the workflow of the gitinfo2 package correctly.
The documentation says (shortend):

*

*Edit and format abc.tex until ready for release

*Commit the release version of abc.tex

*Tag the release

*checkout abc.pdf

*Format & commit the release version of abc.pdf

My question: How can the Git tag be aligned with the formatted PDF? The described workflow is showing two commits... When I am following it, the given tag in the commit history is "one behind". As consequence: when checking out the version where the tag is given, the PDF does not contain the tag.
I do not see different behaviour when using smartgit or commandline tool git.
Is this supposed to be? Can somebody help me?
Thank you,
Thomas
Edit: Added picture to specify my question.
As shown in the screenshot (graphical log view of Smartgit) the commit where the tag is given and the commit where the pdf was added - containing the right release info - are not identical. --> When checking out "Release 1.34" the PDF has not the right info. Only the following commit contains a correct set of data.

Edit 2:
As current workaround I am moving the tag after the PDF commit as described in this post.

A: The main assumption is that abc.pdf is being tracked by git.
Here is a list of command line steps, that keeps the release number up to date (this assumes that abc.pdf has been committed at some point previously)
(start with clean repo, make changes to abc.tex and compile)
git add abc.tex
git commit -m "my commit message goes here"
git tag -a 1.34
git checkout abc.pdf
pdflatex  abc
git add abc.pdf
git commit -m "updated release number in pdf"

Here is the file I have used for abc.tex
\documentclass{article}
\usepackage[mark,grumpy]{gitinfo2}

% gitinfo2 settings
\renewcommand{\gitMark}{Release: \gitRel}

\begin{document}
hello world
\end{document}

One reason your release tag might not be as you intend could be because it isn't being picked up by
RELTAG=$(git describe --tags --long --always --dirty='-*' --match '[0-9]*.*' 2>/dev/null)` in the `.git/hooks/post-.*

files. If your tag starts with anything other than a number, then you need to change the --match part accordingly. For example, if your tag starts with a V, as in V3.2.2, then you might use
RELTAG=$(git describe --tags --long --always --dirty='-*' --match 'V[0-9]*.*' 2>/dev/null)` in the `.git/hooks/post-.*

A: Thanks for the support cmhughes!
I will wrap it up:
My question is a question related to git. gitinfo2 is supposed to work like this - that's fine for me.
Starting from here:

we can

*

*move the tag, as described in this post by doing
git tag -fa 1.34

*or merge the commits (rebase) as described in this post.
git rebase -i HEAD~2
and than change in the upcoming dialog (looks something like this):
pick 2840179 Changing abc.tex
pick 00d844f Adding abc.pdf

# Rebase 8c99d54..00d844f onto 8c99d54
#
....

the second pick (pointing to the last commit) into a squash.
This ends up in a (maybe) more nice history. However, we have to retag afterwards as well with git tag -fa 1.34. Otherwise we loose the tag...:

Thomas


text:
Q: Android Studio Stuck on startup
Hi All,
Does any of you face this problem before? My Android studio stuck on startup. I've tried restart/shut down. Btw, my android studio version is 1.5 on mac

A: If you experience system crash or system auto restart, then please be patient. It take sometime to startup and everything will back to normal :) cheer!

A: You should go to the %appdata% and delete InteliJ folder, after that run program as administrator.
This is probably caused by:

*

*No space on partition

*No write permission in %appdata%

*Bug

If it does not work, try to reinstall.
... 1 more!

*

*Slow write speed or compute speed so it takes much more time as usual.


text:
Q: $L/K$ field extension, $\alpha\in\overline{K}$, does $\deg f_L^\alpha \mid \deg f_K^\alpha$? Let $L/K$ be a field extension.
Let $\alpha\in\overline{K}$.
We know that $f_L^\alpha \mid f_K^\alpha$, do we also have $\deg f_L^\alpha \mid \deg f_K^\alpha$?
Usually $f\mid g$ does not imply $\deg f\mid \deg g$, take for example $X^2 + 1 \mid (X^2+1)(X-1)$, than $2\nmid 3$.
The difference is that the minimal polynomials are irreducible.
We have the tower of fields as shown in the following diagram:

Notice that
$$
  \deg f_L^\alpha \mid \deg f_K^\alpha \iff [L(\alpha):L] \mid [K(\alpha):K].
$$
With the tower law this is equivalent to
$$
  \frac{[L(\alpha):K]}{[L:K]} \mid \frac{[L(\alpha):K]}{[L(\alpha):K(\alpha)]} \iff [L(\alpha):K(\alpha)] \mid [L:K].
$$
Is it true that $\deg f_L^\alpha \mid \deg f_K^\alpha$? Otherwise, do you have a counter example?

A: In general, no. Take $K=\mathbb{Q}$, $L=\mathbb{Q}(2^{1/3})$ and $\alpha=j2^{1/3}$. Then $[L:K]=3$, but $[L(\alpha):K(\alpha)]=2$.
However, if $L/K$ is Galois, and $\alpha$ is separable, the statement becomes true.
Indeed, any $K(\alpha)$-automorphism of $\overline{K}$ will leave $\alpha$ invariant and $L$ stable, thus $L(\alpha)/K(\alpha)$ is Galois as well.
But we have a natural restriction morphism $Gal(L(\alpha)/K(\alpha)) \rightarrow Gal(L/K)$, which is injective. One concludes using Lagrange's theorem (on subgroups).
Edit: just to add another (more ad hoc) sufficient condition. If $K(\alpha)$ and $L$ have coprime dimensions $a$ and $b$ over $K$, then $[L(\alpha):L]=[K(\alpha):K]$ and $[L(\alpha):K(\alpha)]=[L:K]$.
Indeed, $d=[L(\alpha):K]$ is divisible both by $a=[K(\alpha):K]$ and $b=[L:K]$, so as $a$ and $b$ are coprime $d \geq ab$. But $d=b[L(\alpha):L]$. Now $\alpha$ vanishes a polynomial in $K \subset L$ of degree $a$, thus $[L(\alpha):L] \leq a$, thus $d \leq ba$ and $d=ba$, $a=[L(\alpha):L]$. Moreover, $ab=[L(\alpha):K]=[L(\alpha):K(\alpha)][K(\alpha):K]=a[L(\alpha):K(\alpha)]$, which concludes.


text:
Q: apex_util.get_blob was not found on this server I am trying to develop an interactive report in which I am using blob column to download the blob file (that could be jpeg or pdf). I created the download field on the blob column but, when I clicked on it, it gives an error as mentioned below.
"The requested URL /apex/apex_util.get_blob was not found on this server"
Note: I am using oracle apex 5.1.2.
Can anybody please help me to resolve this error.

A: Suppose that BLOB column is named BLOB_COLUMN, and it contains JPEG or PDF. It is one of column in SELECT statement you used to create an interactive report.
By default, BLOB_COLUMN's type is "Plain text". If you just changed it to Download BLOB and filled required BLOB attributes, well - it won't work.
Instead, you should create yet another column in IR's SELECT:
select ...,
  dbms_lob.getlength(blob_column) download_blob
from ...

and apply BLOB attributes to it. I've just tried it on apex.oracle.com, works as expected. If it still doesn't work for you, please, create an example on the same site, provide credentials so that someone of us might have a look.

A: at the BLOB attributes there is a Primary key column. The get_blob uses the same column value from the report to fetch the blob from the given table. So, if you have two ID columns in two tables (joined report) you have to create a view for the other table and use an other column name as ID in  it. Use this view and the new ID column name as a PK.


text:
Q: Is an SSL certificate verification by thumbprint and serialnumber secure enough? I need to validate a few SSL certificates(X509Certificate2) in my app and I was wondering if a decent approach could be by only comparing the X509Certificate2.Thumbprint and X509Certificate2.SerialNumber of the certificate since both should be unique (aside from possible collision of the hash algorithm).
What are the attacking vectors with this approach? I know that a proper validation includes several steps (chain validation, CRL, etc) but if I only have to validate a specific amount of certificates and not "all possible" certificates, this approach looks quite good (comparing to the work I have to put it)


text:
Q: How to evaluate $\sum _{n=1}^{\infty }\sum _{k=1}^{\infty }\frac{\left(-1\right)^{k-1}}{n^2\left(k^2-2n^2\right)}$ As seen in the title I'm interested in a way to evaluate
$$\sum _{n=1}^{\infty }\sum _{k=1}^{\infty }\frac{\left(-1\right)^{k-1}}{n^2\left(k^2-2n^2\right)}$$
But I'm not sure what to do, I did attempt something but ended up with a wrong result
$$\sum _{n=1}^{\infty }\sum _{k=1}^{\infty }\frac{\left(-1\right)^{k-1}}{n^2\left(k^2-2n^2\right)}=\sum _{n=1}^{\infty }\sum _{k=1}^{\infty }\frac{\left(-1\right)^{k-1}}{n^2\left(k-\sqrt{2}n\right)\left(k+\sqrt{2}n\right)}$$
then applying partial fraction decomposition
\begin{align*}
&=\sum _{n=1}^{\infty }\sum _{k=1}^{\infty }\frac{\left(-1\right)^{k-1}}{k^3\left(k-\sqrt{2}n\right)}+\sum _{n=1}^{\infty }\sum _{k=1}^{\infty }\frac{\left(-1\right)^{k-1}}{k^3\left(k+\sqrt{2}n\right)}+\sum _{n=1}^{\infty }\sum _{k=1}^{\infty }\frac{\left(-1\right)^{k-1}}{k^2n^2}\\
&=\sum _{n=1}^{\infty }\sum _{k=1}^{\infty }\frac{\left(-1\right)^{k-1}}{k^3}\int _0^1x^{k-\sqrt{2}n-1}\:\mathrm{d}x+\sum _{n=1}^{\infty }\sum _{k=1}^{\infty }\frac{\left(-1\right)^{k-1}}{k^3}\int _0^1x^{k+\sqrt{2}n-1}\:\mathrm{d}x+\frac{5}{4}\zeta (4)\\
&=-\sum _{n=1}^{\infty }\int _0^1\operatorname{Li}_3\left(-x\right)x^{-\sqrt{2}n-1}\:\mathrm{d}x-\sum _{n=1}^{\infty }\int _0^1\operatorname{Li}_3\left(-x\right)x^{\sqrt{2}n-1}\:\mathrm{d}x+\frac{5}{4}\zeta (4)\\
&=\int _0^1\frac{\operatorname{Li}_3\left(-x\right)}{x\left(1-x^{\sqrt{2}}\right)}\:\mathrm{d}x-\int _0^1\frac{x^{\sqrt{2}}\operatorname{Li}_3\left(-x\right)}{x\left(1-x^{\sqrt{2}}\right)}\:\mathrm{d}x+\frac{5}{4}\zeta (4)\\
&=\int _0^1\frac{\operatorname{Li}_3\left(-x\right)}{x}\:\mathrm{d}x+\frac{5}{4}\zeta (4)\\
&=-\frac{7}{8}\zeta (4)+\frac{5}{4}\zeta (4)\\
&=\frac{3}{8}\zeta (4)
\end{align*}
Which seems to be a wrong answer due to numerical methods and approximations, what did I do wrong? how else could I approach this problem?

A: Let $S_1(n)=\sum\limits_{k=1}^{\infty } \frac{\left ( -1 \right )^{k-1}}{ k^2-2n^2} $, then $S=\sum\limits_{n=1}^{\infty }\left (\sum\limits_{k=1}^{\infty } \frac{\left ( -1 \right )^{k-1}}{n^2\left ( k^2-2n^2 \right )} \right )=\sum\limits_{n=1}^{\infty }\frac{S_1(n)}{n^2}$
Let's consider the integral in the complex plane along a big circle  of radius $R$ (counter-clockwise) with the center at $(0;0)$:
$\oint=\oint_C\frac{\pi}{\sin\pi z}\frac{1}{z^2-2n^2}dz=2\pi i \sum Res\frac{\pi}{\sin\pi z}\frac{1}{z^2-2n^2}$ inside the circle
It can be shown that $\oint\to0$ as $R\to\infty\,\,\, \Rightarrow$
$\sum Res\frac{\pi}{\sin\pi z}\frac{1}{z^2-2n^2}=\sum\limits_{k=-\infty}^{\infty } \frac{(-1)^k}{k^2-2n^2} +\frac{\pi}{\sqrt2 n\sin(\sqrt2 \pi n)}=0$
$-\sum\limits_{k=-\infty}^{\infty } \frac{(-1)^k}{k^2-2n^2}=2S_1(n)+\frac{1}{2n^2}=\frac{\pi}{\sqrt2 n\sin(\sqrt2 \pi n)}\,\,\,\Rightarrow\,\,\,S_1(n)=\frac{\pi}{2\sqrt2 n\sin(\sqrt2 \pi n)}-\frac{1}{4n^2}\,\,\,\Rightarrow$
$$S=\sum\limits_{n=1}^{\infty }\frac{\pi}{2\sqrt2 n^3\sin(\sqrt2 \pi n)}-\frac{1}{4}\zeta(4)$$
The evaluation of $\sum\limits_{n=1}^{\infty }\frac{1}{n^3\sin(\sqrt2 \pi n)}=-\frac{13 \pi^3}{360 \sqrt{2}}$ is done here: Compute the series $\sum_{n=1}^{+\infty} \frac{1}{n^3\sin(n\pi\sqrt{2})}.$
NB  The approach is the same: integration along the closed contour in the complex plane with the special integrand $\biggl(\frac{1}{z^3\sin(\pi z)\sin(\sqrt2\pi z-\pi z)}\biggr)$
Finally,
$$S=-\frac{13\pi^4}{360*4}-\frac{\pi^4}{360}=-\frac{17\pi^4}{1440}$$

A: $$\frac 1{n^2\left(k^2-2n^2\right)}=\frac 1{n^2\left(k-n \sqrt 2\right)\left(k+n \sqrt 2\right)}$$
Using partial fracion decomposition
$$\frac 1{n^2\left(k^2-2n^2\right)}=\frac{1}{2 \sqrt{2} n^3}\left(\frac{1}{k-\sqrt{2} n}-\frac{1}{k+\sqrt{2} n}\right)$$
$$\sum_{k=1}^\infty \frac{(-1)^{k-1}}{k-\sqrt{2} n}=\frac{1}{2}
   \left(H_{-\frac{n}{\sqrt{2}}}-H_{-\frac{n}{\sqrt{2}}-\frac{1}{2}}\right)$$
$$\sum_{k=1}^\infty \frac{(-1)^{k-1}}{k+\sqrt{2} n}=\frac{1}{2}
   \left(H_{\frac{n}{\sqrt{2}}}-H_{\frac{n}{\sqrt{2}}-\frac{1}{2}}\right)$$
$$\sum_{k=1}^\infty\frac{(-1)^{k-1}}{k-\sqrt{2} n}-\sum_{k=1}^\infty \frac{(-1)^{k-1}}{k+\sqrt{2} n}=\pi  \csc \left(\sqrt{2} \pi  n\right)-\frac{1}{\sqrt{2} n}$$
$$\frac{1}{2 \sqrt{2}}\sum_{k=1}^\infty \frac 1 {n^3}\left(\pi  \csc \left(\sqrt{2} \pi  n\right)-\frac{1}{\sqrt{2} n}\right)=\frac{1}{2 \sqrt{2}}\left(-\frac{13 \pi ^3}{360 \sqrt{2}}-\frac{\pi ^4}{90 \sqrt{2}}\right)=-\frac{\pi ^4}{360}-\frac{13 \pi ^3}{1440}$$


text:
Q: set.seed globally R 3.6.1 I am using R Version 3.6.1 and would like to set a seed globally for a R session to get the same sequences of random number for all random number generators I call in a script.
A behavior just as described here: setting seed locally (not globally) in R
Currently I would have to call set.seed() in front of every call to a random number generator to get this (see code). Is there a option to set seeds globally?
# Example output
set.seed(2)
runif(1)
[1] 0.1848823
set.seed(2)
runif(1)
[1] 0.1848823
runif(1)
[1] 0.702374

Also, when I looked it up I found alternating behavior.
Here it is described as more global
setting seed locally (not globally) in R
And here it is more local:
set.seed with R 2.15.2
Thanks in advance


text:
Q: Connection timed out when connecting the socket I am writing code to connect a socket to a server. However, when I try to connect the socket, it throws an exception:

net.connectexception: connect failed: ETIMEOUT

The exception seems to be thrown at a fixed time like 1min. I have referred to many material and I have done the following:

*

*added permission.internet to manifest.xml.

*make the Phone and PC under the same WiFi.

But the exception is still thrown.
Here is my code:
btnSend = (Button) findViewById(R.id.send);
    btnSend.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            mThreadPool.execute(new Runnable() {
                @Override
                public void run() {
                    try {
                        outputStream = socket.getOutputStream();
                        outputStream.write(floatToByte(a));
                        outputStream.flush();

                    } catch (IOException e) {
                         Log.d("send",Log.getStackTraceString(e));
                    }
                    catch(NullPointerException e)
                    {
                        Log.d("send",Log.getStackTraceString(e));
                    }

                }
            });

        }
    });
    btnConnect = (Button) findViewById(R.id.connect);
    btnConnect.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            mThreadPool.execute(new Runnable() {
                @Override
                public void run() {

                    try {

                        socket=new Socket("192.168.43.194",9998)
                        System.out.println(socket.isConnected());
                        boolean m=socket.isConnected();
                        if(m) {
                            Log.d("Connect","True");
                        }
                        if(!m){
                            Log.d("Connect","Connect false");
                        }

                    } catch (IOException e) {
                        e.printStackTrace();
                        Log.d("Connect",Log.getStackTraceString(e));
                    }
                    catch(NullPointerException e){
                        Log.d("Connect",Log.getStackTraceString(e));
                    }
                    catch(NetworkOnMainThreadException e){
                        Log.d("Connect",Log.getStackTraceString(e));
                    }

                }
            });

Here is my logcat:
2021-07-07 22:58:56.950 24255-24560/com.example.magickeyboard D/Connect: java.net.ConnectException: failed to connect to /192.168.43.194 (port 9998) from /:: (port 57742): connect failed: ETIMEDOUT (Connection timed out)
    at libcore.io.IoBridge.connect(IoBridge.java:143)
    at java.net.PlainSocketImpl.socketConnect(PlainSocketImpl.java:142)
    at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:390)
    at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:230)
    at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:212)
    at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:436)
    at java.net.Socket.connect(Socket.java:621)
    at java.net.Socket.connect(Socket.java:570)
    at java.net.Socket.<init>(Socket.java:450)
    at java.net.Socket.<init>(Socket.java:218)
    at com.example.magickeyboard.Activities.Typing$3$1.run(Typing.java:162)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
    at java.lang.Thread.run(Thread.java:929)
 Caused by: android.system.ErrnoException: connect failed: ETIMEDOUT (Connection timed out)
    at libcore.io.Linux.connect(Native Method)
    at libcore.io.ForwardingOs.connect(ForwardingOs.java:95)
    at libcore.io.BlockGuardOs.connect(BlockGuardOs.java:136)
    at libcore.io.ForwardingOs.connect(ForwardingOs.java:95)
    at libcore.io.IoBridge.connectErrno(IoBridge.java:157)

This is the code of my server and I have binded a socket listening on the port.
public class ser {
    public static void main(String[] args) {
        ServerSocket serverSocket = null;
        try {
            serverSocket = new ServerSocket(9998);
            Socket socket = serverSocket.accept();
            InputStream inputStream = socket.getInputStream();
            byte buffer[] = new byte[1024 * 4];
            int temp = 0;
            while ((temp = inputStream.read(buffer)) != -1) {
                System.out.println(new String(buffer, 0, temp));
            }
            serverSocket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

This is the ip address of the PC:


text:
Q: SAPUI5 Login page? i cant find any simmilar to my question soo i want just to know if i can make a "login page" my own instead of the popup

this there a way?
My application is deployed on the cloud platform and goes trough a cloud connector to the sap backend system where it get his odata data from..
Its kinda ugly and i cant find anything to this.. except when the app is deployed in the abap repository.. but my is deployed and running trough the cloud platform.
(Username = SAP User and password also sap user pwd)
so maybe someone can help or paste an example

A: This pop-up is appearing for the logon to your ABAP backend system.

You can simply remove it by setting up Single Sign-On


text:
Q: Build context folder in a remote registry? I am trying to configure a docker build in Jenkins using the docker build step plugin.
I am adding a build step in the project that needs to create an image using a dockerfile

My docker file in  the location 10.113.57.164:root/tapash_docker
What should be format/value for build context folder for this step?

A: Provided your slave is executing this job on 10.113.57.164, then your folder should be:
 /tapash_docker

That is where your Dockerfile is, and anything below /tapash_docker will be part of the build context.


text:
Q: What is datatype of pcollection in apache beam for python version? I have read many tutorials, and they have explained that output of transform is a Pcollection in apache Beam.
Can anyone explain me, exactly how a Pcollection is stored, what datatype it return if we are applying any transformations.
Is it a python dictionary,tuple,list?

A: Apache Beam executes pipelines in a deferred fashion. This means that you can't access the elements of a PCollection as you build your pipeline - because the PCollection has not been computed:
p = beam.Pipeline(runner='....')
input_pcollection = p | ReadFromText(...)

result_pcollection = input_pcollection | beam.Filter(...) | beam.Combine(...)

At this point, you've only told Beam which operations it should execute
in the future - but these operations have not been executed yet.
To actually compute the PCollections, you must:
p.run().wait_until_finish()

To actually inspect PCollections, try running interactively in Jupyter or Collab notebooks: https://colab.sandbox.google.com/github/apache/beam/blob/master/examples/notebooks/get-started/try-apache-beam-py.ipynb


text:
Q: Небезопасный iframe (http) на безопасном (https) сайте Сегодня перевел сайт на https, но возникли некоторые сложности с IFRAME.
Одна из страниц сайта, с помощью iframe, подгружает контент другого сайта, у которого нет сертификата SSL, и который работает по http, но из-за того что на моем сайте установлен https - iframe не загружается.
Firefox Firebug говорит: "Заблокирована загрузка смешанного активного содержимого"
Подскажите, есть ли возможность подгрузить небезопасный сайт на безопасный с помощью iframe или других средств ?

A: Если ты доверяешь содержимому сайта о котором идёт речь то можно попробовать проксировать его через свой веб-сервер, т.е. запрос будет посылаться на твой хост, а веб-сервер будет проксировать запрос на второй сайт и возвращать его ответ.
В apache для этого используется директива ProxyPass, в nginx используется proxy_pass.
Пример для nginx:
server {
    listen 443 ssl;
    ...
    location = /foreign-iframe {
        proxy_pass              http://foreign.site.ru/test.asp;
        proxy_read_timeout      30;
        keepalive_timeout       60;
        proxy_http_version      1.1;

        proxy_set_header        X-Real-IP       $remote_addr;
        proxy_set_header        X-SERVER-PORT   $server_port;
        proxy_set_header        X-FORWARDED-FOR $proxy_add_x_forwarded_for;
        proxy_set_header        X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header        X-ARGS          $args;
        proxy_set_header        X-REQUEST-URI   $request_uri;
    }
}


text:
Q: Combining several looping MySQL queries in PHP I have two tables that pertain to this part of a trivia quiz game: scores and quiz. I have nested numerous PHP and MySQL loops, and I'm hoping there's a more elegant way (and hopefully, fewer database queries) to achieve the same results.
Any suggestions greatly appreciated.
Below is my MySQL structure, PHP code and some sample data.
Table quiz holds information for each quiz in the system, one record per quiz:
  `uid` int(11) NOT NULL AUTO_INCREMENT,
  `category_uid` int(11) NOT NULL,
  `name` varchar(255) NOT NULL,
  `sample` binary(2) NOT NULL,
  `difficulty` varchar(65) NOT NULL,
  `date_created` datetime NOT NULL,
  `date_updated` datetime NOT NULL,
  PRIMARY KEY (`uid`)

A unique ID, a map to categories table (not relevant here), a name, whether it's a sample quiz or not, a difficulty rating, the date it was first created, and the date it was last updated.
Table scores holds results from when a user takes a quiz, one record per question in the quiz (so, ten rows for a 10-question quiz):
  `uid` int(11) NOT NULL AUTO_INCREMENT,
  `unique_uid` varchar(255) NOT NULL,
  `question_uid` int(11) NOT NULL,
  `quiz_uid` int(11) NOT NULL,
  `user_uid` int(11) NOT NULL,
  `answer` varchar(255) NOT NULL,
  `correct` binary(2) NOT NULL,
  `points` int(25) NOT NULL,
  `time` float(20,1) NOT NULL,
  `date_created` datetime NOT NULL,
  PRIMARY KEY (`uid`)

A unique ID for the record, a unique ID for the instance of the quiz being taken, a map to questions table (not relevant here), a map to quiz table, a map to users table (not relevant here), the answer given, whether it was correct or not, the point score awarded, the time in seconds it took for a response, and the time stamp of the record.
Since a player can re-play quizzes, each scores.unique_uid points to a single time playing the quiz. This means a player might play quiz.uid=1 five different times, meaning five different score.unique_uid for a total of (5 times X 10 questions =) 50 rows recorded in the scores table.
What I'm trying to do is retrieve all distinct scores.unique_uid records (a list of every quiz the player has a score for) and then look at some tabulated results for each set of 10 records (one quiz, 10 questions).
The way I'm doing it now is:

*

*looping through a query that returns each unique quiz.uid the player has scored

*looping through another query that returns the scores.unique_uid for each unique instance of the player scoring that particular quiz quiz.uid

*using a third query to retrieve the SUM() data for each set of records with unique scores.unique_uid (I couldn't successfully combined with the DISTINCT query)

Here is my PHP code:
// Query retrieves each unique quiz the player has taken
$ss = sqlQuery("SELECT DISTINCT scores.quiz_uid, quiz.difficulty, quiz.name FROM scores, quiz WHERE scores.user_uid = {$_SESSION['uid']} AND quiz.uid = scores.quiz_uid ORDER BY scores.date_created DESC");
if ( mysql_num_rows( $ss ) > 0 ) {
    while ( $row = mysql_fetch_assoc( $ss ) ){
        /* Step through each quiz and output name and difficulty */
?>

<?php echo ( $row['name'] ); ?> Difficulty: <?php echo( $row['difficulty'] ); ?>

<?php
        // Query retrieves each unique unique_uid scored (each instance of every quiz)
        $eqs = sqlQuery("SELECT DISTINCT unique_uid FROM scores WHERE quiz_uid = {$row['quiz_uid']} AND user_uid = {$_SESSION['uid']}");

        while ( $eqsrow = mysql_fetch_assoc( $eqs ) ){
            /* Step through each quiz played instance, and output score and other details */

            // Query retrieves SUM()s for total time, total points, total correct responses
            $euqs = sqlQuery('SELECT date_created, ' .
                'SUM(time) AS times, SUM(points) AS points, SUM(correct) AS ttlcorrect ' .
                "FROM scores WHERE unique_uid = {$eqsrow['unique_uid']} AND user_uid = {$_SESSION['uid']} ");

            // Output the score
            while ( $euqsrow = @mysql_fetch_assoc( $euqs ) ){
?>

<?php echo( number_format( $euqsrow['points'], 0) ); ?> points
<?php echo( number_format( $euqsrow['times'], 0) ); ?> seconds
<?php echo( number_format( $euqsrow['ttlcorrect'], 0) ); ?> / 10 correct
Played <?php echo( date( 'F j, Y', strtotime($euqsrow['date_created']) ) ); ?>

<?php
            } // Close euqs while()
        } // close $eqs while()
    } // close $ss while()
} // close if()

Here are some sample records for each table.
quiz table:
(uid, category_uid, name, sample, difficulty, date_created, date_updated)
(1, 1, 'Business and Industry', '\0\0', 'Newcomer', '2012-03-15 13:42:30', '2012-03-15 13:42:30'),
(2, 2, 'History', '\0\0', 'Newcomer', '2012-03-15 13:42:30', '2012-03-15 13:42:30'),
(3, 3, 'Sports', '\0\0', 'Newcomer', '2012-03-15 13:42:50', '2012-03-15 13:42:50'),
(4, 4, 'Arts/Entertainment', '\0\0', 'Newcomer', '2012-03-15 13:42:50', '2012-03-15 13:42:50'),
(5, 5, 'Music', '\0\0', 'Newcomer', '2012-03-15 13:43:11', '2012-03-15 13:43:11'),
(6, 6, 'Geography', '\0\0', 'Newcomer', '2012-03-15 13:43:11', '2012-03-15 13:43:11');

scores table:
(uid, unique_uid, question_uid, quiz_uid, user_uid, answer, correct, points, time, date_created)
(81, '1111334693628', 4, 1, 11, 'Paul''s Valley', '0\0', 0, 2.8, '2012-04-17 13:15:40'),
(82, '1111334693628', 6, 1, 11, 'Bartlesville', '1\0', 9, 2.4, '2012-04-17 13:15:44'),
(83, '1111334693628', 3, 1, 11, 'Shawnee', '1\0', 8, 5.9, '2012-04-17 13:15:51'),
(84, '1111334693628', 40, 1, 11, 'Cimarron Turnpike', '0\0', 0, 4.4, '2012-04-17 13:15:57'),
(85, '1111334693628', 1, 1, 11, 'tow package for trucks', '1\0', 9, 3.9, '2012-04-17 13:16:03'),
(86, '1111334693628', 36, 1, 11, 'aviation', '1\0', 6, 9.0, '2012-04-17 13:16:13'),
(87, '1111334693628', 37, 1, 11, 'Altus', '0\0', 0, 3.0, '2012-04-17 13:16:18'),
(88, '1111334693628', 2, 1, 11, 'Bama Pies', '1\0', 7, 6.1, '2012-04-17 13:16:25'),
(89, '1111334693628', 5, 1, 11, 'Gordon Cooper', '0\0', 0, 2.2, '2012-04-17 13:16:29'),
(90, '1111334693628', 38, 1, 11, 'Bartlesville', '1\0', 9, 2.7, '2012-04-17 13:16:33'),
(91, '1131334773558', 13, 3, 11, 'Jim Thorpe', '1\0', 10, 1.5, '2012-04-18 11:26:09'),
(92, '1131334773558', 49, 3, 11, 'Henry Iba', '1\0', 10, 1.8, '2012-04-18 11:26:12'),
(93, '1131334773558', 17, 3, 11, 'Kelli Litsch', '1\0', 10, 1.9, '2012-04-18 11:26:15'),
(94, '1131334773558', 14, 3, 11, 'Bud Wilkinson', '0\0', 0, 4.4, '2012-04-18 11:26:21'),
(95, '1131334773558', 48, 3, 11, 'Charlie Coe', '1\0', 10, 1.7, '2012-04-18 11:26:25'),
(96, '1131334773558', 50, 3, 11, 'Jim Tatum', '1\0', 8, 4.3, '2012-04-18 11:26:31'),
(97, '1131334773558', 47, 3, 11, 'Bobby Murcer', '0\0', 0, 2.4, '2012-04-18 11:26:34'),
(98, '1131334773558', 15, 3, 11, 'Myron Roderick', '1\0', 9, 3.1, '2012-04-18 11:26:39'),
(99, '1131334773558', 46, 3, 11, 'Tommy McDonald', '1\0', 9, 3.6, '2012-04-18 11:26:44'),
(100, '1131334773558', 16, 3, 11, 'five', '0\0', 0, 2.0, '2012-04-18 11:26:48'),
(101, '1131334773620', 15, 3, 11, 'Myron Roderick', '1\0', 9, 2.4, '2012-04-18 11:27:16'),
(102, '1131334773620', 13, 3, 11, 'Jim Thorpe', '1\0', 10, 1.1, '2012-04-18 11:27:18'),
(103, '1131334773620', 49, 3, 11, 'Henry Iba', '1\0', 10, 1.3, '2012-04-18 11:27:21'),
(104, '1131334773620', 16, 3, 11, 'seven', '1\0', 10, 1.8, '2012-04-18 11:27:25'),
(105, '1131334773620', 46, 3, 11, 'Tommy McDonald', '1\0', 10, 1.4, '2012-04-18 11:27:28'),
(106, '1131334773620', 47, 3, 11, 'Darrell Porter', '1\0', 10, 1.8, '2012-04-18 11:27:31'),
(107, '1131334773620', 50, 3, 11, 'Jim Tatum', '1\0', 9, 2.2, '2012-04-18 11:27:35'),
(108, '1131334773620', 14, 3, 11, 'Benny Owen', '1\0', 9, 2.7, '2012-04-18 11:27:39'),
(109, '1131334773620', 17, 3, 11, 'Kelli Litsch', '1\0', 10, 1.8, '2012-04-18 11:27:42'),
(110, '1131334773620', 48, 3, 11, 'Charlie Coe', '1\0', 10, 1.9, '2012-04-18 11:27:46');

A: What about using one MySQL query like
SELECT * FROM quiz LEFT JOIN scores ON quiz.uid = scores.quiz_uid

And then just loop thru it?

A: I was able to come up with a solution by using GROUP. For anyone that might be interested, here's what I did:
// Query retrieves each unique play of each quiz the player has scored
$ss = sqlQuery("SELECT quiz.name, quiz.difficulty, scores.unique_uid, scores.quiz_uid, scores.date_created, SUM(scores.time) AS times, SUM(scores.points) AS points, SUM(scores.correct) AS ttlcorrect FROM scores, quiz WHERE scores.user_uid = {$_SESSION['uid']} AND quiz.uid = scores.quiz_uid GROUP BY scores.unique_uid ORDER BY quiz_uid, scores.date_created DESC");

$last_quiz = 0;
if ( mysql_num_rows( $ss ) > 0 ) {
    while ( $row = mysql_fetch_assoc( $ss ) ){
        /* Step through each play of each quiz */

        if ( $row['quiz_uid'] != $last_quiz ) {
            // Output Details
            $last_quiz = $row['quiz_uid'];
?>

<?php echo ( $row['name'] ); ?> Difficulty: <?php echo( $row['difficulty'] ); ?>

<?php
        }
        // Output Scores
?>

<?php echo( number_format( $row['points'], 0) ); ?> points
<?php echo( number_format( $row['times'], 0) ); ?> seconds
<?php echo( number_format( $row['ttlcorrect'], 0) ); ?> / 10 correct
Played <?php echo( date( 'F j, Y', strtotime($row['date_created']) ) ); ?>

<?php
    } // $ss while()
} // close if
?>


text:
Q: Receiving "invalid or does not take any parameters" when attempting to deploy a contract here is my 2_deploy_contract.js syntax
 const DerbyToken = artifacts.require("./DerbyToken.sol");

module.exports = function(deployer) {
  // Deploy the Migrations contract as our only task
  deployer.deploy(DerbyToken);
};

after I migrate the file using truffle I receive this error message
    Error: Migration /home/cyraidz/token_sale/migrations/2_deploy_contracts.js invalid or does not take any parameters
    at Migration._load (/usr/local/lib/node_modules/truffle/build/webpack:/packages/migrate/Migration.js:55:1)
    at process._tickCallback (internal/process/next_tick.js:68:7)
Truffle v5.3.5 (core: 5.3.5)
Node v10.19.0

A: Add a newline at the end of "2_deploy_contract.js"


text:
Q: Could anyone help me to compute the following code? The following code works good when the value of " r < 21 ". But when r > 20, I get the following error message
General::ovfl: Overflow occurred in computation.
General::stop: Further output of General::ovfl will be suppressed during this calculation.

This is the code which I need to compute for r > 20,
is = .85 {450, 450};
ip = {{60, 10}, {20, 10}};
f[t_, x_, y_, z_] := -x + y;
g[t_, x_, y_, z_] := -x - 0.01 y - y z;
p[t_, x_, y_, z_] := -0.5 z + x^2 - r;
r = 21;
t[0] = 0;
x[0] = 0.1;
y[0] = 0.1;
z[0] = 0.1;
a[0] = 0;
b[0] = -0.1;
c[0] = -0.1;
d[0] = 0.1;
tmax = 20000;
amax = 20000;
h = 0.01;
Do[{t[n] = t[0] + h n, k1 = h f[t[n], x[n], y[n], z[n]];
  l1 = h g[t[n], x[n], y[n], z[n]];
  m1 = h p[t[n], x[n], y[n], z[n]];
  k2 = h f[t[n] + h/2, x[n] + k1/2, y[n] + l1/2, z[n] + m1/2];
  l2 = h g[t[n] + h/2, x[n] + k1/2, y[n] + l1/2, z[n] + m1/2];
  m2 = h p[t[n] + h/2, x[n] + k1/2, y[n] + l1/2, z[n] + m1/2];
  k3 = h f[t[n] + h/2, x[n] + k2/2, y[n] + l2/2, z[n] + m2/2];
  l3 = h g[t[n] + h/2, x[n] + k2/2, y[n] + l2/2, z[n] + m2/2];
  m3 = h p[t[n] + h/2, x[n] + k2/2, y[n] + l2/2, z[n] + m2/2];
  k4 = h f[t[n] + h, x[n] + k3, y[n] + l3, z[n] + m3];
  l4 = h g[t[n] + h, x[n] + k3, y[n] + l3, z[n] + m3];
  m4 = h p[t[n] + h, x[n] + k3, y[n] + l3, z[n] + m3];
  x[n + 1] = x[n] + 1/6 (k1 + 2 k2 + 2 k3 + k4);
  y[n + 1] = y[n] + 1/6 (l1 + 2 l2 + 2 l3 + l4);
  z[n + 1] = z[n] + 1/6 (m1 + 2 m2 + 2 m3 + m4);}, {n, 0, tmax}]
T2 = Table[{x[i], z[i]}, {i, 0, tmax}];
pp1 = ListLinePlot[T2, PlotStyle -> {Blur, Thin}]

Could anyone please help me to solve this issue.

A: The r = 21 solution in the question  becomes exceeding large at abut n = 895, and this has nothing to do with lack of Precision.  I determined this as follows.
r = 21; h = 1/100;
f[t_, x_, y_, z_] := -x + y;
g[t_, x_, y_, z_] := -x - y/100 - y z;
p[t_, x_, y_, z_] := -z/2 + x^2 - r;

Some savings in computation time can be obtained by
t[n] = h n;
k1 = h f[t[n], x[n], y[n], z[n]];
l1 = h g[t[n], x[n], y[n], z[n]];
m1 = h p[t[n], x[n], y[n], z[n]];
k2 = h f[t[n] + h/2, x[n] + k1/2, y[n] + l1/2, z[n] + m1/2];
l2 = h g[t[n] + h/2, x[n] + k1/2, y[n] + l1/2, z[n] + m1/2];
m2 = h p[t[n] + h/2, x[n] + k1/2, y[n] + l1/2, z[n] + m1/2];
k3 = h f[t[n] + h/2, x[n] + k2/2, y[n] + l2/2, z[n] + m2/2];
l3 = h g[t[n] + h/2, x[n] + k2/2, y[n] + l2/2, z[n] + m2/2];
m3 = h p[t[n] + h/2, x[n] + k2/2, y[n] + l2/2, z[n] + m2/2];
k4 = h f[t[n] + h, x[n] + k3, y[n] + l3, z[n] + m3];
l4 = h g[t[n] + h, x[n] + k3, y[n] + l3, z[n] + m3];
m4 = h p[t[n] + h, x[n] + k3, y[n] + l3, z[n] + m3];
xp = Simplify[x[n] + 1/6 (k1 + 2 k2 + 2 k3 + k4)]
yp = Simplify[y[n] + 1/6 (l1 + 2 l2 + 2 l3 + l4)]
zp = Simplify[z[n] + 1/6 (m1 + 2 m2 + 2 m3 + m4)]

The expressions xp, yp, and zp are not reproduced here because they are fairly large.  The structure of the question is that of a recurrence relation, which can be evaluated by
tab = RecurrenceTable[{x[n + 1] == xp, y[n + 1] == yp, z[n + 1] == zp,
    x[0] == .1`100000, y[0] == .1`100000, z[0] == .1`100000}, {x, y, z}, {n, 1, 895}];
N@tab[[-1]]
(* {-1.509523880701748*10^10286856148010, 1.684787554556877*10^17442606938024,
     4.184274805718905*10^12133439661425} *)

which requires just less than two minutes to complete.  A plot of the solution is
ListLinePlot[Transpose@tab, PlotRange -> {-400, 400}, ImageSize -> Large,
    LabelStyle -> {15, Bold, Black}, PlotLegends -> Placed[{x, y, z}, {.3, .2}]]

These curves are insensitive to the Precision of {x[0], y[0], z[0]} so long as it is at least 1000.  Setting these initial values to 1/10 (infinite precision) is impractical, because the computation is so slow.  Below is a plot of the Precision of the solution.
ListLinePlot[Transpose@Map[Precision, tab, {2}], ImageSize -> Large,
    LabelStyle -> {15, Bold, Black}, PlotLegends -> Placed[{x, y, z}, {.3, .2}]]

Clearly, the Precision is more than adequate when the solution begins growing rapidly.  This appears to be the true nature of the solution for r = 21.  Perhaps, the oscillatory equilibrium of the recurrence relation becomes unstable with increasing r.
Work-Around
The code in the question is a fourth-order explicit Runge-Kutta solution of the the third order system of ODEs,
x'[t] == -x[t] + y[t];
y'[t] == -x[t] - y[t]/100 - y[t] z[t];
z'[t] == -z[t]/2 + x[t]^2 - r;

The explicit Runge-Kutta algorithm is unstable for some numerical parameters, and evidently that is the case here.  If it is necessary for some reason to solve these ODEs using this particular algorithm, then decreasing h improves stability.  For h = 1/200, the r = 21 solution is

Of course, there are many faster and more stable algorithms.


text:
Q: Is it possible to check for a verb without creating my own database? I am playing around with a sentence string entry for a project I'm working on in C# and wanted to see if there was an alternative way to search for a verb using a built in function.
Currently, I am using a database table with a list of regular verbs and cycling through those to check if there is a match but wanted to see if there would be a better way to do this?
Consider the following input:
"Develop string matching software for verb"
Program will read the string and check each word,
if (word == isVerb)
    {
        m_verbs.Add(word);
    }

A: you could load the common verbs from disk in a text file. If you have lots of verbs and worry about memory you could bucket them into common and uncommon or alphabetically then load in the dictionaries if needed

A: If you don't want to use the databse option (although highly recommanded), then you need to put them in a data structure (e.g. array or list). You can then use powerful System.Linq extension methods.
For example:
string[] allVerbs = new[] { "eat", "drink" }; // etc
string s = "Develop string matching software for verb";
var words = s.Split(' ');
foreach (var word in words)
    if (allVerbs.Contains(word.ToLower()))
       m_verbs.Add(word);

A: Short answer :
There is a better way.
Long answer :
It's not that simple. The problem is that there is no inbuilt language functionality into the string class in C#. This is an implementation detail that rests on the developer's shoulders.
You have some grammatical (or perhaps lexical is a better word) issues to consider as Owen79 pointed out in his comment. Then there is the question of environment / resource restrictions.
You have a few options available to you :

*

*Web based dictionary services. You can query those with the words of your sentence and get back the 'status' of each word. Then you will take only the statuses you want, like verbs for instance. Here is a link to DictService which also includes a C# code sample.

*A text / xml / other file based solution. Similar approach, you simply look up the words in the file and act according to the presence or absence of the word in the file. You can cache (load into memory) the contents of the file to save on IO operations. Here are the links to lists of regular and irregular verbs.

*Database solution is identical to the previous one with the exception of loading contents into memory. That part may be unnecessary but that depends on your implementation requirements.
Bottom line each solution will require some work but whatever option you go for the key aspects to consider are the platform and the resources available to you. If computational speed is a concern you will most likely need to do some tricks to cut down on lookup times etc.
Hope this helps