问:
Dynamically loading an external webpack bundled ngModule as a route handler
We want to divide our large frontend projects into multiple separately deployed projects which are easier to work with.  I am trying to include a bundled ngModule to handle a route from within another app.  The apps must be ignorant of each other's configuration.  The bundles will share some large dependencies(like Angular) via globals.  We don't need to shake across the bundles and we may just have to accept some duplicate dependencies.

The root router complains that

```<code>Error: No NgModule metadata found for 'TestsetModule'.
</code>```

which leads me to believe the child module is not being angular compiled on load, or is not registering its module for some reason.  I think it may be necessary to manually compile the module, but I'm not sure how to use this https://angular.io/api/core/Compiler#compileModuleAndAllComponentsAsync

The root app loads the child via a route:

```<code>import { ModuleWithProviders } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
const load = require("little-loader");

const routes: Routes = [
  { path: ``, loadChildren: () => new Promise(function (resolve) {
      load('http://localhost:3100/testset-module-bundle.js',(err: any) => {
        console.log('global loaded bundle is: ', (<any>global).TestsetModule )
        resolve((<any>global).TestsetModule)
      }
    )
  })}
];

export const HostRouting: ModuleWithProviders = RouterModule.forRoot(routes);
</code>```

I also tried using angular router's string resolution syntax rather than this weird global thing you see but I had similar issues.

Here is the module which is being loaded, very standard except for the global export:

```<code>import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { HttpModule } from '@angular/http';
//import { MaterialModule } from '@angular/material';
import { FlexLayoutModule } from '@angular/flex-layout';
import { FormsModule }   from '@angular/forms';
import { LoggerModule, Level } from '@churro/ngx-log';

import { FeatureLoggerConfig } from './features/logger/services/feature-logger-config';

import { TestsetComponent } from './features/testset/testset.component';
import { TestsetRouting } from './testset.routing';

@NgModule({
    imports: [
        CommonModule,
        //MaterialModule,
        FlexLayoutModule,
        HttpModule,
        FormsModule,
        LoggerModule.forChild({
          moduleName: 'Testset',
          minLevel: Level.INFO
        }),
        TestsetRouting,
    ],
    declarations: [TestsetComponent],
    providers: [
      /* TODO: Providers go here */
    ]
})
class TestsetModule { }
(<any>global).TestsetModule = TestsetModule

export {TestsetModule as default, TestsetModule};
</code>```

Here is the webpack configuration of the root bundle.  Note the global exports via the poorly named "ProvidePlugin".

```<code>const webpack = require('webpack');
const AotPlugin = require('@ngtools/webpack').AotPlugin;
const path = require('path');
const BrowserSyncPlugin = require('browser-sync-webpack-plugin');
const IgnorePlugin = require('webpack/lib/IgnorePlugin');
const PolyfillsPlugin = require('webpack-polyfills-plugin');
const WebpackSystemRegister = require('webpack-system-register');

module.exports = (envOptions) => {
    envOptions = envOptions || {};
    const config = {

        entry: {
          'bundle': './root.ts'
        },
        output: {

          libraryTarget: 'umd',
          filename: '[name].js',//"bundle.[hash].js",
          chunkFilename: '[name]-chunk.js',
          path: __dirname
          },
          externals: {

          },
        resolve: {
            extensions: ['.ts', '.js', '.html'],
        },
        module: {
            rules: [
                { test: /\.html$/, loader: 'raw-loader' },
                { test: /\.css$/, loader: 'raw-loader' },

            ]
        },
        devtool: '#source-map',
        plugins: [
          new webpack.ProvidePlugin({
            'angular': '@angular/core',
            'ngrouter': '@angular/router',
            'ngxlog':'@churro/ngx-log'
          })

        ]
    };
    config.module.rules.push(
      { test: /\.ts$/, loaders: [
        'awesome-typescript-loader',
        'angular-router-loader',
        'angular2-template-loader',
        'source-map-loader'
      ] }
    );
  }

    return config;
};
</code>```

And here is the webpack configuration of the child bundle.  Note the "externals" which look for angular as a global.

```<code>module.exports = (envOptions) => {
    envOptions = envOptions || {};
    const config = {
        entry: {
          'testset-module-bundle': './src/index.ts'
        },
        output: {
          //library: 'TestsetModule',
          libraryTarget: 'umd',
          filename: '[name].js',//"bundle.[hash].js",
          chunkFilename: '[name]-chunk.js',
          path: path.resolve(__dirname, "dist")
          },
          externals: {
            //expect these to come from the app that imported us
            // name to be required : name from global
             'angular': '@angular/core',
             'ngrouter': '@angular/router',
             'ngxlog': '@churro/ngx-log'
          },
        resolve: {
            extensions: ['.ts', '.js', '.html'],
        },
        module: {
            rules: [
                { test: /\.html$/, loader: 'raw-loader' },
                { test: /\.css$/, loader: 'raw-loader' },

            ]
        },
        devtool: '#source-map',
        plugins: [

        ]
    };

    config.module.rules.push(
      { test: /\.ts$/, loaders: [
        'awesome-typescript-loader',
        'angular-router-loader',
        'angular2-template-loader',
        'source-map-loader'
      ] }
    );
  }

    return config;
};
</code>```

And for good measure here is my tsconfig file which 'awesome-typescript-loader' reads.

```<code>{
  "compilerOptions": {
    "target": "es5",
    "module": "es2015",
    "moduleResolution": "node",
    "sourceMap": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "removeComments": false,
    "noImplicitAny": true,
    "suppressImplicitAnyIndexErrors": true,
    "baseUrl": ".",
    "rootDir": "src",
    "outDir": "app",
    "paths": {
      "@capone/*": [
        "*"
      ],
      "@angular/*": [
        "node_modules/@angular/*"
      ],
      "rxjs/*": [
        "node_modules/rxjs/*"
      ]
    }
  },

  "exclude": ["node_modules", "src/node_modules", "compiled", "src/dev_wrapper_app"],
  "angularCompilerOptions": {
    "genDir": "./compiled",
    "skipMetadataEmit": true
  }
}
</code>```

If you're still reading, awesome.  I was able to get this working when both bundles are part of the same webpack config and the child module is just a chunk.  Angular is designed to do that.  But our use case is to have the children and parent be ignorant of each other until runtime.

答:
As you have mentioned

The apps must be ignorant of each other's configuration.

I had a similar problem in Angular2. I solved it by creating a sub-application. A separate sub-main.browser.ts and index.html file. It had its own dependencies, sharing the same node modules. Both main modules bootstrapping different app-component. We were working on Angular without angular-cli.

In webpack config, I added

```<code>entry: {

  'polyfills': './src/polyfills.browser.ts',
  'main' .   :     './src/main.browser.aot.ts',
  'sub-main' : '/src/sub-main.browser.ts'

},
</code>```

and a more detailed HtmlWebpackPlugin. In the chunks, we load only modules that will be used in both the app. If we see polyfills is common.

```<code>   new HtmlWebpackPlugin({
    template: 'src/index.html',
    title: METADATA.title,
    chunksSortMode: 'dependency',
    metadata: METADATA,
    inject: 'head',
    chunks: ['polyfills','main']
  }),

  new HtmlWebpackPlugin({
    template: 'src/index2.html',
    title: 'Sub app',
    chunksSortMode: 'dependency',
    metadata: METADATA,
     inject: 'head',
    filename: './sub-app.html',
    chunks: ['polyfills','sub-main']
  }),
</code>```

The next task was to create separate endpoints for both sub apps for dev environment.

```<code>devServer: {
      port: METADATA.port,
      host: METADATA.host,
      historyApiFallback: true,
      watchOptions: {
        aggregateTimeout: 300,
        poll: 1000
      },
      proxy: {
   "/sub-app": {
    target: "http://localhost:3009",
    bypass: function(req, res, proxyOptions) {
        return "/index2.html";
    }
  }
}
    },
</code>```

Now when I build the project two different HTML files are generated. Each with their own javascript bundle dependencies and common assets. They can be deployed on a different server as well.

I was able to finish my POC with lots of trial and error. My suggestion will be to look a step above angular. See how webpack is deploying your current project. And If you can configure it to serve your purpose.

Body:
We want to divide our large frontend projects into multiple separately deployed projects which are easier to work with.  I am trying to include a bundled ngModule to handle a route from within another app.  The apps must be ignorant of each other's configuration.  The bundles will share some large dependencies(like Angular) via globals.  We don't need to shake across the bundles and we may just have to accept some duplicate dependencies.

The root router complains that

Error: No NgModule metadata found for 'TestsetModule'.

which leads me to believe the child module is not being angular compiled on load, or is not registering its module for some reason.  I think it may be necessary to manually compile the module, but I'm not sure how to use this https://angular.io/api/core/Compiler#compileModuleAndAllComponentsAsync

The root app loads the child via a route:

import { ModuleWithProviders } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
const load = require("little-loader");

const routes: Routes = [
  { path: ``, loadChildren: () => new Promise(function (resolve) {
      load('http://localhost:3100/testset-module-bundle.js',(err: any) => {
        console.log('global loaded bundle is: ', (<any>global).TestsetModule )
        resolve((<any>global).TestsetModule)
      }
    )
  })}
];

export const HostRouting: ModuleWithProviders = RouterModule.forRoot(routes);

I also tried using angular router's string resolution syntax rather than this weird global thing you see but I had similar issues.

Here is the module which is being loaded, very standard except for the global export:

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { HttpModule } from '@angular/http';
//import { MaterialModule } from '@angular/material';
import { FlexLayoutModule } from '@angular/flex-layout';
import { FormsModule }   from '@angular/forms';
import { LoggerModule, Level } from '@churro/ngx-log';

import { FeatureLoggerConfig } from './features/logger/services/feature-logger-config';

import { TestsetComponent } from './features/testset/testset.component';
import { TestsetRouting } from './testset.routing';

@NgModule({
    imports: [
        CommonModule,
        //MaterialModule,
        FlexLayoutModule,
        HttpModule,
        FormsModule,
        LoggerModule.forChild({
          moduleName: 'Testset',
          minLevel: Level.INFO
        }),
        TestsetRouting,
    ],
    declarations: [TestsetComponent],
    providers: [
      /* TODO: Providers go here */
    ]
})
class TestsetModule { }
(<any>global).TestsetModule = TestsetModule

export {TestsetModule as default, TestsetModule};

Here is the webpack configuration of the root bundle.  Note the global exports via the poorly named "ProvidePlugin".

const webpack = require('webpack');
const AotPlugin = require('@ngtools/webpack').AotPlugin;
const path = require('path');
const BrowserSyncPlugin = require('browser-sync-webpack-plugin');
const IgnorePlugin = require('webpack/lib/IgnorePlugin');
const PolyfillsPlugin = require('webpack-polyfills-plugin');
const WebpackSystemRegister = require('webpack-system-register');

module.exports = (envOptions) => {
    envOptions = envOptions || {};
    const config = {

        entry: {
          'bundle': './root.ts'
        },
        output: {

          libraryTarget: 'umd',
          filename: '[name].js',//"bundle.[hash].js",
          chunkFilename: '[name]-chunk.js',
          path: __dirname
          },
          externals: {

          },
        resolve: {
            extensions: ['.ts', '.js', '.html'],
        },
        module: {
            rules: [
                { test: /\.html$/, loader: 'raw-loader' },
                { test: /\.css$/, loader: 'raw-loader' },

            ]
        },
        devtool: '#source-map',
        plugins: [
          new webpack.ProvidePlugin({
            'angular': '@angular/core',
            'ngrouter': '@angular/router',
            'ngxlog':'@churro/ngx-log'
          })

        ]
    };
    config.module.rules.push(
      { test: /\.ts$/, loaders: [
        'awesome-typescript-loader',
        'angular-router-loader',
        'angular2-template-loader',
        'source-map-loader'
      ] }
    );
  }

    return config;
};

And here is the webpack configuration of the child bundle.  Note the "externals" which look for angular as a global.

module.exports = (envOptions) => {
    envOptions = envOptions || {};
    const config = {
        entry: {
          'testset-module-bundle': './src/index.ts'
        },
        output: {
          //library: 'TestsetModule',
          libraryTarget: 'umd',
          filename: '[name].js',//"bundle.[hash].js",
          chunkFilename: '[name]-chunk.js',
          path: path.resolve(__dirname, "dist")
          },
          externals: {
            //expect these to come from the app that imported us
            // name to be required : name from global
             'angular': '@angular/core',
             'ngrouter': '@angular/router',
             'ngxlog': '@churro/ngx-log'
          },
        resolve: {
            extensions: ['.ts', '.js', '.html'],
        },
        module: {
            rules: [
                { test: /\.html$/, loader: 'raw-loader' },
                { test: /\.css$/, loader: 'raw-loader' },

            ]
        },
        devtool: '#source-map',
        plugins: [

        ]
    };

    config.module.rules.push(
      { test: /\.ts$/, loaders: [
        'awesome-typescript-loader',
        'angular-router-loader',
        'angular2-template-loader',
        'source-map-loader'
      ] }
    );
  }

    return config;
};

And for good measure here is my tsconfig file which 'awesome-typescript-loader' reads.

{
  "compilerOptions": {
    "target": "es5",
    "module": "es2015",
    "moduleResolution": "node",
    "sourceMap": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "removeComments": false,
    "noImplicitAny": true,
    "suppressImplicitAnyIndexErrors": true,
    "baseUrl": ".",
    "rootDir": "src",
    "outDir": "app",
    "paths": {
      "@capone/*": [
        "*"
      ],
      "@angular/*": [
        "node_modules/@angular/*"
      ],
      "rxjs/*": [
        "node_modules/rxjs/*"
      ]
    }
  },

  "exclude": ["node_modules", "src/node_modules", "compiled", "src/dev_wrapper_app"],
  "angularCompilerOptions": {
    "genDir": "./compiled",
    "skipMetadataEmit": true
  }
}

If you're still reading, awesome.  I was able to get this working when both bundles are part of the same webpack config and the child module is just a chunk.  Angular is designed to do that.  But our use case is to have the children and parent be ignorant of each other until runtime.

Body:
As you have mentioned

The apps must be ignorant of each other's configuration.

I had a similar problem in Angular2. I solved it by creating a sub-application. A separate sub-main.browser.ts and index.html file. It had its own dependencies, sharing the same node modules. Both main modules bootstrapping different app-component. We were working on Angular without angular-cli.

In webpack config, I added

entry: {

  'polyfills': './src/polyfills.browser.ts',
  'main' .   :     './src/main.browser.aot.ts',
  'sub-main' : '/src/sub-main.browser.ts'

},

and a more detailed HtmlWebpackPlugin. In the chunks, we load only modules that will be used in both the app. If we see polyfills is common.

   new HtmlWebpackPlugin({
    template: 'src/index.html',
    title: METADATA.title,
    chunksSortMode: 'dependency',
    metadata: METADATA,
    inject: 'head',
    chunks: ['polyfills','main']
  }),

  new HtmlWebpackPlugin({
    template: 'src/index2.html',
    title: 'Sub app',
    chunksSortMode: 'dependency',
    metadata: METADATA,
     inject: 'head',
    filename: './sub-app.html',
    chunks: ['polyfills','sub-main']
  }),

The next task was to create separate endpoints for both sub apps for dev environment.

devServer: {
      port: METADATA.port,
      host: METADATA.host,
      historyApiFallback: true,
      watchOptions: {
        aggregateTimeout: 300,
        poll: 1000
      },
      proxy: {
   "/sub-app": {
    target: "http://localhost:3009",
    bypass: function(req, res, proxyOptions) {
        return "/index2.html";
    }
  }
}
    },

Now when I build the project two different HTML files are generated. Each with their own javascript bundle dependencies and common assets. They can be deployed on a different server as well.

I was able to finish my POC with lots of trial and error. My suggestion will be to look a step above angular. See how webpack is deploying your current project. And If you can configure it to serve your purpose.


来源: stackexchange

问:
Calling toISOString() thows "ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked."
I have this method here in a component:

getTime(): Date {
  const date = new Date();
  date.setHours(this.hour);
  date.setMinutes(this.minute);
  date.setSeconds(0);
  return date;
}
```

<p>which I call within another:</p>

<pre class="lang-xml prettyprint-override"><code><input matInput [hidden]="true" formControlName="time"
           [ngModel]="this.timePicker.getTime().toISOString()"/>
</code>```

However, even though the string gets correctly generated (at least that's how the JSON looks like):

```<code>"time": "2017-11-14T10:30:00.271Z"
</code>```

I'm getting this error:

```<code>CreateGroupComponent.html:40 ERROR Error: ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value: '2017-11-14T10:30:00.338Z'. Current value: '2017-11-14T10:30:00.341Z'.
    at viewDebugError (core.js:9514)
    at expressionChangedAfterItHasBeenCheckedError (core.js:9492)
    at checkBindingNoChanges (core.js:9661)
    at checkNoChangesNodeInline (core.js:13674)
    at checkNoChangesNode (core.js:13646)
    at debugCheckNoChangesNode (
</code>```

I see this error only if I call toISOString(). If I just return the Date object it's fine but converting it to an ISO string gives me that exception. Why?

Talking about toISOString() - where's actually the timezone information in

```<code>2017-11-14T10:30:00.271Z
</code>```

? For me, it's actually supposed to be

```<code>2017-11-14T10:30:00.271Z+01:00
</code>```

答:
This happens because milliseconds change on each getTime call, this is what the error says.

It should be:

```<code>getTime(): Date {
  const date = new Date();
  date.setHours(this.hour);
  date.setMinutes(this.minute);
  date.setSeconds(0);
  date.setMilliseconds(0);
  return date;
}
</code>```

Regarding timezone, the reference states,

The toISOString() method returns a string in simplified extended ISO format (ISO 8601) <...>. The timezone is always zero UTC offset, as denoted by the suffix "Z".

If local time is expected, see this question for possible solutions.

ContentLicense: CC BY-SA 3.0

Body:
I have this method here in a component:

getTime(): Date {
  const date = new Date();
  date.setHours(this.hour);
  date.setMinutes(this.minute);
  date.setSeconds(0);
  return date;
}

which I call within another:

<input matInput [hidden]="true" formControlName="time"
           [ngModel]="this.timePicker.getTime().toISOString()"/>

However, even though the string gets correctly generated (at least that's how the JSON looks like):

"time": "2017-11-14T10:30:00.271Z"

I'm getting this error:

CreateGroupComponent.html:40 ERROR Error: ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value: '2017-11-14T10:30:00.338Z'. Current value: '2017-11-14T10:30:00.341Z'.
    at viewDebugError (core.js:9514)
    at expressionChangedAfterItHasBeenCheckedError (core.js:9492)
    at checkBindingNoChanges (core.js:9661)
    at checkNoChangesNodeInline (core.js:13674)
    at checkNoChangesNode (core.js:13646)
    at debugCheckNoChangesNode (

I see this error only if I call toISOString(). If I just return the Date object it's fine but converting it to an ISO string gives me that exception. Why?

Talking about toISOString() - where's actually the timezone information in

2017-11-14T10:30:00.271Z

? For me, it's actually supposed to be

2017-11-14T10:30:00.271Z+01:00

Body:
This happens because milliseconds change on each getTime call, this is what the error says.

It should be:

getTime(): Date {
  const date = new Date();
  date.setHours(this.hour);
  date.setMinutes(this.minute);
  date.setSeconds(0);
  date.setMilliseconds(0);
  return date;
}

Regarding timezone, the reference states,

The toISOString() method returns a string in simplified extended ISO format (ISO 8601) <...>. The timezone is always zero UTC offset, as denoted by the suffix "Z".

If local time is expected, see this question for possible solutions.


问:
Templated iterator for a std::vector
I am creating a utility function to combine a byte array into a value based on the template type.

I currently have two overloaded functions which accept a pair of forward iterators and a pair of reverse iterators, in order to do take care of big and little endian.

Is it possible to have a templated vector iterator and reduce my two functions into one?

For example, this is what I want to do:

```<code>template <typename T, typename Iter>
inline T combine_bytes(std::vector<unsigned char>::Iter const &start,
                       std::vector<unsigned char>::Iter const &end,
                       bool bigendian)
{
    T ret;
    std::copy(start, end, reinterpret_cast<unsigned char *>(&ret));

    return ret;
}
</code>```

The compilation error I get is:

```<code>Failed to specialize function template 'T Utils::combine_bytes(const Iter &, const Iter &)'
</code>```

答:
You can use a static_assert to ensure the type referenced by your iterator is unsigned char.  Then you don't have to worry about what type of container is being iterated over:

```<code>template <typename T, typename Iter>
inline T combine_bytes(Iter start, Iter end)
{
    static_assert(std::is_same<std::decay_t<decltype(*start)>, unsigned char>::value,
                  "Must use unsigned char");
    T ret;
    std::copy(start, end, reinterpret_cast<unsigned char *>(&ret));

    return ret;
}
</code>```

While you're at it, you may want to add some runtime checking to make sure std::distance(begin, end) == sizeof(T) if you didn't just leave that out to keep the example short.

Title: Templated iterator for a std::vector

Body:
I am creating a utility function to combine a byte array into a value based on the template type.

I currently have two overloaded functions which accept a pair of forward iterators and a pair of reverse iterators, in order to do take care of big and little endian.

Is it possible to have a templated vector iterator and reduce my two functions into one?

For example, this is what I want to do:

template <typename T, typename Iter>
inline T combine_bytes(std::vector<unsigned char>::Iter const &start,
                       std::vector<unsigned char>::Iter const &end,
                       bool bigendian)
{
    T ret;
    std::copy(start, end, reinterpret_cast<unsigned char *>(&ret));

    return ret;
}

The compilation error I get is:

Failed to specialize function template 'T Utils::combine_bytes(const Iter &, const Iter &)'

Body:
You can use a static_assert to ensure the type referenced by your iterator is unsigned char.  Then you don't have to worry about what type of container is being iterated over:

template <typename T, typename Iter>
inline T combine_bytes(Iter start, Iter end)
{
    static_assert(std::is_same<std::decay_t<decltype(*start)>, unsigned char>::value,
                  "Must use unsigned char");
    T ret;
    std::copy(start, end, reinterpret_cast<unsigned char *>(&ret));

    return ret;
}

While you're at it, you may want to add some runtime checking to make sure std::distance(begin, end) == sizeof(T) if you didn't just leave that out to keep the example short.


问:
Could not cast value of type 'UITableViewCell' to 'ProjectName.UserCell'
Hey guys befor you mark this as a duplicate just please hear me out. I have tried everything related to this topic including adding

self.tableView.registerClass(UserCell.self, forCellReuseIdentifier: "cell")

I have also changed my placeholder cell to match the UserCell class

Im Not sure what it could be! I get the error :

Could not cast value of type 'UITableViewCell' (0x1134700e0) to 'Lightning_Chat.UserCell'

with type SIGBRT not sure what could be going on and ive tried everything please help!

here is table view code :

```<code>  public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{
    // not casting for some reason
    let cell : UserCell =  UITableViewCell(style: .subtitle , reuseIdentifier: "cellId") as! UserCell

    cell.textLabel?.text = contacts[indexPath.row].userName
    cell.detailTextLabel?.text = contacts[indexPath.row].score

    if let profileImageUrl = contacts[indexPath.row].picURL {
        let url = URL(string: profileImageUrl)
        URLSession.shared.dataTask(with: url!, completionHandler: { (data, response, error) in

            //download hit an error
            if error != nil {
                print(error!)
                return
            }
            DispatchQueue.main.async {
                cell.profileImageView.image = UIImage(data: data!)

            }

        }).resume()
    }

    return cell;
}
</code>```

here is my view did load :

```<code>override func viewDidLoad() {
    super.viewDidLoad()

    self.tableView.register(UserCell.self, forCellReuseIdentifier: "cellId")

    //irrelevant
    fetchUsers()
}
</code>```

答:
Here are the step to fix your problem

Change your table view content to be dynamic cell, instead of static cell

Maintain the code on your viewDidLoad function self.tableView.register(UserCell.self, forCellReuseIdentifier: "cellId"). Also don't forget to connect table view delegate and datasource

On your table view cellForRowAt index path method, don't instantiate the cell directly. Instead use let cell = self.tableView.dequeueReusableCell(withIdentifier: cellIdentifier)!;

Basically that error you got, is because of mix and match the wrong properties on your table view.

Hope it helps

Body:
Hey guys befor you mark this as a duplicate just please hear me out. I have tried everything related to this topic including adding

self.tableView.registerClass(UserCell.self, forCellReuseIdentifier: "cell")

I have also changed my placeholder cell to match the UserCell class

Im Not sure what it could be! I get the error :

Could not cast value of type 'UITableViewCell' (0x1134700e0) to 'Lightning_Chat.UserCell'

with type SIGBRT not sure what could be going on and ive tried everything please help!

here is table view code :

  public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{
    // not casting for some reason
    let cell : UserCell =  UITableViewCell(style: .subtitle , reuseIdentifier: "cellId") as! UserCell

    cell.textLabel?.text = contacts[indexPath.row].userName
    cell.detailTextLabel?.text = contacts[indexPath.row].score

    if let profileImageUrl = contacts[indexPath.row].picURL {
        let url = URL(string: profileImageUrl)
        URLSession.shared.dataTask(with: url!, completionHandler: { (data, response, error) in

            //download hit an error
            if error != nil {
                print(error!)
                return
            }
            DispatchQueue.main.async {
                cell.profileImageView.image = UIImage(data: data!)

            }

        }).resume()
    }

    return cell;
}

here is my view did load :

override func viewDidLoad() {
    super.viewDidLoad()

    self.tableView.register(UserCell.self, forCellReuseIdentifier: "cellId")

    //irrelevant
    fetchUsers()
}


问:
vb.net date formatting vs c# datetime formatting
I am doing an Visual Studio vb.net WinForm App.

I am used to work with c#. In C# Datetime DataType I have configured as "dd/MM/yyyy" as is configured in Control Panel and Regedit.

In VB.Net, is different, when I create a Date variable like this

Dim var As New Date
var = DateTime.Now```

Date.Now returns format "mm/dd/yyyy".

So every date format a assign to a variable, VB.Net automatically convert to format "mm/dd/yyyy".

I need Date DataType in VB.Net to be configured as C#. I mean, "dd/MM/yyyy" as it is configured in Control Panel.

Is that possible?

Thanks

答:
In C#,

```<code>string date_string = dd.ToString("dd-MM-yyyy");
</code>```

In VB.Net

```<code>Dim date_string As String = dd.ToString("dd-MM-yyyy")
</code>```

Body:
I am doing an Visual Studio vb.net WinForm App.

I am used to work with c#. In C# Datetime DataType I have configured as "dd/MM/yyyy" as is configured in Control Panel and Regedit.

In VB.Net, is different, when I create a Date variable like this

Dim var As New Date
var = DateTime.Now

Date.Now returns format "mm/dd/yyyy".

So every date format a assign to a variable, VB.Net automatically convert to format "mm/dd/yyyy".

I need Date DataType in VB.Net to be configured as C#. I mean, "dd/MM/yyyy" as it is configured in Control Panel.

Is that possible?

Thanks

Body:
In C#,

string date_string = dd.ToString("dd-MM-yyyy");

In VB.Net

Dim date_string As String = dd.ToString("dd-MM-yyyy")


问:
C program for finding rhymes
I received a homework in a University to write a C program for finding rhymes.
Basically, user should input one stanza/strophe within 4 lines.

If 1st and 3rd line end up with words which have same last three letters,
they are recognized by the program as rhyme.

There are also some other things, like if 2nd and 4th end up on the same way.

But, I am just confused - how should I accomplish this?
which library should I include in my program so I could achieve this?

答: OK, i have found it out how to do it! Basically, i need to have 4 char arrays, to include string.h library and then i will use strcmp function to compare only the last 3 letters of the array/line. Thanx for the help guys :) –</p>

Title: C program for finding rhymes


问:
Access Django Website from another computer on same network
As the title says I want to access my django website on a different computer on the same network.

Both are running windows 10 connected to the same network. The host is connect through wifi and the other through ethernet cable.

I've changed the allowed host to my ip address.

```<code>ALLOWED_HOSTS = ['71.89.113.52', 'localhost', '127.0.0.1']
</code>```

And ran the the server.

```<code>(VIRTEN) C:\Users\HP\Desktop\BBTennis\VIRTEN\src>python manage.py 0.0.0.0:8000
</code>```

But I still can't access it on the other computer. When I go to 71.89.113.52:8000 or 0.0.0.0:8000, I get the message, This site can't be reached.

If possible, please present an answer with every direction I should take such as how to configure my network settings or django changes I must make.

答:
The 71.89.113.52 IP looks like a public ID address. I'd guess your request is going to a DNS outside your network and then being blocked on the way back in by the :8000 port being closed in your firewall.

I'd suggest using network tools such as traceroute or ipconfig on your computer to first confirm the IP address of the target computer, and then i'd using python manage.py runserver x.x.x.x:8000 to start the server. If you can't see your other computer already, then running a django server isn't going to change that.

Body:
As the title says I want to access my django website on a different computer on the same network.

Both are running windows 10 connected to the same network. The host is connect through wifi and the other through ethernet cable.

I've changed the allowed host to my ip address.

ALLOWED_HOSTS = ['71.89.113.52', 'localhost', '127.0.0.1']

And ran the the server.

(VIRTEN) C:\Users\HP\Desktop\BBTennis\VIRTEN\src>python manage.py 0.0.0.0:8000

But I still can't access it on the other computer. When I go to 71.89.113.52:8000 or 0.0.0.0:8000, I get the message, This site can't be reached.

If possible, please present an answer with every direction I should take such as how to configure my network settings or django changes I must make.


问:
Send by e-mail SSRS report using SSIS package scheduled in SQL Agent
I have a SSIS package that export SSRS report (report have parameters) in excel and have stored it on disk. Then I can e-mail it. But, I need to e-mail SSRS report using SSIS package without storing it on disc. Also, e-mail addresses have to be from data base table, which will be filtered by field in the table "address type" (main address, region address etc.) that will  depend from choosen parameters in report.
My goal for today is to send stored file by E-mail at least to one recipient. So, here is ScriptTask that I use to send file that I have stored on disc from SSRS with the help of one more Script task in created SSIS Package. Script give next error "", and also error arises if I uncomment string 'objmes.AddAttachment = "e:\report.xls"

```<code>Imports System.Math
Imports Microsoft.SqlServer.Dts.Runtime
Imports System.ComponentModel
Imports System.Diagnostics
<Microsoft.SqlServer.Dts.Tasks.ScriptTask.SSISScriptTaskEntryPointAttribute()> _
<System.CLSCompliantAttribute(False)> _
Partial Public Class ScriptMain
    Inherits Microsoft.SqlServer.Dts.Tasks.ScriptTask.VSTARTScriptObjectModelBase
    Enum ScriptResults
        Success = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Success
        Failure = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Failure
    End Enum

    Public Sub Main()
        Dim objmes
        objmes = CreateObject("CDO.Message")
        objmes.From = "e-mail1"
        objmes.To = "e-mail2"
        objmes.Subject = "my first E-mail"
        objmes.TextBody = "Hello world"
        'objmes.AddAttachment = "e:\report.xls"
        objmes.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/smtpserver") = "smtp.*****.com"
        objmes.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/sendusing") = 2
        objmes.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate") = 1
        objmes.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/sendusername") = "email1"
        objmes.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/sendpassword") = "*******"
        objmes.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/smtpserverport") = 25
        objmes.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/smtpusessl") = 1
        objmes.Configuration.Fields.Update()
        objmes.Send()

    End Sub

End Class
</code>```

I will be grateful for any help!

答:
For your second question that you want to get the email based on the address type

It would be something like this

```<code>CREATE PROCEDURE [dbo].[mail_generation]

-- the input parameters
@addresstypekey as uniqueidentifier

AS
BEGIN
declare @email nvarchar(120)

declare crs cursor for
select c.email
from  contacts c inner join addresstype ad on c.addresstypekey = ad.addresstypekey
where ad.addresstypekey = @addresstypekey

open crs
fetch next from crs into @email

while @@FETCH_STATUS = 0
begin

   EXEC msdb.dbo.sp_send_dbmail @recipients = @email

   fetch next from crs into @email

end

close crs
deallocate crs

END
</code>```

So you have an input parameter which is the address type (main address, region address etc.)

select emails of the specified type

then send mail to each of the recipients have this type of address.

Body:
I have a SSIS package that export SSRS report (report have parameters) in excel and have stored it on disk. Then I can e-mail it. But, I need to e-mail SSRS report using SSIS package without storing it on disc. Also, e-mail addresses have to be from data base table, which will be filtered by field in the table "address type" (main address, region address etc.) that will  depend from choosen parameters in report.
My goal for today is to send stored file by E-mail at least to one recipient. So, here is ScriptTask that I use to send file that I have stored on disc from SSRS with the help of one more Script task in created SSIS Package. Script give next error "", and also error arises if I uncomment string 'objmes.AddAttachment = "e:\report.xls"

Imports System.Math
Imports Microsoft.SqlServer.Dts.Runtime
Imports System.ComponentModel
Imports System.Diagnostics
<Microsoft.SqlServer.Dts.Tasks.ScriptTask.SSISScriptTaskEntryPointAttribute()> _
<System.CLSCompliantAttribute(False)> _
Partial Public Class ScriptMain
    Inherits Microsoft.SqlServer.Dts.Tasks.ScriptTask.VSTARTScriptObjectModelBase
    Enum ScriptResults
        Success = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Success
        Failure = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Failure
    End Enum

    Public Sub Main()
        Dim objmes
        objmes = CreateObject("CDO.Message")
        objmes.From = "e-mail1"
        objmes.To = "e-mail2"
        objmes.Subject = "my first E-mail"
        objmes.TextBody = "Hello world"
        'objmes.AddAttachment = "e:\report.xls"
        objmes.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/smtpserver") = "smtp.*****.com"
        objmes.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/sendusing") = 2
        objmes.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate") = 1
        objmes.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/sendusername") = "email1"
        objmes.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/sendpassword") = "*******"
        objmes.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/smtpserverport") = 25
        objmes.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/smtpusessl") = 1
        objmes.Configuration.Fields.Update()
        objmes.Send()

    End Sub

End Class

I will be grateful for any help!

Body:
For your second question that you want to get the email based on the address type

It would be something like this

CREATE PROCEDURE [dbo].[mail_generation]

-- the input parameters
@addresstypekey as uniqueidentifier

AS
BEGIN
declare @email nvarchar(120)

declare crs cursor for
select c.email
from  contacts c inner join addresstype ad on c.addresstypekey = ad.addresstypekey
where ad.addresstypekey = @addresstypekey

open crs
fetch next from crs into @email

while @@FETCH_STATUS = 0
begin

   EXEC msdb.dbo.sp_send_dbmail @recipients = @email

   fetch next from crs into @email

end

close crs
deallocate crs

END

So you have an input parameter which is the address type (main address, region address etc.)

select emails of the specified type

then send mail to each of the recipients have this type of address.


问:
RabbitMQ: None of the specified endpoints were reachable
My rabbitmq application is running on windows 2012 server, randomly I use to get this error.

```<code>Exception Type: RabbitMQ.Client.Exceptions.BrokerUnreachableException

None of the specified endpoints were reachable

   at RabbitMQ.Client.ConnectionFactory.CreateConnection()

   at Program.Main(String[] args)

Stream does not support writing.

   at System.IO.BufferedStream.EnsureCanWrite()

   at System.IO.BufferedStream.Write(Byte[] array, Int32 offset, Int32 count)

   at RabbitMQ.Client.Impl.SocketFrameHandler.SendHeader()

   at RabbitMQ.Client.Framing.Impl.Connection.StartAndTune()

   at RabbitMQ.Client.Framing.Impl.Connection.Open(Boolean insist)

   at RabbitMQ.Client.Framing.Impl.Connection..ctor(IConnectionFactory factory, Boolean insist, IFrameHandler frameHandler)

   at RabbitMQ.Client.Framing.Impl.ProtocolBase.CreateConnection(IConnectionFactory factory, Boolean insist, IFrameHandler frameHandler)

   at RabbitMQ.Client.ConnectionFactory.CreateConnection()
</code>```

What could be the reason of failing the connection randomly, and automatically it starts connecting.

Can anyone help me out in this.

答:
I had this problem, and finally I could solve it by adding the "Ssl" property of the ConnectionFactory class, with the "ServerName" sub-property specified.

Here is what I did, and it connected to the Rabbit MQ server.
Please pay attention to the "ServerName" part of the code below:

```<code>var rabbitMqConnectionFactory
    = new ConnectionFactory
        {
            HostName = rabbitMqHostName,
            Port = rabbitMqPort,
            UserName = rabbitMqUserName,
            Password = rabbitMqPassword,
            VirtualHost = rabbitMqVirtualHost,
            RequestedHeartbeat = 60,
            Ssl =
                {
                    **ServerName** = rabbitMqHostName,
                    Enabled = useSsl
                }
        };
</code>```

Body:
My rabbitmq application is running on windows 2012 server, randomly I use to get this error.

Exception Type: RabbitMQ.Client.Exceptions.BrokerUnreachableException

None of the specified endpoints were reachable

   at RabbitMQ.Client.ConnectionFactory.CreateConnection()

   at Program.Main(String[] args)

Stream does not support writing.

   at System.IO.BufferedStream.EnsureCanWrite()

   at System.IO.BufferedStream.Write(Byte[] array, Int32 offset, Int32 count)

   at RabbitMQ.Client.Impl.SocketFrameHandler.SendHeader()

   at RabbitMQ.Client.Framing.Impl.Connection.StartAndTune()

   at RabbitMQ.Client.Framing.Impl.Connection.Open(Boolean insist)

   at RabbitMQ.Client.Framing.Impl.Connection..ctor(IConnectionFactory factory, Boolean insist, IFrameHandler frameHandler)

   at RabbitMQ.Client.Framing.Impl.ProtocolBase.CreateConnection(IConnectionFactory factory, Boolean insist, IFrameHandler frameHandler)

   at RabbitMQ.Client.ConnectionFactory.CreateConnection()

What could be the reason of failing the connection randomly, and automatically it starts connecting.

Can anyone help me out in this.

Body:
I had this problem, and finally I could solve it by adding the "Ssl" property of the ConnectionFactory class, with the "ServerName" sub-property specified.

Here is what I did, and it connected to the Rabbit MQ server.
Please pay attention to the "ServerName" part of the code below:

var rabbitMqConnectionFactory
    = new ConnectionFactory
        {
            HostName = rabbitMqHostName,
            Port = rabbitMqPort,
            UserName = rabbitMqUserName,
            Password = rabbitMqPassword,
            VirtualHost = rabbitMqVirtualHost,
            RequestedHeartbeat = 60,
            Ssl =
                {
                    **ServerName** = rabbitMqHostName,
                    Enabled = useSsl
                }
        };


问:
search in a text field which contains json
My Application is in RoR and DB is in MYSQL. I have  a User Table. It contains a field name. Its type is text.
It contains the value like {"first_name"=> 'Allen', "last_name"=> 'PAul'} and some other information.

I am able to store the same in DB by using store: accessors: [], coder: JSON.

Now, I want to retrive all records whose first_name == 'Allen'. So how to achieve this in rails

答:
You have overloaded the name field using ActiveRecord::Store. From the documentation:

Store gives you a thin wrapper around serialize for the purpose of storing hashes in a single column. It's like a simple key/value store baked into your record when you don't care about being able to query that store outside the context of a single record.

You cannot use the field in the manner that you are describing, and attempting to do so goes against the purpose of the API you're using, so I would advise against it. You have several options:

Search the field using some type of slow query (SELECT * FROM User WHERE name LIKE '%foo%')

Instantiate all the records, then parse them (User.all.map { |user| user.name.match(/foo/))

Normalize your database and assign proper fields for each field you want to search by (name splits into first_name and last_name)

Of these three options, only 3 is the right thing to do. The other two may work but should not be used because of the performance and reliability issues it will introduce.

As a bonus to using 3, you can create a method to fulfill the role of name:

```<code>class User < ActiveRecord::Base
  def name
    {
      first_name: first_name,
      last_name: last_name
    }
  end
end
</code>```

You can then search the way you want:

```<code>user = User.where(first_name: 'foo').first
</code>```

And still return the name:

```<code>user.name
=> { first_name: 'foo', last_name: 'bar' }
</code>```

Body:
You have overloaded the name field using ActiveRecord::Store. From the documentation:

Store gives you a thin wrapper around serialize for the purpose of storing hashes in a single column. It's like a simple key/value store baked into your record when you don't care about being able to query that store outside the context of a single record.

You cannot use the field in the manner that you are describing, and attempting to do so goes against the purpose of the API you're using, so I would advise against it. You have several options:

Search the field using some type of slow query (SELECT * FROM User WHERE name LIKE '%foo%')

Instantiate all the records, then parse them (User.all.map { |user| user.name.match(/foo/))

Normalize your database and assign proper fields for each field you want to search by (name splits into first_name and last_name)

Of these three options, only 3 is the right thing to do. The other two may work but should not be used because of the performance and reliability issues it will introduce.

As a bonus to using 3, you can create a method to fulfill the role of name:

class User < ActiveRecord::Base
  def name
    {
      first_name: first_name,
      last_name: last_name
    }
  end
end

You can then search the way you want:

user = User.where(first_name: 'foo').first

And still return the name:

user.name
=> { first_name: 'foo', last_name: 'bar' }


问:
JDBC connectivity to oracle database in UFT
I am facing an issue while trying to establish JDBC connectivity to Oracle Database using VBscript code in UFT 12.02. Tried installing Oracle Driver for RDB Thin as well as Oracle 11g Client.

Error displayed is :

[Microsoft][ODBC Driver Manager] Data source name not found and no
  default driver specified

OR

TNS adaptor not found

Connection string used is :

```<code>Set con= CreateObject("ADODB.Connection")
strConnectionString = "DRIVER=oracle.jdbc.OracleDriver;URL=jdbc:oracle:thin:@<HOST NAME>:1521:TEMPdatabase;uid=username;pwd=password"

strConnectionString= "DRIVER={Oracle Driver for RDB Thin};URL=jdbc:oracle:thin:@<HOST NAME>:1521:TEMPdatabase;uid=username;pwd=password"
</code>```

Also note that I am able to access the DB manually through DBVisualizer by creating a new Driver using Tools>Driver Manager>Create Driver and linking it to rdbthin.jar file from local drive

Please help me out with this issue

答:
You can connect to Oracle DB using ODBC connectivity.
If your machine is 64 bit and if you want to connect to Oracle DB then you need to install both 64 bit and 32 bit oracle clients on your machine.
First 64 bit then 32 bit. You need to add the DSN to 32bit ODBC data source.
You also need to connection details in your tnsnames.ora file in both 64 and 32 bit oracle clients. you can find this file in this path after oracle client installation.
C:\app\mymachine\product\11.2.0\client_1\network\admin\tnsnames.ora

Here is the sample script to connect to Oracle DB,

```<code>Set Con = CreateObject("adodb.connection")
Set rs = CreateObject("adodb.recordset")
Con.Open "DSN="DsnName";Uid="user_id";Pwd="password";"
rs.Open sql, Con
Reporter.ReportEvent micDone ,"DB Function", sql
con.Close
Set con = Nothing
Set rs = Nothing
</code>```

The DsnName in the function should be same as the DSN Name you add in the ODBC data source.

Body:
I am facing an issue while trying to establish JDBC connectivity to Oracle Database using VBscript code in UFT 12.02. Tried installing Oracle Driver for RDB Thin as well as Oracle 11g Client.

Error displayed is :

[Microsoft][ODBC Driver Manager] Data source name not found and no
  default driver specified

OR

TNS adaptor not found

Connection string used is :

Set con= CreateObject("ADODB.Connection")
strConnectionString = "DRIVER=oracle.jdbc.OracleDriver;URL=jdbc:oracle:thin:@<HOST NAME>:1521:TEMPdatabase;uid=username;pwd=password"

strConnectionString= "DRIVER={Oracle Driver for RDB Thin};URL=jdbc:oracle:thin:@<HOST NAME>:1521:TEMPdatabase;uid=username;pwd=password"

Also note that I am able to access the DB manually through DBVisualizer by creating a new Driver using Tools>Driver Manager>Create Driver and linking it to rdbthin.jar file from local drive

Please help me out with this issue

Body:
You can connect to Oracle DB using ODBC connectivity.
If your machine is 64 bit and if you want to connect to Oracle DB then you need to install both 64 bit and 32 bit oracle clients on your machine.
First 64 bit then 32 bit. You need to add the DSN to 32bit ODBC data source.
You also need to connection details in your tnsnames.ora file in both 64 and 32 bit oracle clients. you can find this file in this path after oracle client installation.
C:\app\mymachine\product\11.2.0\client_1\network\admin\tnsnames.ora

Here is the sample script to connect to Oracle DB,

Set Con = CreateObject("adodb.connection")
Set rs = CreateObject("adodb.recordset")
Con.Open "DSN="DsnName";Uid="user_id";Pwd="password";"
rs.Open sql, Con
Reporter.ReportEvent micDone ,"DB Function", sql
con.Close
Set con = Nothing
Set rs = Nothing

The DsnName in the function should be same as the DSN Name you add in the ODBC data source.


问:
Algorithm not showing right output
The Question was:

You are given a binary matrix (i.e. each element of matrix is either 0 or 1) of size n × n. You want to re-arrange 1's in such a way that they form a rectangular region. Note that the rectangular region should be made of only 1's, and all the 1's of the entire matrix should be in this rectangular region.

For achieving rectangular region, you can swap any two elements of the matrix. Please find out the minimum number of swaps needed. If it is not possible to re-arrange 1's in the desired way, please print -1.

Input

First line of the input contains a single integer T denoting number of test cases.
Description of T test cases follows.
First line of each test case will contain a single integer n denoting dimension of matrix.
Each of next n lines will contain n space separated integers denoting the ith row of the matrix.

Output

For each test case, print a single line containing a single integer denoting minimum number of swaps needed or -1 depending on the situation.

Example

Input:

```<code>2

2

0 1

1 0

2

1 1

1 0
</code>```

Output:

```<code>1

-1
</code>```

Explanation

Example case 1. You can swap 1 of second row first column with 0 of first row first column.
After the swap, matrix will look as follows.

```<code>1 1
0 0
</code>```

Here all the 1's form a rectangular region of dimension 1 × 2. In this case, 1 swap will be needed.

Note that you can also swap 1 at first row second column with 0 at second row second column too.
Matrix after this swap will be following.

```<code>0 0
1 1
</code>```

So you need 1 swap in this case too.

So overall, you need 1 swap.

Example case 2. There is no way to create a rectangular region containing 3 1's in a matrix of dimension 2 × 2, hence answer is -1.

My Algorithm [Edit]

First i am Taking Number of Cases from user

Then the order of matrix [will be of nxn order].

So logic is that if matrix is 1x1 then it will simply print 0

else while taking input from user [that will be only 1 or 0] i am counting 1's because the logic i develop that when in a matrix of odd order the 1's will be even then it cannot be arranged in rectangular form.and for even order of matrix if 1's are odd , not arrange able .

Next i am traversing each index if i find one then i move to next element else i try to find 1 in the same colomn if dont find than i am breaking loop showing -1 that it is not arrange able in rectangular form

Than after arranging a row i check the next row whether it is already arranged or not if it is than i break everything and moves to next case

n rectangular form

My Solution

```<code>import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;

public class Main {

    static long startTime;

    public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);
            int numberOfOnes = 0;
            int T = scanner.nextInt();

            for (int t = 1; t <= T; t++) {
                int n = scanner.nextInt();

                int loopCounter, swapCounter = 0;
                boolean rowContainsZero = false;
                int array[][] = new int[n][n];
                boolean reject = true;
                //Worst and the most simpler conditions
                if (n == 1) {
                    System.out.print("0");
                    exitingSystem();
                }
                for (int i = 0; i < n; i++) {
                    for (int j = 0; j < n; j++) {
                        array[i][j] = scanner.nextInt();
                        if (array[i][j] == 1) {
                            numberOfOnes++;
                        }
                    }
                }
                if (n % 2 == 0 && numberOfOnes % 2 != 0) {
                    System.out.println("-1");
                    if (t == T) {
                        exitingSystem();
                    }
                    continue;

                } else if (n % 2 != 0 && numberOfOnes % 2 == 0) {
                    System.out.println("-1");
                    if (t == T) {
                        exitingSystem();
                    }
                    continue;
                }
                //     System.out.println("Here i am");
                //From here swaping processes will take the place
                for (int i = 0; i < n; i++) {
                    for (int j = 0; j < n; j++) {
                        if (array[i][j] == 1) {
                            continue;
                        } else if (array[i][j] == 0) {
                            loopCounter = i;
                            reject = true;
                            while (loopCounter < n) {
                                if (array[loopCounter][j] == 1) {
                                    int temp = array[loopCounter][j];
                                    array[loopCounter][j] = array[i][j];
                                    array[i][j] = temp;
                                    reject = false;
                                    swapCounter += 1;
                                    break;
                                }
                                loopCounter++;
                            }
                             if (rowContainsZero) {
                                System.out.println("" + swapCounter);
                                    break;
                            }
                            if (reject == true) {
                                System.out.println("-1");
                                break;
                            } else {
                                for (int m = i + 1; m < n; m++) {
                                    for (int k = 0; k < n; k++) {
                                        if (array[m][k] == 0) {
                                            rowContainsZero = true;
                                        } else {
                                            rowContainsZero = false;
                                            break;
                                        }
                                    }
                                }
                            }

                        } else {
                            System.out.println("0's and 1's were Expected :(");
                            exitingSystem();
                        }
                    }
                    if (reject == true) {
                        break;
                    }
                }
            }

    }

    public static void exitingSystem() {
        System.exit(0);
    }

}
</code>```

BUT THE CODECHEF COMPUTER SAYING WRONG ANSWER + They allowed to take input from keyboard too

答:
I think your algorithm isn't fully correct.

I think the following is a counter-example for your step 4 / odd order (n=3) and even number of ones (numberOfOnes=4):

```<code>1 1 0
1 1 0
0 0 0
</code>```

This should give 0.
Similar for n=4 and numberOfOnes=3:

```<code>1 1 1 0
0 0 0 0
0 0 0 0
0 0 0 0
</code>```

This should give 0 as well.

I haven't yet deeply analyzed your steps 5 and 6.

Here are some more examples:

```<code>1 1 1 0
1 1 0 0
1 1 1 0
1 1 0 0
</code>```

This should give -1, as from 10 ones you can only form rectangles of the form 2*5 or 1*10, which both don't fit into the 4*4 frame.

```<code>1 1 1 0
1 1 0 0
1 1 1 0
1 0 0 0
</code>```

This should give 1, as by moving the lower-left 1 two palces up and right, you get a 3*3 rectangle.

Title: Algorithm not showing right output

Body:
The Question was:

You are given a binary matrix (i.e. each element of matrix is either 0 or 1) of size n × n. You want to re-arrange 1's in such a way that they form a rectangular region. Note that the rectangular region should be made of only 1's, and all the 1's of the entire matrix should be in this rectangular region.

For achieving rectangular region, you can swap any two elements of the matrix. Please find out the minimum number of swaps needed. If it is not possible to re-arrange 1's in the desired way, please print -1.

Input

First line of the input contains a single integer T denoting number of test cases.
Description of T test cases follows.
First line of each test case will contain a single integer n denoting dimension of matrix.
Each of next n lines will contain n space separated integers denoting the ith row of the matrix.

Output

For each test case, print a single line containing a single integer denoting minimum number of swaps needed or -1 depending on the situation.

Example

Input:

2

2

0 1

1 0

2

1 1

1 0

Output:

1

-1

Explanation

Example case 1. You can swap 1 of second row first column with 0 of first row first column.
After the swap, matrix will look as follows.

1 1
0 0

Here all the 1's form a rectangular region of dimension 1 × 2. In this case, 1 swap will be needed.

Note that you can also swap 1 at first row second column with 0 at second row second column too.
Matrix after this swap will be following.

0 0
1 1

So you need 1 swap in this case too.

So overall, you need 1 swap.

Example case 2. There is no way to create a rectangular region containing 3 1's in a matrix of dimension 2 × 2, hence answer is -1.

My Algorithm [Edit]

First i am Taking Number of Cases from user

Then the order of matrix [will be of nxn order].

So logic is that if matrix is 1x1 then it will simply print 0

else while taking input from user [that will be only 1 or 0] i am counting 1's because the logic i develop that when in a matrix of odd order the 1's will be even then it cannot be arranged in rectangular form.and for even order of matrix if 1's are odd , not arrange able .

Next i am traversing each index if i find one then i move to next element else i try to find 1 in the same colomn if dont find than i am breaking loop showing -1 that it is not arrange able in rectangular form

Than after arranging a row i check the next row whether it is already arranged or not if it is than i break everything and moves to next case

n rectangular form

My Solution

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;

public class Main {

    static long startTime;

    public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);
            int numberOfOnes = 0;
            int T = scanner.nextInt();

            for (int t = 1; t <= T; t++) {
                int n = scanner.nextInt();

                int loopCounter, swapCounter = 0;
                boolean rowContainsZero = false;
                int array[][] = new int[n][n];
                boolean reject = true;
                //Worst and the most simpler conditions
                if (n == 1) {
                    System.out.print("0");
                    exitingSystem();
                }
                for (int i = 0; i < n; i++) {
                    for (int j = 0; j < n; j++) {
                        array[i][j] = scanner.nextInt();
                        if (array[i][j] == 1) {
                            numberOfOnes++;
                        }
                    }
                }
                if (n % 2 == 0 && numberOfOnes % 2 != 0) {
                    System.out.println("-1");
                    if (t == T) {
                        exitingSystem();
                    }
                    continue;

                } else if (n % 2 != 0 && numberOfOnes % 2 == 0) {
                    System.out.println("-1");
                    if (t == T) {
                        exitingSystem();
                    }
                    continue;
                }
                //     System.out.println("Here i am");
                //From here swaping processes will take the place
                for (int i = 0; i < n; i++) {
                    for (int j = 0; j < n; j++) {
                        if (array[i][j] == 1) {
                            continue;
                        } else if (array[i][j] == 0) {
                            loopCounter = i;
                            reject = true;
                            while (loopCounter < n) {
                                if (array[loopCounter][j] == 1) {
                                    int temp = array[loopCounter][j];
                                    array[loopCounter][j] = array[i][j];
                                    array[i][j] = temp;
                                    reject = false;
                                    swapCounter += 1;
                                    break;
                                }
                                loopCounter++;
                            }
                             if (rowContainsZero) {
                                System.out.println("" + swapCounter);
                                    break;
                            }
                            if (reject == true) {
                                System.out.println("-1");
                                break;
                            } else {
                                for (int m = i + 1; m < n; m++) {
                                    for (int k = 0; k < n; k++) {
                                        if (array[m][k] == 0) {
                                            rowContainsZero = true;
                                        } else {
                                            rowContainsZero = false;
                                            break;
                                        }
                                    }
                                }
                            }

                        } else {
                            System.out.println("0's and 1's were Expected :(");
                            exitingSystem();
                        }
                    }
                    if (reject == true) {
                        break;
                    }
                }
            }

    }

    public static void exitingSystem() {
        System.exit(0);
    }

}

BUT THE CODECHEF COMPUTER SAYING WRONG ANSWER + They allowed to take input from keyboard too

Body:
I think your algorithm isn't fully correct.

I think the following is a counter-example for your step 4 / odd order (n=3) and even number of ones (numberOfOnes=4):

1 1 0
1 1 0
0 0 0

This should give 0.
Similar for n=4 and numberOfOnes=3:

1 1 1 0
0 0 0 0
0 0 0 0
0 0 0 0

This should give 0 as well.

I haven't yet deeply analyzed your steps 5 and 6.

Here are some more examples:

1 1 1 0
1 1 0 0
1 1 1 0
1 1 0 0

This should give -1, as from 10 ones you can only form rectangles of the form 2*5 or 1*10, which both don't fit into the 4*4 frame.

1 1 1 0
1 1 0 0
1 1 1 0
1 0 0 0

This should give 1, as by moving the lower-left 1 two palces up and right, you get a 3*3 rectangle.


问:
Rails irb default directory
I'm trying to include a source code file when I run irb but irb is unable to find it.

For example, say I am in the following directory in terminal:

```<code>/dan/rubyapp/
</code>```

Assume I have a file named "firstapp.rb" in /dan/rubyapp/

I startup irb and from the irb prompt I type

```<code>> require "firstapp.rb"
</code>```

but the file can't be found. If I type "Dir.pwd" it shows as

```<code>/dan/rubyapp/
</code>```

The only way I can get "require" to work is if I include the full path like so

```<code>> require "/dan/rubyapp/firstapp.rb"
</code>```

Is that the only way I can get this to work? All the tutorials I see online simply do "require file_name" so I assumed it would work.

here is the output from $: at irb

```<code>ruby-1.9.2-p0 > $:
 => ["/Users/Daniel/.rvm/gems/ruby-1.9.2-p0/gems/wirble-0.1.3/bin",
"/Users/Daniel/.rvm/gems/ruby-1.9.2-p0/gems/wirble-0.1.3/lib",
"/Users/Daniel/.rvm/rubies/ruby-1.9.2-p0/lib/ruby/site_ruby/1.9.1",
"/Users/Daniel/.rvm/rubies/ruby-1.9.2-p0/lib/ruby/site_ruby/1.9.1/x86_64-darwin10.4.0",
"/Users/Daniel/.rvm/rubies/ruby-1.9.2-p0/lib/ruby/site_ruby",
"/Users/Daniel/.rvm/rubies/ruby-1.9.2-p0/lib/ruby/vendor_ruby/1.9.1",
"/Users/Daniel/.rvm/rubies/ruby-1.9.2-p0/lib/ruby/vendor_ruby/1.9.1/x86_64-darwin10.4.0",
"/Users/Daniel/.rvm/rubies/ruby-1.9.2-p0/lib/ruby/vendor_ruby",
"/Users/Daniel/.rvm/rubies/ruby-1.9.2-p0/lib/ruby/1.9.1",
"/Users/Daniel/.rvm/rubies/ruby-
1.9.2-p0/lib/ruby/1.9.1/x86_64-darwin10.4.0"]
</code>```

答:
The problem is that the current working directory is no longer in your path (as of Ruby 1.9.2).  There are a few different ways around the problem.

1) In a ruby file itself, you can use the method require_relative instead of require.  This will load a file relative to the loaction of the file containing the require_relative method:
http://extensions.rubyforge.org/rdoc/classes/Kernel.html

```<code>require_relative 'firstapp.rb'
</code>```

This, however, will not work in irb.

2) Your other option is to include the current path in your argument to the require method.  This will work in irb or in a ruby file.  For instance:

```<code>require './firstapp.rb'
</code>```

The reason this was implemented in ruby was to avoid inadvertently requiring the wrong file if there are different files with the same name in different directories in the path (similar to how *nix does not include the current directory "." in its path)

ContentLicense: CC BY-SA 2.5

Title: Rails irb default directory

Body:
I'm trying to include a source code file when I run irb but irb is unable to find it.

For example, say I am in the following directory in terminal:

/dan/rubyapp/

Assume I have a file named "firstapp.rb" in /dan/rubyapp/

I startup irb and from the irb prompt I type

> require "firstapp.rb"

but the file can't be found. If I type "Dir.pwd" it shows as

/dan/rubyapp/

The only way I can get "require" to work is if I include the full path like so

> require "/dan/rubyapp/firstapp.rb"

Is that the only way I can get this to work? All the tutorials I see online simply do "require file_name" so I assumed it would work.

here is the output from $: at irb

ruby-1.9.2-p0 > $:
 => ["/Users/Daniel/.rvm/gems/ruby-1.9.2-p0/gems/wirble-0.1.3/bin",
"/Users/Daniel/.rvm/gems/ruby-1.9.2-p0/gems/wirble-0.1.3/lib",
"/Users/Daniel/.rvm/rubies/ruby-1.9.2-p0/lib/ruby/site_ruby/1.9.1",
"/Users/Daniel/.rvm/rubies/ruby-1.9.2-p0/lib/ruby/site_ruby/1.9.1/x86_64-darwin10.4.0",
"/Users/Daniel/.rvm/rubies/ruby-1.9.2-p0/lib/ruby/site_ruby",
"/Users/Daniel/.rvm/rubies/ruby-1.9.2-p0/lib/ruby/vendor_ruby/1.9.1",
"/Users/Daniel/.rvm/rubies/ruby-1.9.2-p0/lib/ruby/vendor_ruby/1.9.1/x86_64-darwin10.4.0",
"/Users/Daniel/.rvm/rubies/ruby-1.9.2-p0/lib/ruby/vendor_ruby",
"/Users/Daniel/.rvm/rubies/ruby-1.9.2-p0/lib/ruby/1.9.1",
"/Users/Daniel/.rvm/rubies/ruby-
1.9.2-p0/lib/ruby/1.9.1/x86_64-darwin10.4.0"]

Body:
The problem is that the current working directory is no longer in your path (as of Ruby 1.9.2).  There are a few different ways around the problem.

1) In a ruby file itself, you can use the method require_relative instead of require.  This will load a file relative to the loaction of the file containing the require_relative method:
http://extensions.rubyforge.org/rdoc/classes/Kernel.html

require_relative 'firstapp.rb'

This, however, will not work in irb.

2) Your other option is to include the current path in your argument to the require method.  This will work in irb or in a ruby file.  For instance:

require './firstapp.rb'

The reason this was implemented in ruby was to avoid inadvertently requiring the wrong file if there are different files with the same name in different directories in the path (similar to how *nix does not include the current directory "." in its path)


问:
jQuery autocomplete data returned but not displayed
I'm trying to get data from my SQL tables using Jquery auto complete and when I search the data is being returned correctly but it's not being displayed graphically with a drop down box.

my search.ctp

```<code><?php use Cake\Routing\Router; ?>

<?php echo $this->Form->input('id', ['type' => 'text']); ?>

<script>
jQuery('#id').autocomplete({
    source:'<?php echo Router::url(array('controller' => 'Invoices', 'action' => 'search')); ?>'
});
</script>
</code>```

my search function

```<code>public function search()
{
    if ($this->request->is('ajax'))
    {
        $name = $this->request->query['term'];
        $resultArr = $this
            ->Invoices
            ->find()
            ->where(
                ['Invoices.id LIKE' => ($name . '%')],
                ['Invoices.id' => 'string']
            );

        $resultsArr = [];
        foreach ($resultArr as $result)  {
            $resultsArr[] = (strval($result['id']));
        }

        $this->set('invoices', $resultsArr);
        // This line is what handles converting your array into json
        // To get this to work you must load the request handler
        $this->set('_serialize', ['invoices']);
    }
}
</code>```

as you can see it is returning data but no drop down.

答: Solved it by adding json_encode($resultsArr); before serializing the data in my search function.

Body:
I'm trying to get data from my SQL tables using Jquery auto complete and when I search the data is being returned correctly but it's not being displayed graphically with a drop down box.

my search.ctp

<?php use Cake\Routing\Router; ?>

<?php echo $this->Form->input('id', ['type' => 'text']); ?>

my search function

public function search()
{
    if ($this->request->is('ajax'))
    {
        $name = $this->request->query['term'];
        $resultArr = $this
            ->Invoices
            ->find()
            ->where(
                ['Invoices.id LIKE' => ($name . '%')],
                ['Invoices.id' => 'string']
            );

        $resultsArr = [];
        foreach ($resultArr as $result)  {
            $resultsArr[] = (strval($result['id']));
        }

        $this->set('invoices', $resultsArr);
        // This line is what handles converting your array into json
        // To get this to work you must load the request handler
        $this->set('_serialize', ['invoices']);
    }
}

as you can see it is returning data but no drop down.


问:
Tesseract TessBaseApi init() Error
I am using rmtheis tess-two depencies in my project.
Have read many tutorials but nothing helped me.

```<code>package com.example.shaur.ocrapp;

import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.googlecode.tesseract.android.TessBaseAPI;

import java.io.IOException;

public class MainActivity extends AppCompatActivity {

    private static int RESULT_LOAD_IMAGE = 1;

    Button button;
    ImageView image;
    TextView result;
    Bitmap bitmap;
    private static final int GALLERY = 4;

    private static String TESSBASE_PATH= Environment.getRootDirectory().getPath();
    private static final String DEFAULT_LANGUAGE = "eng";

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

        button = (Button) findViewById(R.id.button);
        image = (ImageView) findViewById(R.id.image);
        result = (TextView) findViewById(R.id.result);

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(Intent.ACTION_PICK);
                intent.setType("image/*");

                startActivityForResult(intent, GALLERY);
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == GALLERY) {
            Uri uri = data.getData();
            try {
                bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), uri);
            } catch (IOException e) {
                e.printStackTrace();
            }
            image.setImageBitmap(bitmap);

            final TessBaseAPI baseApi = new TessBaseAPI();

            //Error HERE
            baseApi.init(TESSBASE_PATH, DEFAULT_LANGUAGE);
            baseApi.setPageSegMode(TessBaseAPI.PageSegMode.PSM_SINGLE_LINE);
            baseApi.setVariable(TessBaseAPI.VAR_SAVE_BLOB_CHOICES, TessBaseAPI.VAR_TRUE);

            baseApi.setImage(bitmap);
            String outputText = baseApi.getUTF8Text();
            baseApi.end();

            Log.i("TEXT:",outputText);
            if(DEFAULT_LANGUAGE.equalsIgnoreCase("eng")){
                outputText = outputText.replaceAll("[^a-zA-Z0-9]+", " ");
            }
            result.setText(outputText);

        }
    }
}
</code>```

I read somewhere set Data Path as getFilesDir()+ "/tesseract/". This method id not work. Then I tried  PATH-> "/mnt/sdcard/tessract/"

My eng.traineddata is in the assets folder.

Log Message where Error Comes->

com.example.shaur.ocrapp E/AndroidRuntime: FATAL EXCEPTION: main
                                                                          Process: com.example.shaur.ocrapp, PID: 5736
                                                                          java.lang.RuntimeException: Failure delivering result
  ResultInfo{who=null, request=4, result=-1, data=Intent {
  dat=content://media/external/images/media/43105 flg=0x1
  launchParam=MultiScreenLaunchParams { mDisplayId=0 mBaseDisplayId=0
  mFlags=0 } (has extras) }} to activity
  {com.example.shaur.ocrapp/com.example.shaur.ocrapp.MainActivity}:
  java.lang.IllegalArgumentException: Data path must contain subfolder
  tessdata!
                                                                              at android.app.ActivityThread.deliverResults(ActivityThread.java:4520)
                                                                              at
  android.app.ActivityThread.handleSendResult(ActivityThread.java:4563)
                                                                              at android.app.ActivityThread.-wrap22(ActivityThread.java)
                                                                              at
  android.app.ActivityThread$H.handleMessage(ActivityThread.java:1698)
                                                                              at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                              at android.os.Looper.loop(Looper.java:154)
                                                                              at android.app.ActivityThread.main(ActivityThread.java:6776)
                                                                              at java.lang.reflect.Method.invoke(Native Method)
                                                                              at
  com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1518)
                                                                              at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1408)
                                                                           Caused by: java.lang.IllegalArgumentException: Data path must contain
  subfolder tessdata!
                                                                              at
  com.googlecode.tesseract.android.TessBaseAPI.init(TessBaseAPI.java:311)
                                                                              at
  com.googlecode.tesseract.android.TessBaseAPI.init(TessBaseAPI.java:284)
                                                                              at
  com.example.shaur.ocrapp.MainActivity.onActivityResult(MainActivity.java:73)
                                                                              at android.app.Activity.dispatchActivityResult(Activity.java:7295)
                                                                              at android.app.ActivityThread.deliverResults(ActivityThread.java:4516)
                                                                              at
  android.app.ActivityThread.handleSendResult(ActivityThread.java:4563)
                                                                              at android.app.ActivityThread.-wrap22(ActivityThread.java)
                                                                              at
  android.app.ActivityThread$H.handleMessage(ActivityThread.java:1698)
                                                                              at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                              at android.os.Looper.loop(Looper.java:154)
                                                                              at android.app.ActivityThread.main(ActivityThread.java:6776)
                                                                              at java.lang.reflect.Method.invoke(Native Method)
                                                                              at
  com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1518)
                                                                              at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1408)

Log Message clearly tells "Caused by: java.lang.IllegalArgumentException: Data path must contain subfolder tessdata!". Where Should I create this directory. Is it my phone sdcard where I need to create a folder manually and name it as tesseract and add there a subfolder with tessdata having eng.traineddata.

Image of my directory view

If there is any other error in my code regarding tessaract do highlight and tell the correct method.

答:
Tesseract don't handle the assets folder, you need to copy the .datas to somewhere acessible like /data/Android/yourapppackage/assets/tesseract and use that path.

I did made the Tesseract work only, don't know if Tess-Two does handle that case.

Lets suppose you add the data to /assets/

Then in your code you get the Stream from assets and copy the file to inside the device in the path i mentioned, then in the tesseract impl you use it

Title: Tesseract TessBaseApi init() Error

Body:
I am using rmtheis tess-two depencies in my project.
Have read many tutorials but nothing helped me.

package com.example.shaur.ocrapp;

import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.googlecode.tesseract.android.TessBaseAPI;

import java.io.IOException;

public class MainActivity extends AppCompatActivity {

    private static int RESULT_LOAD_IMAGE = 1;

    Button button;
    ImageView image;
    TextView result;
    Bitmap bitmap;
    private static final int GALLERY = 4;

    private static String TESSBASE_PATH= Environment.getRootDirectory().getPath();
    private static final String DEFAULT_LANGUAGE = "eng";

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

        button = (Button) findViewById(R.id.button);
        image = (ImageView) findViewById(R.id.image);
        result = (TextView) findViewById(R.id.result);

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(Intent.ACTION_PICK);
                intent.setType("image/*");

                startActivityForResult(intent, GALLERY);
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == GALLERY) {
            Uri uri = data.getData();
            try {
                bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), uri);
            } catch (IOException e) {
                e.printStackTrace();
            }
            image.setImageBitmap(bitmap);

            final TessBaseAPI baseApi = new TessBaseAPI();

            //Error HERE
            baseApi.init(TESSBASE_PATH, DEFAULT_LANGUAGE);
            baseApi.setPageSegMode(TessBaseAPI.PageSegMode.PSM_SINGLE_LINE);
            baseApi.setVariable(TessBaseAPI.VAR_SAVE_BLOB_CHOICES, TessBaseAPI.VAR_TRUE);

            baseApi.setImage(bitmap);
            String outputText = baseApi.getUTF8Text();
            baseApi.end();

            Log.i("TEXT:",outputText);
            if(DEFAULT_LANGUAGE.equalsIgnoreCase("eng")){
                outputText = outputText.replaceAll("[^a-zA-Z0-9]+", " ");
            }
            result.setText(outputText);

        }
    }
}

I read somewhere set Data Path as getFilesDir()+ "/tesseract/". This method id not work. Then I tried  PATH-> "/mnt/sdcard/tessract/"

My eng.traineddata is in the assets folder.

Log Message where Error Comes->

com.example.shaur.ocrapp E/AndroidRuntime: FATAL EXCEPTION: main
                                                                          Process: com.example.shaur.ocrapp, PID: 5736
                                                                          java.lang.RuntimeException: Failure delivering result
  ResultInfo{who=null, request=4, result=-1, data=Intent {
  dat=content://media/external/images/media/43105 flg=0x1
  launchParam=MultiScreenLaunchParams { mDisplayId=0 mBaseDisplayId=0
  mFlags=0 } (has extras) }} to activity
  {com.example.shaur.ocrapp/com.example.shaur.ocrapp.MainActivity}:
  java.lang.IllegalArgumentException: Data path must contain subfolder
  tessdata!
                                                                              at android.app.ActivityThread.deliverResults(ActivityThread.java:4520)
                                                                              at
  android.app.ActivityThread.handleSendResult(ActivityThread.java:4563)
                                                                              at android.app.ActivityThread.-wrap22(ActivityThread.java)
                                                                              at
  android.app.ActivityThread$H.handleMessage(ActivityThread.java:1698)
                                                                              at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                              at android.os.Looper.loop(Looper.java:154)
                                                                              at android.app.ActivityThread.main(ActivityThread.java:6776)
                                                                              at java.lang.reflect.Method.invoke(Native Method)
                                                                              at
  com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1518)
                                                                              at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1408)
                                                                           Caused by: java.lang.IllegalArgumentException: Data path must contain
  subfolder tessdata!
                                                                              at
  com.googlecode.tesseract.android.TessBaseAPI.init(TessBaseAPI.java:311)
                                                                              at
  com.googlecode.tesseract.android.TessBaseAPI.init(TessBaseAPI.java:284)
                                                                              at
  com.example.shaur.ocrapp.MainActivity.onActivityResult(MainActivity.java:73)
                                                                              at android.app.Activity.dispatchActivityResult(Activity.java:7295)
                                                                              at android.app.ActivityThread.deliverResults(ActivityThread.java:4516)
                                                                              at
  android.app.ActivityThread.handleSendResult(ActivityThread.java:4563)
                                                                              at android.app.ActivityThread.-wrap22(ActivityThread.java)
                                                                              at
  android.app.ActivityThread$H.handleMessage(ActivityThread.java:1698)
                                                                              at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                              at android.os.Looper.loop(Looper.java:154)
                                                                              at android.app.ActivityThread.main(ActivityThread.java:6776)
                                                                              at java.lang.reflect.Method.invoke(Native Method)
                                                                              at
  com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1518)
                                                                              at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1408)

Log Message clearly tells "Caused by: java.lang.IllegalArgumentException: Data path must contain subfolder tessdata!". Where Should I create this directory. Is it my phone sdcard where I need to create a folder manually and name it as tesseract and add there a subfolder with tessdata having eng.traineddata.

Image of my directory view

If there is any other error in my code regarding tessaract do highlight and tell the correct method.


问:
Trying to learn prepared statements in PHP but I cannot get it to work
Below is my function listRecordsMatching($accNo) which connects to my mySQL server to match all records that have a specific account number. I know my problem lies in the way I write my SQL.

My table has the following structure: (int)id, (string)cheque-no, (double)amount, (date)cheque-date, (string)customer, (int)account.

NOTE: conn() is a global function in my config file that returns the mysqli object connected to my server.

EDIT: Since the conn() function is leading to some confusion:

EDIT2: I have found the answer. After doing $stmt->execute() I must bind the results to variables to use them. $stmt->bind_results($var1, $var2, ...)

```<code>// Create connection
$conn = new mysqli($servername, $username, $password);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}
$GLOBALS['conn'] = $conn;
function conn(){
    return $GLOBALS['conn'];
}

function listRecordsMatching($accNo){
    //prepare statement
    $stmt = conn()->prepare("SELECT * FROM `mfs-cheque-app`.`cheques` WHERE `account` = ?");
    $stmt->bind_param('i', $accNo);
    $stmt->execute();
    $row=$stmt->fetch(PDO::FETCH_ASSOC);
    var_dump($row) // outputs NULL
    echo "<form id='records'>1";
    while(true){
        if (!$row) break;
        $c = new Cheque($row['cheque-no'],$row['amount'],$row['cheque-date'],$row['customer'],$row['account']);
        echo $c->list(); // outputs formatted html
    }
    echo "2</form>";
}
OUT>>> NULL<form id="records">12</form>
</code>```

答: You are using 2 different Variables $accNo and $account ...change one of them to match the other and it will probably start working.

Body:
Below is my function listRecordsMatching($accNo) which connects to my mySQL server to match all records that have a specific account number. I know my problem lies in the way I write my SQL.

My table has the following structure: (int)id, (string)cheque-no, (double)amount, (date)cheque-date, (string)customer, (int)account.

NOTE: conn() is a global function in my config file that returns the mysqli object connected to my server.

EDIT: Since the conn() function is leading to some confusion:

EDIT2: I have found the answer. After doing $stmt->execute() I must bind the results to variables to use them. $stmt->bind_results($var1, $var2, ...)

// Create connection
$conn = new mysqli($servername, $username, $password);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}
$GLOBALS['conn'] = $conn;
function conn(){
    return $GLOBALS['conn'];
}

function listRecordsMatching($accNo){
    //prepare statement
    $stmt = conn()->prepare("SELECT * FROM `mfs-cheque-app`.`cheques` WHERE `account` = ?");
    $stmt->bind_param('i', $accNo);
    $stmt->execute();
    $row=$stmt->fetch(PDO::FETCH_ASSOC);
    var_dump($row) // outputs NULL
    echo "<form id='records'>1";
    while(true){
        if (!$row) break;
        $c = new Cheque($row['cheque-no'],$row['amount'],$row['cheque-date'],$row['customer'],$row['account']);
        echo $c->list(); // outputs formatted html
    }
    echo "2</form>";
}
OUT>>> NULL<form id="records">12</form>