text:
Q: No NgModule metadata found for 'AppModule' Error in Angular 5 server-side rendering with --env.prod I'm trying to upgrade an ASP.NET Core + Angular 4 SPA project from .NET Core 2.0.0/Angular4 to .NET Core 2.0.3/Angular5. I managed to get everything working properly except for the server-side rendering in a production environment, i/e when I publish the app:

An unhandled exception has occurred: No NgModule metadata found for 'AppModule'.
  Error: No NgModule metadata found for 'AppModule'.

The issue only happens when both of these two conditions are met:

*

*Webpack builds the packages using the --env.prod switch

*The Index.cshtml view file contains the asp-prerender-module parameter, just like in the following example:
<app asp-prerender-module="ClientApp/dist/main-server">Loading...</app>
If I remove the switch and/or the parameter, the problem disappears (together with SSR).
There's a bunch of other info I can give:

*

*It's not something related to IIS, it happens at Kestrel-level.

*It's not related to the web server machine because I can even reproduce it with locally by manually launching Webpack with the --end.prod switch right before a Debug or Release run.

*It doesn't seem to have anything to do with the source code, as I can reproduce it even with a single-component sample app with very basic AppModule files and trivial code.

*The project was running perfectly fine with .NET Core 2.0.0 and Angular 4.3.x.

*The only major thing I changed in the webpack.config.js file is replacing the AotPlugin with the new, Angular5-specific AngularCompilerPlugin provided by the @ngtools/webpack package: I think that might as well be the cause, as the --env.prod switch makes use of that AOT compiler instead of the JIT one. That, or something related to the .NET SpaServices package - maybe not on-par with the new Angular5 and/or the new AoT compiler?

Sadly, I can't revert to the former AotPlugin because it throws errors as well - which is perfectly understandable, as it's not meant to be used with Angular5.
Software Versions

*

*.NET Core 2.0.3

*Angular 5.0.2

*@ngtools/webpack 1.8.2 (also tried with 1.8.1 - same outcome)

*WebPack 2.6.1 (also tried with 2.5.6 - same outcome)

webpack.config.js
const path = require('path');
const webpack = require('webpack');
const merge = require('webpack-merge');
const AotPlugin = require('@ngtools/webpack').AngularCompilerPlugin;
const CheckerPlugin = require('awesome-typescript-loader').CheckerPlugin;

module.exports = (env) => {
    // Configuration in common to both client-side and server-side bundles
    const isDevBuild = !(env && env.prod);
    const sharedConfig = {
        stats: { modules: false },
        context: __dirname,
        resolve: { extensions: [ '.js', '.ts' ] },
        output: {
            filename: '[name].js',
            publicPath: 'dist/' // Webpack dev middleware, if enabled, handles requests for this URL prefix
        },
        module: {
            rules: [
                { test: /(?:\.ngfactory\.js|\.ngstyle\.js|\.ts)$/, include: /ClientApp/, use: isDevBuild ? ['awesome-typescript-loader?silent=true', 'angular2-template-loader'] : '@ngtools/webpack' },
                { test: /\.html$/, use: 'html-loader?minimize=false' },
                { test: /\.css$/, use: [ 'to-string-loader', isDevBuild ? 'css-loader' : 'css-loader?minimize' ] },
                { test: /\.(png|jpg|jpeg|gif|svg)$/, use: 'url-loader?limit=25000' }
            ]
        },
        plugins: [new CheckerPlugin()]
    };

    // Configuration for client-side bundle suitable for running in browsers
    const clientBundleOutputDir = './wwwroot/dist';
    const clientBundleConfig = merge(sharedConfig, {
        entry: { 'main-client': './ClientApp/boot.browser.ts' },
        output: { path: path.join(__dirname, clientBundleOutputDir) },
        plugins: [
            new webpack.DllReferencePlugin({
                context: __dirname,
                manifest: require('./wwwroot/dist/vendor-manifest.json')
            })
        ].concat(isDevBuild ? [
            // Plugins that apply in development builds only
            new webpack.SourceMapDevToolPlugin({
                filename: '[file].map', // Remove this line if you prefer inline source maps
                moduleFilenameTemplate: path.relative(clientBundleOutputDir, '[resourcePath]') // Point sourcemap entries to the original file locations on disk
            })
        ] : [
            // Plugins that apply in production builds only
            new webpack.optimize.UglifyJsPlugin(),
            new AotPlugin({
                tsConfigPath: './tsconfig.json',
                entryModule: path.join(__dirname, 'ClientApp/app/app.module.browser#AppModule'),
                exclude: ['./**/*.server.ts']
            })
        ])
    });

    // Configuration for server-side (prerendering) bundle suitable for running in Node
    const serverBundleConfig = merge(sharedConfig, {
        resolve: { mainFields: ['main'] },
        entry: { 'main-server': './ClientApp/boot.server.ts' },
        plugins: [
            new webpack.DllReferencePlugin({
                context: __dirname,
                manifest: require('./ClientApp/dist/vendor-manifest.json'),
                sourceType: 'commonjs2',
                name: './vendor'
            })
        ].concat(isDevBuild ? [] : [
            // Plugins that apply in production builds only
            new AotPlugin({
                tsConfigPath: './tsconfig.json',
                entryModule: path.join(__dirname, 'ClientApp/app/app.module.server#AppModule'),
                exclude: ['./**/*.browser.ts']
            })
        ]),
        output: {
            libraryTarget: 'commonjs',
            path: path.join(__dirname, './ClientApp/dist')
        },
        target: 'node',
        devtool: 'inline-source-map'
    });

    return [clientBundleConfig, serverBundleConfig];
};

A: The @ngtool/webpack configuration for Angular 5 is somewhat different form Angular 2/4. So, I've changed the webpack.config.js as following,
const path = require('path');
const webpack = require('webpack');
const merge = require('webpack-merge');
const AngularCompilerPlugin = require('@ngtools/webpack').AngularCompilerPlugin;
const CheckerPlugin = require('awesome-typescript-loader').CheckerPlugin;

module.exports = (env) => {
    // Configuration in common to both client-side and server-side bundles
    const isDevBuild = !(env && env.prod);
    const sharedConfig = {
        stats: { modules: false },
        context: __dirname,
        resolve: { extensions: [ '.js', '.ts' ] },
        output: {
            filename: '[name].js',
            publicPath: 'dist/' // Webpack dev middleware, if enabled, handles requests for this URL prefix
        },
        module: {
            rules: [
                { test: /\.ts$/, include: /ClientApp/, use: isDevBuild ? ['awesome-typescript-loader?silent=true', 'angular2-template-loader'] : '@ngtools/webpack' },
                { test: /\.html$/, use: 'html-loader?minimize=false' },
                { test: /\.css$/, use: [ 'to-string-loader', isDevBuild ? 'css-loader' : 'css-loader?minimize' ] },
                { test: /\.(png|jpg|jpeg|gif|svg)$/, use: 'url-loader?limit=25000' },
                {
                    test: /(?:\.ngfactory\.js|\.ngstyle\.js)$/,
                    loader: '@ngtools/webpack',
                    options: {
                        tsConfigPath: '/tsconfig.json',
                    }
                }
            ]
        },
        plugins: [new CheckerPlugin()]
    };

    // Configuration for client-side bundle suitable for running in browsers
    const clientBundleOutputDir = './wwwroot/dist';
    const clientBundleConfig = merge(sharedConfig, {
        entry: { 'main-client': './ClientApp/boot.browser.ts' },
        output: { path: path.join(__dirname, clientBundleOutputDir) },
        plugins: [
            new webpack.DllReferencePlugin({
                context: __dirname,
                manifest: require('./wwwroot/dist/vendor-manifest.json')
            })
        ].concat(isDevBuild ? [
            // Plugins that apply in development builds only
            new webpack.SourceMapDevToolPlugin({
                filename: '[file].map', // Remove this line if you prefer inline source maps
                moduleFilenameTemplate: path.relative(clientBundleOutputDir, '[resourcePath]') // Point sourcemap entries to the original file locations on disk
            })
        ] : [
            // Plugins that apply in production builds only
                new webpack.optimize.UglifyJsPlugin(),
                new AngularCompilerPlugin({
                    tsConfigPath: './tsconfig.json',
                    entryModule: path.join(__dirname, 'ClientApp/app/app.module.browser#AppModule'),
                    exclude: ['./**/*.server.ts']
                })
        ])
    });

    // Configuration for server-side (prerendering) bundle suitable for running in Node
    const serverBundleConfig = merge(sharedConfig, {
        resolve: { mainFields: ['main'] },
        entry: { 'main-server': './ClientApp/boot.server.ts' },
        plugins: [
            new webpack.DllReferencePlugin({
                context: __dirname,
                manifest: require('./ClientApp/dist/vendor-manifest.json'),
                sourceType: 'commonjs2',
                name: './vendor'
            })
        ].concat(isDevBuild ? [] : [
            // Plugins that apply in production builds only
            new AngularCompilerPlugin({
                tsConfigPath: './tsconfig.json',
                entryModule: path.join(__dirname, 'ClientApp/app/app.module.server#AppModule'),
                exclude: ['./**/*.browser.ts']
            })
        ]),
        output: {
            libraryTarget: 'commonjs',
            path: path.join(__dirname, './ClientApp/dist')
        },
        target: 'node',
        devtool: 'inline-source-map'
    });

    return [clientBundleConfig, serverBundleConfig];
};

And here is my package.json file,
   {
  "dependencies": {
    "@angular/animations": "^5.0.2",
    "@angular/cdk": "^5.0.0-rc0",
    "@angular/cli": "^1.6.0-beta.2",
    "@angular/common": "^5.0.2",
    "@angular/compiler": "^5.0.2",
    "@angular/compiler-cli": "^5.0.2",
    "@angular/core": "^5.0.2",
    "@angular/forms": "^5.0.2",
    "@angular/http": "^5.0.2",
    "@angular/material": "^5.0.0-rc0",
    "@angular/platform-browser": "^5.0.2",
    "@angular/platform-browser-dynamic": "^5.0.2",
    "@angular/platform-server": "^5.0.2",
    "@angular/router": "^5.0.2",
    "@ngtools/webpack": "^1.8.3",
    "@types/webpack-env": "^1.13.2",
    "angular2-template-loader": "0.6.2",
    "aspnet-prerendering": "^3.0.1",
    "aspnet-webpack": "^2.0.1",
    "awesome-typescript-loader": "^3.4.0",
    "bootstrap": "3.3.7",
    "css": "2.2.1",
    "css-loader": "^0.28.7",
    "es6-shim": "0.35.3",
    "event-source-polyfill": "0.0.12",
    "expose-loader": "0.7.4",
    "extract-text-webpack-plugin": "^3.0.2",
    "file-loader": "^1.1.5",
    "html-loader": "^0.5.1",
    "isomorphic-fetch": "2.2.1",
    "jquery": "3.2.1",
    "json-loader": "^0.5.7",
    "preboot": "^5.1.7",
    "raw-loader": "0.5.1",
    "reflect-metadata": "0.1.10",
    "request": "^2.83.0",
    "rxjs": "^5.5.2",
    "style-loader": "^0.19.0",
    "to-string-loader": "1.1.5",
    "typescript": "^2.6.1",
    "url-loader": "^0.6.2",
    "webpack": "^3.8.1",
    "webpack-hot-middleware": "^2.20.0",
    "webpack-merge": "^4.1.1",
    "zone.js": "^0.8.18"
  },
  "devDependencies": {
    "@types/chai": "^4.0.5",
    "@types/jasmine": "^2.8.2",
    "@types/node": "^8.0.53",
    "chai": "^4.1.2",
    "jasmine-core": "2.8.0",
    "karma": "1.7.1",
    "karma-chai": "0.1.0",
    "karma-chrome-launcher": "2.2.0",
    "karma-cli": "1.0.1",
    "karma-jasmine": "1.1.0",
    "karma-webpack": "2.0.6"
  },
  "name": "aspnetcoreangularspa",
  "private": true,
  "scripts": {
    "test": "karma start ClientApp/test/karma.conf.js"
  },
  "version": "0.0.0"
}

If you still having problems running the solution, please have a look at this repository for a working solution.
Hope it helps :)

A: As others suggested, the temporary solution is to remove the SSR (Server Side Rendering). That means opening the Home/Index.cshtml file and change
<app asp-prerender-module="ClientApp/dist/main-server">Loading...</app>

to
<app>Loading...</app>

A: I found your Issue while searching for a solution to my problem described here:
https://github.com/aspnet/JavaScriptServices/issues/1388
So i tried your webpack-config and also tried to run the app from the repository, but when i do "dotnet publish" and then run the app i get this error:
Microsoft.AspNetCore.Diagnostics.ExceptionHandlerMiddleware[0]
      An unhandled exception has occurred: No NgModule metadata found for 'AppModule'.
      Error: No NgModule metadata found for 'AppModule'.
    at NgModuleResolver.module.exports.NgModuleResolver.resolve

A: solution from mak0t0san working for me and ssr still working (angular 5.2.0),

*

*update ngtoolwebpack to 1.10.2

*typescript 2.6.2

and change webpack.config.js with that
const path = require('path');
const webpack = require('webpack');
const { DllReferencePlugin, SourceMapDevToolPlugin} = require('webpack');
const merge = require('webpack-merge');
const {AngularCompilerPlugin, PLATFORM} = require('@ngtools/webpack');
const CheckerPlugin = require('awesome-typescript-loader').CheckerPlugin;
const UglifyJsPlugin = require('uglifyjs-webpack-plugin');

module.exports = (env) => {
    // Configuration in common to both client-side and server-side bundles
    const isDevBuild = !(env && env.prod);
    const sharedConfig = {
        stats: {modules: false},
        context: __dirname,
        resolve: {extensions: ['.js', '.ts']},
        output: {
            filename: '[name].js',
            chunkFilename:'[id].chunk.js',
            publicPath: 'dist/' // Webpack dev middleware, if enabled, handles requests for this URL prefix
        },
        module: {
            rules: [
                {test: /\.html$/, use: 'html-loader?minimize=false'},
                {test: /\.css$/, use: ['to-string-loader', isDevBuild ? 'css-loader' : 'css-loader?minimize']},
                {test: /\.(png|jpg|jpeg|gif|svg)$/, use: 'url-loader?limit=25000'},
                {
                    test: /\.(scss)$/,
                    use: [{
                        loader: 'style-loader', // inject CSS to page
                    }, {
                        loader: 'css-loader', // translates CSS into CommonJS modules
                    }, {
                        loader: 'postcss-loader', // Run post css actions
                        options: {
                            plugins: function () { // post css plugins, can be exported to postcss.config.js
                                return [
                                    require('precss'),
                                    require('autoprefixer')
                                ];
                            }
                        }
                    }, {
                        loader: 'sass-loader' // compiles Sass to CSS
                    }]
                }
            ]
        },
        plugins: [new CheckerPlugin()]
    };

    // Configuration for client-side bundle suitable for running in browsers
    const clientBundleOutputDir = './wwwroot/dist';
    const clientBundleConfig = merge(sharedConfig, {
        module:{
            rules:[
                {
                    test: /\.ts$/,
                    use: ['@ngtools/webpack']
                },
            ]
        },
        entry: {'main-client': './ClientApp/boot.browser.ts'},
        output: {path: path.join(__dirname, clientBundleOutputDir)},
        plugins: [
            new DllReferencePlugin({
                context: __dirname,
                manifest: require('./wwwroot/dist/vendor-manifest.json')
            }),
            new AngularCompilerPlugin({
                "mainPath": path.join(__dirname, 'ClientApp/boot.browser.ts'),
                platform: PLATFORM.Browser,
                tsConfigPath: './tsconfig.json',
                entryModule: path.join(__dirname, 'ClientApp/app/app.browser.module#AppModule'),
                sourceMap: true
            })
        ].concat(isDevBuild ? [
            // Plugins that apply in development builds only
            new SourceMapDevToolPlugin({
                filename: '[file].map', // Remove this line if you prefer inline source maps
                moduleFilenameTemplate: path.relative(clientBundleOutputDir, '[resourcePath]') // Point sourcemap entries to the original file locations on disk
            })
        ] : [
            // Plugins that apply in production builds only
          new UglifyJsPlugin({
                sourceMap: true
            })
        ])
    });

    // Configuration for server-side (prerendering) bundle suitable for running in Node
    const serverBundleConfig = merge(sharedConfig, {
        module:{
          rules:[
              { test: /\.ts$/, use: ['awesome-typescript-loader?silent=true', 'angular2-template-loader', 'angular2-router-loader'] },
          ]
        },
        resolve: { mainFields: ['main'] },
        entry: { 'main-server': './ClientApp/boot.server.ts' },
        plugins: [
            new webpack.DllReferencePlugin({
                context: __dirname,
                manifest: require('./ClientApp/dist/vendor-manifest.json'),
                sourceType: 'commonjs2',
                name: './vendor'
            })
        ],
        output: {
            libraryTarget: 'commonjs',
            path: path.join(__dirname, './ClientApp/dist')
        },
        target: 'node',
        devtool: 'inline-source-map'
    });

    return [clientBundleConfig, serverBundleConfig];
};

A: As written at the @MMiebach's link:

Angular 5 includes breaking changes (versus Angular 4) meaning that the code for server-side rendering has to be very different.

Luckily, Microsoft released their new SPA project template for Angular 5. It can be installed with
dotnet new --install Microsoft.DotNet.Web.Spa.ProjectTemplates::2.0.0

After that command dotnet new angular will use the 5th Angular instead of 4th.
By default, server-side rendering is not turned on, but there are instructions how to do it in Docs by MS.


text:
Q: Issues with A background URLSession with identifier I  tried this code in my project to download large files in background and it works fine. I start downloading in UIViewController. If I go to another view and back to the UIViewController ,it stop reloading the progress bar.
I got the Issues with A background URLSession with identifier  already exists!. I Want to create new session every time when UIViewController load. I want invalidate all background session when dismiss the view controller. I tried all possibilities to resolve this issue but don't get succeed.
Click Here

A: When you create a background session, you're doing two things:

*

*Telling nsurlsessiond (a background daemon) to create a session.

*Creating a local session in your app that is connected to that session.

The purpose of the identifier is to allow your app to reconnect to the external session (controlled by nsurlsessiond) if your app gets terminated by the operating system.
To my knowledge, it is not normally possible for your app to voluntarily dissociate its session from the background session.  So when your app tries to create a session with the same identifier, suddenly there are two sessions that are both trying to talk to the same external session in nsurlsessiond, and things go very wrong.  That's not a supported way to use the API.
The background session object must be kept alive the entire time that your app is running.  Don't try to dispose of it and recreate it within a single launch.  You should not ever create a session with the same ID unless your app gets relaunched.
Note, however, that if your app gets relaunched to handle background events (iOS only), when you call the completion handler provided by the event, your app's local session does get invalidated, and you need to create it if your app does anything after that.  That's the only situation I'm aware of where a background session ever stops being associated with the background session in nsurlsessiond, and thus that's the only situation where you should ever create a session with the same ID twice in a single launch (once when you're asked to handle background events, and then potentially again when you get a didFinishLaunching call to indicate that the user foregrounded your app).

redpajama_set_name: RedPajamaStackExchange


text:
Q: Custom Gridview getitemid() does not return right row_id I am using custom GridView inside ScrollView. I know it is not the right way. I do not have any other way to accomplished my app layout.
I am trying to get item id == row_id of database in GridView but it does not return right id. Instead of giving row_id it gives me position id of item that does not match with database row_id
I know position id is row_id in Adapter, I do not know why id is not matching with database.
Here is GridView I used on layout
 <info.androidhive.slidingmenu.MyGridView
    android:id="@+id/gridview11"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:columnWidth="278dp"
    android:numColumns="2"
    android:verticalSpacing="2dp"
    android:horizontalSpacing="0dp"
    android:stretchMode="columnWidth"
    android:gravity="center"
    android:isScrollContainer="false"
    android:focusable="false"
    android:focusableInTouchMode="false"
 />

Here is Custom MyGridview code. I used this from Github
import android.content.Context;
import android.util.AttributeSet;
import android.view.ViewGroup;
import android.widget.GridView;

/**
 * ScrollViewの中のGridViewでも高さを可変にする<br>
 * https://stackoverflow.com/questions/8481844/gridview-height-gets-cut
 */
public class MyGridView extends GridView
{

    boolean expanded = false;

    public MyGridView(Context context)
    {
        super(context);
    }

    public MyGridView(Context context, AttributeSet attrs)
    {
        super(context, attrs);
    }

    public MyGridView(Context context, AttributeSet attrs,
                                    int defStyle)
    {
        super(context, attrs, defStyle);
    }

    public boolean isExpanded()
    {
        return expanded;
    }

    @Override
    public void onMeasure(int widthMeasureSpec, int heightMeasureSpec)
    {
        // HACK! TAKE THAT ANDROID!
        if (isExpanded())
        {
            // Calculate entire height by providing a very large height hint.
            // View.MEASURED_SIZE_MASK represents the largest height possible.
            int expandSpec = MeasureSpec.makeMeasureSpec(MEASURED_SIZE_MASK,
                    MeasureSpec.AT_MOST);
            super.onMeasure(widthMeasureSpec, expandSpec);

            ViewGroup.LayoutParams params = getLayoutParams();
            params.height = getMeasuredHeight();
        }
        else
        {
            super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        }
    }

    public void setExpanded(boolean expanded)
    {
        this.expanded = expanded;
    }
}

Finally here is onlcikListener code that does not work properly
 try {
            // OnClick

            best_product_gridview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                    //get position index of item here.

                    String indexid = String.valueOf(position);
                    Log.d("Index of Selected ", indexid);

                    // calling function
                     globalVariable.product_id =  position;
                    ((MainActivity)getActivity()).product();

                }
            });

    }
    catch (Exception e)
    {
      Log.d("Error BestPrduct View","" + e);
    }

Here is Adapter class
package info.androidhive.slidingmenu.AdpaterClass;

import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.squareup.picasso.Picasso;

import java.util.ArrayList;
import java.util.HashMap;

import info.androidhive.slidingmenu.R;
import info.androidhive.slidingmenu.library.Function_List;
import info.androidhive.slidingmenu.library.Global_JsonTags;
import info.androidhive.slidingmenu.library.Global_Variable;

/**
 * Created by clint19 on 1/21/2016.
 */
public class Best_Product extends BaseAdapter {
    View gridView;
    private Context context;
  /*  private DisplayImageOptions options;*/

    private LayoutInflater inflater;

    // josn vaules from json file library
    Global_JsonTags jsontags = new Global_JsonTags();
    Function_List lib_function =  new Function_List();
    Global_Variable globalVariable = new Global_Variable();
    private ArrayList<HashMap<String, String>> MyArr = new ArrayList<HashMap<String, String>>();

    public Best_Product(Context c,ArrayList<HashMap<String, String>> json_value) {
        // TODO Auto-generated method stub
        context = c;
        MyArr = json_value;

    }

    public int getCount() {
        // TODO Auto-generated method stub
        Log.d("size of item", "" + MyArr.size());
        return MyArr.size();
    }

    public Object getItem(int position) {
        // TODO Auto-generated method stub
        return position;
    }

    public long getItemId(int position) {
        // TODO Auto-generated method stub
        return position;

    }

    public View getView(int position, View convertView, ViewGroup parent) {
        final ViewHolder holder;
        View view = convertView;
        TextView product_name;
        TextView product_price;
        ImageView imageView;
        LayoutInflater inflater = (LayoutInflater) context
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

        View gridView;
        if (view == null) {
            view = new View(context);
            view = inflater.inflate(R.layout.home_best_collection, parent, false);
            holder = new ViewHolder();
            assert view != null;
            imageView = (ImageView) view.findViewById(R.id.imageView26);
           // holder.imageView = (ImageView) view.findViewById(R.id.imageView26);
            holder.progressBar = (ProgressBar) view.findViewById(R.id.progress);
            product_name = (TextView) view.findViewById(R.id.textView21);
            product_price = (TextView) view.findViewById(R.id.textView23);

            String name = MyArr.get(position).get("product_name");
            int namelength = name.length();
            if(namelength >= 33)
            {
                product_name.setText(MyArr.get(position).get("product_name").substring(0, 29) + "...");
            }
            else{product_name.setText(MyArr.get(position).get("product_name"));}
            product_price.setText(MyArr.get(position).get("product_price"));
            String product_status = MyArr.get(position).get("product_status");

            if(product_status.equals("false"))
            {

                Button add_to_cart = (Button) view.findViewById(R.id.add_to_cart1);
                add_to_cart.setVisibility(View.GONE);
                View background_height = (View) view.findViewById(R.id.bestproduct1);
            }
            else
            {
                Button add_to_cart = (Button) view.findViewById(R.id.add_to_cart1);
                add_to_cart.setVisibility(View.VISIBLE);
            }
            Log.d("setting up text", "setting up text");

            Picasso.with(context)
                    .load(MyArr.get(position).get("product_image"))
                    .placeholder(R.drawable.ic_stub) // optional
                    .error(R.drawable.ic_error)         // optional
                    .into(imageView);

            //view.setTag(holder);
        } else {
            holder = (ViewHolder) view.getTag();
        }

        return view;
    }

    static class ViewHolder {
        ImageView imageView;
        ProgressBar progressBar;
    }

}

I am trying to get id from 2 hour but no luck.
I followed these question How to add gridview setOnItemClickListener and Android gridview OnItemClickListener and this one Get ID of View in GridView
 and may more.
Can anyone tell me what is wrong.

A:
i m trying to get item id == row_id of database of GridView but it
  does not right id

That's because  you didn't properly override getItemId in your Adapter. Assuming that the dataset you feeding the adapter with, is made of bean classes, what you will have to do is to override getItemId(int position), which returns a long, and let it return the correct id. E.g.
@Override
public long getItemId(int position) {
   return getItem(position).getId();
}

the correct value is passed as last parameter, long id, in onItemClick.
If you are subclassing the CursorAdapter(or one its concrete implementations), and you should, since you have a cursor based solution,
you don't need to override it. The  CursorAdapter already returns value of the _id columns of the cursor at position.
Edit
@Override
public long getItemId(int position) {
   HashMap<String, String> mapAtPostion = MyArr.get(position);
   return Long.valueOf(mapAtPostion.get("product_id"));
}

A: You are getting position of the item because that is what you are returning from your method getItemId. You need to return the database row_id from that method.
Change your method like this
@Override
public long getItemId(int position) {
   return Long.valueOf(MyArr.get(position).get("product_id"));
}

A: @Override
public long getItemId(int position) {

    return position;
}

CustmeAdapter Example
public class CustomAdapter extends BaseAdapter{

String [] result;
Context context;
int [] imageId;
private static LayoutInflater inflater=null;
public CustomAdapter(MainActivity mainActivity, String[] prgmNameList, int[] prgmImages) {
    // TODO Auto-generated constructor stub
    result=prgmNameList;
    context=mainActivity;
    imageId=prgmImages;
     inflater = ( LayoutInflater )context.
             getSystemService(Context.LAYOUT_INFLATER_SERVICE);

}

@Override
public int getCount() {
    // TODO Auto-generated method stub
    return result.length;
}

@Override
public Object getItem(int position) {
    // TODO Auto-generated method stub
    return position;
}

@Override
public long getItemId(int position) {
    // TODO Auto-generated method stub
    return position;
}

public class Holder
{
    TextView tv;
    ImageView img;
}
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
    // TODO Auto-generated method stub
    Holder holder=new Holder();
    View rowView;

         rowView = inflater.inflate(R.layout.program_list, null);
         holder.tv=(TextView) rowView.findViewById(R.id.textView1);
         holder.img=(ImageView) rowView.findViewById(R.id.imageView1);

     holder.tv.setText(result[position]);
     holder.img.setImageResource(imageId[position]);

     rowView.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            Toast.makeText(context, "You Clicked "+result[position], Toast.LENGTH_LONG).show();
        }
    });

    return rowView;
}

}


text:
Q: JUnit assertTrue is ambiguous for two strings, and test case fails for doubles I'm trying to write a JUnit test to confirm that my variables are saving correctly. I'm having trouble passing the test cases for doubles and strings
@Test
public void testConstructor() {
    Flight test = new Flight(200, "Canada", "Mexico", "03/02/99 7:50 pm", 500, 10);
    assertEquals(200, test.flightNumber);
    assertEquals(10, test.capacity);
    assertEquals(Double.valueOf(500), test.originalPrice);

    String a ="Canada";
    String b = test.origin;
    assertTrue(a.equals(b));
}

My double case seems to be failing despite the fact that both values clearly should be 500, and I getting this error for assertTrue:

both method assertTrue(boolean) in Assert and method
assertTrue(Boolean) in assertions match

I don't even know why it's saying boolean, shouldn't they be strings?
This is the code the test case is testing:
public int flightNumber, capacity, numberOfSeatsLeft;
public double originalPrice;
public String origin, destination, departureTime;

public Flight(int flightNumber, String origin, String destination, String departureTime, double originalPrice, int capacity) {
    if (destination.equals(origin)) {
        throw new IllegalArgumentException("Already at destination");
    }
    this.origin=origin;
    this.destination=destination;
    this.departureTime=departureTime;
    this.originalPrice=originalPrice;
    this.flightNumber=flightNumber;
    this.capacity=capacity;
}

A: You are trying to use assertEquals(Double, double), a wrapper class and it's corresponding primitive counterpart, and there is no such method in junit. It's caused by your field originalPrice being double, but Double.valueOf(500) returns a Double. You should either use assertEquals(double, double), but it's deprecated, or assertEquals(Object, Object). You can call it like this:
assertEquals(Double.valueOf(500), Double.valueOf(test.originalPrice));


text:
Q: Reference 2 rows on same column/table, from a different table I'm working on a stat tracking webpage for a virtual hockey league on Xbox. I have my basic table layout setup, but I am struggling with how to create the query that will allow me to show the schedule. Below is my basic table layout, and what I'd like to do is have it display something like:
Game 1:
 New York vs Chicago
 Detroit vs Boston
Game 2:
 Boston vs New York
 Chicago vs Detroit
SELECT homeTeam.name AS HOME_TEAMNAME
FROM GameSchedule Sched

INNER JOIN GameStats GameStatsHome
ON Sched.ID = GameStatsHome.gameSchedule_ID
AND Sched.homeTeam_ID = GameStatsHome.team_ID

INNER JOIN Team homeTeam
ON homeTeam.ID = gameStatsHome.team_ID

I realize where I'm running into the problem is trying to pull the Team.name for both GameSchedule.awayTeam_ID and GameSchedule.homeTeam_ID. But I haven't been able to figure out how to do this. I feel like I'm close..but then again, I have no idea what I'm doing, and have spent about 3 days trying to figure this one query out. I think if someone can point me in the right direction, I should be good for the rest of what I need... Any help would be greatly appreciated.
Table: Team
-----------------------------------------------------------
| ID | name       | abbreviation | conference | division |
-----------------------------------------------------------
|  1  | New York  |      TMA     |      1     |     1    |
|  2  | Chicago   |      TMB     |      1     |     1    |
|  3  | Detroit   |      TMC     |      1     |     1    |
|  4  | Boston    |      TMD     |      1     |     1    |
-----------------------------------------------------------

Table: GameSchedule
------------------------------------------------
| ID | awayTeam_ID | homeTeam_ID | gameTime_ID |
------------------------------------------------
| 1  |     1       |      2      |      1      |
| 2  |     3       |      4      |      1      |
| 3  |     4       |      1      |      2      |
| 4  |     2       |      3      |      2      |
------------------------------------------------

Table: GameStats
------------------------------------------
| ID | gameSchedule_ID | team_ID | goals |
------------------------------------------
| 1  |        1        |    1    |   5   |
| 2  |        1        |    2    |   3   |
| 3  |        2        |    3    |   6   |
| 4  |        2        |    4    |   1   |
| 5  |        3        |    1    |   2   |
| 6  |        3        |    4    |   5   |
------------------------------------------

A: This will provide you both names
SELECT
    away.Name as AwayTeam,
    home.Name as HomeTeam
FROM
    Game_Schedule gs
    JOIN Team away ON t.ID = gs.AwayTeam_ID
    JOIN Team home ON t.ID = gs.HomeTeam_ID

You can do whatever you want to in these joins!


text:
Q: No callback in htcaptcha implementation I am trying to automate the login on the website called stake.us. They had implemented a hcaptcha to stop bots from logging into the website. I am using 2captcha service to get the solution for the captcha. Now the verification code that is supplied by the 2captcha needs to be entered into two hidden fields and than we either need to click a submit button or there should be a callback. The submit button is not there, so they are using a callback here. I researched the network tab, however I was not able to identify the callback function.
Things I tried till now.

*

*Checked the network tab thoroughly to identify the callback request.

*Tried to find similar question and check for any possible solution on stack overflow or any other website

*Looked up hcaptcha documentation. However, I was not able to understand anything significant.

Important Links:

*

*hcaptcha docs

*stack overflow similar question 1

*stack overflow similar question 2

*A video on how to identify the callback

*Gist to override the render method to make our own callback
If anyone can help me in finding the callback function. Please let me know. I will really appreciate your help.

A: I tried to lookup your site, but do not see the Hcaptcha on the site. So its probably hidden or exists on a subsequent page. Hcaptcha implementation varies from site to site so without the pagesource and the Iframes it difficult to figure the correct callback .. if at all.
You are on the correct track on the network tab, Although clear out any current transactions first and then solve the captcha manually. Then check the Network tab for something like a 404 and it should have a PAYLOAD. Then you can write your function to encapsulate that payload and send it across.  I provided 3 solutions for a similar Hcaptcha issue Selenium (Python) Webdriver can't access a website . Hopefully one of the solutions work. Good Luck

A: They pass a solved captcha token using GraphQL. Look for a POST-request containing the "RequestLoginUser" operation.
Here is a working example of a Python solution (sorry not JS):

import httpx
from unicaps import CaptchaSolvingService, CaptchaSolver

HEADERS = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:104.0) Gecko/20100101 Firefox/104.0'
}

# GraphQL data for the RequestLoginUser operation
data = {
    "query": "mutation RequestLoginUser($name: String, $email: String, $password: String!, "
             "$captcha: String!) {\n  requestLoginUser(\n    name: $name\n    email: $email\n    "
             "password: $password\n    captcha: $captcha\n  ) {\n    loginToken\n    "
             "hasTfaEnabled\n    requiresLoginCode\n    user {\n      id\n      name\n      "
             "__typename\n    }\n    __typename\n  }\n}\n",
    "operationName": "RequestLoginUser",
    "variables": {
        "email":"<<YOUR_EMAIL_HERE>>",
        "password":"<<YOUR_PASSWORD>>",
        "captcha":"<<WE WILL SOLVE HCAPTCHA AND PLACE TOKEN HERE>>"
    }
}

# init solver and solve hCaptcha
solver = CaptchaSolver(CaptchaSolvingService.TWOCAPTCHA, '<<YOUR_API_KEY_HERE>>')
solved = solver.solve_hcaptcha(
    site_key='08a8899d-4c15-47cc-b7a6-d287258d8e1c',
    page_url='https://stake.us/?tab=login'
)

# put the solved CAPTCHA token into the payload data
data["variables"]["captcha"] = solved.solution.token

# log in
response = httpx.post(
    'https://api.stake.us/graphql',
    headers=HEADERS,
    json=data
)

# the response JSON would contain loginToken that we must use in further requests
print(response.json())


text:
Q: Saving list of lists into another list of list but with changes in python i have a list like this one :
list1= [['Sarah', 55, 7, 'x'], ['John', 24, 8, 'x']]

and i want to copy it to another list but keeping it as a matrix like that :
list2= [['Sarah', 55.0, 7.0], ['John', 24.0, 8.0]]

so what i want to do is making every number a float and deleting the last element of every sub-list

A: You could use a nested list comprehension, casting  to float all strings that satisfy str.isnumeric:
[[float(j) if str(j).isnumeric() else j for j in i] for *i, _ in list1]
# [['Sarah', 55.0, 7.0], ['John', 24.0, 8.0]]

A: You can use a simple list comprehension here:
[[name, *map(float, i)] for name, i, _ in list1]

Results:
[['Sarah', 55.0, 7.0], ['John', 24.0, 8.0]]

A: list1 = [['Sarah', 55, 7, 'x'], ['John', 24, 8, 'x']]

list2 = [[] for x in range(len(list1))]

x = 0

for rp in range(len(list1)):
    #len(list1[rp])-1 for not count the last element for each array
    for tp in range(len(list1[rp])-1):
        #check the type of item string
        if "str" in str(type(list1[rp][tp])):
            list2[x].append(list1[rp][tp])
        #check the type of item int
        elif "int" in str(type(list1[rp][tp])):
            #convert the item int to float
            td = float(list1[rp][tp])
            list2[x].append(td)

    x += 1

print("List 1 :" + str(list1))
print("List 2 :" + str(list2))

#OUTPUT
#List 1 :[['Sarah', 55, 7, 'x'], ['John', 24, 8, 'x']]
#List 2 :[['Sarah', 55.0, 7.0], ['John', 24.0, 8.0]]

A: You could use unpacking to make the conversion clearer:
list2 = [ [name,float(n1),float(n2)] for name,n1,n2,_ in list1 ]


text:
Q: Запрос: Обновить поле в зависимости другого поля Почему-то не хочет работать запрос:
UPDATE table SET field1 = IF(field2 = 0, 1, field1) WHERE id = ' . $id;

Правильно ли я его построил? Нужно в зависимости от значения поля записать в него другое значение или оставить прежнее.

A: Может так?
UPDATE table
   SET field1 = CASE
  WHEN field2 = 0 THEN 1
  ELSE field1
END

A: SELECT CASE <variable> WHEN <value>      THEN <returnvalue>
                       WHEN <othervalue> THEN <returnthis>
                                     ELSE <returndefaultcase>
       END
FROM <table>

Подстройте под себя.

A: Мне кажется, что в запросе просто не хватает одной буковки:
UPDATE table SET field1 = IIF(field2 = 0, 1, field1) WHERE id = ' . $id;

Функция IIF


text:
Q: How can I get only the first line in a file that starts with "1." followed by any character except a number? I have this file
1.1some text
2.some text
1.line I need

How can I print only the first line in a file that start with "1." followed by any character except a number?
I expect this:
1.line I need

my code is this
q=$(grep "^[0-9].[a-z]"  "file")
echo $q

Thank you

A: With your shown samples, please try following grep code. Simple explanation would be: Using grep's m1 option to print only first match and exit from program then in main program mentioning regex to match lines that start from 1. followed by a non-digit character, if match is found then print the line.
grep -m1 '^1\.[^0-9]'  Input_file

A:
How can I print only the first line in a file that start with 1.followed by any character except a number?

Using sed, you can use:
sed '/^1\.[^0-9]/!d;q' file

1.line I need

Details:

*

*-n: Suppresses regular output

*/^1\.[^0-9]/: Search for a line starting with 1 followed by a dot and a non-digit

*!d: Deletes all non-matching lines

*q: Quits further processing

Similar solution in awk would be:
awk '/^1\.[^0-9]/{print; exit}' file


text:
Q: Large data retrieval from IBM Domino I am trying to collect account data and group data from IBM Domino v9.0.
The code that I wrote  for collecting data used the lotus.domino.View API. The code works fine for a small data set, I ran the code for 40 users and it was fine. When I ran the code to extract the data for 10k users, it takes roughly around 3-4 hrs to extract the data, which is not acceptable.
Can you please suggest me some other API with which we can retrieve data at much faster rate?
The code that i am currently using is as follows:
private static void testUserDataRetrieval(String host, String userName, String password) throws Exception{
    Session s = NotesFactory.createSession(host, userName, password);
    Database db = s.getDatabase(s.getServerName(), "names");
    File outFile = new File("C:\\Users\\vishva\\Desktop\\dominoExtract.txt");
    FileWriter writer = new FileWriter(outFile);
    View view = db.getView("($Users)");
    ViewEntryCollection entryCollection = view.getAllEntries();
    writer.write("\n--------------------------------- Printing data for view:"+view.getName()+"("+view.getEntryCount()+")--------------------------------------------");
    Vector<Object> columnNames = view.getColumnNames();
    for(int i = 0; i< entryCollection.getCount(); i++){
        ViewEntry entry = entryCollection.getNextEntry();
        if(entry == null) continue;
        Vector<Object> colValues = entry.getColumnValues();
        for(int j = 0; j < columnNames.size(); j++)
            writer.write("\n"+columnNames.get(j)+":"+colValues.get(j));
        writer.write("\n*****************************************");
    }
    writer.flush();
    writer.close();
}

Please let me know which other API should I use to increase the speed for data retrieval?

A: First of all: You read the count of the collection in every run of your for- loop. That makes it very slow. The for- loop is not necessary at all. Second: You never recycle the objects. That is MANDATORY when working with domino objects, as otherwise your code will eat up the memory faster than you can think:
private static void testUserDataRetrieval(String host, String userName, String password) throws Exception{
  Session s = NotesFactory.createSession(host, userName, password);
  Database db = s.getDatabase(s.getServerName(), "names");
  File outFile = new File("C:\\Users\\vishva\\Desktop\\dominoExtract.txt");
  FileWriter writer = new FileWriter(outFile);
  View view = db.getView("($Users)");
  ViewEntryCollection entryCollection = view.getAllEntries();
  writer.write("\n--------------------------------- Printing data for view:"+view.getName()+"("+view.getEntryCount()+")--------------------------------------------");
  Vector<Object> columnNames = view.getColumnNames();
  ViewEntry entry = entryCollection.getFirstEntry();
  ViewEntry entryNext;
  while(entry != null) {
    Vector<Object> colValues = entry.getColumnValues();
    for(int j = 0; j < columnNames.size(); j++)
        writer.write("\n"+columnNames.get(j)+":"+colValues.get(j));
    writer.write("\n*****************************************");
    entryNext = entryCollection.getNextEntry();
    entry.recycle();
    entry = entryNext ;
  }

writer.flush();
writer.close();

}

A: By default, your View object has the isAutoUpdate property set to true.  That means it is synchronizing with any changes that are occurring on the back end instead of just giving you a one-time snapshot.  Add this:
view.setAutoUpdate(false);

Also, you should probably investigate using the ViewNavigator class. See here for an article detailing performance improvements in this class as of Domino 8.5.2. It's written by the lead developer for the classes.  Also see this blog post for a lot of interesting detail.

A: Thanks Everyone for their input.
For retrieving the users i tried out the LDAP API later on, and it worked like charm. I was able to retrieve 10k accounts in 23 seconds, much acceptable. The code that i used was as follows
    private void extractDominoDataViaLdap(){
    String [] args = new String[]{"192.168.21.156","Administrator","password","","C:\\Users\\vishva\\Desktop"};
    String server = args[0];
    String userName = args[1];
    String password = args[2];
    String baseDN = args[3];
    String fileLocation = args[4];
    // Set up environment for creating initial context
    Hashtable<String, Object> env = new Hashtable<String, Object>(11);
    env.put(Context.INITIAL_CONTEXT_FACTORY,"com.sun.jndi.ldap.LdapCtxFactory");
    env.put(Context.PROVIDER_URL, "ldap://"+server+":389");

    long time = System.currentTimeMillis();
    // Authenticate as S. User and password "mysecret"
    env.put(Context.SECURITY_AUTHENTICATION, "simple");
    env.put(Context.SECURITY_PRINCIPAL, userName);
    env.put(Context.SECURITY_CREDENTIALS, password);
    FileWriter writer = null;
    BufferedWriter out = null;
    try {
        DirContext ctx = new InitialDirContext(env);
        //fetching user data
        // Create the search controls
        SearchControls searchCtls = new SearchControls();
        // Specify the attributes to return
        String returnedAtts[] = {"FullName","dn","displayname","givenName","sn","location","mail","mailfile","mailserver"};
        searchCtls.setReturningAttributes(returnedAtts);
        // Specify the search scope
        searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);
        searchCtls.setCountLimit(0);
        // specify the LDAP search filter
        String searchFilter = "objectClass=inetOrgPerson";

        // Specify the Base for the search
        String searchBase = baseDN;

        // Search for objects using the filter
        NamingEnumeration<SearchResult> answer = ctx.search(searchBase,searchFilter, searchCtls);

        writer = new FileWriter(fileLocation+"\\users.csv");
        out = new BufferedWriter(writer);
        for(String attr : returnedAtts)
            out.write(attr+",");
        out.write("\n");
        int count = 0;
        // Loop through the search results
        while (answer.hasMoreElements()) {
            ++count;
            SearchResult sr = (SearchResult) answer.next();
            Attributes attrs = sr.getAttributes();
            StringBuilder sb = new StringBuilder();
            for(String attr : returnedAtts)
                sb.append("\""+((attrs.get(attr) != null)?attrs.get(attr).get():"")+"\"").append(",");
            out.write(sb.toString()+"\n");
            out.flush();
        }
        System.out.println("# of users returned: "+count);
        out.close();
        writer.close();
    }
}


text:
Q: login instagram with php curl I want to login this page with php:
But I get error when I try to login with php.
When I try to login below code is always changing. So I cannot login.
The code is:
 <input type="hidden" name="csrfmiddlewaretoken" value="728a44ea6f15dee51406b0c82be3a03b"/>

Thanks for advance help

A: Obviously Instagram is protected against cross-site request forgery. You can read all about this attack here.
Actually the Instagram guys do not want you to submit the login form without showing it first. That is what csrfmiddlewaretoken is for: They give it to you (random value) when the form is displayed and when you submit it, they check whether you returned the one they gave you. See the OWASP cross-site request forgery prevention cheat sheet.
So basically what you have to do is request the login form, get the token from it and then log in in a second request and include that token in it.
(Maybe they do some double checking there; in this case you'll have to send the token twice: both in your post data and as a cookie.)

A: You must open the page with the form and read the value of "csrfmiddlewaretoken" into a var (with a regex for example).
You also have to store the session cookie (curl has a method for storing cookies in a container file, or you can do it yourself by parsing the answer headers and storing the cookie value to set it in you request header for later requests).
Then you can set the "csrfmiddlewaretoken" in your login request (which needs to send the session cookie).


text:
Q: How can I move a control in Delphi at runtime using the keyboard? I added an option to move a control at runtime with the mouse, based on this and it's working well.
But I was trying to find some code to do the same trick but with the keyboard  -- pretty much like moving a component at design time (only moving).
How can this be achieved?

A: This is very easy if you know how to do the different parts of it.

*

*Create a new VCL application.

*Drop a TShape on the form.

*Add the following OnKeyDown event handler to the form:
procedure TForm1.FormKeyDown(Sender: TObject; var Key: Word;
  Shift: TShiftState);
const
  D = 2;
begin
  case Key of
    VK_UP:
      Shape1.Top := Shape1.Top - D;
    VK_DOWN:
      Shape1.Top := Shape1.Top + D;
    VK_LEFT:
      Shape1.Left := Shape1.Left - D;
    VK_RIGHT:
      Shape1.Left := Shape1.Left + D;
  end;
end;

*Run the application.

This being said, however:
Creating animations by moving controls on a form is wrong.
Instead, if you want to create animations, the right thing to do is to draw them manually using GDI, GDI+, OpenGL, or DirectX/Direct2D. Here is my standard example of how to do this.


text:
Q: How to remove any number characters from a string This is my current attempt which is not working:
  const word = "abcd123";
  const filteredNum = word.split("").filter((e) => Number(e) !== NaN);
  console.log(filteredNum);

A: Try this:

const word = "abcd123";
const result = word.match(/\d+/)[0];

console.log(result);

A: using isNan() function

    let word = "abcd123";
    let filteredNum = word.split("").filter((e) => !isNaN(e));
    console.log(filteredNum);
    console.log(filteredNum.join(""))


text:
Q: ICMP echos and replies arrive, but no ping (kvm hosts and guests) This are the steps I took building my setup:

*

*I have 2 computers (both x86 running Ubuntu 14.04 LTS).

*I install 2 Virtual Machines (VMs) - one on each machine.

*Both VMs are Ubuntu Server 14.04 LTS.

*On one x86 I run one VM using kvm. On the other x86 I run the other VM using VirtualBox.

*I connect both x86s through a Router.

====================================================
(ubuntu1)[KVM](X86,1)------{Router}------(X86,2)[VirtualBox](ubuntu2)
====================================================
Now, I allow IPv4 forwarding on all 4 machines (change on /etc/sysctl.conf, and using sysctl -p), and set all 4 machines to have a single NIC (eth0), and set it in /etc/network/interfaces to manual).
Next, I start by assigning addresses to the NICs of the two x86s , set default gateways and ping around. Everything works great. After that I assign an address to one VM (instead of the x86 on which this VM is running on). Again - works great. And finally - set an IP address to the second VM (again, instead of the x86 on which the second VM is running on).
At a certain point - ping doesn't work. When I check the packets, I can see that one VM answers and the other does not. I checked this in the following ways:

*

*I choose one VM (let's say ubuntu1) and I ping and tcpdump on this machine (ping [IP_ADDRESS_ubuntu2] & followed by tcpdump -i eth0)

*Connect the wire between the x86s to a hub (duplicating the packets) and wireshark-ing it.

The result is always the same - I can see one VM registers echos of ICMP packets to the other (this is the one that replies) and the other VM registers echos and replies from the other VM.
So - ICMP packets actually arrive the machine, but ping shows nothing!
Here's an example of the last setup:
====================================================
(55.55.55.55)[KVM]-----------{Router}-----------[VirtualBox](22.22.22.22)
====================================================
Running ping and tcpdump on 55.55.55.55:
root@55.55.55.55:/home# ping 22.22.22.22 &
root@55.55.55.55:/home# PING 22.22.22.22 (22.22.22.22) 56(84) bytes of data.
root@55.55.55.54:/home# tcpdump -i eth0
tcpdump: verbose output suppressed, use -v or -vv for full protocol decode
listening on eth0, link-type EN10MB (Ethernet), capture size 65535 bytes
07:10:11.758872 IP 55.55.55.55 > 22.22.22.22: ICMP echo request, id 5499, seq 6, length 64
07:10:12.758785 IP 55.55.55.55 > 22.22.22.22: ICMP echo request, id 5499, seq 7, length 64
07:10:13.766994 IP 55.55.55.55 > 22.22.22.22: ICMP echo request, id 5499, seq 8, length 64
07:10:14.767637 IP 55.55.55.55 > 22.22.22.22: ICMP echo request, id 5499, seq 9, length 64

Running ping and tcpdump on 22.22.22.22:
root@22.22.22.22:/home# ping 55.55.55.55 &
root@22.22.22.22:/home# PING 55.55.55.55 (55.55.55.55) 56(84) bytes of data.
root@22.22.22.22:/home# tcpdump -i eth0
tcpdump: verbose output suppressed, use -v or -vv for full protocol decode
listening on eth0, link-type EN10MB (Ethernet), capture size 262144 bytes
15:58:01.883915 IP 22.22.22.22 > 55.55.55.55: ICMP echo request, id 4099, seq 8, length 64
15:58:01.884390 IP 55.55.55.55 > 22.22.22.22: ICMP echo reply, id 4099, seq 8, length 64
15:58:02.885795 IP 22.22.22.22 > 55.55.55.55: ICMP echo request, id 4099, seq 9, length 64
15:58:02.886298 IP 55.55.55.55 > 22.22.22.22: ICMP echo reply, id 4099, seq 9, length 64

Note, though, that the machine "knows" where the other machine is:
root@55.55.55.55:/home/rad# ip route get 22.22.22.22
22.22.22.22 via 55.55.55.1 dev eth2  src 55.55.55.55
    cache

Ideas?
UPDATE 1
output of various commands:
root@55.55.55.55:/home# iptables -S
-P INPUT ACCEPT
-P FORWARD ACCEPT
-P OUTPUT ACCEPT

root@55.55.55.55:/home# iptables -t nat -S
-P PREROUTING ACCEPT
-P INPUT ACCEPT
-P OUTPUT ACCEPT
-P POSTROUTING ACCEPT

root@55.55.55.55:/home# netstat -rn
Kernel IP routing table
Destination     Gateway         Genmask         Flags   MSS Window  irtt Iface
0.0.0.0         55.55.55.1      0.0.0.0         UG        0 0          0 eth0
55.55.55.0      0.0.0.0         255.255.255.0   U         0 0          0 eth0

UPDATE 2
A change of an IP address on one side (55.55.55.55 --> 55.55.55.54) gets an ICMP reply - meaning ping works.
A change of an IP address on the other-side makes no difference.
root@55.55.55.55:/home/rad# ifconfig eth0 55.55.55.54/24
root@55.55.55.55:/home/rad# ping 22.22.22.22
PING 22.22.22.22 (22.22.22.22) 56(84) bytes of data.
64 bytes from 22.22.22.22: icmp_seq=1 ttl=63 time=1.05 ms
64 bytes from 22.22.22.22: icmp_seq=2 ttl=63 time=0.568 ms
64 bytes from 22.22.22.22: icmp_seq=3 ttl=63 time=0.692 ms
64 bytes from 22.22.22.22: icmp_seq=4 ttl=63 time=0.597 ms

switching back to the 55.55.55.55 IP address, denies the ICMP reply again.
Directions
Several directions I'm thinking in, but still haven't found an answer:

*

*the HW address of a neighbor machine is listed somewhere and associated with an IP address, preventing the packets from being routed to the correct location

*the arp cache values Tresh1, Tresh2 and Tresh3 are not being set correctly, preventing the garbage collection of iproute2 from cleaning the registries - thus enabling the arp cache to be replaced

*some kernel feature related to routing dumps the packets, confusing between the host and the guest machines


text:
Q: How to express the anti-commutator in the form of a density operator?
$
\newcommand{\ket}[1]{|{#1}\rangle}
\newcommand{\bra}[1]{\langle{#1}|}
\newcommand{\braket}[2]{\langle{#1}|{#2}\rangle}
\newcommand{\acomm}[2]{\left\{#1,#2\right\}}
$Let $\{ \ket{1} \ket{1} \ket{2} ... \}$ be a complete set of orthonormal basis states for an infinite dimensional state space. Let $\hat{A} \ket{n} = n\ket{n-1}$ and $\hat{B} \ket{n} = \ket{n+1}$, how to express the anti-commutator $\acomm{\hat{A}}{\hat{B}} = \hat{A}\hat{B}+\hat{B}\hat{A}$ in the form $$\sum_{n,m=0}^{\infty}\lambda_{nm}\ket{n}\bra{m}?$$

I know that I need to look for an expression, whose effect is the same as
\begin{align}
\bra{m}\acomm{\hat{A}}{\hat{B}}\ket{n}
=& \bra{m}\hat{A}\hat{B} + \hat{B}\hat{A}\ket{n} \nonumber\\
=& \bra{m} (\hat{A}\ket{n+1} + \hat{B}n\ket{n-1}) \nonumber\\
=& \bra{m}((n+1)\ket{n} + n\ket{n}) \nonumber\\
=& (2n+1)\braket{m}{n} \nonumber
.
\end{align}
But I feel very confused about how to express the anti-commutator in that specific form.

A: You have almost completed the job since you have computed the desired matrix elements. Any operator $O$ can be written as
$$O = \sum_{m,n} O_{m,n} |m\rangle \langle n| \,, \mbox{ where} \quad O_{mn} = \langle m|O|n\rangle.$$
So, in your case as you have computed the answer is
$$\{A,B\} = \sum_{m,n} (2n+1)\delta_{m,n} |m\rangle \langle n| = \sum_{n} (2n+1)|n\rangle \langle n|.$$


text:
Q: How do I get my devices to recognize the correct router and IP subnet? The Basics
Our home has a DSL line coming in to a modem on the second floor. A line then goes down to a switch/hub and through to our downstairs living room where a wireless router is set up. Up until last week, we received reliable 3Mbps Internet in this fashion to our devices (mostly iOS devices).
We also have DirecTV's whole-home DVR, which as I understand it means they linked all the DirecTV boxes together with Ethernet and also connected one DirecTV box to the wireless router.
The Events
The issue began when we added a new MacBook Air to the mix, which could not connect to the Internet. When everyone else had IP addresses in the 173.191.X.X range, this MBA kept giving itself a 166.X.X.X address and reported itself as "able to connect to the Internet" when it surely could not. Even giving it a static IP would not work. We had to renew the DHCP license until it randomly flipped to a 173.191.X.X IP address.
At the same time, we tried to upgrade our modem since it's about 7+ years old. To our great misfortune, the new modem seemed unable to get a PPP connection from the ISP. We switched back to the old modem, and now it seems like a free-for-all with our devices.
How My MacBook Pro reacts
My MBP, when I turn off/on wifi, will sometimes land me with a 192.168.X.X IP address, which I believe is a NAT-like 'local' IP address. My MBP will show me the router's IP and with that information I can connect to the web interface of my modem (Paradyne). I can look at the settings for a little bit, but eventually (30 seconds) I am forcibly redirected to my router's (Netgear) web interface. I can make changes here as well.
Whether or not I have Internet connectivity at this point seems random. If I renew my DHCP lease, it will give me another 192.168.X.X IP address for one second, at which time it disappears and I am given a 173.191.X.X IP address and Internet access (yay). This is the only device which can reliably get an Internet connection. My MacBook has been unable to connect through a wired connection to the modem or the router during this whole time.
How all the other devices react
None of the other devices can reliably connect to the network. If any of the devices receive the 192.168.X.X IP address, they cannot connect at all. If they receive the 173.191.X.X IP address, they can connect - problem is that has happened only twice, once through static addressing and once on a random DHCP lease renewal.
On top of this, some of the devices are experiencing the same issue as the MacBook Air - they're getting a third type of IP address of 166.X.X.X. None of the devices we're working with besides my MacBook Pro have an Ethernet port, so I don't know if a wired connection works for them.
The Kicker and my specific question
The funny part is that I unplugged the line from the modem to the router and my MacBook still connects. It even shows on the router that it is receiving no Internet connection. This makes me believe there's a direct line from modem to router via the DirecTV installation.
I have tried completely restarting from scratch with the modem and cycling power on the router. The router is about 4 years old.
What I want is for all the devices to recognize the 173.191.X.X IP address as the way to go, but I know this is strange because I can only access the web interfaces for my router and modem using 192.168.X.X.
Do I have multiple DHCP servers working against each other here? Is there a possible direct line from the router to the modem made by the DirecTV box links? How can I tell where these devices are receiving their IP addresses?
UPDATE, May 18 2014 I ran the 'ipconfig getpacket' on my MBP (with option en1 for wireless) and on the MBA (with option en0 for wireless, not sure why it's different) and got surprising information:
MacBook Pro (always connects)
yiaddr = 173.191.X.X //machine address
giaddr = 166.82.100.1 //gateway address
server_identifier (ip): 207.91.5.220 //DHCP server address
subnet_mask (ip): 255.255.254.0
router (ip_mult): {173.191.252.1}  // router address
domain_name_server (ip_mult): {207.91.X.X, 166.102.X.X}
domain_name (string): [companyA].net
MacBook Air (never connects)
yiaddr = 166.82.X.X
giaddr = 166.82.100.1
server_identifier (ip): 207.91.5.220
subnet_mask (ip): 255.255.255.0
router (ip_mult): {166.82.228.1}
domain_name_server (ip_mult): {207.91.X.X, 166.102.X.X}
domain_name (string): [companyA].net
So somehow the MBA knows who to connect to (domain_name) and has an ip address deriving from the gateway address. They both have the same DHCP server address, different subnet masks, different routers... What is the cause of this difference?
Update, May 21 2014
We now have Internet! I will post a solution when I figure out exactly what happened. We ended up removing everything and starting over outside where we first get the DSL line. we connected that to the modem, then directly to the router, and connected all machines with wifi successfully. Then step by step we added complexity in the form of walls and more wiring.
Right now it seems like the problem may have come from the "filter" the ISP put on our DSL line or from our hub/switch. I'll update again later.

A: I would expect 5 ethernet sockets on your router, one is the uplink, the other i'll call subnet ports. Four will be grouped or distinct from one other
Connect the modem directly to the uplink port on your router so the router gets the 173 address on the internet (be sure to remove that hub/switch between them that is causing the weird problem because every device races for the single external ip)
The mediabox should connect to a subnet port on the router. And the wifi base station too. The router can be the DHCP server, but the wifi base station too, and that could be the source of flapping problems. You would have the 192.168 subnet managed by the router on the wired/ethernet and let the wifi run on the 172.16 range. But if you can manage the ranges op the dhcp address pool then you can still create one subnet in 192.168.
Connect the uplink port of the hub/switch to one of the subnet ports of the router only if you need to wire more devices.
The mediabox could be a bridge and i would not expect al lot of config options.

A: UPDATE: Sorry this took me so long to get back to.
Apparently Our problem was with our ISP and with our modem. The ISP was not giving us the speeds we asked for.
On top of that (and the actual answer to the problem) was that, as @datasmid suggested, we had too much complexity and ended with multiple DHCP servers. The switch/hub was giving out ip addresses, as was our router.
Simplifying the problem by starting from the very beginning (literally outside, connecting the ISP link to our modem and that to our router), we got a connection for all devices.
To all those who will come here later: Simplify the problem. We took away the switch/hub, disconnected our DirecTV from the connection, and made sure we could see every wire. That helped us figure out that the modem our ISP sent us was not working.
We then got bunch of 192.x.x.x connections as we should have. The other issues of my MacBook Pro connection and others not all came from these central issues.


text:
Q: What is a mathematical definition of the Maxwellian spacetime? While this problem originated in physics, the question is purely mathematical. Because Maxwell's equations were not invariant under the Galilean transformation, Maxwell proposed his version of spacetime. It is as a 4D collection of points, such that:

*

*Between any two points $p(t, x, y, z)$ and $q(t', x', y', z')$ there is a definite temporal interval $T(p, q) = t' − t$.

*Between any two simultaneous points $p(t, x, y, z)$ and $q(t, x', y', z')$ there is a definite Euclidean distance
$$R(p,q) = \sqrt{(x' − x)^2 + (y' − y)^2 + (z' − z)^2}$$

*Any worldline $\gamma$ through the point $p$ has a definite twist $\Omega(γ, p)$.

As a result of the third condition, linear acceleration is not absolute like in the Galilean spacetime. There is not enough structure in
the Maxwellian spacetime to distinguish straight worldlines from curved
worldlines.
However, rotation is still absolute, because the third condition allows telling when a worldline is "twisted". For a worldline $\gamma$ and a point $p$ on $\gamma$, the absolute rotation of $\gamma$ w.r.t. $p$ is given by $\Omega(γ, p)$.

(Image and partial content credit: Jonathan Bain, NY University.)
Properties of the Maxwellian spacetime:

*

*No inertial frames (as opposed to many inertial frames in the Galilean spacetime).

*Velocity is relative.

*Acceleration is relative (as opposed to absolute in the Galilean spacetime).

*Rotation is absolute.

*Simultaneity is absolute.

The mathematical definition of the Galilean spacetime is a tuple $(\mathbb{R}^4,t_{ab},h^{ab},\nabla)$ where $t_{ab}$ (temporal metric) and $h^{ab}$ (spatial metric) are tensor fields and $\nabla$ is the coordinate derivative operator specifying the geodesic trajectories (Spacetime Structure).
A single metric does not work, because the speed of light is infinite, so time and space should be treated separately with the temporal metric:
$$t_{ab}=(\text{d}_a t)(\text{d}_b t)$$
and the spatial metric:
$$h^{ab}=\left(\dfrac{\partial}{\partial x}\right)^a\left(\dfrac{\partial}{\partial x}\right)^b+
\left(\dfrac{\partial}{\partial y}\right)^a\left(\dfrac{\partial}{\partial y}\right)^b+
\left(\dfrac{\partial}{\partial z}\right)^a\left(\dfrac{\partial}{\partial z}\right)^b$$
Finally, $\nabla$ on $\mathbb{R}^4$
is a unique flat derivative operator that for each coordinate $x^i$ satisfies:
$$\nabla_a\left(\dfrac{\partial}{\partial x^i}\right)^b=\mathbf{0}$$
In turn, the Newtonian spacetime is the same tuple with an additional structure $(\mathbb{R}^4,t_{ab},h^{ab},\nabla,\lambda^a)$ where $\lambda^a$ is a field that adds the preferred frame of rest:
$$\lambda^a=\left(\dfrac{\partial}{\partial t}\right)^a$$
What is a rigorous mathematical definition of the Maxwellian spacetime? Intuitively, it may be the same Galilean tuple, but with some additional structure (or a reduced structure) similar to how the Newtonian spacetime is created by adding $\lambda$ to the Galilean tuple. Thanks for your help!

A: Following your definition of a Galilean Spacetime, I will mostly rewrite what is found in https://arxiv.org/pdf/1707.02393.pdf. A Maxwellian spacetime is a tuple $(M,t_a,h^{ab},\Omega)$ where $M$ is a smooth manifold diffeomorphic to $\mathbb{R}^4$, $t_a$ is a temporal metric on $M$, $h^{ab}$ is a spatial metric on $M$, and $\Omega$ is a standard of rotation compatible with $t_a$ and $h^{ab}$. Further, the metric $h^{ab}$ is complete on spatial surfaces $\mathbb{R}^3_t$ foliated by $t:M\to \mathbb{R}$.
For any given $M$, we have a unique spatial derivative operator $D$ which obeys $D_a h^{bc}=0$.
(One change I am making here is not including the derivative in the tuple. It might be linquistics, but if there is a unique derivative $\nabla_a(\partial/\partial_i)^b=0$, we don't need to specify it in our choice of tuple. By picking $M$, we are automatically picking $\nabla$)


text:
Q: How to debug a task configuration instead of running one on JetBrains IDE startup Is there a way to force JetBrains IDE startup tasks to be debugged instead of being run?
Specifically, I want to configure WebStorm Settings | Tools | Startup Tasks to automatically perform a JavaScript debug task on IDE startup. The debug task only works by debugging it instead of running it, but it seems that WebStorm performs startup tasks by simply running it. I'm using WebStorm 2022.3.
I'm expecting the task to be performed on startup as if it is executed by clicking the Debug button on the top right of the IDE.

A: debug mode for startup tasks is not supported right now. However, we have a corresponding feature request on our bug tracker. We would appreciate it if you could upvote the issue to demonstrate additional interest and bring increased awareness to the issue.


text:
Q: Name is stored inside database table of SQLiteDatabase instead of its ID I'm having trouble with SQLiteDatabase. I've managed to store data into table. Unfortunately, I've stored name inside table instead of it's id. I need to store the id inside the table.
Please take a look at my codes and see if there's anything wrong or anything missing from the codes.
This is my database codes
LikesDBAdapter.java
public class LikesDBAdapter extends AnniversaryDBAdapter
{
    public static final String KEY_ROWID = "likes_id";
    public static final String KEY_LIKES = "like";
    public static final String KEY_NAME = "name_id";
    private static final String TAG = "DBAdapter";
    private static final String CREATE_TABLE_LIKES = "likes";

    //private SQLiteDatabase db;

    public LikesDBAdapter(Context ctx)
    {
        super(ctx);

    }

        public long insertLikes(String likes, String name)
        {
            ContentValues initialValues = new ContentValues();
            initialValues.put(KEY_LIKES, likes);
            initialValues.put(KEY_NAME, name);
            return db.insert(CREATE_TABLE_LIKES, null, initialValues);
        }// end insertContact()

        public boolean deleteLikes(long rowId)
        {
            return db.delete(CREATE_TABLE_LIKES, KEY_ROWID + "=" + rowId, null) > 0;
        }// end deleteContact()

        public Cursor getAllLikes()
        {
            return db.query(CREATE_TABLE_LIKES, new String[]
                    { KEY_ROWID, KEY_LIKES, KEY_NAME }, null, null, null, null, null);
        }// end getAllContacts()

        public Cursor getLikes(long rowId) throws SQLException
        {
            Cursor mCursor = db.query(true, CREATE_TABLE_LIKES, new String[] {
                    KEY_ROWID, KEY_LIKES, KEY_NAME }, KEY_ROWID + "=" + rowId,
                    null, null, null, null, null);
            if (mCursor != null)
            {
                mCursor.moveToFirst();
            }
            return mCursor;
        }// end getContact()

}//end DBAdapter

Oh this is another database class where 5 tables are created within one DBAdapter class
public class AnniversaryDBAdapter
{

    private static final String DATABASE_NAME = "Tables";
    private static final int DATABASE_VERSION = 2;

     private static final String CREATE_TABLE_TITLE = "create table titles(title_id integer primary key autoincrement, title text not null, image text not null);";
    private static final String CREATE_TABLE_BUDDIESLIST = "create table buddiesList(name_id integer primary key autoincrement, name text not null);";
    private static final String CREATE_TABLE_LIKES = "create table likes(likes_id integer primary key autoincrement,like text not null, name text not null);";
    private static final String CREATE_TABLE_DISLIKES = "create table dislike(dlike_id integer primary key autoincrement, dislike text not null, name text not null);";
    private static final String CREATE_TABLE_EVENTS = "create table events" +
            "(event_id integer primary key autoincrement, " +
            "title text not null, location text not null, " +
            "starttime text not null, " +
            "endtime text not null, " +
            "desc text not null, " +
            "alarm text not null, " +
            "date text not null, " +
            "name_id integer not null);";

This is another code where I need to insert information into database table
btnSave = (Button) findViewById(R.id.btnSave);
        btnSave.setOnClickListener(new View.OnClickListener()
            {

                @Override
                public void onClick(View v)
                {
                    likeDB.open();
                    long like_id;

                    Spinner nameSpinner = (Spinner) findViewById(R.id.nameSpinner);
                    String NameValue = nameSpinner.getSelectedItem().toString();

                    EditText txtLikes = (EditText) findViewById(R.id.txtLikes);
                    String LikeValue = txtLikes.getText().toString();

                    like_id = likeDB.insertLikes(LikeValue, NameValue);
                    likeDB.close();

                    dlikeDB.open();
                    long dlike_id;

                    Spinner names = (Spinner) findViewById(R.id.nameSpinner);
                    String NamesValue = names.getSelectedItem().toString();

                    EditText txtDislikes = (EditText) findViewById(R.id.txtDislikes);
                    String DislikeValue = txtDislikes.getText().toString();

                    dlike_id = dlikeDB.insertDislikes(DislikeValue, NamesValue);
                    dlikeDB.close();

                    Toast.makeText(getBaseContext(), "Your information is saved successfully! :D", Toast.LENGTH_LONG).show();

                }
            });

I've declared the likeDB and dlikeDB above onCreate() method
LikesDBAdapter likeDB = new LikesDBAdapter(this);
DislikesDBAdapter dlikeDB = new DislikesDBAdapter(this);

UPDATE

i've edited the codes. I've removed some codes of the AnniversaryDBAdapter class in the post.

A: Why are you surprised? You are inserting name in the database in your insertLikes function
    public long insertLikes(String likes, String name)
    {
        ContentValues initialValues = new ContentValues();
        initialValues.put(KEY_LIKES, likes);
        ***initialValues.put(KEY_NAME, name);***
        return db.insert(CREATE_TABLE_LIKES, null, initialValues);
    }// end insertContact()


text:
Q: How to determine the current directory in a batch file How can I determine the current directory in a batch file. Other than %~dp0.
So that when I run the batch file from source folder (consisting of my files) it returns the path of source folder, where ever it may be.

A: The environment variable %cd% contains the current folder:
H:\Downloads>type currentdir.bat
echo %cd%
H:\Downloads>currentdir.bat

H:\Downloads>echo H:\Downloads
H:\Downloads

H:\Downloads>


text:
Q: How are you supposed to do client-side data fetching on route transition with getServerSideProps? Next.js 9.3 introduced getServerSideProps. In the getInitialProps documentation it now says:

If you're using Next.js 9.3 or newer, we recommend that you use getStaticProps or getServerSideProps instead of getInitialProps.

The thing is: getInitialProps doesn't just provide props on the server side. It also runs on the client and provides props when a route transitions. After an initial server render, if the route changed, getInitialProps runs on the client. So, how do the new methods introduced in 9.3 account for this pretty basic use case?

A: getServerSideProps

getServerSideProps only runs on server-side and never runs on the browser. If a page uses getServerSideProps , then:
When you request this page directly, getServerSideProps runs at the request time, and this page will be pre-rendered with the returned props.
When you request this page on client-side page transitions through next/link (documentation) or next/router (documentation), Next.js sends an API request to the server, which runs getServerSideProps. It'll return JSON that contains the result of running getServerSideProps, and the JSON will be used to render the page.
All this work will be handled automatically by Next.js, so you don't need to do anything extra as long as you have getServerSideProps defined.

For more info.
getStaticProps

Only runs at build time
When a page with getStaticProps is pre-rendered at build time, in addition to the page HTML file, Next.js generates a JSON file holding the result of running getStaticProps.
This JSON file will be used in client-side routing through next/link (documentation) or next/router (documentation). When you navigate to a page that's pre-rendered using getStaticProps, Next.js fetches this JSON file (pre-computed at build time) and uses it as the props for the page component. This means that client-side page transitions will not call getStaticProps as only the exported JSON is used.

For more info


text:
Q: A false conjecture by de Polignac (This question would be similar to my other on Goldbach's conjecture so I'll change the "rules")
In 1848 de Polignac claimed that "every odd integer is the sum of a prime $p$ and a power of $2$". For example $55=47+2^3=23+2^5.$
Now I have to show that $509$ and $877$ discredit this claim.
What I did is: set $p=509-2^n$ and showed that for every $n$, $p$ is composed (as long as it is nonnegative) checking all the possible values, then I did the same thing for $877$. Fortunately this time I had to check less cases because on the growth of $2^n$ but it still took me a few times.
My question is: how can I prove this without checking case by case and WITHOUT modular arithmetic (which is in the next chap.) ??
EDIT: This question is problem 17 at page 59 (chap.3: the primes and their distribution) of the book "Elementary number theory" by D. M. Burton.


text:
Q: Editing long text TextView causes a 'FAILED BINDER TRANSACTION' error in Accessibility code I have a TextView with a fairly long document in it (~1800 lines, 70k characters). The document has a number of spans applied in order to provide formatting. This all works quite well.
However, while editing text, I intermittently get the following error:
E/JavaBinder: !!! FAILED BINDER TRANSACTION !!!  (parcel size = 119652)
E/AccessibilityManager: Error during sending EventType: TYPE_VIEW_TEXT_SELECTION_CHANGED; EventTime: 67446779; PackageName: <package name>; MovementGranularity: 0; Action: 0; ContentChangeTypes: []; WindowChangeTypes: [] [ ClassName: android.widget.EditText; Text: [

<ENTIRE CONTENTS OF DOCUMENT>

]; ContentDescription: null; ItemCount: 78607; CurrentItemIndex: -1; Enabled: true; Password: false; Checked: false; FullScreen: false; Scrollable: false; BeforeText: null; FromIndex: 78585; ToIndex: 78585; ScrollX: 0; ScrollY: 0; MaxScrollX: 0; MaxScrollY: 0; ScrollDeltaX: -1; ScrollDeltaY: -1; AddedCount: -1; RemovedCount: -1; ParcelableData: null ]; recordCount: 0
    android.os.DeadObjectException: Transaction failed on small parcel; remote process probably died
        at android.os.BinderProxy.transactNative(Native Method)
        at android.os.BinderProxy.transact(BinderProxy.java:540)
        at android.view.accessibility.IAccessibilityManager$Stub$Proxy.sendAccessibilityEvent(IAccessibilityManager.java:580)
E/AccessibilityManager:     at android.view.accessibility.AccessibilityManager.sendAccessibilityEvent(AccessibilityManager.java:606)
        at android.view.ViewRootImpl.requestSendAccessibilityEvent(ViewRootImpl.java:8618)
        at android.view.ViewGroup.requestSendAccessibilityEvent(ViewGroup.java:1094)
        at android.view.ViewGroup.requestSendAccessibilityEvent(ViewGroup.java:1094)
        at android.view.ViewGroup.requestSendAccessibilityEvent(ViewGroup.java:1094)
        at android.view.ViewGroup.requestSendAccessibilityEvent(ViewGroup.java:1094)
        at android.view.ViewGroup.requestSendAccessibilityEvent(ViewGroup.java:1094)
        at android.view.ViewGroup.requestSendAccessibilityEvent(ViewGroup.java:1094)
        at android.view.ViewGroup.requestSendAccessibilityEvent(ViewGroup.java:1094)
        at android.view.ViewGroup.requestSendAccessibilityEvent(ViewGroup.java:1094)
        at android.view.ViewGroup.requestSendAccessibilityEvent(ViewGroup.java:1094)
        at android.view.View.requestParentSendAccessibilityEvent(View.java:8333)
        at android.view.View.sendAccessibilityEventUncheckedInternal(View.java:8326)
        at android.view.View.sendAccessibilityEventUnchecked(View.java:8297)
        at android.widget.TextView.sendAccessibilityEventUnchecked(TextView.java:12217)
        at android.view.View.sendAccessibilityEventInternal(View.java:8274)
        at android.widget.TextView.sendAccessibilityEventInternal(TextView.java:12206)
        at android.view.View.sendAccessibilityEvent(View.java:8238)
        at android.widget.TextView.onSelectionChanged(TextView.java:10488)

This sometimes causes the app to crash as well.
As best as I can tell, this is caused by the Accessibility Service code trying to send to much data as part of an intent.
Can anyone this of how I could prevent this. I know I could just block the accessibility code from firing (i.e. override the method in TextView), but I would rather a not potentially disrupt users who rely on accessibility.


text:
Q: Regex to check for repeating characters inside a string I have a string for username and it can contain a (period) . (underscore) _. But I don't want the string to have more than 1 repeating . or _. So for example:
alpha.beta.gamma and alpha.beta_gamma are acceptable.
alpha..beta, alpha__beta and alpha._beta etc. are not acceptable.
Here is the regex that I am using ".*([._])\\1{1,}.*"
It works for same characters, so it returns true for alpha..beta and alpha__beta. However, the regex returns false for alpha._beta.
How can I modify the regex to make it work for both . and _ repeating match?

A: use this : .*([._]){2,}.*
see Demo

A: The following should do the trick, by ensuring that the username does NOT match an undesired format:
// should not match this
/.*[._]{2,}.*/

This will ensure no more than one of either _ or . can appear consecutively.
You may also want to consider being more specific than .*, potentially something like [A-Za-z0-9]*.

A: Recall that in RegEx, groups and */+ operators can be arbitrarily nested.
This here matches all strings that start with some characters, and then are followed by arbitrarily many blocks, where each block starts with a '.' or a '_' and ends with arbitrarily many characters.
"[a-zA-Z]+([._][a-zA-Z]+)*"
Example (uses Scala, but that's irrelevant, it's the same String literals, and the same java.util.regex library):
for (example <- List(
  "aa.bb_c", "aa_.bb", "abc..cb", "a.b.c_d",
  "uidh.dh_thh.ths", "_a", "a_", "a_b_c",
  "tdh_ins_utu", "ghs.tah..hua",
  "kqkz..wkmqjk", ".wkqj", "..wkqm")
) println(
  ("'" + example + "' : ").padTo(20, ' ') +
  example.matches("[a-zA-Z]+([._][a-zA-Z]+)*")
)

Output:
'aa.bb_c' :         true
'aa_.bb' :          false
'abc..cb' :         false
'a.b.c_d' :         true
'uidh.dh_thh.ths' : true
'_a' :              false
'a_' :              false
'a_b_c' :           true
'tdh_ins_utu' :     true
'ghs.tah..hua' :    false
'kqkz..wkmqjk' :    false
'.wkqj' :           false
'..wkqm' :          false

A: An alternative, non-regex way, is just a simple method to check if(s.contains...) and your 4 options (..,__,._,_.);
return !(s.contains("..") || s.contains("__") || s.contains("._") || s.contains("_."));


text:
Q: Spark DataFrame Pivot with sort order in aggregation I'm wondering how to pivot and maintain order in aggregation.
DataFrame
+--------------+-------------+----------------+-----+
|CITY          |country      |STATE           |ORDER|
+--------------+-------------+----------------+-----+
|3. Corning    |United States|New York        |3    |
|1. Albany     |United States|New York        |1    |
|2. Batavia    |United States|New York        |2    |
|3. Campbell   |United States|California      |3    |
|2. Bakersfield|United States|California      |2    |
|1. Arvin      |United States|California      |1    |
|2. Tofino     |Canada       |British Columbia|2    |
|3. Vancouver  |Canada       |British Columbia|3    |
|1. Cranbrook  |Canada       |British Columbia|1    |
+--------------+-------------+----------------+-----+

Actual Result
+-------------+-------------------------------------+-------------------------------------+---------------------------------+
|COUNTRY      |British Columbia                     |California                           |New York                         |
+-------------+-------------------------------------+-------------------------------------+---------------------------------+
|United States|                                     |3. Campbell; 2. Bakersfield; 1. Arvin|3. Corning; 1. Albany; 2. Batavia|
|Canada       |2. Tofino; 3. Vancouver; 1. Cranbrook|                                     |                                 |
+-------------+-------------------------------------+-------------------------------------+---------------------------------+

Desire Output
+-------------+-------------------------------------+-------------------------------------+---------------------------------+
|COUNTRY      |British Columbia                     |California                           |New York                         |
+-------------+-------------------------------------+-------------------------------------+---------------------------------+
|United States|                                     |1. Arvin; 2. Bakersfield; 3. Campbell|1. Albany; 2. Batavia; 3. Corning|
|Canada       |1. Cranbrook; 2. Tofino; 3. Vancouver|                                     |                                 |
+-------------+-------------------------------------+-------------------------------------+---------------------------------+

Sample Code
import static org.apache.spark.sql.functions.col;
import static org.apache.spark.sql.functions.collect_list;
import static org.apache.spark.sql.functions.lit;

import java.io.Serializable;
import java.util.Arrays;
import java.util.List;

import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.apache.spark.sql.Dataset;
import org.apache.spark.sql.Row;
import org.apache.spark.sql.SparkSession;
import org.apache.spark.sql.functions;

public class TestPivotOrder implements Serializable {
    private static final long serialVersionUID = -1L;

    private static String COUNTRY = "COUNTRY";
    private static String STATE = "STATE";
    private static String CITY = "CITY";
    private static String ORDER = "ORDER";

    public static void main(String[] args) {
        TestPivotOrder app = new TestPivotOrder();
        app.start();
    }

    private void start() {

        // display warning and error messages only
        Logger.getLogger("org.apache").setLevel(Level.WARN);

        SparkSession sparkSession = SparkSession.builder()
             .appName("Pivot with Order").master("local").getOrCreate();

        Dataset<Row> df = getData(sparkSession);

        df = df
            .withColumn(ORDER, functions.regexp_extract(col(STATE), "(\\d+)", 0))
            .withColumn(STATE, functions.regexp_replace(col(STATE), ".(\\d+)", ""))
            .withColumn(CITY, functions.concat(col(ORDER), lit(". "), col(CITY)));

        /*
        +--------------+-------------+----------------+-----+
        |CITY          |country      |STATE           |ORDER|
        +--------------+-------------+----------------+-----+
        |3. Corning    |United States|New York        |3    |
        |1. Albany     |United States|New York        |1    |
        |2. Batavia    |United States|New York        |2    |
        |3. Campbell   |United States|California      |3    |
        |2. Bakersfield|United States|California      |2    |
        |1. Arvin      |United States|California      |1    |
        |2. Tofino     |Canada       |British Columbia|2    |
        |3. Vancouver  |Canada       |British Columbia|3    |
        |1. Cranbrook  |Canada       |British Columbia|1    |
        +--------------+-------------+----------------+-----+
         */
        df.show(10, false);

        df = df
            .groupBy(df.col(COUNTRY))
            .pivot(df.col(STATE))
            .agg(functions.concat_ws("; ", collect_list(df.col(CITY))));

        df.show(10, false);

        sparkSession.stop();
    }

    private Dataset<Row> getData(SparkSession spark) {

        List<Item> list = Arrays.asList(
                new Item("United States","New York.3","Corning"),
                new Item("United States","New York.1","Albany"),
                new Item("United States","New York.2","Batavia"),

                new Item("United States","California.3","Campbell"),
                new Item("United States","California.2","Bakersfield"),
                new Item("United States","California.1","Arvin"),

                new Item("Canada","British Columbia.2","Tofino"),
                new Item("Canada","British Columbia.3","Vancouver"),
                new Item("Canada","British Columbia.1","Cranbrook")
            );

        return spark.createDataFrame(list, Item.class);
    }
}

Item Class
import java.io.Serializable;

public class Item implements Serializable {

    private static final long serialVersionUID = -1639L;

    private String country;
    private String state;
    private String city;

    public Item(String country, String state, String city) {
        this.country = country;
        this.state = state;
        this.city = city;
    }

    public String getCountry() {
        return country;
    }

    public String getState() {
        return state;
    }

    public String getCity() {
        return city;
    }
}

A: // sort_array then mkString with array
        df = df
        .groupBy(df.col(COUNTRY))
        .pivot(df.col(STATE))
        .agg(sort_array(collect_list(df.col(CITY))));


text:
Q: callback in route component causes Maximum update depth exceeded This code causes a re-render loop, but I don't know how exactly I can approach this. I know the setStartDrawingAction and the setSaveAndResetAction lines are the culprit. But how can I fix this?
<Switch location={location}>
    <Route
      exact
      path="/analyse/measures"
      component={() => {
        return (
          <MapMeasuresContainer
            startDrawing={(callback: any) => {
              setStartDrawingAction(callback);
            }}
            saveAndReset={(callback: any) => {
              setsaveAndResetAction(callback);
            }}
            selectPolygon={(polygon: any) => selectPolygon(polygon)}
          />
        );
      }}
      key="measures"
    />
</Switch>

A: You need to use render instead of component.
The problem is every time when you pass as function to component prop it remounts again, like Parsing the JSX does not call it. It just ends up creating the function expression. So basically it creates a new anonymous type each time, causing re-mounting of the dom.
If we want to pass prop to Component, we need to use the render method for preventing remounting.

A: When returning a function instead of a mounted component you need to use render instead of component.
When you use component the router uses React.createElement to create a new React element from the given component. That means if you provide an inline function to the component prop, you would create a new component every render
docs


text:
Q: Object spark is not a member of package org When importing the following in Eclipse Scala-IDE
import org.apache.spark.SparkContext
import org.apache.spark.SparkContext._

I get this error:
Object spark is not a member of package org
I installed the sbt-0.13.9.msi
What else should I do?
build.sbt
name := "scala-spark-app"

version := "1.0"

scalaVersion := "2.10.4"

libraryDependencies += "org.apache.spark" %% "spark-core" % "1.5.2"

A: I was receiving the same compilation error (on my Mac) with IntelliJ whereas sbt compile executed successfully. The following steps solved my problem:

*

*sbt clean

*sbt gen-idea (to rebuild IntelliJ project files)

*quit and restart IntelliJ

I hope this helps.


text:
Q: Problems with copy value TableColumn invisible To hide (make invisible) TableColumns normally do:
TableColumn.setMinWidth(0);
TableColumn.setMaxWidth(0);

or remove from the model with removeColumn method (column);
But at run time we have the need to leave invisible or visible the column and ends up being more practical to use setMinWidth (0) and setMaxWidth (0).
This creates a problem because if the user selects a table row and press Ctrl+C and paste it into a text file,  it can copy the value of the hidden column!!!
We could to solve the problem using TransferHandler to not perform CopyAction of JComponent. How TableColumn is not a JComponent would not give to solve this way.
Another alternative would be to define: (JTable to disallow selection lines)
JTable.setRowSelectionAllowed(false)

Well this last solution would not be feasible for me because I need to keep the permit selection of rows in the table. Does anyone have another solution to restrict copying of values from all the columns?

A:
To hide (make invisible) TableColumns normally do:

TableColumn.setMinWidth(0);
TableColumn.setMaxWidth(0);

*

*this isn't good way, playing with zero size, this column isn't hiddenonly has un_natural size, still is accesible for all mouse & key events

*you have to removeColumn() from JTables view


text:
Q: I'm Going Back Through Time For some reason, the new-nav is going crazy. It sets my rep back like by 200 rep, and thinks the most recent comment wasn't viewed. I know this sounds crazy, but it is the truth. Here's a screenshot:

This is not a fake because you can still see the tab where I am writing this question. But everything else is not correct. At the time of writing this post, we are at 71.3k questions, not 71.2k. senshin did not have the newest question right now, I did not have any notifications while writing, nor do I have 3,643 right now (I actually have 3,832 rep).
So is this a late April Fools/Welcome back to School joke or is this a major time bug? If yes to major time bug, please tell me what is going on. Using Google Chrome. Oh, everything is normal after refresh. This happened to me about 3 times today.
EDIT: Here it comes again...