问:
How to distribute package for expo? (.web.js, .js configuration)
I want to distribute a package for expo. This package was created while building my app in expo SDK36.

Like many expo dependencies, I use massively the .ios.js, .android.js and .web.js extensions.

While importing a source I have distributed on npm, resolver only import .js without any distinction.

As an example this package should work with expo:

This is the @expo/webpack-config resolved extensions:

```<code>[
  ".web.expo.ts",
  ".web.expo.tsx",
  ".web.expo.mjs",
  ".web.expo.js",
  ".web.expo.jsx",
  ".expo.ts",
  ".expo.tsx",
  ".expo.mjs",
  ".expo.js",
  ".expo.jsx",
  ".web.ts",
  ".web.tsx",
  ".web.mjs",
  ".web.js",
  ".web.jsx",
  ".ts",
  ".tsx",
  ".mjs",
  ".js",
  ".jsx",
  ".json",
  ".wasm"
]
</code>```

But it does not, I have to manually import by suffixing in my sources with.web.

How can I configure expo or my distributed package in order to be able to import proper sources for each environment when sources are imported from node_modules ?

Edit

I was wrong to expect my extensions to work with the main field of my package.json, I have reconfigured my repo with :

```<code>/home/dka/workspace/github.com/yeutech-lab/react-cookiebot/src
├── CookieBot.js
├── CookieBot.native.js
└── index.js
</code>```

Questions  :

I have used .native.js so my reactjs users (not only expo and react-native users) will import the .js file by default

Because of (1), others react user's (neither react-native nor expo) don't need some sort of extra configuration to support react-native extensions .web.js, .ios.js, .android.is, .native.js and .js.

In case I do prefer .web.js instead of (1), it will not be possible for my react user to do as in (2), and in this case: what would be the way for them to configure react-native extensions in their project?

For all react-native users, may I know where the extension can be configured in native projects? (I believe web project can be configured in webpack with config.resolve.extensions)

答:
Regarding the main field

In a node module, you can make the bundler resolve a platform specific "main" file by deleting the file extension in your package.json.

```<code> -  "main": "index.js"
 +  "main": "index"
</code>```

I would advise against this though as the bundler resolution could work differently in bundlers other than Webpack and Metro. It would be safer to have one "main" file re-export the contents of other platform specific modules (It appears this is what you did in your edit, but I'll leave the explanation here for completeness):

index.js

```<code>export * from './module';
</code>```

module.js Vanilla JS

module.web.js React Native for web

module.native.js React Native

In case I do prefer .web.js instead of (1), it will not be possible for my react user to do as in (2), and in this case: what would be the way for them to configure react-native extensions in their project?

It's important to remember that .web.js can still be resolved even if the project isn't a React Native web project. Create React App resolves .web.js extensions for every project.

On web, users can configure their platform extensions by modifying the config.resolve.extensions field of the Webpack config. In Expo this can be done by running expo customize:web.

Configure native extensions

This can be done by editing the project's Metro config: Example.

Body:
I want to distribute a package for expo. This package was created while building my app in expo SDK36.

Like many expo dependencies, I use massively the .ios.js, .android.js and .web.js extensions.

While importing a source I have distributed on npm, resolver only import .js without any distinction.

As an example this package should work with expo:

This is the @expo/webpack-config resolved extensions:

[
  ".web.expo.ts",
  ".web.expo.tsx",
  ".web.expo.mjs",
  ".web.expo.js",
  ".web.expo.jsx",
  ".expo.ts",
  ".expo.tsx",
  ".expo.mjs",
  ".expo.js",
  ".expo.jsx",
  ".web.ts",
  ".web.tsx",
  ".web.mjs",
  ".web.js",
  ".web.jsx",
  ".ts",
  ".tsx",
  ".mjs",
  ".js",
  ".jsx",
  ".json",
  ".wasm"
]

But it does not, I have to manually import by suffixing in my sources with.web.

How can I configure expo or my distributed package in order to be able to import proper sources for each environment when sources are imported from node_modules ?

Edit

I was wrong to expect my extensions to work with the main field of my package.json, I have reconfigured my repo with :

/home/dka/workspace/github.com/yeutech-lab/react-cookiebot/src
├── CookieBot.js
├── CookieBot.native.js
└── index.js

Questions  :

I have used .native.js so my reactjs users (not only expo and react-native users) will import the .js file by default

Because of (1), others react user's (neither react-native nor expo) don't need some sort of extra configuration to support react-native extensions .web.js, .ios.js, .android.is, .native.js and .js.

In case I do prefer .web.js instead of (1), it will not be possible for my react user to do as in (2), and in this case: what would be the way for them to configure react-native extensions in their project?

For all react-native users, may I know where the extension can be configured in native projects? (I believe web project can be configured in webpack with config.resolve.extensions)

Body:
Regarding the main field

In a node module, you can make the bundler resolve a platform specific "main" file by deleting the file extension in your package.json.

 -  "main": "index.js"
 +  "main": "index"

I would advise against this though as the bundler resolution could work differently in bundlers other than Webpack and Metro. It would be safer to have one "main" file re-export the contents of other platform specific modules (It appears this is what you did in your edit, but I'll leave the explanation here for completeness):

index.js

export * from './module';

module.js Vanilla JS

module.web.js React Native for web

module.native.js React Native

In case I do prefer .web.js instead of (1), it will not be possible for my react user to do as in (2), and in this case: what would be the way for them to configure react-native extensions in their project?

It's important to remember that .web.js can still be resolved even if the project isn't a React Native web project. Create React App resolves .web.js extensions for every project.

On web, users can configure their platform extensions by modifying the config.resolve.extensions field of the Webpack config. In Expo this can be done by running expo customize:web.

Configure native extensions

This can be done by editing the project's Metro config: Example.


来源: stackexchange

问:
A way to exclude action filters in ASP.NET MVC?
I've run into several cases in ASP.NET MVC where I wanted to apply an action filter on every action except one or two.  For example, say you have an AccountController.  Every action in it requires the user be logged in, so you add [Authorize] at the controller level.  But say you want to include the login page in AccountController.  The problem is, users sent to the login page aren't authorized, so this would result in an infinite loop.

The obvious fix (other than moving the Login action to another controller) is to move the [Authorize] from the controller to all action methods except Login.  Well that ain't fun, especially when you have a lot of methods or forget to add [Authorize] to a new method.

Rails makes this easy with an ability to exclude filters.  ASP.NET MVC doesn't let you.  So I decided to make it possible and it was easier than I thought.

```<code>    /// <summary>
/// This will disable any filters of the given type from being applied.  This is useful when, say, all but on action need the Authorize filter.
/// </summary>
[AttributeUsage(AttributeTargets.Method|AttributeTargets.Class, AllowMultiple=true)]
public class ExcludeFilterAttribute : ActionFilterAttribute
{

    public ExcludeFilterAttribute(Type toExclude)
    {
        FilterToExclude = toExclude;
    }

    /// <summary>
    /// The type of filter that will be ignored.
    /// </summary>
    public Type FilterToExclude
    {
        get;
        private set;
    }
}

/// <summary>
/// A subclass of ControllerActionInvoker that implements the functionality of IgnoreFilterAttribute.  To use this, just override Controller.CreateActionInvoker() and return an instance of this.
/// </summary>
public class ControllerActionInvokerWithExcludeFilter : ControllerActionInvoker
{
    protected override FilterInfo GetFilters(ControllerContext controllerContext, ActionDescriptor actionDescriptor)
    {
        //base implementation does all the hard work.  we just prune off the filters to ignore
        var filterInfo = base.GetFilters(controllerContext, actionDescriptor);
        foreach( var toExclude in filterInfo.ActionFilters.OfType<ExcludeFilterAttribute>().Select(f=>f.FilterToExclude).ToArray() )
        {
            RemoveWhere(filterInfo.ActionFilters, filter => toExclude.IsAssignableFrom(filter.GetType()));
            RemoveWhere(filterInfo.AuthorizationFilters, filter => toExclude.IsAssignableFrom(filter.GetType()));
            RemoveWhere(filterInfo.ExceptionFilters, filter => toExclude.IsAssignableFrom(filter.GetType()));
            RemoveWhere(filterInfo.ResultFilters, filter => toExclude.IsAssignableFrom(filter.GetType()));
        }
        return filterInfo;
    }

    /// <summary>
    /// Removes all elements from the list that satisfy the condition.  Returns the list that was passed in (minus removed elements) for chaining.  Ripped from one of my helper libraries (where it was a pretty extension method).
    /// </summary>
    private static IList<T> RemoveWhere<T>(IList<T> list, Predicate<T> predicate)
    {

        if (list == null || list.Count == 0)
            return list;
        //note: didn't use foreach because an exception will be thrown when you remove items during enumeration
        for (var i = 0; i < list.Count; i++)
        {
            var item = list[i];
            if (predicate(item))
            {
                list.RemoveAt(i);
                i--;
            }
        }
        return list;
    }
}

/// <summary>
/// An example of using the ExcludeFilterAttribute.  In this case, Action1 and Action3 require authorization but not Action2.  Notice the CreateActionInvoker() override.  That's necessary for the attribute to work and is probably best to put in some base class.
/// </summary>
[Authorize]
public class ExampleController : Controller
{
    protected override IActionInvoker CreateActionInvoker()
    {
        return new ControllerActionInvokerWithExcludeFilter();
    }

    public ActionResult Action1()
    {
        return View();
    }

    [ExcludeFilter(typeof(AuthorizeAttribute))]
    public ActionResult Action2()
    {
        return View();
    }

    public ActionResult Action3()
    {
        return View();
    }

}
</code>```

The example is right there.  As you can see, this was pretty straightforward to do and works great.  I hope it's useful to anyone?

答:
I prefer the solution outlined here. Though it's not as generic a solution as yours, I found it a bit more straightforward.

In my case, I was looking for a way to enable a CompressionFilter on everything but a few items. So I created an empty attribute like this:

```<code>[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
public sealed class DisableCompression : Attribute { }
</code>```

Then in the main attribute, check for the presence of the attribute like so:

```<code>[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = false)]
public class CompressionFilter : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        bool disabled = filterContext.ActionDescriptor.IsDefined(typeof(DisableCompression), true) ||
                        filterContext.ActionDescriptor.ControllerDescriptor.IsDefined(typeof(DisableCompression), true);
        if (disabled)
            return;

        // action filter logic here...
    }
}
</code>```

Though the page I linked to mentions that this is for MVC 3, it seems to work well enough way back in MVC 1 as well.

EDIT: showing some usage here in response to comments. Before I made the changes above, it looked exactly like this, except without the [DisableCompression] attribute flagging the method I wanted to exclude. There's no other refactoring involved.

```<code>[CompressionFilter]
public abstract class BaseController : Controller
{
}

public class SomeController : BaseController
{
    public ActionResult WantThisActionCompressed()
    {
        // code
    }

    [DisableCompression]
    public ActionResult DontWantThisActionCompressed()
    {
        // code
    }
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I've run into several cases in ASP.NET MVC where I wanted to apply an action filter on every action except one or two.  For example, say you have an AccountController.  Every action in it requires the user be logged in, so you add [Authorize] at the controller level.  But say you want to include the login page in AccountController.  The problem is, users sent to the login page aren't authorized, so this would result in an infinite loop.

The obvious fix (other than moving the Login action to another controller) is to move the [Authorize] from the controller to all action methods except Login.  Well that ain't fun, especially when you have a lot of methods or forget to add [Authorize] to a new method.

Rails makes this easy with an ability to exclude filters.  ASP.NET MVC doesn't let you.  So I decided to make it possible and it was easier than I thought.

    ///
/// This will disable any filters of the given type from being applied.  This is useful when, say, all but on action need the Authorize filter.
///
[AttributeUsage(AttributeTargets.Method|AttributeTargets.Class, AllowMultiple=true)]
public class ExcludeFilterAttribute : ActionFilterAttribute
{

    public ExcludeFilterAttribute(Type toExclude)
    {
        FilterToExclude = toExclude;
    }

    ///
    /// The type of filter that will be ignored.
    ///
    public Type FilterToExclude
    {
        get;
        private set;
    }
}

///
/// A subclass of ControllerActionInvoker that implements the functionality of IgnoreFilterAttribute.  To use this, just override Controller.CreateActionInvoker() and return an instance of this.
///
public class ControllerActionInvokerWithExcludeFilter : ControllerActionInvoker
{
    protected override FilterInfo GetFilters(ControllerContext controllerContext, ActionDescriptor actionDescriptor)
    {
        //base implementation does all the hard work.  we just prune off the filters to ignore
        var filterInfo = base.GetFilters(controllerContext, actionDescriptor);
        foreach( var toExclude in filterInfo.ActionFilters.OfType<ExcludeFilterAttribute>().Select(f=>f.FilterToExclude).ToArray() )
        {
            RemoveWhere(filterInfo.ActionFilters, filter => toExclude.IsAssignableFrom(filter.GetType()));
            RemoveWhere(filterInfo.AuthorizationFilters, filter => toExclude.IsAssignableFrom(filter.GetType()));
            RemoveWhere(filterInfo.ExceptionFilters, filter => toExclude.IsAssignableFrom(filter.GetType()));
            RemoveWhere(filterInfo.ResultFilters, filter => toExclude.IsAssignableFrom(filter.GetType()));
        }
        return filterInfo;
    }

    ///
    /// Removes all elements from the list that satisfy the condition.  Returns the list that was passed in (minus removed elements) for chaining.  Ripped from one of my helper libraries (where it was a pretty extension method).
    ///
    private static IList<T> RemoveWhere<T>(IList<T> list, Predicate<T> predicate)
    {

        if (list == null || list.Count == 0)
            return list;
        //note: didn't use foreach because an exception will be thrown when you remove items during enumeration
        for (var i = 0; i < list.Count; i++)
        {
            var item = list[i];
            if (predicate(item))
            {
                list.RemoveAt(i);
                i--;
            }
        }
        return list;
    }
}

///
/// An example of using the ExcludeFilterAttribute.  In this case, Action1 and Action3 require authorization but not Action2.  Notice the CreateActionInvoker() override.  That's necessary for the attribute to work and is probably best to put in some base class.
///
[Authorize]
public class ExampleController : Controller
{
    protected override IActionInvoker CreateActionInvoker()
    {
        return new ControllerActionInvokerWithExcludeFilter();
    }

    public ActionResult Action1()
    {
        return View();
    }

    [ExcludeFilter(typeof(AuthorizeAttribute))]
    public ActionResult Action2()
    {
        return View();
    }

    public ActionResult Action3()
    {
        return View();
    }

}

The example is right there.  As you can see, this was pretty straightforward to do and works great.  I hope it's useful to anyone?

Body:
I prefer the solution outlined here. Though it's not as generic a solution as yours, I found it a bit more straightforward.

In my case, I was looking for a way to enable a CompressionFilter on everything but a few items. So I created an empty attribute like this:

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
public sealed class DisableCompression : Attribute { }

Then in the main attribute, check for the presence of the attribute like so:

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = false)]
public class CompressionFilter : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        bool disabled = filterContext.ActionDescriptor.IsDefined(typeof(DisableCompression), true) ||
                        filterContext.ActionDescriptor.ControllerDescriptor.IsDefined(typeof(DisableCompression), true);
        if (disabled)
            return;

        // action filter logic here...
    }
}

Though the page I linked to mentions that this is for MVC 3, it seems to work well enough way back in MVC 1 as well.

EDIT: showing some usage here in response to comments. Before I made the changes above, it looked exactly like this, except without the [DisableCompression] attribute flagging the method I wanted to exclude. There's no other refactoring involved.

[CompressionFilter]
public abstract class BaseController : Controller
{
}

public class SomeController : BaseController
{
    public ActionResult WantThisActionCompressed()
    {
        // code
    }

    [DisableCompression]
    public ActionResult DontWantThisActionCompressed()
    {
        // code
    }
}

ContentLicense: CC BY-SA 3.0


问:
Ignite cache transaction forcibly rolled back
I'm using transactions for cache operations in Apache Ignite. I'm seeing warnings in my log where a transaction is forcibly rolled back. Like this:

16-02-2020 02:09:38.249 [-#115][157   ] WARN
  e.internal.processors.cache.distributed.near.GridNearTxLocal-[warning
  ][ 488] The transaction was forcibly rolled back because a timeout is
  reached:
  GridNearTxLocal[xid=fcdfebb4071-00000000-0b85-8094-0000-000000000005,
  xidVersion=GridCacheVersion [topVer=193298580, order=1581818772943,
  nodeOrder=5], concurrency=PESSIMISTIC, isolation=SERIALIZABLE,
  state=ROLLED_BACK, invalidate=false, rollbackOnly=true,
  nodeId=612b38ca-ffbf-46bf-a27b-00fc68555ff7, timeout=10000,
  duration=10006]

It looks like this warning appears in my log randomly and not related to my cache operations.

I'm starting my transaction with this:

```<code>Ignite ignite = Ignition.ignite();
IgniteTransactions transactions = ignite.transactions();
tx = transactions.txStart(TransactionConcurrency.PESSIMISTIC, TransactionIsolation.SERIALIZABLE, TRANSACTION_TIMEOUT, 0);
</code>```

and ending:

```<code>  try
  {
      if (tx.state() == TransactionState.ACTIVE)
      {
          if (commit)
              tx.commit();
          else
              tx.rollback();
      }
  } catch (Exception e)
  {
      logger.error(String.format("Error ending transaction for thread(%d) with commit=%b", Thread.currentThread().getId(), commit));

      // re-throw
      throw new Exception(e);
  } finally
  {
      tx.close();
      tx = null;
  }
</code>```

Why am I not getting the rollback-warning as a TransactionRollbackException on my transaction.commit() call? Isn't commit() supposed to wait until the transaction is fully done?

答: Maybe you never even reach commit(), instead of hanging on some operation earlier than that. You are not guaranteed to ever reach commit: instead, either locking up earlier, failing to catch unhandled error, or just doing busy work indefinitely.</p>

ContentLicense: CC BY-SA 4.0

Body:
I'm using transactions for cache operations in Apache Ignite. I'm seeing warnings in my log where a transaction is forcibly rolled back. Like this:

16-02-2020 02:09:38.249 [-#115][157   ] WARN
  e.internal.processors.cache.distributed.near.GridNearTxLocal-[warning
  ][ 488] The transaction was forcibly rolled back because a timeout is
  reached:
  GridNearTxLocal[xid=fcdfebb4071-00000000-0b85-8094-0000-000000000005,
  xidVersion=GridCacheVersion [topVer=193298580, order=1581818772943,
  nodeOrder=5], concurrency=PESSIMISTIC, isolation=SERIALIZABLE,
  state=ROLLED_BACK, invalidate=false, rollbackOnly=true,
  nodeId=612b38ca-ffbf-46bf-a27b-00fc68555ff7, timeout=10000,
  duration=10006]

It looks like this warning appears in my log randomly and not related to my cache operations.

I'm starting my transaction with this:

Ignite ignite = Ignition.ignite();
IgniteTransactions transactions = ignite.transactions();
tx = transactions.txStart(TransactionConcurrency.PESSIMISTIC, TransactionIsolation.SERIALIZABLE, TRANSACTION_TIMEOUT, 0);

and ending:

  try
  {
      if (tx.state() == TransactionState.ACTIVE)
      {
          if (commit)
              tx.commit();
          else
              tx.rollback();
      }
  } catch (Exception e)
  {
      logger.error(String.format("Error ending transaction for thread(%d) with commit=%b", Thread.currentThread().getId(), commit));

      // re-throw
      throw new Exception(e);
  } finally
  {
      tx.close();
      tx = null;
  }

Why am I not getting the rollback-warning as a TransactionRollbackException on my transaction.commit() call? Isn't commit() supposed to wait until the transaction is fully done?


问:
Class 'Illuminate\Session\CommandsServiceProvider' not found in laravel 6.1
```<code>    /**
     * @param  string  $provider
     * @return \Illuminate\Support\ServiceProvider
     */
    public function createProvider($provider)
    {
        return new $provider($this->app);
    }
</code>```

答:
Server Requirements

The Laravel framework has a few system requirements. Before we will install laravel 6.1 on windows, read some system requirements.

```<code>PHP >= 7.2.0
BCMath PHP Extension
Ctype PHP Extension
JSON PHP Extension
Mbstring PHP Extension
OpenSSL PHP Extension
PDO PHP Extension
Tokenizer PHP Extension
XML PHP Extension
</code>```

Body:
Server Requirements

The Laravel framework has a few system requirements. Before we will install laravel 6.1 on windows, read some system requirements.

PHP >= 7.2.0
BCMath PHP Extension
Ctype PHP Extension
JSON PHP Extension
Mbstring PHP Extension
OpenSSL PHP Extension
PDO PHP Extension
Tokenizer PHP Extension
XML PHP Extension


问:
Postgres Node search query using LIKE, how to set %
I have a weird problem I encountered using Postgresql and Node. I would like to use LIKE in my query together with % at the beginning and end of searched term. I have no issue using it in the plain SQL:

THIS WORKS:

```<code>SELECT * FROM vehicle WHERE module_imei LIKE '%searchterm%' OR custom_id LIKE '%searchterm%'
</code>```

However, using it in Node is a bit of challenge. I haven't been successful in resolving it yet:
THIS DOES NOT WORK:

```<code>  getVehiclesSearch: async function({ search }) {
    let response;
    try {
      response = await pool.query(`SELECT * FROM vehicle WHERE module_imei LIKE %$1% OR custom_id LIKE %$1%`, [search]);
      if(response) return response.rows;
    } catch(error) {
      // handle error
      console.error(error);
      // do not throw anything
    }
  },
</code>```

Doing above will produce: syntax error at or near "%"

```<code>SELECT * FROM vehicle WHERE module_imei LIKE '%${$1}%' OR custom_id LIKE '%${$1}%
</code>```

Doing above will produce: $1 is not defined

```<code>SELECT * FROM vehicle WHERE module_imei LIKE '%$1%' OR custom_id LIKE '%$1%'
</code>```

Doing above will produce: bind message supplies 1 parameters, but prepared statement "" requires 0

I kind of struggle factoring the % in so it won't crash the query. Simply run out of ideas after trying above and variables of those. Thanks for your kind help.

答:
You are missing single quotes, also I don't recognize a db adapter you use, but you can use template literals (watch out for sql injection!!!)</p>

```<code>response = await pool.query(`SELECT * FROM vehicle WHERE module_imei LIKE '%${search}%' OR custom_id LIKE '%${search}%'`);
</code>```

Body:
I have a weird problem I encountered using Postgresql and Node. I would like to use LIKE in my query together with % at the beginning and end of searched term. I have no issue using it in the plain SQL:

THIS WORKS:

SELECT * FROM vehicle WHERE module_imei LIKE '%searchterm%' OR custom_id LIKE '%searchterm%'

However, using it in Node is a bit of challenge. I haven't been successful in resolving it yet:
THIS DOES NOT WORK:

  getVehiclesSearch: async function({ search }) {
    let response;
    try {
      response = await pool.query(`SELECT * FROM vehicle WHERE module_imei LIKE %$1% OR custom_id LIKE %$1%`, [search]);
      if(response) return response.rows;
    } catch(error) {
      // handle error
      console.error(error);
      // do not throw anything
    }
  },

Doing above will produce: syntax error at or near "%"

SELECT * FROM vehicle WHERE module_imei LIKE '%${$1}%' OR custom_id LIKE '%${$1}%

Doing above will produce: $1 is not defined

SELECT * FROM vehicle WHERE module_imei LIKE '%$1%' OR custom_id LIKE '%$1%'

Doing above will produce: bind message supplies 1 parameters, but prepared statement "" requires 0

I kind of struggle factoring the % in so it won't crash the query. Simply run out of ideas after trying above and variables of those. Thanks for your kind help.

Body:
You are missing single quotes, also I don't recognize a db adapter you use, but you can use template literals (watch out for sql injection!!!)

response = await pool.query(`SELECT * FROM vehicle WHERE module_imei LIKE '%${search}%' OR custom_id LIKE '%${search}%'`);


问:
Issue presenting empty tableview text and image
Essentially I have a tableview that must display an image text when it is not presenting any rows.

I have the following structure decoding the JSON:

```<code>var sections = [JSONSection]()

struct JSONSection {
    let date : String
    var items : [JSONStructure]
}

struct JSONStructure: Decodable {

    let person: String
    let processtime: String

    enum CodingKeys : String, CodingKey {
        case person, processtime
    }

}

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

    let section = sections[section].items

    if section.count == 0 { tableView.setEmptyView(title: "Text", message: "Message")
    } else {
        tableView.restore()
    }

    return section.count

}
</code>```

I get no error but instead of the custom message I just get a blank tableview (White background)

This is most likely caused by how I am writing the conditional, am I defining sectionn.count wrong?

答:
Set your dataSource and delegate in viewDidLoad:</p>

```<code>self.tableView.delegate = self
self.tableView.dataSource = self
</code>```

Body:
Essentially I have a tableview that must display an image text when it is not presenting any rows.

I have the following structure decoding the JSON:

var sections = [JSONSection]()

struct JSONSection {
    let date : String
    var items : [JSONStructure]
}

struct JSONStructure: Decodable {

    let person: String
    let processtime: String

    enum CodingKeys : String, CodingKey {
        case person, processtime
    }

}

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

    let section = sections[section].items

    if section.count == 0 { tableView.setEmptyView(title: "Text", message: "Message")
    } else {
        tableView.restore()
    }

    return section.count

}

I get no error but instead of the custom message I just get a blank tableview (White background)

This is most likely caused by how I am writing the conditional, am I defining sectionn.count wrong?

Body:
Set your dataSource and delegate in viewDidLoad:

self.tableView.delegate = self
self.tableView.dataSource = self


问:
How to allow client managers to test functions in Youtrack?
I'm trying to set up YouTrack as a bug tracker, but I can't find a way to give my client's managers to open up issues. </p>

答: For a user to be able to create issues, they need to posses the Create Issue permission. This permission is included in Reporters role. So the easiest solution would be to grant your client's managers the Reporter role in the project.</p>


问:
How do I clone a single branch in Git?
I have a local Git repository in ~/local_repo. It has a few branches:

```<code>$ git branch
* master
  rails
  c
  c++
</code>```

To clone the local repository, I do:

```<code>$ git clone ~/local_repo new_repo
Initialized empty Git repository in /home/username/new_repo/.git/
</code>```

The new_repo master branch points to the local_repo master branch, and I can push / pull.

But I am unable to clone another branch. I want to only pull the branch I want (e.g. rails), so that the new repository has a master branch that pushes to and pulls from local_repo's rails branch, by default. How do I accomplish this, or perhaps something similar with local_repo tracking the master local_repo?

答:
There are primarily 2 solutions for this:

You need to specify the branch name with -b command switch. Here is the syntax of the command to clone the specific git branch.

```<code>git clone -b <BRANCH_NAME> <GIT_REMOTE_URL>
</code>```

Example:

```<code>git clone -b tahir https://github.com/Repository/Project.git
</code>```

The following command will clone the branch tahir from the git repository.The above command clones only the specific branch but fetches the details of other branches. You can view all branches details with command.

```<code>git branch -a
</code>```

You can use --single-branch flag to prevent fetching details of other branches like below:

```<code>git clone -b <BRANCH_NAME> --single-branch <GIT_REMOTE_URL>
</code>```

Example:

```<code>git clone -b tahir --single-branch \
https://github.com/Repository/Project.git
</code>```

Now if you do a git branch -a, it will only show your current single branch that you have cloned and not all the branches. So it depends on you how you want it.

Title: How do I clone a single branch in Git?

Body:
I have a local Git repository in ~/local_repo. It has a few branches:

$ git branch
* master
  rails
  c
  c++

To clone the local repository, I do:

$ git clone ~/local_repo new_repo
Initialized empty Git repository in /home/username/new_repo/.git/

The new_repo master branch points to the local_repo master branch, and I can push / pull.

But I am unable to clone another branch. I want to only pull the branch I want (e.g. rails), so that the new repository has a master branch that pushes to and pulls from local_repo's rails branch, by default. How do I accomplish this, or perhaps something similar with local_repo tracking the master local_repo?

Body:
There are primarily 2 solutions for this:

You need to specify the branch name with -b command switch. Here is the syntax of the command to clone the specific git branch.

git clone -b <BRANCH_NAME> <GIT_REMOTE_URL>

Example:

git clone -b tahir https://github.com/Repository/Project.git

The following command will clone the branch tahir from the git repository.The above command clones only the specific branch but fetches the details of other branches. You can view all branches details with command.

git branch -a

You can use --single-branch flag to prevent fetching details of other branches like below:

git clone -b <BRANCH_NAME> --single-branch <GIT_REMOTE_URL>

Example:

git clone -b tahir --single-branch \
https://github.com/Repository/Project.git

Now if you do a git branch -a, it will only show your current single branch that you have cloned and not all the branches. So it depends on you how you want it.


问:
Why sub() and gsub() have the same results?
```<code>x <- c("This is a sentence about axis",
     "A second pattern is also listed here")

sub(".*is", "XY", x)
#[1] "XY"         "XYted here"

gsub(".*is", "XY", x)
#[1] "XY"         "XYted here"
</code>```

答:
When you are using the pattern ".*is", it matches everything from start of the string to the last "is", which in first sentence is  "is" in "axis" and "is" in "listed" in 2nd string. Hence, everything upto that part gets replaced by "XY".

What probably you might be expecting is :

```<code>sub("is", "XY", x)
#[1] "ThXY is a sentence about axis"        "A second pattern XY also listed here"

gsub("is", "XY", x)
#[1] "ThXY XY a sentence about axXY"        "A second pattern XY also lXYted here
</code>```

As you can see in the sub call only the first "is" is replaced whereas in gsub all of the instances of "is" are replaced with "XY".

Body:
When you are using the pattern ".*is", it matches everything from start of the string to the last "is", which in first sentence is  "is" in "axis" and "is" in "listed" in 2nd string. Hence, everything upto that part gets replaced by "XY".

What probably you might be expecting is :

sub("is", "XY", x)
#[1] "ThXY is a sentence about axis"        "A second pattern XY also listed here"

gsub("is", "XY", x)
#[1] "ThXY XY a sentence about axXY"        "A second pattern XY also lXYted here

As you can see in the sub call only the first "is" is replaced whereas in gsub all of the instances of "is" are replaced with "XY".


问:
Resolving clang Warnings in a Simple C Scanner
I have a basic C code with the intent of reading the contents of a file via opening a file, reading the contents and closing a file. Although the following code compiles and works, the clang compiler gives some extra warnings, which I was unable to address.

```<code>#include <stdio.h>

char* scanFile(FILE *fl, char* ch);

int main(int argc, char const* argv[])
{
    FILE *file;
    char *ch = "\0";

    ch = scanFile(file, ch);
    fclose(file);

    printf("%s\n", ch);
    return 0;
}

char* scanFile(FILE *fl, char* ch)
{
    fl = fopen("/tmp/test.txt", "r");
    if (fl)
    {
        while ((ch = getchar()) != EOF) { putchar(ch); }
    }

    return ch;
}
</code>```

When I try to compile my code, the following warnings are flashed by my clang.

```<code>clang scanFile scanFile.c
scanFile.c:22:20: warning: incompatible integer to pointer conversion assigning to 'char *'
from 'int' [-Wint-conversion]
    while ((ch = getchar()) != EOF) { putchar(ch); }
               ^ ~~~~~~~~~
scanFile.c:22:33: warning: comparison between pointer and integer ('char *' and 'int')
    while ((ch = getchar()) != EOF) { putchar(ch); }
           ~~~~~~~~~~~~~~~~ ^  ~~~
scanFile.c:22:51: warning: incompatible pointer to integer conversion passing 'char *' to parameter of type 'int' [-Wint-conversion]
    while ((ch = getchar()) != EOF) { putchar(ch); }
                                              ^~
/Library/Developer/CommandLineTools/SDKs/MacOSX10.14.sdk/usr/include/stdio.h:172:17: note: passing argument to parameter here
int      putchar(int);
                ^
3 warnings generated.
ld: can't link with a main executable file 'scanFile' for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
</code>```

However, since the compilation process is devoid of any serious ERRORs, when I run the executable file generated as the result of my compilation above, I get the following on my screen (the following faux-latin is the file that should be read and outputted as so in my C code.)

```<code>Ergo ego senator inimicus, si ita vultis, homini, amicus esse, sicut semper fui, rei publicae debeo.
Quid? si ipsas inimicitias, depono rei publicae causa, quis me tandem iure reprehendet, praesertim cum ego omnium meorum consiliorum atque factorum exempla semper ex summorum hominum consiliis atque factis mihi censuerim petenda.

Eodem tempore etiam Hymetii praeclarae indolis viri negotium est actitatum, cuius hunc novimus esse textum.
Cum Africam pro consule regeret Carthaginiensibus victus inopia iam lassatis, ex horreis
Romano populo destinatis frumentum dedit, pauloque postea cum provenisset segetum copia, integre sine ulla restituit mora.

Et hanc quidem praeter oppida multa duae civitates exornant Seleucia opus Seleuci regis, et Claudiopolis quam deduxit coloniam Claudius Caesar.
Isaura enim antehac nimium potens, olim subversa ut rebellatrix interneciva aegre vestigia claritudinis pristinae monstrat admodum pauca.
[1]    59823 segmentation fault  ./scanFile
</code>```

NOTE: BUT IT ALSO GIVES A ' 59823 segmentation fault  ./scanfile ' error still.

EXTRA: clang -Wall gives;

```<code>C clang -Wall scanFile.c
scanFile.c:10:19: warning: variable 'file' is uninitialized when used here [-Wuninitialized]
    ch = scanFile(file, ch);
              ^~~~
scanFile.c:7:15: note: initialize the variable 'file' to silence this warning
    FILE *file;
          ^
               = NULL
scanFile.c:22:20: warning: incompatible integer to pointer conversion assigning to 'char *' from 'int' [-Wint-conversion]
    while ((ch = getchar()) != EOF) { putchar(ch); }
               ^ ~~~~~~~~~
scanFile.c:22:33: warning: comparison between pointer and integer ('char *' and 'int')
    while ((ch = getchar()) != EOF) { putchar(ch); }
           ~~~~~~~~~~~~~~~~ ^  ~~~
scanFile.c:22:51: warning: incompatible pointer to integer conversion passing 'char *' to parameter of type 'int' [-Wint-conversion]
    while ((ch = getchar()) != EOF) { putchar(ch); }
                                              ^~
/Library/Developer/CommandLineTools/SDKs/MacOSX10.14.sdk/usr/include/stdio.h:172:17: note: passing argument to parameter here
int      putchar(int);
                ^
4 warnings generated.
</code>```

答:
Ahmet you have a few errors in your code:

You are not allocating memory for resulting string. When you define a string like you do char *ch = "\0"; it is called string literal. Trying to modify a string literal is undefined behaviour. You can read more about string literals at here. This is giving you segmentation fault.

You are trying to pass a file pointer to scanFile function, to close the file when the function is finished. But when you pass file pointer to scanFile function, it is passed by value. And compiler warning you that you didn't initialize it before passing it. When scanFile function opens the file and assigns the resulting file pointer to its parameter, it can not be accessable outside of the function. You have to return a file pointer to do that.

You are using getchar to read a character from a file. It is used to get character from stdin. By default it get characters from keyboard. You should use fgetc to get character from a file.

Here is a working example for you which UPDATED for checking errno for possible malloc or fopen failure:

```<code>#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>

#define MAX_BUFFER_SIZE 1000

struct {
    FILE *fPtr;
    char *text;
} typedef Result;

Result scanFile(const char *fileName);

int main(int argc, char const* argv[]) {
    Result result = scanFile("text.txt");
    printf("Result:\n%s\n", result.text);
    return 0;
    if (errno != 0) {
        printf("Program ended with error: %d\n", errno);
        return -1;
    }

    printf("Result:\n%s\n", result.text);
    // Close the file
    fclose(result.fPtr);
    // Free buffer
    free(result.text);
    return 0;
}

Result scanFile(const char *fileName) {

    Result result;

    result.text = (char *)malloc(sizeof(char)*MAX_BUFFER_SIZE);

    if (result.text == NULL) {
        printf("scanFile: Faield to allocate memory!\n");
        printf("scanFile: %s\n", strerror( errno ));
        return result;
    }

    result.fPtr = fopen(fileName, "r");

    if (result.fPtr == NULL) {
        printf("scanFile: Faield to open file!\n");
        printf("scanFile: %s\n", strerror( errno ));
        return result;
    }

    unsigned int count = 0;
    int ch;

    while ((ch = fgetc(result.fPtr)) != EOF) {
        if (count < MAX_BUFFER_SIZE) {
            result.text[count] = ch;
            ++count;
        } else {
            printf("scanFile: Exceeded buffer size!\n");
            break;
        }
    }

    return result;
}
</code>```

Body:
I have a basic C code with the intent of reading the contents of a file via opening a file, reading the contents and closing a file. Although the following code compiles and works, the clang compiler gives some extra warnings, which I was unable to address.

#include <stdio.h>

char* scanFile(FILE *fl, char* ch);

int main(int argc, char const* argv[])
{
    FILE *file;
    char *ch = "\0";

    ch = scanFile(file, ch);
    fclose(file);

    printf("%s\n", ch);
    return 0;
}

char* scanFile(FILE *fl, char* ch)
{
    fl = fopen("/tmp/test.txt", "r");
    if (fl)
    {
        while ((ch = getchar()) != EOF) { putchar(ch); }
    }

    return ch;
}

When I try to compile my code, the following warnings are flashed by my clang.

clang scanFile scanFile.c
scanFile.c:22:20: warning: incompatible integer to pointer conversion assigning to 'char *'
from 'int' [-Wint-conversion]
    while ((ch = getchar()) != EOF) { putchar(ch); }
               ^ ~~~~~~~~~
scanFile.c:22:33: warning: comparison between pointer and integer ('char *' and 'int')
    while ((ch = getchar()) != EOF) { putchar(ch); }
           ~~~~~~~~~~~~~~~~ ^  ~~~
scanFile.c:22:51: warning: incompatible pointer to integer conversion passing 'char *' to parameter of type 'int' [-Wint-conversion]
    while ((ch = getchar()) != EOF) { putchar(ch); }
                                              ^~
/Library/Developer/CommandLineTools/SDKs/MacOSX10.14.sdk/usr/include/stdio.h:172:17: note: passing argument to parameter here
int      putchar(int);
                ^
3 warnings generated.
ld: can't link with a main executable file 'scanFile' for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)

However, since the compilation process is devoid of any serious ERRORs, when I run the executable file generated as the result of my compilation above, I get the following on my screen (the following faux-latin is the file that should be read and outputted as so in my C code.)

Ergo ego senator inimicus, si ita vultis, homini, amicus esse, sicut semper fui, rei publicae debeo.
Quid? si ipsas inimicitias, depono rei publicae causa, quis me tandem iure reprehendet, praesertim cum ego omnium meorum consiliorum atque factorum exempla semper ex summorum hominum consiliis atque factis mihi censuerim petenda.

Eodem tempore etiam Hymetii praeclarae indolis viri negotium est actitatum, cuius hunc novimus esse textum.
Cum Africam pro consule regeret Carthaginiensibus victus inopia iam lassatis, ex horreis
Romano populo destinatis frumentum dedit, pauloque postea cum provenisset segetum copia, integre sine ulla restituit mora.

Et hanc quidem praeter oppida multa duae civitates exornant Seleucia opus Seleuci regis, et Claudiopolis quam deduxit coloniam Claudius Caesar.
Isaura enim antehac nimium potens, olim subversa ut rebellatrix interneciva aegre vestigia claritudinis pristinae monstrat admodum pauca.
[1]    59823 segmentation fault  ./scanFile

NOTE: BUT IT ALSO GIVES A ' 59823 segmentation fault  ./scanfile ' error still.

EXTRA: clang -Wall gives;

C clang -Wall scanFile.c
scanFile.c:10:19: warning: variable 'file' is uninitialized when used here [-Wuninitialized]
    ch = scanFile(file, ch);
              ^~~~
scanFile.c:7:15: note: initialize the variable 'file' to silence this warning
    FILE *file;
          ^
               = NULL
scanFile.c:22:20: warning: incompatible integer to pointer conversion assigning to 'char *' from 'int' [-Wint-conversion]
    while ((ch = getchar()) != EOF) { putchar(ch); }
               ^ ~~~~~~~~~
scanFile.c:22:33: warning: comparison between pointer and integer ('char *' and 'int')
    while ((ch = getchar()) != EOF) { putchar(ch); }
           ~~~~~~~~~~~~~~~~ ^  ~~~
scanFile.c:22:51: warning: incompatible pointer to integer conversion passing 'char *' to parameter of type 'int' [-Wint-conversion]
    while ((ch = getchar()) != EOF) { putchar(ch); }
                                              ^~
/Library/Developer/CommandLineTools/SDKs/MacOSX10.14.sdk/usr/include/stdio.h:172:17: note: passing argument to parameter here
int      putchar(int);
                ^
4 warnings generated.

Body:
Ahmet you have a few errors in your code:

You are not allocating memory for resulting string. When you define a string like you do char *ch = "\0"; it is called string literal. Trying to modify a string literal is undefined behaviour. You can read more about string literals at here. This is giving you segmentation fault.

You are trying to pass a file pointer to scanFile function, to close the file when the function is finished. But when you pass file pointer to scanFile function, it is passed by value. And compiler warning you that you didn't initialize it before passing it. When scanFile function opens the file and assigns the resulting file pointer to its parameter, it can not be accessable outside of the function. You have to return a file pointer to do that.

You are using getchar to read a character from a file. It is used to get character from stdin. By default it get characters from keyboard. You should use fgetc to get character from a file.

Here is a working example for you which UPDATED for checking errno for possible malloc or fopen failure:

#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>

#define MAX_BUFFER_SIZE 1000

struct {
    FILE *fPtr;
    char *text;
} typedef Result;

Result scanFile(const char *fileName);

int main(int argc, char const* argv[]) {
    Result result = scanFile("text.txt");
    printf("Result:\n%s\n", result.text);
    return 0;
    if (errno != 0) {
        printf("Program ended with error: %d\n", errno);
        return -1;
    }

    printf("Result:\n%s\n", result.text);
    // Close the file
    fclose(result.fPtr);
    // Free buffer
    free(result.text);
    return 0;
}

Result scanFile(const char *fileName) {

    Result result;

    result.text = (char *)malloc(sizeof(char)*MAX_BUFFER_SIZE);

    if (result.text == NULL) {
        printf("scanFile: Faield to allocate memory!\n");
        printf("scanFile: %s\n", strerror( errno ));
        return result;
    }

    result.fPtr = fopen(fileName, "r");

    if (result.fPtr == NULL) {
        printf("scanFile: Faield to open file!\n");
        printf("scanFile: %s\n", strerror( errno ));
        return result;
    }

    unsigned int count = 0;
    int ch;

    while ((ch = fgetc(result.fPtr)) != EOF) {
        if (count < MAX_BUFFER_SIZE) {
            result.text[count] = ch;
            ++count;
        } else {
            printf("scanFile: Exceeded buffer size!\n");
            break;
        }
    }

    return result;
}


问:
What does 'low in coupling and high in cohesion' mean
I have problems understanding the statement low in coupling and high in cohesion. I have googled and read a lot about this, but still finding it hard to understand.

To what I understand is High cohesion means, that we should have classes that are specialized to perform a particular function. Hope this is correct? Like a credit card validation class, which is specialized to validate credit cards only.

And still don't understand what low Coupling means?

答:
I think you have red so many definitions but in the case you still have doubts or In case you are new to programming and want to go deep into this then I will suggest you to watch this video,
https://youtu.be/HpJTGW9AwX0
It's just reference to get more info about polymorphism...
Hope you get better understanding with this</p>


问:
Exception: Unmarshalling unknown type code occurred at run time
I am working on Android app and we are working as a team. I am facing a serious issue. And that is when ever I try to get the data from intent it gives me following exception

Parcel android.os.Parcel@355932a: Unmarshalling unknown type code
  4784211 at offset 712

I know on SO there are a lot of helping material related to this issue, but my case is different and quiet mind boggling .....

Here is a quick code to see how I am getting my object

```<code>       try {
                if (data.hasExtra("KEY_MY_MODEL")) {

                    MyCustomModel newSelectedModel = data.getParcelableExtra("KEY_MY_MODEL");

                    //DO SOME THING WITH OBJECT
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
</code>```

Case1:
I am getting exception on first line if (data.hasExtra("KEY_MY_MODEL")) {

and this is quiet funny because when I inspect the intent object (data) while debugging and if I look into intent object using debugging I can see all my custom object.

The keys of getting object are same, if in any case the key is wrong I think the code inside the  if condition must not get run. as it will return false.

But instead of returning false it is giving the above mentioned exception.

Case2: As I told you we are working in team, the same set of code is running perfectly on other system, but when I run app from my system and install app on device, it is giving the exception I mentioned above.

This is very much frustrating. I think there is something wrong with proguard, as I read on S.O but its still not helpful. Any Idea why this is happening? This looks like a big bug.

Note: I am using A.S 3.5 and on other system A.S 3.5 is in use, even we have same set of sdk, configurations and other things are quiet
  identical on both sides...

答:
It seems to be a ProGuard issue

Just add this line in proguard.rules.pro/txt

```<code>-keepclassmembers class * implements android.os.Parcelable {
    static ** CREATOR;
}
</code>```

Body:
I am working on Android app and we are working as a team. I am facing a serious issue. And that is when ever I try to get the data from intent it gives me following exception

Parcel android.os.Parcel@355932a: Unmarshalling unknown type code
  4784211 at offset 712

I know on SO there are a lot of helping material related to this issue, but my case is different and quiet mind boggling .....

Here is a quick code to see how I am getting my object

       try {
                if (data.hasExtra("KEY_MY_MODEL")) {

                    MyCustomModel newSelectedModel = data.getParcelableExtra("KEY_MY_MODEL");

                    //DO SOME THING WITH OBJECT
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

Case1:
I am getting exception on first line if (data.hasExtra("KEY_MY_MODEL")) {

and this is quiet funny because when I inspect the intent object (data) while debugging and if I look into intent object using debugging I can see all my custom object.

The keys of getting object are same, if in any case the key is wrong I think the code inside the  if condition must not get run. as it will return false.

But instead of returning false it is giving the above mentioned exception.

Case2: As I told you we are working in team, the same set of code is running perfectly on other system, but when I run app from my system and install app on device, it is giving the exception I mentioned above.

This is very much frustrating. I think there is something wrong with proguard, as I read on S.O but its still not helpful. Any Idea why this is happening? This looks like a big bug.

Note: I am using A.S 3.5 and on other system A.S 3.5 is in use, even we have same set of sdk, configurations and other things are quiet
  identical on both sides...

Body:
It seems to be a ProGuard issue

Just add this line in proguard.rules.pro/txt

-keepclassmembers class * implements android.os.Parcelable {
    static ** CREATOR;
}


问:
Servlet Compiling error
I developed simple servlet using Apache Tomcat 6.

Firstly I write simple Hello World print servlet. Then set CLASSPATH for servlet-api.jar and compile and copy webapps/login/WEB-INF/classes/test/HelloServlet.class. That's working fine.

After I write simple JDBC connection in the servlet. I downloaded MySQL J-Connector and set CLASSPATH like this:

```<code>C:\Program Files\apache-tomcat-6.0.32\lib\servlet-api.jar;C:\Program Files\apache-tomcat-6.0.32\lib\mysql-connector-java-5.1.16-bin.jar
</code>```

then try to compile; it then shows the following message:

```<code>"Unreported exception java.lang.ClassNotFoundException; must be caught or declared to be thrown"
</code>```

How should I solve that?

答: Keep your  Class.forName()       under try catch block & classpath should ends with (.;) check it once.

Title: Servlet Compiling error

Body:
I developed simple servlet using Apache Tomcat 6.

Firstly I write simple Hello World print servlet. Then set CLASSPATH for servlet-api.jar and compile and copy webapps/login/WEB-INF/classes/test/HelloServlet.class. That's working fine.

After I write simple JDBC connection in the servlet. I downloaded MySQL J-Connector and set CLASSPATH like this:

C:\Program Files\apache-tomcat-6.0.32\lib\servlet-api.jar;C:\Program Files\apache-tomcat-6.0.32\lib\mysql-connector-java-5.1.16-bin.jar

then try to compile; it then shows the following message:

"Unreported exception java.lang.ClassNotFoundException; must be caught or declared to be thrown"

How should I solve that?


问:
How to write a schema for this code in node .js
```<code> _id :hhjjdfghjkkmdfghjkl8888
  orderDetail:
  [
     {
        fitoName:,
        fitoCode:,
        ProviderName:
        ProviderCode:
        Quantity:
        storUrl:fitotouch.com/fivestart/chinasore
     },
     {
        fitoName:,
        fitoCode:,
        ProviderName:
        ProviderCode:
        Quantity:
        storUrl:fitotouch.com/fivestart/chinasore
     }
  ]
}
</code>```

答:
You can do it like this:</p>

```<code>const mongoose = require("mongoose");

const OrderDetails = mongoose.Schema(
  {
    fitoName: String,
    fitoCode: String,
    providerName: String,
    providerCode: String,
    quantity: Number,
    storUrl: String
  },
  { _id: false } // If you don't want an ID to be created by MongoDB
);

const Orders = mongoose.model(
  "orders",
  new mongoose.Schema(
    {
      orderDetail: {
        type: [OrderDetails],
        required: true
      }
    },
    { timestamps: true }
  )
);
</code>```

Body:
You can do it like this:

const mongoose = require("mongoose");

const OrderDetails = mongoose.Schema(
  {
    fitoName: String,
    fitoCode: String,
    providerName: String,
    providerCode: String,
    quantity: Number,
    storUrl: String
  },
  { _id: false } // If you don't want an ID to be created by MongoDB
);

const Orders = mongoose.model(
  "orders",
  new mongoose.Schema(
    {
      orderDetail: {
        type: [OrderDetails],
        required: true
      }
    },
    { timestamps: true }
  )
);


问:
ViewPager doesn't scroll vertically when is inside a CoordinatorLayout
I'm making and android app where the main activity consists in a TabLayout and a ViewPager, a Floating action button is needed to start another activity, the problem is that when I add a CoordinatorLayout the ViewPager doesn't scroll (The viewPager contains 3 fragments one with a RecyclerView and the other two contains just textview with a lot of text, so all of them must scroll vertically.

The ViewPager works perfectly, but when I put it inside a CoordinatorLayout is not possible to do vertical scroll in any of the fragments loaded in the ViewPager.

I tried to add android:nestedScrollingEnabled="true" in every fragment root layout but it doesn't work.

EDIT:
All of the fragments loaded in the ViewPager have ScrollView as Root view.
This is my Main activity layout:

```<code><?xml version="1.0" encoding="utf-8"?>
<androidx.drawerlayout.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true">

    <androidx.coordinatorlayout.widget.CoordinatorLayout

        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".MainActivity">
        <com.google.android.material.appbar.AppBarLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
            app:elevation="0dp"
            >

            <androidx.appcompat.widget.Toolbar
                android:id="@+id/toolbar"
                android:layout_width="match_parent"
                android:layout_height="?attr/actionBarSize"
                android:background="@color/colorPrimary"
                app:popupTheme="@style/ThemeOverlay.AppCompat.Light"

                />

            <com.google.android.material.tabs.TabLayout
                android:id="@+id/TabLayoutPrincipal"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                app:tabIndicatorColor="@color/colorAccent"
                app:tabGravity="fill"
                app:tabMode="fixed"/>

            <androidx.viewpager.widget.ViewPager
                android:id="@+id/ViewPagerPrincipal"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:background="@android:color/white"
                app:layout_behavior="@string/appbar_scrolling_view_behavior"
                android:nestedScrollingEnabled="true"
                />

        </com.google.android.material.appbar.AppBarLayout>

        <com.google.android.material.floatingactionbutton.FloatingActionButton
            android:id="@+id/addShotFAB"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@drawable/ic_add_white_24dp"
            android:layout_gravity="bottom|end"
            android:layout_margin="16dp"/>

    </androidx.coordinatorlayout.widget.CoordinatorLayout>

    <com.google.android.material.navigation.NavigationView
        android:id="@+id/nav_view"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:fitsSystemWindows="true"
        app:menu="@menu/menu_drawer"/>

</androidx.drawerlayout.widget.DrawerLayout>
</code>```

This is what inside of the fragment with the RecyclerView:

```<code><?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:nestedScrollingEnabled="true">

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/RecViewTomas"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
</code>```

The another fragment:

```<code><?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent"
    >

    <FrameLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <TextView
            android:textSize="50sp"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="There are many variations of passages of Lorem Ipsum available, but the majority have suffered alteration in some form, by injected humour, or randomised words which don't look even slightly believable. If you are going to use a passage of Lorem Ipsum, you need to be sure there isn't anything embarrassing hidden in the middle of text. All the Lorem Ipsum generators on the Internet tend to repeat predefined chunks as necessary, making this the first true generator on the Internet. It uses a dictionary of over 200 Latin words, combined with a handful of model sentence structures, to generate Lorem Ipsum which looks reasonable. The generated Lorem Ipsum is therefore always free from repetition, injected humour, or non-characteristic words etc.
            Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of  (The Extremes of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of ethics, very popular during the Renaissance. The first line of Lorem Ipsum,  comes from a line in section 1.10.32.

The standard chunk of Lorem Ipsum used since the 1500s is reproduced below for those interested. Sections 1.10.32 and 1.10.33 from by Cicero are also reproduced in their exact original form, accompanied by English versions from the 1914 translation by H. Rackham."/>

    </FrameLayout>

</ScrollView>
</code>```

答:
I think AppBarLayout has issues with nested scrolling views, because it wasn't intended to be parent for viewgroups with nested scroll.
But you can change your layout like:

```<code><?xml version="1.0" encoding="utf-8"?>
<androidx.drawerlayout.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true">

    <androidx.coordinatorlayout.widget.CoordinatorLayout

        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".MainActivity">

        <com.google.android.material.appbar.AppBarLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
            app:elevation="0dp">

            <androidx.appcompat.widget.Toolbar
                android:id="@+id/toolbar"
                android:layout_width="match_parent"
                android:layout_height="?attr/actionBarSize"
                android:background="@color/colorPrimary"
                app:popupTheme="@style/ThemeOverlay.AppCompat.Light"

                />
        </com.google.android.material.appbar.AppBarLayout>

        <FrameLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            app:layout_behavior="@string/appbar_scrolling_view_behavior">

        <com.google.android.material.tabs.TabLayout
            android:id="@+id/TabLayoutPrincipal"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            app:tabGravity="fill"
            app:tabIndicatorColor="@color/colorAccent"
            app:tabMode="fixed" />

        <androidx.viewpager.widget.ViewPager
            android:id="@+id/ViewPagerPrincipal"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="@android:color/white" />
        </FrameLayout>

        <com.google.android.material.floatingactionbutton.FloatingActionButton
            android:id="@+id/addShotFAB"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="bottom|end"
            android:layout_margin="16dp" />
    </androidx.coordinatorlayout.widget.CoordinatorLayout>

    <com.google.android.material.navigation.NavigationView
        android:id="@+id/nav_view"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:fitsSystemWindows="true" />

</androidx.drawerlayout.widget.DrawerLayout>
</code>```

so, ViewPager becomes child of CoordinatorLayout not AppBarLayout and everything should work.

Body:
I'm making and android app where the main activity consists in a TabLayout and a ViewPager, a Floating action button is needed to start another activity, the problem is that when I add a CoordinatorLayout the ViewPager doesn't scroll (The viewPager contains 3 fragments one with a RecyclerView and the other two contains just textview with a lot of text, so all of them must scroll vertically.

The ViewPager works perfectly, but when I put it inside a CoordinatorLayout is not possible to do vertical scroll in any of the fragments loaded in the ViewPager.

I tried to add android:nestedScrollingEnabled="true" in every fragment root layout but it doesn't work.

EDIT:
All of the fragments loaded in the ViewPager have ScrollView as Root view.
This is my Main activity layout:

<?xml version="1.0" encoding="utf-8"?>
<androidx.drawerlayout.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true">

    <androidx.coordinatorlayout.widget.CoordinatorLayout

        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".MainActivity">
        <com.google.android.material.appbar.AppBarLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
            app:elevation="0dp"
            >

            <androidx.appcompat.widget.Toolbar
                android:id="@+id/toolbar"
                android:layout_width="match_parent"
                android:layout_height="?attr/actionBarSize"
                android:background="@color/colorPrimary"
                app:popupTheme="@style/ThemeOverlay.AppCompat.Light"

                />

            <com.google.android.material.tabs.TabLayout
                android:id="@+id/TabLayoutPrincipal"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                app:tabIndicatorColor="@color/colorAccent"
                app:tabGravity="fill"
                app:tabMode="fixed"/>

            <androidx.viewpager.widget.ViewPager
                android:id="@+id/ViewPagerPrincipal"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:background="@android:color/white"
                app:layout_behavior="@string/appbar_scrolling_view_behavior"
                android:nestedScrollingEnabled="true"
                />

        </com.google.android.material.appbar.AppBarLayout>

        <com.google.android.material.floatingactionbutton.FloatingActionButton
            android:id="@+id/addShotFAB"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@drawable/ic_add_white_24dp"
            android:layout_gravity="bottom|end"
            android:layout_margin="16dp"/>

    </androidx.coordinatorlayout.widget.CoordinatorLayout>

    <com.google.android.material.navigation.NavigationView
        android:id="@+id/nav_view"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:fitsSystemWindows="true"
        app:menu="@menu/menu_drawer"/>

</androidx.drawerlayout.widget.DrawerLayout>

This is what inside of the fragment with the RecyclerView:

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:nestedScrollingEnabled="true">

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/RecViewTomas"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>

The another fragment:

<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent"
    >

    <FrameLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <TextView
            android:textSize="50sp"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="There are many variations of passages of Lorem Ipsum available, but the majority have suffered alteration in some form, by injected humour, or randomised words which don't look even slightly believable. If you are going to use a passage of Lorem Ipsum, you need to be sure there isn't anything embarrassing hidden in the middle of text. All the Lorem Ipsum generators on the Internet tend to repeat predefined chunks as necessary, making this the first true generator on the Internet. It uses a dictionary of over 200 Latin words, combined with a handful of model sentence structures, to generate Lorem Ipsum which looks reasonable. The generated Lorem Ipsum is therefore always free from repetition, injected humour, or non-characteristic words etc.
            Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of  (The Extremes of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of ethics, very popular during the Renaissance. The first line of Lorem Ipsum,  comes from a line in section 1.10.32.

The standard chunk of Lorem Ipsum used since the 1500s is reproduced below for those interested. Sections 1.10.32 and 1.10.33 from by Cicero are also reproduced in their exact original form, accompanied by English versions from the 1914 translation by H. Rackham."/>

    </FrameLayout>

</ScrollView>

Body:
I think AppBarLayout has issues with nested scrolling views, because it wasn't intended to be parent for viewgroups with nested scroll.
But you can change your layout like:

<?xml version="1.0" encoding="utf-8"?>
<androidx.drawerlayout.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true">

    <androidx.coordinatorlayout.widget.CoordinatorLayout

        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".MainActivity">

        <com.google.android.material.appbar.AppBarLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
            app:elevation="0dp">

            <androidx.appcompat.widget.Toolbar
                android:id="@+id/toolbar"
                android:layout_width="match_parent"
                android:layout_height="?attr/actionBarSize"
                android:background="@color/colorPrimary"
                app:popupTheme="@style/ThemeOverlay.AppCompat.Light"

                />
        </com.google.android.material.appbar.AppBarLayout>

        <FrameLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            app:layout_behavior="@string/appbar_scrolling_view_behavior">

        <com.google.android.material.tabs.TabLayout
            android:id="@+id/TabLayoutPrincipal"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            app:tabGravity="fill"
            app:tabIndicatorColor="@color/colorAccent"
            app:tabMode="fixed" />

        <androidx.viewpager.widget.ViewPager
            android:id="@+id/ViewPagerPrincipal"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="@android:color/white" />
        </FrameLayout>

        <com.google.android.material.floatingactionbutton.FloatingActionButton
            android:id="@+id/addShotFAB"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="bottom|end"
            android:layout_margin="16dp" />
    </androidx.coordinatorlayout.widget.CoordinatorLayout>

    <com.google.android.material.navigation.NavigationView
        android:id="@+id/nav_view"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:fitsSystemWindows="true" />

</androidx.drawerlayout.widget.DrawerLayout>

so, ViewPager becomes child of CoordinatorLayout not AppBarLayout and everything should work.


问:
How can I install Scipy for pypy from pyenv?
I use pypy via pyenv on Ubuntu 18.04. How can I install scipy for this setup? Installing scipy for pypy is possible, but maybe I need to do extra steps using pyenv?

The Error

```<code>$ echo "pypy3.6-7.3.0" > ".python-version"
$ python --version
Python 3.6.9 (1608da62bfc7, Dec 23 2019, 10:50:04)
[PyPy 7.3.0 with GCC 7.3.1 20180303 (Red Hat 7.3.1-5)]

$ python -m pip install scipy
Collecting scipy
  Using cached scipy-1.4.1.tar.gz (24.6 MB)
  Installing build dependencies ... error
  ERROR: Command errored out with exit status 1:
[...]
      /home/moose/.pyenv/versions/pypy3.6-7.3.0/include/detail/common.h:134:19: fatal error: cstddef: No such file or directory
       #include <cstddef>
[...]
      SystemError: Cannot compile 'Python.h'. Perhaps you need to install pypy-dev|pypy-devel.
</code>```

The full message is on gist.github.com

My System

```<code>$ apt list --installed | grep python | grep dev
libpython-all-dev/bionic,now 2.7.15~rc1-1 amd64 [installed,automatic]
libpython-dev/bionic,now 2.7.15~rc1-1 amd64 [installed,automatic]
libpython2.7-dev/bionic-updates,now 2.7.17-1~18.04 amd64 [installed,automatic]
libpython3-dev/bionic-updates,now 3.6.7-1~18.04 amd64 [installed,automatic]
libpython3.6-dev/bionic-updates,now 3.6.9-1~18.04 amd64 [installed,automatic]
python-all-dev/bionic,now 2.7.15~rc1-1 amd64 [installed,automatic]
python-dev/bionic,now 2.7.15~rc1-1 amd64 [installed]
python2.7-dev/bionic-updates,now 2.7.17-1~18.04 amd64 [installed,automatic]
python3-dev/bionic-updates,now 3.6.7-1~18.04 amd64 [installed]
python3.6-dev/bionic-updates,now 3.6.9-1~18.04 amd64 [installed]

$ apt list --installed | grep pypy
pypy/bionic,now 5.10.0+dfsg-3build2 amd64 [installed,automatic]
pypy-dev/bionic,bionic,now 5.10.0+dfsg-3build2 all [installed]
pypy-lib/bionic,now 5.10.0+dfsg-3build2 amd64 [installed,automatic]

$ apt list --installed | grep -E "blas|atlas|lapack"
libblas-dev/bionic,now 3.7.1-4ubuntu1 amd64 [installed]
libblas3/bionic,now 3.7.1-4ubuntu1 amd64 [installed,automatic]
libgslcblas0/bionic,now 2.4+dfsg-6 amd64 [installed,automatic]
liblapack-dev/bionic,now 3.7.1-4ubuntu1 amd64 [installed]
liblapack3/bionic,now 3.7.1-4ubuntu1 amd64 [installed,automatic]
</code>```

答: The problem is the missing cstddef, which would seem to indicate you are missing the g++ include libararies. Did you install g++ or only gcc?

Body:
I use pypy via pyenv on Ubuntu 18.04. How can I install scipy for this setup? Installing scipy for pypy is possible, but maybe I need to do extra steps using pyenv?

The Error

$ echo "pypy3.6-7.3.0" > ".python-version"
$ python --version
Python 3.6.9 (1608da62bfc7, Dec 23 2019, 10:50:04)
[PyPy 7.3.0 with GCC 7.3.1 20180303 (Red Hat 7.3.1-5)]

$ python -m pip install scipy
Collecting scipy
  Using cached scipy-1.4.1.tar.gz (24.6 MB)
  Installing build dependencies ... error
  ERROR: Command errored out with exit status 1:
[...]
      /home/moose/.pyenv/versions/pypy3.6-7.3.0/include/detail/common.h:134:19: fatal error: cstddef: No such file or directory
       #include <cstddef>
[...]
      SystemError: Cannot compile 'Python.h'. Perhaps you need to install pypy-dev|pypy-devel.

The full message is on gist.github.com

My System

$ apt list --installed | grep python | grep dev
libpython-all-dev/bionic,now 2.7.15~rc1-1 amd64 [installed,automatic]
libpython-dev/bionic,now 2.7.15~rc1-1 amd64 [installed,automatic]
libpython2.7-dev/bionic-updates,now 2.7.17-1~18.04 amd64 [installed,automatic]
libpython3-dev/bionic-updates,now 3.6.7-1~18.04 amd64 [installed,automatic]
libpython3.6-dev/bionic-updates,now 3.6.9-1~18.04 amd64 [installed,automatic]
python-all-dev/bionic,now 2.7.15~rc1-1 amd64 [installed,automatic]
python-dev/bionic,now 2.7.15~rc1-1 amd64 [installed]
python2.7-dev/bionic-updates,now 2.7.17-1~18.04 amd64 [installed,automatic]
python3-dev/bionic-updates,now 3.6.7-1~18.04 amd64 [installed]
python3.6-dev/bionic-updates,now 3.6.9-1~18.04 amd64 [installed]

$ apt list --installed | grep pypy
pypy/bionic,now 5.10.0+dfsg-3build2 amd64 [installed,automatic]
pypy-dev/bionic,bionic,now 5.10.0+dfsg-3build2 all [installed]
pypy-lib/bionic,now 5.10.0+dfsg-3build2 amd64 [installed,automatic]

$ apt list --installed | grep -E "blas|atlas|lapack"
libblas-dev/bionic,now 3.7.1-4ubuntu1 amd64 [installed]
libblas3/bionic,now 3.7.1-4ubuntu1 amd64 [installed,automatic]
libgslcblas0/bionic,now 2.4+dfsg-6 amd64 [installed,automatic]
liblapack-dev/bionic,now 3.7.1-4ubuntu1 amd64 [installed]
liblapack3/bionic,now 3.7.1-4ubuntu1 amd64 [installed,automatic]


问:
WPF WebBrowser Content Size
I reviewed all of the related questions but was unable to get an answer.

How do I get the current content size of the WebBrowser control in WPF?

答:
To determine the actual size(using javascript) of the browser window, use the following properties:

in Internet Explorer (backward-compatibility mode):

```<code>document.body.offsetWidth, document.body.offsetHeight
</code>```

in Internet Explorer (standards mode, document.compatMode=='CSS1Compat'):

```<code>document.documentElement.offsetWidth, document.documentElement.offsetHeight
</code>```

in most other browsers:

```<code>window.innerWidth, window.innerHeight
The following code sets the variables winW and winH to the actual width and height of the browser window, and outputs the width and height values. If the user has a very old browser, then winW and winH are set to 630 and 460, respectively.

var winW = 630, winH = 460;
if (document.body && document.body.offsetWidth) {
 winW = document.body.offsetWidth;
 winH = document.body.offsetHeight;
}
if (document.compatMode=='CSS1Compat' &&
    document.documentElement &&
    document.documentElement.offsetWidth ) {
 winW = document.documentElement.offsetWidth;
 winH = document.documentElement.offsetHeight;
}
if (window.innerWidth && window.innerHeight) {
 winW = window.innerWidth;
 winH = window.innerHeight;
}

document.writeln('Window width = '+winW);
document.writeln('Window height = '+winH);
</code>```

In your browser, this code produces the following output:

```<code>Window width = 1280
Window height = 675
</code>```

Notes:

If the above code executes within a frame or iframe, it will give you the frame's width and height.

The computed width and height do not include the title bar, menu bar, status bar, or toolbar(s) - but may include the horizontal and vertical scrollbar(s), if any.

The code that uses document.body.offsetWidth and offsetHeight should be executed after the browser has parsed the  tag.

If the user resizes the browser window, you may need to recompute the width and height (use window.onresize to do so).

Similarly, if the user zooms in (or zooms out) you may also need to recompute the width and height.

Title: WPF WebBrowser Content Size

Body:
To determine the actual size(using javascript) of the browser window, use the following properties:

in Internet Explorer (backward-compatibility mode):

document.body.offsetWidth, document.body.offsetHeight

in Internet Explorer (standards mode, document.compatMode=='CSS1Compat'):

document.documentElement.offsetWidth, document.documentElement.offsetHeight

in most other browsers:

window.innerWidth, window.innerHeight
The following code sets the variables winW and winH to the actual width and height of the browser window, and outputs the width and height values. If the user has a very old browser, then winW and winH are set to 630 and 460, respectively.

var winW = 630, winH = 460;
if (document.body && document.body.offsetWidth) {
 winW = document.body.offsetWidth;
 winH = document.body.offsetHeight;
}
if (document.compatMode=='CSS1Compat' &&
    document.documentElement &&
    document.documentElement.offsetWidth ) {
 winW = document.documentElement.offsetWidth;
 winH = document.documentElement.offsetHeight;
}
if (window.innerWidth && window.innerHeight) {
 winW = window.innerWidth;
 winH = window.innerHeight;
}

document.writeln('Window width = '+winW);
document.writeln('Window height = '+winH);

In your browser, this code produces the following output:

Window width = 1280
Window height = 675

Notes:

If the above code executes within a frame or iframe, it will give you the frame's width and height.

The computed width and height do not include the title bar, menu bar, status bar, or toolbar(s) - but may include the horizontal and vertical scrollbar(s), if any.

The code that uses document.body.offsetWidth and offsetHeight should be executed after the browser has parsed the  tag.

If the user resizes the browser window, you may need to recompute the width and height (use window.onresize to do so).

Similarly, if the user zooms in (or zooms out) you may also need to recompute the width and height.


问:
How is GAN based Image to segmentation map different from SOTA semantic segmentation methods?
I have been looking around into papers like Pix2Pix and DeeplabV3. And In pix2pix paper there is an image to segmentation task performed. similarly, DeeplabV3 is used for segmentation tasks. I want to understand when should I use GAN for segmentation and when should I use SOTA segmentation methods. What are the pros and cons of these methods on the semantic segmentation?</p>

答:
I guess someone may find an example but I haven't seen a GAN method performing better than the state of the art segmentation methods so far. In my understanding GANs are more interesting for domain transfer, or weakly supervised methods in general. However, if you have a set of data with corresponding pixel annotations, I think that you should follow the "standard" semantic segmentation papers.

If you want to know which methods perform better in general, I would recommend you to follow some computer vision challenges and check for the best performing methods (e.g. kaggle, grand-challenge.org, conference challenges, ...).

One website is interesting to keep track of different methods on a single graph:  https://paperswithcode.com/task/semantic-segmentation

Therefore if you are wondering what would work best for semantic segmentation, I would certainly advise you to look at deeplab as you mentionned or this repository, quite effective.


问:
The box "contacts" is already open and of type Box<Contact> when trying to access Hive database in flutter
I initialized box database in main as follow

```<code>void main() async {
    WidgetsFlutterBinding.ensureInitialized();
    final appDocumentDirectory = await path_provider.getApplicationDocumentsDirectory();
    Hive.init(appDocumentDirectory.path);
    Hive.registerAdapter(ContactAdapter());
    runApp(MyApp());
}
</code>```

then I open box in the material app by using FutureBuilder plugin as follows:

```<code>  FutureBuilder(
      future: Hive.openBox<Contact>('contacts'),
      builder: (context, snapshot) {
        if(snapshot.connectionState == ConnectionState.done){
          if(snapshot.hasError){
            return Text(snapshot.error.toString() );
          }
          return ContactPage();
        } else {
          return Scaffold();
        }
      }
    ),
</code>```

and inside ContactPage()

I create this:-

```<code>  ValueListenableBuilder(
                valueListenable: Hive.box<Contact>('contacts').listenable(),
                builder: (context,Box<Contact> box,_){
                  if(box.values.isEmpty){
                    return Text('data is empty');
                  } else {
                    return ListView.builder(
                      itemCount: box.values.length,
                      itemBuilder: (context,index){
                        var contact = box.getAt(index);
                        return ListTile(
                          title: Text(contact.name),
                          subtitle: Text(contact.age.toString()),
                        );
                      },
                    );
                  }
                },
               )
</code>```

when I run the application I get the following error

```<code>The following HiveError was thrown while handling a gesture:
The box "contacts" is already open and of type Box<Contact>.
</code>```

and when I tried to use the box without opening it, I got error mean the box is not open.

Do I have to use box without opening it inside ValueListenableBuilder?
But then I have to open same box again in the different widget to add data on it.

答:
It is probably because you are trying to open the box inside FutureBuilder. If somehow it tries to rebuild itself, it will try to open the box which is already opened. Can you try to open the box after you register the adapter like:

```<code>void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  final appDocumentDirectory = await path_provider.getApplicationDocumentsDirectory();
  Hive.init(appDocumentDirectory.path);
  Hive.registerAdapter(ContactAdapter());
  await Hive.openBox<Contact>('contacts');
  runApp(MyApp());
}
</code>```

And instead of FutureBuilder just return ContactPage

Body:
I initialized box database in main as follow

void main() async {
    WidgetsFlutterBinding.ensureInitialized();
    final appDocumentDirectory = await path_provider.getApplicationDocumentsDirectory();
    Hive.init(appDocumentDirectory.path);
    Hive.registerAdapter(ContactAdapter());
    runApp(MyApp());
}

then I open box in the material app by using FutureBuilder plugin as follows:

  FutureBuilder(
      future: Hive.openBox<Contact>('contacts'),
      builder: (context, snapshot) {
        if(snapshot.connectionState == ConnectionState.done){
          if(snapshot.hasError){
            return Text(snapshot.error.toString() );
          }
          return ContactPage();
        } else {
          return Scaffold();
        }
      }
    ),

and inside ContactPage()

I create this:-

  ValueListenableBuilder(
                valueListenable: Hive.box<Contact>('contacts').listenable(),
                builder: (context,Box<Contact> box,_){
                  if(box.values.isEmpty){
                    return Text('data is empty');
                  } else {
                    return ListView.builder(
                      itemCount: box.values.length,
                      itemBuilder: (context,index){
                        var contact = box.getAt(index);
                        return ListTile(
                          title: Text(contact.name),
                          subtitle: Text(contact.age.toString()),
                        );
                      },
                    );
                  }
                },
               )

when I run the application I get the following error

The following HiveError was thrown while handling a gesture:
The box "contacts" is already open and of type Box<Contact>.

and when I tried to use the box without opening it, I got error mean the box is not open.

Do I have to use box without opening it inside ValueListenableBuilder?
But then I have to open same box again in the different widget to add data on it.

Body:
It is probably because you are trying to open the box inside FutureBuilder. If somehow it tries to rebuild itself, it will try to open the box which is already opened. Can you try to open the box after you register the adapter like:

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  final appDocumentDirectory = await path_provider.getApplicationDocumentsDirectory();
  Hive.init(appDocumentDirectory.path);
  Hive.registerAdapter(ContactAdapter());
  await Hive.openBox<Contact>('contacts');
  runApp(MyApp());
}

And instead of FutureBuilder just return ContactPage


问:
Gnuplot: transparency of data points when using palette
Is there a way to plot transparent data points when using palette?

I currently have the following code:

```<code>set style fill transparent solid 0.2 noborder
set palette rgb 22,13,-22
plot 'mydata.dat' u 1:2:3 ps 0.3 palette
</code>```

My feeling is that transparency is overwritten by the arguments of the plot command.

答:
Is there a way to plot transparent data points when using palette?

If you check help palette you will not find (or I overlooked) a statement about transparency in the palette. It looks like you can set the palette in different ways for RGB, but not for ARGB (A=alpha channel for transparency). So, I assume it is not possible with palette to have transparency (please correct me if I am wrong).
As workaround you have to set your transparency "manually" by setting the color with some transparency.
You can find the formulae behind the palettes by typing show palette rgbformulae.

The following examples creates a plot with random point positions in xrange[0:1] and yrange[0:1] and random points size (from 2 to 6) and random transparency (from 0x00 to 0xff). The color is determined by x according to your "manual palette". I hope you can adapt this example to your needs.

Code:

```<code>### "manual" palette with transparency
reset session

# These are the rgb formulae behind palette 22,13,-22
set angle degrees
r(x) = 3*x-1 < 0 ? 0: (3*x-1 > 1) ? 1 : 3*x-1
g(x) = sin(180*x)
b(x) = 1-(3*x-1) < 0 ? 0: (1-(3*x-1) > 1) ? 1 : 1-(3*x-1)

set xrange [0:1]
set yrange[-0.1:1.1]

RandomSize(n) = rand(0)*4+2              # random size from 2 to 6
RandomTransp(n) = int(rand(0)*0xff)<<24  # random transparency from 0x00 to 0xff
myColor(x) = (int(r(x)*0xff)<<16) + (int(g(x)*0xff)<<8) + int(b(x)*0xff) + RandomTransp(0)

set samples 200
plot '+' u (x=rand(0)):(rand(0)):(RandomSize(0)):(myColor(x)) w p pt 7 ps var lc rgb var not

### end of code
</code>```

Result:

Body:
Is there a way to plot transparent data points when using palette?

I currently have the following code:

set style fill transparent solid 0.2 noborder
set palette rgb 22,13,-22
plot 'mydata.dat' u 1:2:3 ps 0.3 palette

My feeling is that transparency is overwritten by the arguments of the plot command.

Body:
Is there a way to plot transparent data points when using palette?

If you check help palette you will not find (or I overlooked) a statement about transparency in the palette. It looks like you can set the palette in different ways for RGB, but not for ARGB (A=alpha channel for transparency). So, I assume it is not possible with palette to have transparency (please correct me if I am wrong).
As workaround you have to set your transparency "manually" by setting the color with some transparency.
You can find the formulae behind the palettes by typing show palette rgbformulae.

The following examples creates a plot with random point positions in xrange[0:1] and yrange[0:1] and random points size (from 2 to 6) and random transparency (from 0x00 to 0xff). The color is determined by x according to your "manual palette". I hope you can adapt this example to your needs.

Code:

### "manual" palette with transparency
reset session

# These are the rgb formulae behind palette 22,13,-22
set angle degrees
r(x) = 3*x-1 < 0 ? 0: (3*x-1 > 1) ? 1 : 3*x-1
g(x) = sin(180*x)
b(x) = 1-(3*x-1) < 0 ? 0: (1-(3*x-1) > 1) ? 1 : 1-(3*x-1)

set xrange [0:1]
set yrange[-0.1:1.1]

RandomSize(n) = rand(0)*4+2              # random size from 2 to 6
RandomTransp(n) = int(rand(0)*0xff)<<24  # random transparency from 0x00 to 0xff
myColor(x) = (int(r(x)*0xff)<<16) + (int(g(x)*0xff)<<8) + int(b(x)*0xff) + RandomTransp(0)

set samples 200
plot '+' u (x=rand(0)):(rand(0)):(RandomSize(0)):(myColor(x)) w p pt 7 ps var lc rgb var not

### end of code

Result:


问:
How to exclude special characters from android keypad for EditText
Hi I want to show only numbers and characters on the keypad for EditText in android, I did try to add the attribute android:inputType = text|number but it did not work.

Please help me with any other better suggestion. thanks in advance.

答:
try using this method it worked for me:

```<code>public static InputFilter[] getFilter(String blockChars) {
   return new InputFilter[]{(source, start, end, dest, dstart, dend) -> {
        for (int i = start; i < end; i++) {
            if (source != null && blockChars.contains("" + source.charAt(i))) {
                return source.subSequence(start, i);
            }
        }
        return null;
    }};
</code>```

add this line for your edit text

```<code>edittext.setFilters(getFilter("@~"));
</code>```

Body:
try using this method it worked for me:

public static InputFilter[] getFilter(String blockChars) {
   return new InputFilter[]{(source, start, end, dest, dstart, dend) -> {
        for (int i = start; i < end; i++) {
            if (source != null && blockChars.contains("" + source.charAt(i))) {
                return source.subSequence(start, i);
            }
        }
        return null;
    }};

add this line for your edit text

edittext.setFilters(getFilter("@~"));