问:
Including NSIS script in CMake
Is it possible to include an NSIS script from CMake that uses CPack together with NSIS? It appears that I'm limited to only a few commands (doc), but some commands suggest that there is a way to include the whole NSIS script, particulary:

```<code>CPACK_NSIS_EXTRA_PREINSTALL_COMMANDS,
CPACK_NSIS_EXTRA_INSTALL_COMMANDS,
CPACK_NSIS_EXTRA_UNINSTALL_COMMANDS
</code>```

However, when I try to call these commands:

```<code>SET(CPACK_NSIS_EXTRA_PREINSTALL_COMMANDS "!include extra_preinstall.nsh")
</code>```

Nothing happens. (Excluding /NONFATAL throws an error, so presumably the script cannot be found.)

Checking basic functionality:

```<code>SET(CPACK_NSIS_EXTRA_PREINSTALL_COMMANDS "MessageBox MB_OK \\\"Hello world!\\\"")
</code>```

Doesn't do anything with the installer.

Why doesn't a Hello World button appear? Why is the script file not found (even though I put it on every level of CMake hiearchy)?

答:
Preinstall doesn't mean that it's executed before the install section, so you actually have to click "install", then the command is executed.
The same goes for Install and Uninstall.

As for including external scripts: including with absolute path solves everything. If absolute path is not available, it can be easily obtained using CMake tools.

Title: Including NSIS script in CMake

Body:
Is it possible to include an NSIS script from CMake that uses CPack together with NSIS? It appears that I'm limited to only a few commands (doc), but some commands suggest that there is a way to include the whole NSIS script, particulary:

CPACK_NSIS_EXTRA_PREINSTALL_COMMANDS,
CPACK_NSIS_EXTRA_INSTALL_COMMANDS,
CPACK_NSIS_EXTRA_UNINSTALL_COMMANDS

However, when I try to call these commands:

SET(CPACK_NSIS_EXTRA_PREINSTALL_COMMANDS "!include extra_preinstall.nsh")

Nothing happens. (Excluding /NONFATAL throws an error, so presumably the script cannot be found.)

Checking basic functionality:

SET(CPACK_NSIS_EXTRA_PREINSTALL_COMMANDS "MessageBox MB_OK \\\"Hello world!\\\"")

Doesn't do anything with the installer.

Why doesn't a Hello World button appear? Why is the script file not found (even though I put it on every level of CMake hiearchy)?


来源: stackexchange

问:
How to locate a link in protractor
I am trying to locate a link which after clicking a pop up panel would show up for logging in. But it seems I can't get to the link. I have tried different methods like xpath, findElement, locating by css or class name or .. but nothing has worked. Any advice would be appreciated. </p>

答:
By default you can also locate a link with one of the following lines:

element(by.linkText('TEXT OF THE LINK'))...

element(by.partialLinkText('PARTIAL TEXT OF THE LINK'))...

element(by.tagName('a'))...

See here for a more detailed information about the different locators.

Complement:

If the link only appears if you click on your pop up panel, then you need to wait until your link becomes visible and clickable.

In that case, you can wait for your element to become visible with following:

```<code>var EC = protractor.ExpectedConditions;
var isClickable = EC.elementToBeClickable(element(by.partialLinkText('Sign up')));

browser.wait(isClickable, 5000); //Waits 5 seconds for your element to become visible and clickable, otherwise a timeout exception will be thrown

element(by.partialLinkText('Sign up')).click(); // Or do something else with your element
</code>```

ContentLicense: CC BY-SA 3.0

Title: How to locate a link in protractor

Body:
By default you can also locate a link with one of the following lines:

element(by.linkText('TEXT OF THE LINK'))...

element(by.partialLinkText('PARTIAL TEXT OF THE LINK'))...

element(by.tagName('a'))...

See here for a more detailed information about the different locators.

Complement:

If the link only appears if you click on your pop up panel, then you need to wait until your link becomes visible and clickable.

In that case, you can wait for your element to become visible with following:

var EC = protractor.ExpectedConditions;
var isClickable = EC.elementToBeClickable(element(by.partialLinkText('Sign up')));

browser.wait(isClickable, 5000); //Waits 5 seconds for your element to become visible and clickable, otherwise a timeout exception will be thrown

element(by.partialLinkText('Sign up')).click(); // Or do something else with your element


问:
Constraining columns with each other in SSRS
I'm learning MSBI tools and came across a requirement in SSRS wherein we need to constrain report parameter 2 with parameter 1.

i.e. if I have parameters setup on [AdventureWorks2008R2].[HumanResources].[Department] table and if I select "Group Name" (Parameter 1) as "Manufacturing" then the "Name" (Parameter 2) drop down should populate only relevant values("Production" and "Production Control") specific to selected parameter 1 value ("Manufacturing")

I have been exposed to OBIEE tool and know that under this tool we have a "constrain" option under Prompts to achieve the same.

I could come up with the following solution under SSRS:
Created two datasets for each of the parameters with below queries.

Parameter 1 (GroupName)

```<code> SELECT DISTINCT GroupName
    FROM            HumanResources.Department
</code>```

Parameter 2 (DeptName)

```<code>SELECT        Name
FROM            HumanResources.Department
WHERE        (GroupName = @GroupName)
</code>```

This worked. However if there are 5 such parameters which are to be constrained then with this solution I would have to create 5 such datasets and accordingly build the WHERE clause for each parameter.
Is there a better solution to achieve the same (there should be..)

I'm new to SSRS and therefore would appreciate any pointers here.
Thanks!

答:
What you are talking about is called "Cascading Parameters" and they are implemented exactly as you did. You can read about them here:
Adding Cascading Parameters (SSRS)

So if you need to implement 5 of such parameters you have to write 5 queries for 5 datasets each one containing WHERE referencing parameter defined in previous dataset

Body:
I'm learning MSBI tools and came across a requirement in SSRS wherein we need to constrain report parameter 2 with parameter 1.

i.e. if I have parameters setup on [AdventureWorks2008R2].[HumanResources].[Department] table and if I select "Group Name" (Parameter 1) as "Manufacturing" then the "Name" (Parameter 2) drop down should populate only relevant values("Production" and "Production Control") specific to selected parameter 1 value ("Manufacturing")

I have been exposed to OBIEE tool and know that under this tool we have a "constrain" option under Prompts to achieve the same.

I could come up with the following solution under SSRS:
Created two datasets for each of the parameters with below queries.

Parameter 1 (GroupName)

 SELECT DISTINCT GroupName
    FROM            HumanResources.Department

Parameter 2 (DeptName)

SELECT        Name
FROM            HumanResources.Department
WHERE        (GroupName = @GroupName)

This worked. However if there are 5 such parameters which are to be constrained then with this solution I would have to create 5 such datasets and accordingly build the WHERE clause for each parameter.
Is there a better solution to achieve the same (there should be..)

I'm new to SSRS and therefore would appreciate any pointers here.
Thanks!


问:
ClassNotFound Exception in Eclipse when starting thread, using packages in Java
I've just refactored a project in Eclipse to use packages instead of the default package to better organise my code. I have a test program which creates a number of Runnable objects, each of which are run sequentially to each other, but in parallel with the main program.

Before refactoring this worked fine, with each thread dutifully performing its task. However, since moving things into packages I'm getting a ClassNotFound exception as soon as one of the Runnable classes attempts to use a class from another package. Stacktrace follows:

```<code>java.lang.ClassNotFoundException: Tweet
at java.net.URLClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Unknown Source)
at java.io.ObjectInputStream.resolveClass(Unknown Source)
at java.io.ObjectInputStream.readNonProxyDesc(Unknown Source)
at java.io.ObjectInputStream.readClassDesc(Unknown Source)
at java.io.ObjectInputStream.readOrdinaryObject(Unknown Source)
at java.io.ObjectInputStream.readObject0(Unknown Source)
at java.io.ObjectInputStream.readObject(Unknown Source)
at indexing.TweetCleanup.run(TweetCleanup.java:84)
at java.lang.Thread.run(Unknown Source)
</code>```

In this trace 'TweetCleanup' is the Runnable class, and 'Tweet' is the class not found. I've included it in TweetCleanup as 'common.Tweet' (where common is the package). I've used a separate test program to see if it can see the class in the main thread, which runs successfully.

All I can think of is that the Thread needs to be supplied some classpath to 'see' the Tweet class, however this wasn't the case before refactoring as packages. I believe the default behaviour of a child Thread is to use the classpath of its parent, which includes 'common.Tweet'.

I'm using Eclipse Helios as my IDE.

Any tips would be appreciated!

Cheers,

P

答:
Not a Threading problem at all, but you're using Java Serialization somehow and you try to read an Object from a stream which has "older" objects stored within it.

I suspect you're using some kind of persistence by Java Serialization, and your TweetCleanup-Thread is reading in the old "database". Delete this file and your program will work again.

Note that renaming packages or moving classes is a binary incompatible change - you cannot deserialize such objects anymore.

ContentLicense: CC BY-SA 2.5

Body:
I've just refactored a project in Eclipse to use packages instead of the default package to better organise my code. I have a test program which creates a number of Runnable objects, each of which are run sequentially to each other, but in parallel with the main program.

Before refactoring this worked fine, with each thread dutifully performing its task. However, since moving things into packages I'm getting a ClassNotFound exception as soon as one of the Runnable classes attempts to use a class from another package. Stacktrace follows:

java.lang.ClassNotFoundException: Tweet
at java.net.URLClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Unknown Source)
at java.io.ObjectInputStream.resolveClass(Unknown Source)
at java.io.ObjectInputStream.readNonProxyDesc(Unknown Source)
at java.io.ObjectInputStream.readClassDesc(Unknown Source)
at java.io.ObjectInputStream.readOrdinaryObject(Unknown Source)
at java.io.ObjectInputStream.readObject0(Unknown Source)
at java.io.ObjectInputStream.readObject(Unknown Source)
at indexing.TweetCleanup.run(TweetCleanup.java:84)
at java.lang.Thread.run(Unknown Source)

In this trace 'TweetCleanup' is the Runnable class, and 'Tweet' is the class not found. I've included it in TweetCleanup as 'common.Tweet' (where common is the package). I've used a separate test program to see if it can see the class in the main thread, which runs successfully.

All I can think of is that the Thread needs to be supplied some classpath to 'see' the Tweet class, however this wasn't the case before refactoring as packages. I believe the default behaviour of a child Thread is to use the classpath of its parent, which includes 'common.Tweet'.

I'm using Eclipse Helios as my IDE.

Any tips would be appreciated!

Cheers,

P


问:
Best way to store a list of objects in ASP.Net MVC
In my current project, I am building an object list from multiple database tables. I am currently storing them in the user session (Global.asax/Session_Start) as showed below.

```<code>protected void Session_Start()
{
    Session.Add("listeOF", new ListOf());
}
</code>```

This is working and I can use the data, but I was wondering if there's a better way to store it (by better I mean faster access). I call this data in my controllers.

答:
You need some other data store to keep it across postback requests, so if it's global to the application, you can use application cache, but if it's specific to the user, then session is fine. If there isn't that much data involved and it's not that intensive as a read, you may want to consider whether there is a benefit to caching a chunk of data vs just re-querying it when needed.

To get more advanced and present another alternative that is more involved, a CQRS implementation is a possibility (also see this); the idea there is one data container is for transaction data, and another for reads (whether that is a separate database or table, or even a document database as some possibilities).

ContentLicense: CC BY-SA 4.0

Body:
In my current project, I am building an object list from multiple database tables. I am currently storing them in the user session (Global.asax/Session_Start) as showed below.

protected void Session_Start()
{
    Session.Add("listeOF", new ListOf());
}

This is working and I can use the data, but I was wondering if there's a better way to store it (by better I mean faster access). I call this data in my controllers.


问:
Firebase: Provided bucket does not match the Storage bucket of the current instance in Swift
I have the following code:

```<code>let storageRef = FIRStorage().reference(forURL: "gs://slugbug-....appspot.com") // dots intentional
let imageRef = storageRef.child("testImage.jpg")
</code>```

But the app crashes and I get the following message:

Terminating app due to uncaught exception
  'NSInvalidArgumentException', reason: 'Provided bucket:
  slugbug-....appspot.com does not match the Storage bucket of the
  current instance: (null)'

Even if I use

```<code>let storageRef = FIRStorage().reference()
</code>```

The bucket is nil.

Why?

答:
I figured out the solution:

I changed the code from:

```<code>let storageRef = FIRStorage().reference(forURL: "gs://slugbug-....appspot.com")
</code>```

to:

```<code>let storageRef = FIRStorage.storage().reference(forURL: "gs://slugbug-....appspot.com")
</code>```

... a very subtle but annoying bug

Body:
I have the following code:

let storageRef = FIRStorage().reference(forURL: "gs://slugbug-....appspot.com") // dots intentional
let imageRef = storageRef.child("testImage.jpg")

But the app crashes and I get the following message:

Terminating app due to uncaught exception
  'NSInvalidArgumentException', reason: 'Provided bucket:
  slugbug-....appspot.com does not match the Storage bucket of the
  current instance: (null)'

Even if I use

let storageRef = FIRStorage().reference()

The bucket is nil.

Why?

Body:
I figured out the solution:

I changed the code from:

let storageRef = FIRStorage().reference(forURL: "gs://slugbug-....appspot.com")

to:

let storageRef = FIRStorage.storage().reference(forURL: "gs://slugbug-....appspot.com")

... a very subtle but annoying bug


问:
UNICODE_STRING to ANSI_STRING conversion with RtlUnicodeStringToAnsiString
The documentation on RtlUnicodeStringToAnsiString is rather vague about its possible failures - by vague I mean it doesn't say anything about them.

I'm not exactly sure how/if it deals with different encodings, or if my understanding is so flawed that it doesn't even come into the equation, but let's assume input is UTF-16 for argument's sake.

If all the characters are within the ASCII range then there is no problem, they can just get truncated and lose the high order byte - The first 128 Unicode code points are the ASCII characters and UTF-16 encodes U+0000 to U+D7FF as numerically equal to the code points.[1][2]

Note: UNICODE_STRING has a WCHAR* Buffer, and ANSI_STRING a CHAR* Buffer, as may be expected.

[Skipping over 129-255 and locales/codepages]

What happens with characters above 255? There is an RtlUnicodeToUTF8N function so it's safe to assume it doesn't convert to UTF-8.

How about code points outside BMP (surrogate pairs and whatnot)?

I saw a function that does something like the code below:

```<code>char *pTarget = reinterpret_cast<char*>(char_str);
const WCHAR  *pSource = reinterpret_cast<const WCHAR*>(wchar_str);

for ( long i = 0; i < targetMaxSizeInBytes; i++ )
{
    *pTarget = static_cast<char>(*pSource);

    if (L'\0' == *pSource)
        break;

    pTarget++;
    pSource++;
}
</code>```

This would cause problems with any non-ASCII characters, correct?

Update:

From RbMm's answer:

RtlUnicodeStringToAnsiString is shell over RtlUnicodeToMultiByteN routine

I get a little more information:

Like RtlUnicodeToMultiByteSize, RtlUnicodeToMultiByteN supports only precomposed Unicode characters that are mapped to the current system ANSI code page installed at system boot.

WideCharToMultiByte has an option to be notified if a default character is used in the conversion for a character that cannot be represented in the specified code page:

lpUsedDefaultChar [out, optional]

Pointer to a flag that indicates if the function has used a default character in the conversion. The flag is set to TRUE if one or more characters in the source string cannot be represented in the specified code page. Otherwise, the flag is set to FALSE. This parameter can be set to NULL.

However, it seems RtlUnicodeToMultiByteN, and therefore RtlUnicodeStringToAnsiString, simply don't support characters outside the current code page?

I tried a few characters and got seemingly random conversions (see below) - more importantly, I got STATUS_SUCCESS returned.

```<code>U+03A3 Σ -> 0n83 'S'
U+03A4 Τ -> 0n63 '?'
U+03A5 Υ -> 0n63 '?'
U+03A6 Φ -> 0n70 'F'
</code>```

答:
Not sure if this helps, but I have used WideCharToMultiByte before to convert from UTF-16 (wchar_t*) and UTF-8 (char*), passing the CP_UTF8 as the code page.

Edit: I just noted the kernel tag. The function I quoted is in user mode (kernel32.dll), so probably not useful for kernel mode code. :(

Body:
The documentation on RtlUnicodeStringToAnsiString is rather vague about its possible failures - by vague I mean it doesn't say anything about them.

I'm not exactly sure how/if it deals with different encodings, or if my understanding is so flawed that it doesn't even come into the equation, but let's assume input is UTF-16 for argument's sake.

If all the characters are within the ASCII range then there is no problem, they can just get truncated and lose the high order byte - The first 128 Unicode code points are the ASCII characters and UTF-16 encodes U+0000 to U+D7FF as numerically equal to the code points.[1][2]

Note: UNICODE_STRING has a WCHAR* Buffer, and ANSI_STRING a CHAR* Buffer, as may be expected.

[Skipping over 129-255 and locales/codepages]

What happens with characters above 255? There is an RtlUnicodeToUTF8N function so it's safe to assume it doesn't convert to UTF-8.

How about code points outside BMP (surrogate pairs and whatnot)?

I saw a function that does something like the code below:

char *pTarget = reinterpret_cast<char*>(char_str);
const WCHAR  *pSource = reinterpret_cast<const WCHAR*>(wchar_str);

for ( long i = 0; i < targetMaxSizeInBytes; i++ )
{
    *pTarget = static_cast<char>(*pSource);

    if (L'\0' == *pSource)
        break;

    pTarget++;
    pSource++;
}

This would cause problems with any non-ASCII characters, correct?

Update:

From RbMm's answer:

RtlUnicodeStringToAnsiString is shell over RtlUnicodeToMultiByteN routine

I get a little more information:

Like RtlUnicodeToMultiByteSize, RtlUnicodeToMultiByteN supports only precomposed Unicode characters that are mapped to the current system ANSI code page installed at system boot.

WideCharToMultiByte has an option to be notified if a default character is used in the conversion for a character that cannot be represented in the specified code page:

lpUsedDefaultChar [out, optional]

Pointer to a flag that indicates if the function has used a default character in the conversion. The flag is set to TRUE if one or more characters in the source string cannot be represented in the specified code page. Otherwise, the flag is set to FALSE. This parameter can be set to NULL.

However, it seems RtlUnicodeToMultiByteN, and therefore RtlUnicodeStringToAnsiString, simply don't support characters outside the current code page?

I tried a few characters and got seemingly random conversions (see below) - more importantly, I got STATUS_SUCCESS returned.

U+03A3 Σ -> 0n83 'S'
U+03A4 Τ -> 0n63 '?'
U+03A5 Υ -> 0n63 '?'
U+03A6 Φ -> 0n70 'F'


问:
EventFilter in Context Menu in JavaFx
My javafx application has graphs made of nodes and edges. The Edges are implemented using 'Line' shape. There is a 'ContentMenu' used on edges when the user right clicks on it. There is another ContextMenu used with the main UI canvas on which the graph is constructed.

The issue is that the canvas context menu is overriding the edge contextmenu. Whenever a user right clicks an edge, its contextmenu appears and then quickly disappears to show the canvas contextmenu.

I've written an EventFilter on right click MOUSE_RELEASED of the edges to consume the mouse event, but this doesnt solve the issue either.

答:
You chose wrong event. You need to consume ContextMenuEvent to suppress Context Menu. See next code

```<code>    node.addEventFilter(ContextMenuEvent.ANY, new EventHandler<Event>() {
        @Override
        public void handle(Event event) {
            event.consume();
        }
    });
</code>```

Title: EventFilter in Context Menu in JavaFx

Body:
You chose wrong event. You need to consume ContextMenuEvent to suppress Context Menu. See next code

    node.addEventFilter(ContextMenuEvent.ANY, new EventHandler<Event>() {
        @Override
        public void handle(Event event) {
            event.consume();
        }
    });


问:
time complexity of arr.delete() in ruby
```<code>arr = [5, 6, 5, 4, 3, 1, 2, 5, 4, 3, 3, 3]
</code>```

Delete all occurrences of a given element

```<code>arr.delete(5)
#  => [6, 3, 1, 2, 4, 3, 3]
</code>```

What is the time complexity of the above Ruby code and how it works internally?

答:
There are several different locations where the behavior of Ruby is specified:

The Ruby Spec Suite,

The ISO/IEC 30170:2012 Ruby Programming Language Specification,

The Ruby Programming Language by David Flanagan and Yukihiro Matsumoto,

The Ruby Documentation,

and matz's brain.

Unfortunately, we cannot read the last one, but we can look at all the other ones, and none of them specifies any performance requirements for Array#delete:

The Ruby Spec Suite for Array#delete: core/array/delete_spec.rb only specifies the return values and exceptions, no performance requirements.

The ISO Ruby Programming Language Specification doesn't specify Array#delete at all (it only specifies a minimal subset of Ruby, and an even more minimal subset of the core library; the standard library is left out completely).

The Ruby Programming Language doesn't mention Array#delete either in section 3.3 Arrays nor in section 9.5.2 Arrays.

The Ruby Documentation for Array#delete doesn't say anything about performance.

However, there is another thing we can consider: the common sense expectations of the Ruby community. In general, anything in Ruby which violates the Ruby community's common sense expectations of how it should behave is simply not going to get accepted. So, what can we expect from an Array#delete method?

It has to look at all elements of the Array, so it cannot possibly be faster than O(n), where n is the size of the array.

The naive approach would delete all occurrences individually, needing to shift all subsequent elements, which is an O(n) operation executed O(d) times, so the naive approach is O(d*n), where d is the number of occurrences of the item to delete.

So, we know that we cannot get better than O(n), and we know that even the most naive implementation is O(dn). In other words: you have to be extra clever to be even slower than O(dn), and we will assume that nobody would do that on purpose.

Therefore, we can conclude that the actual performance of Array#delete is somewhere between O(n) (the best possible case) and O(d*n) (the simplest, most naive case).

We could, of course, look at one of the implementations, e.g. Rubinius's is in core/array.rb, and you can see that it actually collects the items first and then shrinks the array in one step, thus making it O(n).

Topaz's implementation is in lib-topaz/array.rb. It actually just delegates to Array#delete_if, which also is O(n) by collecting all deletions first and then resizing the array in one go.

JRuby's implementation is in core/src/main/java/org/jruby/RubyArray.java and also uses the optimization to avoid being O(d*n).

But, this only tells you how that specific version of that specific implementation behaves right now. It doesn't tell you anything about future or past versions, it doesn't tell you anything about other implementations. The only thing you can rely is the specifications (which don't say anything) and common sense.

Title: time complexity of arr.delete() in ruby

Body:
arr = [5, 6, 5, 4, 3, 1, 2, 5, 4, 3, 3, 3]

Delete all occurrences of a given element

arr.delete(5)
#  => [6, 3, 1, 2, 4, 3, 3]

What is the time complexity of the above Ruby code and how it works internally?


问:
How to load a model in another controller using a custom PHP MVC
My application have this folders stucture:

application

library

Model.php

Controller.php

View.php

models

Settings_Model.php

Home_Model.php

controllers

settings.php

home.php

views

settings

index.php

home

index.php

index.php

.htaccess

library/Model.php

```<code> class Database extends PDO{
        public function __construct($DB_TYPE, $DB_HOST, $DB_NAME, $DB_USER, $DB_PASS){
              parent::__construct($DB_TYPE.':host='.$DB_HOST.';dbname='.$DB_NAME, $DB_USER, $DB_PASS);
        }
  }
</code>```

library/Controller

```<code> class Controller{

      function __construct(){
           $this->view = new View();
      }

      public function loadModel($name){
           $path = 'application/models/' . $name . '_model.php';

           if(file_exists($path)){
                require 'application/models/' . $name . '_model.php';
                $modelName = $name . '_Model';
                $this->model = new $modelName();
           }
      }
 }
</code>```

library/View

```<code> class View{

      function __construct(){
           $this->view = new View();
      }

      public function render($name){
           require 'application/views/' . $name . '.php';
      }
 }
</code>```

In Models folder I created this model called Settings_Model.php : models/Settings_Model.php

```<code> class Settings_Model extends Model{
    public function __construct(){parent::__construct();}

    function settings(){
       $stmt = $this->db->prepare("SELECT * FROM `mv_settings`");
       $stmt->execute();
       $stmt->setFetchMode(PDO::FETCH_OBJ);
       return $stmt->fetch();
    }
 }
</code>```

In Controllers folder I have this Controller called settings.php :
 controllers/settings.php

```<code>class Settings extends Controller {

    function __construct(){parent::__construct();}

    public function index(){
        $this->view->settings = $this->model->settings();
        $this->view->render('settings/index');
    }
}
</code>```

And In Views folder I created a folder called settings and inside this folder I created an index.php file:
 settings/index

and this is how to call the settings method inside settings/index:

$this->settings->fieldName;

So now when we go to Home view, I did the same procedure:
 - create a Home_Model class and inside this model I created the same settings method:

```<code> class Home_Model extends Model{
    public function __construct(){parent::__construct();}

    function settings(){
       $stmt = $this->db->prepare("SELECT * FROM `mv_settings`");
       $stmt->execute();
       $stmt->setFetchMode(PDO::FETCH_OBJ);
       return $stmt->fetch();
    }
 }
</code>```

and then goes to the controllers folder and create Home controller:

```<code>class Home extends Controller {

    function __construct(){parent::__construct();}

    public function index(){
        $this->view->settings = $this->model->settings();
        $this->view->render('home/index');
    }
}
</code>```

and then call the settings method inside home/index:

$this->settings->fieldName;

What Im asking is how to avoid not to create the same method settings again and again each time we need to call that method in another view file???

NB: Im still a newbie.

答:
if you want to access the same settings() function in all models then you should create it in Base model.php.

```<code>class Model{

  function settings(){
       $stmt = $this->db->prepare("SELECT * FROM `mv_settings`");
       $stmt->execute();
       $stmt->setFetchMode(PDO::FETCH_OBJ);
       return $stmt->fetch();
    }

  }
</code>```

then your settings model need to be like

```<code> class Settings_Model extends Model{
    public function __construct(){parent::__construct();}

 }
</code>```

and your Home_model

```<code> class Home_Model extends Model{
    public function __construct(){parent::__construct();}

 }
</code>```

Now you can access settings() in all your models extending Model, no need to create it again and again.

Body:
My application have this folders stucture:

application

library

Model.php

Controller.php

View.php

models

Settings_Model.php

Home_Model.php

controllers

settings.php

home.php

views

settings

index.php

home

index.php

index.php

.htaccess

library/Model.php

 class Database extends PDO{
        public function __construct($DB_TYPE, $DB_HOST, $DB_NAME, $DB_USER, $DB_PASS){
              parent::__construct($DB_TYPE.':host='.$DB_HOST.';dbname='.$DB_NAME, $DB_USER, $DB_PASS);
        }
  }

library/Controller

 class Controller{

      function __construct(){
           $this->view = new View();
      }

      public function loadModel($name){
           $path = 'application/models/' . $name . '_model.php';

           if(file_exists($path)){
                require 'application/models/' . $name . '_model.php';
                $modelName = $name . '_Model';
                $this->model = new $modelName();
           }
      }
 }

library/View

 class View{

      function __construct(){
           $this->view = new View();
      }

      public function render($name){
           require 'application/views/' . $name . '.php';
      }
 }

In Models folder I created this model called Settings_Model.php : models/Settings_Model.php

 class Settings_Model extends Model{
    public function __construct(){parent::__construct();}

    function settings(){
       $stmt = $this->db->prepare("SELECT * FROM `mv_settings`");
       $stmt->execute();
       $stmt->setFetchMode(PDO::FETCH_OBJ);
       return $stmt->fetch();
    }
 }

In Controllers folder I have this Controller called settings.php :
 controllers/settings.php

class Settings extends Controller {

    function __construct(){parent::__construct();}

    public function index(){
        $this->view->settings = $this->model->settings();
        $this->view->render('settings/index');
    }
}

And In Views folder I created a folder called settings and inside this folder I created an index.php file:
 settings/index

and this is how to call the settings method inside settings/index:

$this->settings->fieldName;

So now when we go to Home view, I did the same procedure:
 - create a Home_Model class and inside this model I created the same settings method:

 class Home_Model extends Model{
    public function __construct(){parent::__construct();}

    function settings(){
       $stmt = $this->db->prepare("SELECT * FROM `mv_settings`");
       $stmt->execute();
       $stmt->setFetchMode(PDO::FETCH_OBJ);
       return $stmt->fetch();
    }
 }

and then goes to the controllers folder and create Home controller:

class Home extends Controller {

    function __construct(){parent::__construct();}

    public function index(){
        $this->view->settings = $this->model->settings();
        $this->view->render('home/index');
    }
}

and then call the settings method inside home/index:

$this->settings->fieldName;

What Im asking is how to avoid not to create the same method settings again and again each time we need to call that method in another view file???

NB: Im still a newbie.

Body:
if you want to access the same settings() function in all models then you should create it in Base model.php.

class Model{

  function settings(){
       $stmt = $this->db->prepare("SELECT * FROM `mv_settings`");
       $stmt->execute();
       $stmt->setFetchMode(PDO::FETCH_OBJ);
       return $stmt->fetch();
    }

  }

then your settings model need to be like

 class Settings_Model extends Model{
    public function __construct(){parent::__construct();}

 }

and your Home_model

 class Home_Model extends Model{
    public function __construct(){parent::__construct();}

 }

Now you can access settings() in all your models extending Model, no need to create it again and again.


问:
Centering a bootstrap 3 progress bar horizontally?
I am not able to center two progress bars inside two columns the same way used in the other 2 rows.

Currently:

Expectation:

Progress bars code:

```<code><div class="row top-row">
                    <div class="col-md-6 text-center">
                        <div class="progress" style="width:120px;">
                            <div class="progress-bar" role="progressbar" aria-valuenow="70" aria-valuemin="0" aria-valuemax="100" style="width:70%">70%
                            </div>
                        </div>
                    </div>

                    <div class="col-md-6 text-center">
                        <div class="progress" style="width:120px;">
                            <div class="progress-bar" role="progressbar" aria-valuenow="70" aria-valuemin="0" aria-valuemax="100" style="width:70%">70%
                            </div>
                        </div>
                    </div>
                </div>
</code>```

The two squares which seem to work:

```<code><div class="row top-row">
                    <div class="col-md-6 text-center">
                        <div class="charBox">img1</div>
                    </div>

                    <div class="col-md-6 text-center">
                        <div class="charBox">img2</div>
                    </div>
                </div>
</code>```

Top row is .top-row {margin-top: 20px;} just to distance the rows.

What would be the correct way to center those progress bars the same way as the other two rows? Appreciate some help, thanks!

答:
If I remember correctly, Bootstrap doesn't have an option for this.. In itself but you can do it by adding your own class to the element and then adding some styling for that class.

Where you have your col-md-6 add another class of column-centered

Then in your css do add in some styles...

```<code>.column-centered {
   float: none;
   margin: 0 auto;
}
</code>```

Body:
I am not able to center two progress bars inside two columns the same way used in the other 2 rows.

Currently:

Expectation:

Progress bars code:

70%

70%

The two squares which seem to work:

img1

img2

Top row is .top-row {margin-top: 20px;} just to distance the rows.

What would be the correct way to center those progress bars the same way as the other two rows? Appreciate some help, thanks!

Body:
If I remember correctly, Bootstrap doesn't have an option for this.. In itself but you can do it by adding your own class to the element and then adding some styling for that class.

Where you have your col-md-6 add another class of column-centered

Then in your css do add in some styles...

.column-centered {
   float: none;
   margin: 0 auto;
}


问:
Uncaught (in promise) DOMException: Quota exceeded
I am trying to see the demo of offline status  from the below link and I get DOMException: Quota exceeded.

https://serviceworke.rs/offline-status_demo.html

This error occurs only in chrome. It works fine in firefox without error in firefox.

The error occurs in the install event of the service worker.
Code from the service worker in posted below for reference.

// /serviceworker-cookbook/offline-status/

var CACHE_NAME = 'dependencies-cache';

// Files required to make this app work offline
var REQUIRED_FILES = [
  'random-1.png',
  'random-2.png',
  'random-3.png',
  'random-4.png',
  'random-5.png',
  'random-6.png',
  'style.css',
  'index.html',
  'index.js',
  'app.js'
];

self.addEventListener('install', function(event) {
  // Perform install step:  loading each required file into cache
  event.waitUntil(  // Error occurs here... Why???
    caches.open(CACHE_NAME)
      .then(function(cache) {
        // Add all offline dependencies to the cache
        console.log('[install] Caches opened, adding all core components' +
          'to cache');
        return cache.addAll(REQUIRED_FILES);
      })
      .then(function() {
        console.log('[install] All required resources have been cached, ' +
          'we\'re good!');
        return self.skipWaiting();
      })
  );
});

self.addEventListener('fetch', function(event) {
  event.respondWith(
    caches.match(event.request)
      .then(function(response) {
        // Cache hit - return the response from the cached version
        if (response) {
          console.log(
            '[fetch] Returning from ServiceWorker cache: ',
            event.request.url
          );
          return response;
        }

        // Not in cache - return the result from the live server
        // `fetch` is essentially a "fallback"
        console.log('[fetch] Returning from server: ', event.request.url);
        return fetch(event.request);
      }
    )
  );
});

self.addEventListener('activate', function(event) {
  console.log('[activate] Activating ServiceWorker!');

  // Calling claim() to force a "controllerchange" event on navigator.serviceWorker
  console.log('[activate] Claiming this ServiceWorker!');
  event.waitUntil(self.clients.claim());
});```

How to rectify this error? Is there a way to increase the quota limit in chrome?

EDIT1:

This link says that the Chrome checks quota limit per origin whereas firefox has unlimited quota.

Is there a way to delete all the files cached from the origin (reset to original state) ?

答:
The solution that I can think of based on your code, you can give version to your cache name and then whenever you don't want old assets you can delete the whole cache and keep the new cache. for instance:

```<code>self.addEventListener('activate', function(event) {

  var cacheWhitelist = ['dependencies-cache-**v1**', 'dependencies-2-cache-**v1**'];// Version for your cache list

  event.waitUntil(
    caches.keys().then(function(cacheNames) {
      return Promise.all(
        cacheNames.map(function(cacheName) {
          if (cacheWhitelist.indexOf(cacheName) === -1) {
            return caches.delete(cacheName);
          }
        })
      );
    })
  );
});
</code>```

I hope this is what you are looking for.

Body:
I am trying to see the demo of offline status  from the below link and I get DOMException: Quota exceeded.

https://serviceworke.rs/offline-status_demo.html

This error occurs only in chrome. It works fine in firefox without error in firefox.

The error occurs in the install event of the service worker.
Code from the service worker in posted below for reference.

// /serviceworker-cookbook/offline-status/

var CACHE_NAME = 'dependencies-cache';

// Files required to make this app work offline
var REQUIRED_FILES = [
  'random-1.png',
  'random-2.png',
  'random-3.png',
  'random-4.png',
  'random-5.png',
  'random-6.png',
  'style.css',
  'index.html',
  'index.js',
  'app.js'
];

self.addEventListener('install', function(event) {
  // Perform install step:  loading each required file into cache
  event.waitUntil(  // Error occurs here... Why???
    caches.open(CACHE_NAME)
      .then(function(cache) {
        // Add all offline dependencies to the cache
        console.log('[install] Caches opened, adding all core components' +
          'to cache');
        return cache.addAll(REQUIRED_FILES);
      })
      .then(function() {
        console.log('[install] All required resources have been cached, ' +
          'we\'re good!');
        return self.skipWaiting();
      })
  );
});

self.addEventListener('fetch', function(event) {
  event.respondWith(
    caches.match(event.request)
      .then(function(response) {
        // Cache hit - return the response from the cached version
        if (response) {
          console.log(
            '[fetch] Returning from ServiceWorker cache: ',
            event.request.url
          );
          return response;
        }

        // Not in cache - return the result from the live server
        // `fetch` is essentially a "fallback"
        console.log('[fetch] Returning from server: ', event.request.url);
        return fetch(event.request);
      }
    )
  );
});

self.addEventListener('activate', function(event) {
  console.log('[activate] Activating ServiceWorker!');

  // Calling claim() to force a "controllerchange" event on navigator.serviceWorker
  console.log('[activate] Claiming this ServiceWorker!');
  event.waitUntil(self.clients.claim());
});

How to rectify this error? Is there a way to increase the quota limit in chrome?

EDIT1:

This link says that the Chrome checks quota limit per origin whereas firefox has unlimited quota.

Is there a way to delete all the files cached from the origin (reset to original state) ?

Body:
The solution that I can think of based on your code, you can give version to your cache name and then whenever you don't want old assets you can delete the whole cache and keep the new cache. for instance:

self.addEventListener('activate', function(event) {

  var cacheWhitelist = ['dependencies-cache-**v1**', 'dependencies-2-cache-**v1**'];// Version for your cache list

  event.waitUntil(
    caches.keys().then(function(cacheNames) {
      return Promise.all(
        cacheNames.map(function(cacheName) {
          if (cacheWhitelist.indexOf(cacheName) === -1) {
            return caches.delete(cacheName);
          }
        })
      );
    })
  );
});

I hope this is what you are looking for.


问:
Error when using Hibernate tools Session factory
I get org.hibernate.MappingException: entity class not found: Company

In my Spring MVC project I already have classes mapped with annotations and I use Hibernate. I installed and configured Hibernate Tools to use HSql editor and mapping diagram. The mapping diagram opens, but the Hsql editor won't run. In Hibernate Code Generation Configurations I have only exported XML mappings and XML configuration. How can I fix this so Hsql editor will work?

Mappings I added through Edit launch configuration properties in Hibernate Tools.

Update: When I right click on on my class file (Open source file) hibernate=>Configuration=>Company(or any other class files) hibernate throws error: Can't find source file. but if I click on Mapping file it opens.

Here's the hibernate cfg file and it's located in src folder:
Updated:

```<code>    <?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
    "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
    "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory name="sessionFactory">
    <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
    <property name="hibernate.connection.password">xxxx</property>
    <property name="hibernate.connection.url">jdbc:mysql://<host><:port>/<database></property>
    <property name="hibernate.connection.username">root</property>
    <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
    <mapping resource="com/web/handyman/entity/Company.hbm.xml"></mapping>
     <mapping resource="com/web/handyman/entity/Address.hbm.xml"></mapping>
     <mapping resource="com/web/handyman/entity/Customers.hbm.xml"></mapping>
     <mapping resource="com/web/handyman/entity/Handyman.hbm.xml"></mapping>
     <mapping resource="com/web/handyman/entity/Locations.hbm.xml"></mapping>
     <mapping resource="com/web/handyman/entity/User.hbm.xml"></mapping>
     <mapping resource="com/web/handyman/entity/UserRoles.hbm.xml"></mapping>
     <mapping resource="com/web/handyman/entity/WorkOrder.hbm.xml"></mapping>
</session-factory>
</code>```

and here's my Company.hbm.xml and it's located in com.web.handyman.entity package:

```<code><?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<!-- Generated Jun 8, 2017 12:00:36 PM by Hibernate Tools 5.1.0.Alpha1 -->
<hibernate-mapping>
<class name="Company" table="company" catalog="" optimistic-lock="version">
    <id name="id" type="java.lang.Integer">
        <column name="id" />
        <generator class="identity" />
    </id>
    <many-to-one name="address" class="Address" fetch="select">
        <column name="address_id" />
    </many-to-one>
    <property name="companyName" type="string">
        <column name="company_name" length="45" />
    </property>
    <property name="phoneNumber" type="string">
        <column name="phone_number" length="25" />
    </property>
    <property name="fax" type="string">
        <column name="fax" length="25" />
    </property>
    <property name="email" type="string">
        <column name="email" length="25" />
    </property>
    <property name="website" type="string">
        <column name="website" length="45" />
    </property>
    <property name="info" type="string">
        <column name="info" length="250" />
    </property>
    <set name="customerses" table="customers" inverse="true" lazy="true" fetch="select">
        <key>
            <column name="company_id" />
        </key>
        <one-to-many class="Customers" />
    </set>
</class>
</hibernate-mapping>
</code>```

Here's the hibernate error:

```<code>    org.hibernate.MappingException: entity class not found: Company
at org.hibernate.mapping.PersistentClass.getMappedClass(PersistentClass.java:132)
at org.hibernate.tuple.PropertyFactory.getGetter(PropertyFactory.java:323)
at org.hibernate.tuple.PropertyFactory.buildIdentifierAttribute(PropertyFactory.java:63)
at org.hibernate.tuple.entity.EntityMetamodel.<init>(EntityMetamodel.java:138)
at org.hibernate.persister.entity.AbstractEntityPersister.<init>(AbstractEntityPersister.java:509)
at org.hibernate.persister.entity.SingleTableEntityPersister.<init>(SingleTableEntityPersister.java:124)
at sun.reflect.GeneratedConstructorAccessor275.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
at org.hibernate.persister.internal.PersisterFactoryImpl.createEntityPersister(PersisterFactoryImpl.java:96)
at org.hibernate.persister.internal.PersisterFactoryImpl.createEntityPersister(PersisterFactoryImpl.java:77)
at org.hibernate.internal.SessionFactoryImpl.<init>(SessionFactoryImpl.java:344)
at org.hibernate.boot.internal.SessionFactoryBuilderImpl.build(SessionFactoryBuilderImpl.java:465)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:708)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:724)
at sun.reflect.GeneratedMethodAccessor734.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.jboss.tools.hibernate.runtime.common.Util.invokeMethod(Util.java:43)
at org.jboss.tools.hibernate.runtime.common.AbstractConfigurationFacade.buildTargetSessionFactory(AbstractConfigurationFacade.java:321)
at org.jboss.tools.hibernate.runtime.common.AbstractConfigurationFacade.buildSessionFactory(AbstractConfigurationFacade.java:169)
at org.hibernate.console.ConsoleConfiguration$5.execute(ConsoleConfiguration.java:285)
at org.hibernate.console.execution.DefaultExecutionContext.execute(DefaultExecutionContext.java:63)
at org.hibernate.console.ConsoleConfiguration.execute(ConsoleConfiguration.java:108)
at org.hibernate.console.ConsoleConfiguration.buildSessionFactory(ConsoleConfiguration.java:280)
at org.hibernate.eclipse.console.actions.ExecuteQueryAction.execute(ExecuteQueryAction.java:82)
at org.hibernate.eclipse.console.actions.ExecuteQueryAction.run(ExecuteQueryAction.java:55)
at org.eclipse.jface.action.Action.runWithEvent(Action.java:473)
at org.hibernate.eclipse.console.actions.ExecuteQueryAction.runWithEvent(ExecuteQueryAction.java:59)
at org.eclipse.jface.action.ActionContributionItem.handleWidgetSelection(ActionContributionItem.java:595)
at org.eclipse.jface.action.ActionContributionItem.access$2(ActionContributionItem.java:511)
at org.eclipse.jface.action.ActionContributionItem$6.handleEvent(ActionContributionItem.java:462)
at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:84)
at org.eclipse.swt.widgets.Display.sendEvent(Display.java:4481)
at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1329)
at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:3819)
at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:3430)
at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine$4.run(PartRenderingEngine.java:1127)
at org.eclipse.core.databinding.observable.Realm.runWithDefault(Realm.java:337)
at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine.run(PartRenderingEngine.java:1018)
at org.eclipse.e4.ui.internal.workbench.E4Workbench.createAndRunUI(E4Workbench.java:156)
at org.eclipse.ui.internal.Workbench$5.run(Workbench.java:694)
at org.eclipse.core.databinding.observable.Realm.runWithDefault(Realm.java:337)
at org.eclipse.ui.internal.Workbench.createAndRunWorkbench(Workbench.java:606)
at org.eclipse.ui.PlatformUI.createAndRunWorkbench(PlatformUI.java:150)
at org.eclipse.ui.internal.ide.application.IDEApplication.start(IDEApplication.java:139)
at org.eclipse.equinox.internal.app.EclipseAppHandle.run(EclipseAppHandle.java:196)
at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.runApplication(EclipseAppLauncher.java:134)
at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.start(EclipseAppLauncher.java:104)
at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:380)
at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:235)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.eclipse.equinox.launcher.Main.invokeFramework(Main.java:669)
at org.eclipse.equinox.launcher.Main.basicRun(Main.java:608)
at org.eclipse.equinox.launcher.Main.run(Main.java:1515)
at org.eclipse.equinox.launcher.Main.main(Main.java:1488)
Caused by: org.hibernate.boot.registry.classloading.spi.ClassLoadingException: Unable to load class [Company]
at org.hibernate.boot.registry.classloading.internal.ClassLoaderServiceImpl.classForName(ClassLoaderServiceImpl.java:229)
at org.hibernate.boot.internal.ClassLoaderAccessImpl.classForName(ClassLoaderAccessImpl.java:62)
at org.hibernate.mapping.PersistentClass.getMappedClass(PersistentClass.java:127)
... 58 more
 Caused by: java.lang.ClassNotFoundException: Could not load requested class : Company
at org.hibernate.boot.registry.classloading.internal.ClassLoaderServiceImpl$AggregatedClassLoader.findClass(ClassLoaderServiceImpl.java:217)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:348)
at org.hibernate.boot.registry.classloading.internal.ClassLoaderServiceImpl.classForName(ClassLoaderServiceImpl.java:226)
... 60 more
</code>```

答: add Company.hbm.xml in hibernate configuration file</p>

Body:
I get org.hibernate.MappingException: entity class not found: Company

In my Spring MVC project I already have classes mapped with annotations and I use Hibernate. I installed and configured Hibernate Tools to use HSql editor and mapping diagram. The mapping diagram opens, but the Hsql editor won't run. In Hibernate Code Generation Configurations I have only exported XML mappings and XML configuration. How can I fix this so Hsql editor will work?

Mappings I added through Edit launch configuration properties in Hibernate Tools.

Update: When I right click on on my class file (Open source file) hibernate=>Configuration=>Company(or any other class files) hibernate throws error: Can't find source file. but if I click on Mapping file it opens.

Here's the hibernate cfg file and it's located in src folder:
Updated:

    <?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
    "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
    "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory name="sessionFactory">
    <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
    <property name="hibernate.connection.password">xxxx</property>
    <property name="hibernate.connection.url">jdbc:mysql://<host><:port>/<database></property>
    <property name="hibernate.connection.username">root</property>
    <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
    <mapping resource="com/web/handyman/entity/Company.hbm.xml"></mapping>
     <mapping resource="com/web/handyman/entity/Address.hbm.xml"></mapping>
     <mapping resource="com/web/handyman/entity/Customers.hbm.xml"></mapping>
     <mapping resource="com/web/handyman/entity/Handyman.hbm.xml"></mapping>
     <mapping resource="com/web/handyman/entity/Locations.hbm.xml"></mapping>
     <mapping resource="com/web/handyman/entity/User.hbm.xml"></mapping>
     <mapping resource="com/web/handyman/entity/UserRoles.hbm.xml"></mapping>
     <mapping resource="com/web/handyman/entity/WorkOrder.hbm.xml"></mapping>
</session-factory>

and here's my Company.hbm.xml and it's located in com.web.handyman.entity package:

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">

<hibernate-mapping>
<class name="Company" table="company" catalog="" optimistic-lock="version">
    <id name="id" type="java.lang.Integer">
        <column name="id" />
        <generator class="identity" />
    </id>
    <many-to-one name="address" class="Address" fetch="select">
        <column name="address_id" />
    </many-to-one>
    <property name="companyName" type="string">
        <column name="company_name" length="45" />
    </property>
    <property name="phoneNumber" type="string">
        <column name="phone_number" length="25" />
    </property>
    <property name="fax" type="string">
        <column name="fax" length="25" />
    </property>
    <property name="email" type="string">
        <column name="email" length="25" />
    </property>
    <property name="website" type="string">
        <column name="website" length="45" />
    </property>
    <property name="info" type="string">
        <column name="info" length="250" />
    </property>
    <set name="customerses" table="customers" inverse="true" lazy="true" fetch="select">
        <key>
            <column name="company_id" />
        </key>
        <one-to-many class="Customers" />
    </set>
</class>
</hibernate-mapping>

Here's the hibernate error:

    org.hibernate.MappingException: entity class not found: Company
at org.hibernate.mapping.PersistentClass.getMappedClass(PersistentClass.java:132)
at org.hibernate.tuple.PropertyFactory.getGetter(PropertyFactory.java:323)
at org.hibernate.tuple.PropertyFactory.buildIdentifierAttribute(PropertyFactory.java:63)
at org.hibernate.tuple.entity.EntityMetamodel.<init>(EntityMetamodel.java:138)
at org.hibernate.persister.entity.AbstractEntityPersister.<init>(AbstractEntityPersister.java:509)
at org.hibernate.persister.entity.SingleTableEntityPersister.<init>(SingleTableEntityPersister.java:124)
at sun.reflect.GeneratedConstructorAccessor275.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
at org.hibernate.persister.internal.PersisterFactoryImpl.createEntityPersister(PersisterFactoryImpl.java:96)
at org.hibernate.persister.internal.PersisterFactoryImpl.createEntityPersister(PersisterFactoryImpl.java:77)
at org.hibernate.internal.SessionFactoryImpl.<init>(SessionFactoryImpl.java:344)
at org.hibernate.boot.internal.SessionFactoryBuilderImpl.build(SessionFactoryBuilderImpl.java:465)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:708)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:724)
at sun.reflect.GeneratedMethodAccessor734.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.jboss.tools.hibernate.runtime.common.Util.invokeMethod(Util.java:43)
at org.jboss.tools.hibernate.runtime.common.AbstractConfigurationFacade.buildTargetSessionFactory(AbstractConfigurationFacade.java:321)
at org.jboss.tools.hibernate.runtime.common.AbstractConfigurationFacade.buildSessionFactory(AbstractConfigurationFacade.java:169)
at org.hibernate.console.ConsoleConfiguration$5.execute(ConsoleConfiguration.java:285)
at org.hibernate.console.execution.DefaultExecutionContext.execute(DefaultExecutionContext.java:63)
at org.hibernate.console.ConsoleConfiguration.execute(ConsoleConfiguration.java:108)
at org.hibernate.console.ConsoleConfiguration.buildSessionFactory(ConsoleConfiguration.java:280)
at org.hibernate.eclipse.console.actions.ExecuteQueryAction.execute(ExecuteQueryAction.java:82)
at org.hibernate.eclipse.console.actions.ExecuteQueryAction.run(ExecuteQueryAction.java:55)
at org.eclipse.jface.action.Action.runWithEvent(Action.java:473)
at org.hibernate.eclipse.console.actions.ExecuteQueryAction.runWithEvent(ExecuteQueryAction.java:59)
at org.eclipse.jface.action.ActionContributionItem.handleWidgetSelection(ActionContributionItem.java:595)
at org.eclipse.jface.action.ActionContributionItem.access$2(ActionContributionItem.java:511)
at org.eclipse.jface.action.ActionContributionItem$6.handleEvent(ActionContributionItem.java:462)
at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:84)
at org.eclipse.swt.widgets.Display.sendEvent(Display.java:4481)
at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1329)
at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:3819)
at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:3430)
at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine$4.run(PartRenderingEngine.java:1127)
at org.eclipse.core.databinding.observable.Realm.runWithDefault(Realm.java:337)
at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine.run(PartRenderingEngine.java:1018)
at org.eclipse.e4.ui.internal.workbench.E4Workbench.createAndRunUI(E4Workbench.java:156)
at org.eclipse.ui.internal.Workbench$5.run(Workbench.java:694)
at org.eclipse.core.databinding.observable.Realm.runWithDefault(Realm.java:337)
at org.eclipse.ui.internal.Workbench.createAndRunWorkbench(Workbench.java:606)
at org.eclipse.ui.PlatformUI.createAndRunWorkbench(PlatformUI.java:150)
at org.eclipse.ui.internal.ide.application.IDEApplication.start(IDEApplication.java:139)
at org.eclipse.equinox.internal.app.EclipseAppHandle.run(EclipseAppHandle.java:196)
at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.runApplication(EclipseAppLauncher.java:134)
at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.start(EclipseAppLauncher.java:104)
at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:380)
at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:235)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.eclipse.equinox.launcher.Main.invokeFramework(Main.java:669)
at org.eclipse.equinox.launcher.Main.basicRun(Main.java:608)
at org.eclipse.equinox.launcher.Main.run(Main.java:1515)
at org.eclipse.equinox.launcher.Main.main(Main.java:1488)
Caused by: org.hibernate.boot.registry.classloading.spi.ClassLoadingException: Unable to load class [Company]
at org.hibernate.boot.registry.classloading.internal.ClassLoaderServiceImpl.classForName(ClassLoaderServiceImpl.java:229)
at org.hibernate.boot.internal.ClassLoaderAccessImpl.classForName(ClassLoaderAccessImpl.java:62)
at org.hibernate.mapping.PersistentClass.getMappedClass(PersistentClass.java:127)
... 58 more
 Caused by: java.lang.ClassNotFoundException: Could not load requested class : Company
at org.hibernate.boot.registry.classloading.internal.ClassLoaderServiceImpl$AggregatedClassLoader.findClass(ClassLoaderServiceImpl.java:217)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:348)
at org.hibernate.boot.registry.classloading.internal.ClassLoaderServiceImpl.classForName(ClassLoaderServiceImpl.java:226)
... 60 more


问:
React Native APK build failure Unable to process incoming event 'ProgressComplete'
Suddenly i cannot build a release apk with the following error:

[04/07/2017, 20:37:22]    Transforming files (18437ms) bundle:
  start bundle: finish bundle: Writing bundle output to:
  D:\likecounter\android\app\build\intermediates\assets\release\index.android.bundle
  bundle: Done writing bundle output bundle: Copying 13 asset files
  bundle: Done copying assets

FAILURE: Build failed with an exception.

What went wrong: Unable to process incoming event 'ProgressComplete '
  (ProgressCompleteEvent)

Try: Run with --stacktrace option to get the stack trace. Run with
  --info or --debug option to get more log output.

I tried to use the suggested flags, but they weren't helpful.

The only thing i can think that could cause this problem is when i tried to press the run button on Android Studio it suggested to allow something that has to do with "instant run" and i naively agreed.

I tried to take the following steps:

Change gradle version from 2.2.3 to 2.1.2

Cancel instant run in Android studio configuration by reaching Build,
Execution, Deployment -> Instant Run -> un-select everything

答:
i did gradlew clean
then i close android studio and open it again
then gradlew assembleRelease
then it works</p>


问:
strcpy and sprintf in C
I'm trying to set some string variables like this:

```<code>char thingA[7], thingB[7], thingC[7];
strcpy(thingA, "StringA");
strcpy(thingB, "StringB");
strcpy(thingC, "StringC");
printf("%s\n", thingA);
printf("%s\n", thingB);
printf("%s\n", thingC);
</code>```

but instead of outputting like this:

```<code>StringA
StringB
StringC
</code>```

it outputs like this:

```<code>StringA StringB StringC
StringB StringC
StringC
</code>```

I've tried this with sprintf, but get the same result.
I honestly have no idea what's going on, or how to fix this, and I can't find anything on it online, since searching for this kind of stuff has proven hard for some reason.
So basically why is it storing string b and c in a, and c in b?

答:
The usual error: your declarations are one byte short. If you count the characters in your constant strings, there are 7, and you need space for the terminating'\0', otherwise you will overwrite memory and get undefined bahvaior.

So declare them as [8], and it will work.

Title: strcpy and sprintf in C

Body:
I'm trying to set some string variables like this:

char thingA[7], thingB[7], thingC[7];
strcpy(thingA, "StringA");
strcpy(thingB, "StringB");
strcpy(thingC, "StringC");
printf("%s\n", thingA);
printf("%s\n", thingB);
printf("%s\n", thingC);

but instead of outputting like this:

StringA
StringB
StringC

it outputs like this:

StringA StringB StringC
StringB StringC
StringC

I've tried this with sprintf, but get the same result.
I honestly have no idea what's going on, or how to fix this, and I can't find anything on it online, since searching for this kind of stuff has proven hard for some reason.
So basically why is it storing string b and c in a, and c in b?


问:
Working with linked list + struct C
Here is the linked list and the struct:

```<code>#define MAX_PATH_SIZE (256)
#define MAX_NAME_SIZE (50)
struct Frame
{
    char *name;
    unsigned int duration;
    char *path;  // may change to FILE*
};

typedef struct Frame frame_t;
struct Link
{
    frame_t *frame;
    struct Link *next;
};

typedef struct Link link_t;
</code>```

And here's my function:

```<code>link_t* createFrame(char name[], int duration, char path[]){
frame_t * temp = (frame_t*)malloc(sizeof(frame_t));
temp->duration = duration;

strncpy(temp->name, name,MAX_NAME_SIZE);
strncpy(temp->path, path,MAX_PATH_SIZE);
link_t* newFrame = (link_t*)malloc(sizeof(link_t));

newFrame->frame = temp;
return newFrame;
}
</code>```

The problem is that the function stop working in the line "strncpy(temp->name)..", the weird thing is that the temp->duration is working but it doesn't work with strings. Error: "Unhandled exception at 0x0F744645 (msvcr120d.dll)"

答:
Try this :</p>

```<code>#define MAX_PATH_SIZE (256)
#define MAX_NAME_SIZE (50)

struct Frame
{
    char name[MAX_NAME_SIZE];
    unsigned int duration;
    char path[MAX_PATH_SIZE];  // may change to FILE*
};

typedef struct Frame frame_t;
struct Link
{
    frame_t *frame;
    struct Link *next;
};

typedef struct Link link_t;

link_t* createFrame(char name[MAX_NAME_SIZE], int duration, char path[MAX_PATH_SIZE]){
    frame_t * temp = (frame_t*)malloc(sizeof(frame_t));
    temp->duration = duration;

    strncpy(temp->name, name, MAX_NAME_SIZE);
    strncpy(temp->path, path, MAX_PATH_SIZE);
    link_t* newFrame = (link_t*)malloc(sizeof(link_t));

    newFrame->frame = temp;
    return newFrame;
}
</code>```

Title: Working with linked list + struct C

Body:
Here is the linked list and the struct:

#define MAX_PATH_SIZE (256)
#define MAX_NAME_SIZE (50)
struct Frame
{
    char *name;
    unsigned int duration;
    char *path;  // may change to FILE*
};

typedef struct Frame frame_t;
struct Link
{
    frame_t *frame;
    struct Link *next;
};

typedef struct Link link_t;

And here's my function:

link_t* createFrame(char name[], int duration, char path[]){
frame_t * temp = (frame_t*)malloc(sizeof(frame_t));
temp->duration = duration;

strncpy(temp->name, name,MAX_NAME_SIZE);
strncpy(temp->path, path,MAX_PATH_SIZE);
link_t* newFrame = (link_t*)malloc(sizeof(link_t));

newFrame->frame = temp;
return newFrame;
}

The problem is that the function stop working in the line "strncpy(temp->name)..", the weird thing is that the temp->duration is working but it doesn't work with strings. Error: "Unhandled exception at 0x0F744645 (msvcr120d.dll)"

Body:
Try this :

#define MAX_PATH_SIZE (256)
#define MAX_NAME_SIZE (50)

struct Frame
{
    char name[MAX_NAME_SIZE];
    unsigned int duration;
    char path[MAX_PATH_SIZE];  // may change to FILE*
};

typedef struct Frame frame_t;
struct Link
{
    frame_t *frame;
    struct Link *next;
};

typedef struct Link link_t;

link_t* createFrame(char name[MAX_NAME_SIZE], int duration, char path[MAX_PATH_SIZE]){
    frame_t * temp = (frame_t*)malloc(sizeof(frame_t));
    temp->duration = duration;

    strncpy(temp->name, name, MAX_NAME_SIZE);
    strncpy(temp->path, path, MAX_PATH_SIZE);
    link_t* newFrame = (link_t*)malloc(sizeof(link_t));

    newFrame->frame = temp;
    return newFrame;
}


问:
Regex to find last token on a string
I was wondering if there is a way having this

```<code>var string = "foo::bar"
</code>```

To get the last part of the string: "bar" using just regex.

I was trying to do look-aheads but couldn't master them enough to do this.

--

UPDATE

Perhaps some examples will make the question clearer.

```<code>var st1 = "foo::bar::0"
match should be 0

var st2 = "foo::bar::0-3aab"
match should be 0-3aab

var st3 = "foo"
no match should be found
</code>```

答:
I wouldn't use regular expressions for this (although you certainly can); I'd split the string on ::, since that's conceptually what you want to do.

```<code>function lastToken(str) {
  var xs = str.split('::');
  return xs.length > 1 ? xs.pop() : null;
}
</code>```

If you really want just a regular expression, you can use /::((?:[^:]|:(?!:))*)$/.  First, it matches a literal ::.  Then, we use parentheses to put the desired thing in capturing group 1.  The desired thing is one or more copies of a (?:...)-bracketed string; this bracketing groups without capturing.  We then look for either [^:], a non-colon character, or :(?!:), a colon followed by a non-colon.  The (?!...) is a negative lookahead, which matches only if the next token doesn't match the contained pattern.  Since JavaScript doesn't support negative lookbehinds, I can't see a good way to avoid capturing the :: as well, but you can wrap this in a function:

```<code>function lastTokenRegex(str) {
  var m = str.match(/::((?:[^:]|:(?!:))*)$/);
  return m && m[1];
}
</code>```

Title: Regex to find last token on a string

Body:
I was wondering if there is a way having this

var string = "foo::bar"

To get the last part of the string: "bar" using just regex.

I was trying to do look-aheads but couldn't master them enough to do this.

--

UPDATE

Perhaps some examples will make the question clearer.

var st1 = "foo::bar::0"
match should be 0

var st2 = "foo::bar::0-3aab"
match should be 0-3aab

var st3 = "foo"
no match should be found

Body:
I wouldn't use regular expressions for this (although you certainly can); I'd split the string on ::, since that's conceptually what you want to do.

function lastToken(str) {
  var xs = str.split('::');
  return xs.length > 1 ? xs.pop() : null;
}

If you really want just a regular expression, you can use /::((?:[^:]|:(?!:))*)$/.  First, it matches a literal ::.  Then, we use parentheses to put the desired thing in capturing group 1.  The desired thing is one or more copies of a (?:...)-bracketed string; this bracketing groups without capturing.  We then look for either [^:], a non-colon character, or :(?!:), a colon followed by a non-colon.  The (?!...) is a negative lookahead, which matches only if the next token doesn't match the contained pattern.  Since JavaScript doesn't support negative lookbehinds, I can't see a good way to avoid capturing the :: as well, but you can wrap this in a function:

function lastTokenRegex(str) {
  var m = str.match(/::((?:[^:]|:(?!:))*)$/);
  return m && m[1];
}


问:
How to building uber-JAR with all non-transtive dependencies?
I have Maven project that consists of the following modules and submodules:

```<code>A
  B      (with external dependencies like junit, spring, etc.)
  C      (with external dependencies as well)
  A-all  (with B and C defined as dependencies)
</code>```

I would like the last module to build uber-JAR containing both B and C jars. I tried to use maven-assembly-plugin with jar-with-dependencies desciptor but the ultimate jar contains also transitive dependencies, i.e. dependencies used by B and C.

How can I build jar with all non-transitive dependencies of A-all module?

答: I think you can set the useTransitiveDependencies flag of assembly plugin to false.

Body:
I have Maven project that consists of the following modules and submodules:

A
  B      (with external dependencies like junit, spring, etc.)
  C      (with external dependencies as well)
  A-all  (with B and C defined as dependencies)

I would like the last module to build uber-JAR containing both B and C jars. I tried to use maven-assembly-plugin with jar-with-dependencies desciptor but the ultimate jar contains also transitive dependencies, i.e. dependencies used by B and C.

How can I build jar with all non-transitive dependencies of A-all module?


问:
Why boost log not found?
I successfully build my project on locale machine, but when i upload my build in Travis i see this:

CMake Error at /usr/share/cmake-3.2/Modules/FindBoost.cmake:1182
  (message):

Unable to find the requested Boost libraries.

Boost version: 1.46.1

Boost include path: /usr/include

Could not find the following static Boost libraries:

boost_log

Some (but not all) of the required Boost libraries were found.  You
  may

need to install these additional Boost libraries.  Alternatively,
  set

BOOST_LIBRARYDIR to the directory containing Boost libraries or
  BOOST_ROOT

to the location of Boost.

Call Stack (most recent call first):

CMakeLists.txt:18 (find_package)

-- Configuring incomplete, errors occurred!

I many time search this error in google, but i not found answer. My CMakeList file this:

```<code>cmake_minimum_required(VERSION 3.2)
project(Recast-server)

set(CMAKE_CXX_STANDARD 14)

file(GLOB_RECURSE SOURCE_FILES
        "src/*.h"
        "src/*.c"
        "src/*.cpp")

include_directories(src/headers/)

set(Boost_USE_STATIC_LIBS   ON)
set(Boost_USE_MULTITHREADED ON)

add_definitions(-DBOOST_LOG_DYN_LINK)

find_package(Boost 1.46 COMPONENTS  system
                                    thread
                                    log
                                    log_setup
                                    program_options
                                    filesystem
             REQUIRED)
include_directories(${Boost_INCLUDE_DIR})

add_executable(Recast-server ${SOURCE_FILES})

target_link_libraries(Recast-server ${Boost_LIBRARIES})
target_link_libraries(Recast-server ${CMAKE_THREAD_LIBS_INIT})
</code>```

You can ask(or try commit) also in this PullRequest: https://github.com/bender-wardrobe/Recast/pull/15

Big Thanks for your answer <3

答:
If I remember correctly Boost.Log was only added in later versions of Boost.

For earlier versions of Boost you can use the standalone Boost.Log from http://boost-log.sf.net

edit

You set the version 1.46 in your CMakeLists.txt. Maybe try a later version. Don't know about Travis.

Title: Why boost log not found?

Body:
I successfully build my project on locale machine, but when i upload my build in Travis i see this:

CMake Error at /usr/share/cmake-3.2/Modules/FindBoost.cmake:1182
  (message):

Unable to find the requested Boost libraries.

Boost version: 1.46.1

Boost include path: /usr/include

Could not find the following static Boost libraries:

boost_log

Some (but not all) of the required Boost libraries were found.  You
  may

need to install these additional Boost libraries.  Alternatively,
  set

BOOST_LIBRARYDIR to the directory containing Boost libraries or
  BOOST_ROOT

to the location of Boost.

Call Stack (most recent call first):

CMakeLists.txt:18 (find_package)

-- Configuring incomplete, errors occurred!

I many time search this error in google, but i not found answer. My CMakeList file this:

cmake_minimum_required(VERSION 3.2)
project(Recast-server)

set(CMAKE_CXX_STANDARD 14)

file(GLOB_RECURSE SOURCE_FILES
        "src/*.h"
        "src/*.c"
        "src/*.cpp")

include_directories(src/headers/)

set(Boost_USE_STATIC_LIBS   ON)
set(Boost_USE_MULTITHREADED ON)

add_definitions(-DBOOST_LOG_DYN_LINK)

find_package(Boost 1.46 COMPONENTS  system
                                    thread
                                    log
                                    log_setup
                                    program_options
                                    filesystem
             REQUIRED)
include_directories(${Boost_INCLUDE_DIR})

add_executable(Recast-server ${SOURCE_FILES})

target_link_libraries(Recast-server ${Boost_LIBRARIES})
target_link_libraries(Recast-server ${CMAKE_THREAD_LIBS_INIT})

You can ask(or try commit) also in this PullRequest: https://github.com/bender-wardrobe/Recast/pull/15

Big Thanks for your answer <3


问:
Handle auto scroll
I have an autoscroll usercontrol, I need to handle the scroll event when I focus a control and it centers automatically.

I have tried the Scroll event but it seems it doesn't work when the scroll is made by the usercontrol itself

答:
In your UserControl, try overriding the ScrollToControl function:</p>

```<code>protected override Point ScrollToControl(Control activeControl) {
  return this.DisplayRectangle.Location;
}
</code>```

Title: Handle auto scroll

Body:
In your UserControl, try overriding the ScrollToControl function:

protected override Point ScrollToControl(Control activeControl) {
  return this.DisplayRectangle.Location;
}


问:
Xcode 9 - Could not load the “sampleImage” image referenced from a nib
I converted Swift 3.1 to Swift 4.0 syntax using Xcode 9.0 beta, and I have a strange problem. My images in Assets folder in the project are not loaded on my real device. I receive this information Could not load the “sampleImage” image referenced from a nib. Everything works fine in simulator. Can somebody explain me, why?

Update

After updating my iOS to iOS 11 I can see images in my app. But does it mean, that apps installed on iOS 10 and earlier will have a problem with displaying images?

答:
I doubt apps running iOS 10 and earlier will have problems displaying images. In my experience as an iOS developer when you update to a beta Xcode release and Swift SDK you have to update to the newest iOS beta to utilize the SDK and test apps. That changes once the beta tags are removed.

The following Apple document states that "The beta OS must be installed on your device (Mac, Apple TV, Apple Watch or iOS device). The beta OS, when offered, is available on the respective developer download page. For example, see iOS Downloads."

https://developer.apple.com/library/content/technotes/tn2249/_index.html


答:
I didn't know the find_in_set() function and took a more handcrafted approach. Not that it makes any sense given the first answer, but I'll post it anyway:</p>

```<code>SELECT id
FROM (
    SELECT '757392' AS id UNION
    SELECT '733602' UNION
    SELECT '749955' UNION
    SELECT '744304' UNION
    SELECT '746852' UNION
    SELECT '753904' UNION
    SELECT '755117' UNION
    SELECT '636163' UNION
    SELECT '564931' UNION
    SELECT '740787' UNION
    SELECT '751450' UNION
    SELECT '743799' UNION
    SELECT '643918' UNION
    SELECT '749903' UNION
    SELECT '571888' UNION
    SELECT '30207'  UNION
    SELECT '705953' UNION
    SELECT '749120' UNION
    SELECT '749001' UNION
    SELECT '749192' UNION
    SELECT '749978' UNION
    SELECT '750840' UNION
    SELECT '544228' UNION
    SELECT '702121' UNION
    SELECT '746246' UNION
    SELECT '383667' UNION
    SELECT '558790' UNION
    SELECT '585628' UNION
    SELECT '592771' UNION
    SELECT '745818' UNION
    SELECT '749375' UNION
    SELECT '241209' UNION
    SELECT '749235' UNION
    SELECT '746860' UNION
    SELECT '748318' UNION
    SELECT '748016' UNION
    SELECT '748951' UNION
    SELECT '747321' UNION
    SELECT '748684' UNION
    SELECT '748225' UNION
    SELECT '565375' UNION
    SELECT '748673' UNION
    SELECT '747869' UNION
    SELECT '748522' UNION
    SELECT '748335' UNION
    SELECT '744775' UNION
    SELECT '672229' UNION
    SELECT '578056' UNION
    SELECT '713127' UNION
    SELECT '740234' UNION
    SELECT '632608' UNION
    SELECT '711135' UNION
    SELECT '746528' UNION
    SELECT '362131' UNION
    SELECT '742223' UNION
    SELECT '746567' UNION
    SELECT '745224' UNION
    SELECT '332989' UNION
    SELECT '439837' UNION
    SELECT '745418' UNION
    SELECT '673582' UNION
    SELECT '269584' UNION
    SELECT '742606' UNION
    SELECT '745135' UNION
    SELECT '746950' UNION
    SELECT '476134' UNION
    SELECT '740830' UNION
    SELECT '742949' UNION
    SELECT '276934') AS id_list
WHERE id NOT IN (
    SELECT id
    FROM users);
</code>```

Title: Check which IDs from a set do not exists in a table

Body:
I have a list of user IDs, like this:

757392,733602,749955,744304,746852,753904,755117,636163,564931,740787,751450,743799,643918,
749903,571888,30207,705953,749120,749001,749192,749978,750840,544228,702121,746246,383667,
558790,585628,592771,745818,749375,241209,749235,746860,748318,748016,748951,747321,748684,
748225,565375,748673,747869,748522,748335,744775,672229,578056,713127,740234,632608,711135,
746528,362131,742223,746567,745224,332989,439837,745418,673582,269584,742606,745135,746950,
476134,740830,742949,276934

I have a MySQL table users with the id field.

How do I check - using a query - which IDs of the ones I have do not exists in the users table?

This sounds like a simple problem to me, yet I couldn't find any example on StackOverflow which would address a fixed set of ID values.

Body:
I didn't know the find_in_set() function and took a more handcrafted approach. Not that it makes any sense given the first answer, but I'll post it anyway:

SELECT id
FROM (
    SELECT '757392' AS id UNION
    SELECT '733602' UNION
    SELECT '749955' UNION
    SELECT '744304' UNION
    SELECT '746852' UNION
    SELECT '753904' UNION
    SELECT '755117' UNION
    SELECT '636163' UNION
    SELECT '564931' UNION
    SELECT '740787' UNION
    SELECT '751450' UNION
    SELECT '743799' UNION
    SELECT '643918' UNION
    SELECT '749903' UNION
    SELECT '571888' UNION
    SELECT '30207'  UNION
    SELECT '705953' UNION
    SELECT '749120' UNION
    SELECT '749001' UNION
    SELECT '749192' UNION
    SELECT '749978' UNION
    SELECT '750840' UNION
    SELECT '544228' UNION
    SELECT '702121' UNION
    SELECT '746246' UNION
    SELECT '383667' UNION
    SELECT '558790' UNION
    SELECT '585628' UNION
    SELECT '592771' UNION
    SELECT '745818' UNION
    SELECT '749375' UNION
    SELECT '241209' UNION
    SELECT '749235' UNION
    SELECT '746860' UNION
    SELECT '748318' UNION
    SELECT '748016' UNION
    SELECT '748951' UNION
    SELECT '747321' UNION
    SELECT '748684' UNION
    SELECT '748225' UNION
    SELECT '565375' UNION
    SELECT '748673' UNION
    SELECT '747869' UNION
    SELECT '748522' UNION
    SELECT '748335' UNION
    SELECT '744775' UNION
    SELECT '672229' UNION
    SELECT '578056' UNION
    SELECT '713127' UNION
    SELECT '740234' UNION
    SELECT '632608' UNION
    SELECT '711135' UNION
    SELECT '746528' UNION
    SELECT '362131' UNION
    SELECT '742223' UNION
    SELECT '746567' UNION
    SELECT '745224' UNION
    SELECT '332989' UNION
    SELECT '439837' UNION
    SELECT '745418' UNION
    SELECT '673582' UNION
    SELECT '269584' UNION
    SELECT '742606' UNION
    SELECT '745135' UNION
    SELECT '746950' UNION
    SELECT '476134' UNION
    SELECT '740830' UNION
    SELECT '742949' UNION
    SELECT '276934') AS id_list
WHERE id NOT IN (
    SELECT id
    FROM users);


问:
Error when build NDK of AndEngine example
I'm trying to build AndEngine sample on my MacOS Android Studio 2.3.2.
But get this error. Cannot figure out what is the problem. Strange thing is the same project build normally on Windows, same version of Android Studio.

```<code>> FAILURE: Build failed with an exception.
What went wrong:
Execution failed for task ':andEngine:externalNativeBuildRelease'.
> Build command failed.
  Error while executing process /Users/apple/Library/Android/sdk/ndk-bundle/ndk-build with arguments {NDK_PROJECT_PATH=null APP_BUILD_SCRIPT=/Users/apple/Documents/workspace/AndroidStudio/AndEngineExamples-GLES2/andEngine/src/main/jni/Android.mk

  NDK_APPLICATION_MK=/Users/apple/Documents/workspace/AndroidStudio/AndEngineExamples-GLES2/andEngine/src/main/jni/Application.mk APP_ABI=mips NDK_ALL_ABIS=mips NDK_DEBUG=0 APP_PLATFORM=android-9 NDK_OUT=/Users/apple/Documents/workspace/AndroidStudio/AndEngineExamples-GLES2/andEngine/build/intermediates/ndkBuild/release/obj NDK_LIBS_OUT=/Users/apple/Documents/workspace/AndroidStudio/AndEngineExamples-GLES2/andEngine/build/intermediates/ndkBuild/release/lib /Users/apple/Documents/workspace/AndroidStudio/AndEngineExamples-GLES2/andEngine/build/intermediates/ndkBuild/release/obj/local/mips/libandengine.so}
  Android NDK: android-9 is unsupported. Using minimum supported version android-14.
  [mips] Compile++      : andengine_shared <= BufferUtils.cpp
  /Users/apple/Documents/workspace/AndroidStudio/AndEngineExamples-GLES2/andEngine/src/main/jni/src/BufferUtils.cpp:13:2: error: use of undeclared identifier 'memcpy'
          memcpy(bufferAddress, dataAddress + pOffset, pLength << 2);
          ^
</code>```

My Application.mk file:

```<code># Build both ARMv5TE and ARMv7-A and x86 machine code.
APP_ABI := armeabi armeabi-v7a x86
APP_STL := gnustl_shared
</code>```

And Android.mk:

```<code>LOCAL_PATH:= $(call my-dir)

include $(CLEAR_VARS)

LOCAL_MODULE             := andengine_shared
LOCAL_MODULE_FILENAME    := libandengine
LOCAL_CFLAGS             := -Werror
LOCAL_SRC_FILES          := src/GLES20Fix.c \
                             src/BufferUtils.cpp
LOCAL_LDLIBS             := -lGLESv2
LOCAL_EXPORT_C_INCLUDES  := $(LOCAL_PATH)/src

include $(BUILD_SHARED_LIBRARY)
</code>```

答:
Android NDK: android-9 is unsupported. Using minimum supported version
  android-14.

Add APP_PLATFORM := android-14 in Application.mk file

If you do not have that line then version of your SDK is taken from project.properties files.

Body:
I'm trying to build AndEngine sample on my MacOS Android Studio 2.3.2.
But get this error. Cannot figure out what is the problem. Strange thing is the same project build normally on Windows, same version of Android Studio.

> FAILURE: Build failed with an exception.
What went wrong:
Execution failed for task ':andEngine:externalNativeBuildRelease'.
> Build command failed.
  Error while executing process /Users/apple/Library/Android/sdk/ndk-bundle/ndk-build with arguments {NDK_PROJECT_PATH=null APP_BUILD_SCRIPT=/Users/apple/Documents/workspace/AndroidStudio/AndEngineExamples-GLES2/andEngine/src/main/jni/Android.mk

  NDK_APPLICATION_MK=/Users/apple/Documents/workspace/AndroidStudio/AndEngineExamples-GLES2/andEngine/src/main/jni/Application.mk APP_ABI=mips NDK_ALL_ABIS=mips NDK_DEBUG=0 APP_PLATFORM=android-9 NDK_OUT=/Users/apple/Documents/workspace/AndroidStudio/AndEngineExamples-GLES2/andEngine/build/intermediates/ndkBuild/release/obj NDK_LIBS_OUT=/Users/apple/Documents/workspace/AndroidStudio/AndEngineExamples-GLES2/andEngine/build/intermediates/ndkBuild/release/lib /Users/apple/Documents/workspace/AndroidStudio/AndEngineExamples-GLES2/andEngine/build/intermediates/ndkBuild/release/obj/local/mips/libandengine.so}
  Android NDK: android-9 is unsupported. Using minimum supported version android-14.
  [mips] Compile++      : andengine_shared <= BufferUtils.cpp
  /Users/apple/Documents/workspace/AndroidStudio/AndEngineExamples-GLES2/andEngine/src/main/jni/src/BufferUtils.cpp:13:2: error: use of undeclared identifier 'memcpy'
          memcpy(bufferAddress, dataAddress + pOffset, pLength << 2);
          ^

My Application.mk file:

# Build both ARMv5TE and ARMv7-A and x86 machine code.
APP_ABI := armeabi armeabi-v7a x86
APP_STL := gnustl_shared

And Android.mk:

LOCAL_PATH:= $(call my-dir)

include $(CLEAR_VARS)

LOCAL_MODULE             := andengine_shared
LOCAL_MODULE_FILENAME    := libandengine
LOCAL_CFLAGS             := -Werror
LOCAL_SRC_FILES          := src/GLES20Fix.c \
                             src/BufferUtils.cpp
LOCAL_LDLIBS             := -lGLESv2
LOCAL_EXPORT_C_INCLUDES  := $(LOCAL_PATH)/src

include $(BUILD_SHARED_LIBRARY)


问:
Zip a folder using SSIS
I am trying to zip a Folder in SSIS, there are 12 files in the source folder and I need to zipthat folder. I can get the files to zip fine my problem is the folders.

I have to use winzip to create the zipped packages.

Can anyone point me to a good tutorial. I haven't been able to implement any of the samples that I have found.

Thanks

答:
Adding a Script Task, yuo can use the ZipFile (class) here reference, you must refer to the System.IO.Compression.FileSystem assembly in the project (.NET Framework 4.5).

You need to provide to the Script Task the folder to be zipped and the name of the compressed folder as ReadOnlyVariables (to be added in the tab ReadOnlyVariables)

These two variables must be defined in the Variables tab (String type) of the package and can be changed dynamically through a cycle (eg. for each)

I use these two variables:

```<code>sFolderCompressed - the folder '.zip' that you want to obtain eg. C:\folder1\result.zip
sFolderSource - the source folder containing the files affected eg. C:\folder1\folder2
</code>```

The script is made using c#, choose Script Language: Microsoft Visual C#

This is the code to be added in the Main method:

```<code>using System.IO.Compression;

    public void Main()
    {
        try
        {
            string zipPath = (string)Dts.Variables["User::sFolderCompressed"].Value;
            string startPath = (string)Dts.Variables["User::sFolderSource"].Value;

            ZipFile.CreateFromDirectory(startPath, zipPath);
        }
        catch (Exception objException)
        {
            Dts.TaskResult = (int)ScriptResults.Failure;
            // Log the exception
        }
        Dts.TaskResult = (int)ScriptResults.Success;
    }
</code>```

I hope can help.

Title: Zip a folder using SSIS

Body:
Adding a Script Task, yuo can use the ZipFile (class) here reference, you must refer to the System.IO.Compression.FileSystem assembly in the project (.NET Framework 4.5).

You need to provide to the Script Task the folder to be zipped and the name of the compressed folder as ReadOnlyVariables (to be added in the tab ReadOnlyVariables)

These two variables must be defined in the Variables tab (String type) of the package and can be changed dynamically through a cycle (eg. for each)

I use these two variables:

sFolderCompressed - the folder '.zip' that you want to obtain eg. C:\folder1\result.zip
sFolderSource - the source folder containing the files affected eg. C:\folder1\folder2

The script is made using c#, choose Script Language: Microsoft Visual C#

This is the code to be added in the Main method:

using System.IO.Compression;

    public void Main()
    {
        try
        {
            string zipPath = (string)Dts.Variables["User::sFolderCompressed"].Value;
            string startPath = (string)Dts.Variables["User::sFolderSource"].Value;

            ZipFile.CreateFromDirectory(startPath, zipPath);
        }
        catch (Exception objException)
        {
            Dts.TaskResult = (int)ScriptResults.Failure;
            // Log the exception
        }
        Dts.TaskResult = (int)ScriptResults.Success;
    }

I hope can help.


问:
How to create/insert WMI object?
I'm doing a software that manages the Windows power plans in C#, and to get the Power Plans and set it's settings is easy by the ManagementObjet. But I want to create a new Power Plan, in other words, create a new WMI object, and I don't know how to do that.

Do any one knows how to create it?

答:
You can't do this in WMI.  You can use the Win32 APIs for Power Scheme Management as described here to create your plan, and then monitor/manage it using WMI.

To create a power scheme, you need to
  first duplicate an existing scheme by
  using the PowerDuplicateScheme
  function, specifying the GUID of the
  scheme you wish to base your new
  scheme upon. You should copy one of
  the built-in schemes and modify the
  power settings to your needs.

Title: How to create/insert WMI object?


问:
PSQL unnest function not working as expected
I tried the solution from this post but I'm still getting an error.

Query:

```<code>SELECT unnest(team)
FROM table_of_teams
WHERE team LIKE '%akg%';
</code>```

Error:

```<code>ERROR:  operator does not exist: character varying[] ~~ unknown
LINE 5: WHERE team LIKE '%akg%'
                   ^
HINT:  No operator matches the given name and argument type(s). You might need to add explicit type casts.
</code>```

Table Structure:

```<code>                            Table "public.table_of_teams"
       Column       |            Type             |                   Modifiers
--------------------+-----------------------------+-------------------------------------------------
 teamid             | integer                     | not null default nextval('team_seq'::regclass)
 index              | integer                     |
 name               | character varying           |
 grouping           | character varying           |
 hour_of_day        | integer[]                   |
 day_of_week        | integer[]                   |
 team               | character varying[]         |
</code>```

答:
If I understand correctly and you want to extract the teams that meet the given condition, you could put the unnest call in a subquery and apply the condition in the surrounding query:

```<code>SELECT single_team
FROM   (SELECT unnest(team) single_team
        FROM table_of_teams) t
WHERE single_team LIKE '%akg%';
</code>```

Body:
I tried the solution from this post but I'm still getting an error.

Query:

SELECT unnest(team)
FROM table_of_teams
WHERE team LIKE '%akg%';

Error:

ERROR:  operator does not exist: character varying[] ~~ unknown
LINE 5: WHERE team LIKE '%akg%'
                   ^
HINT:  No operator matches the given name and argument type(s). You might need to add explicit type casts.

Table Structure:

                            Table "public.table_of_teams"
       Column       |            Type             |                   Modifiers
--------------------+-----------------------------+-------------------------------------------------
 teamid             | integer                     | not null default nextval('team_seq'::regclass)
 index              | integer                     |
 name               | character varying           |
 grouping           | character varying           |
 hour_of_day        | integer[]                   |
 day_of_week        | integer[]                   |
 team               | character varying[]         |

Body:
If I understand correctly and you want to extract the teams that meet the given condition, you could put the unnest call in a subquery and apply the condition in the surrounding query:

SELECT single_team
FROM   (SELECT unnest(team) single_team
        FROM table_of_teams) t
WHERE single_team LIKE '%akg%';


问:
Jquery maphilight : want to add simple new features
I'm a beginner with Jquery so those questions should be pretty easy to answer. I'd like to modify the map hilight script (http://plugins.jquery.com/project/maphilight) to add 2 features :

Question 1. I'd like to be able to highlight some areas by keeping the mouse button pressed instead of having to click and release the button.

Here is the relevant part of the code :

$.fn.maphilight = function(opts) {
opts = $.extend({}, $.fn.maphilight.defaults, opts);

return this.each(function() {
    mouseclick = function(e,id)
    {
    ...}

```<code>// MY CHANGES
mouseover = function(e, id)
{
    if(pressed)
    mouseclick(e,id)
}
</code>```

I tried to call the mouseclick function in mouseover but it doesn't highlight anything. I'm probably not calling the function in the right way ?

Question 2. I'd like to be able to change the color used to highlight areas after pressing a button.

Thanks

答:
I had the same problem.

I ended up extending the plugin to allow for clicks. You can get that code here:

https://github.com/thekevinscott/maphilight

All you need to do is pass in an additional argument in the options, 'stayClicked', as true. Subsequently, any clicks on the map will leave those areas highlighted.

As for your point #2... not sure about that. You'll probably have to modify the plugin a bit yourself.

Body:
I'm a beginner with Jquery so those questions should be pretty easy to answer. I'd like to modify the map hilight script (http://plugins.jquery.com/project/maphilight) to add 2 features :

Question 1. I'd like to be able to highlight some areas by keeping the mouse button pressed instead of having to click and release the button.

Here is the relevant part of the code :

$.fn.maphilight = function(opts) {
opts = $.extend({}, $.fn.maphilight.defaults, opts);

return this.each(function() {
    mouseclick = function(e,id)
    {
    ...}

// MY CHANGES
mouseover = function(e, id)
{
    if(pressed)
    mouseclick(e,id)
}

I tried to call the mouseclick function in mouseover but it doesn't highlight anything. I'm probably not calling the function in the right way ?

Question 2. I'd like to be able to change the color used to highlight areas after pressing a button.

Thanks


问:
How to close md-select on button click inside md-select?
How can i close my md-select on button click inside md-select window?

JS

```<code>$scope.closeSelectBox = () => {
  var esc = jQuery.Event("keydown");
  esc.which =  27
  esc.keyCode = 27
  $(document).trigger(esc)
}
</code>```

HTML

```<code><md-input-container style="max-width: 150px; width: 150">
  <label>Helper:</label>
  <md-select ng-model='vm.selectedHelpers' multiple>
    <md-select-header style="height: 25px">
      <md-button ng-click="closeSelectBox()">Close</md-button>
    </md-select-header>
    <md-option ng-repeat='item in vm.helpers' ng-value='item'>
      {{item.name}}
    </md-option>
  </md-select>
</md-input-container>
</code>```

jsFiddle

答:
SOLVED
Need only trigger click on md-backdrop

```<code>$("md-backdrop").trigger ("click")
</code>```

Working Fiddle

Body:
How can i close my md-select on button click inside md-select window?

JS

$scope.closeSelectBox = () => {
  var esc = jQuery.Event("keydown");
  esc.which =  27
  esc.keyCode = 27
  $(document).trigger(esc)
}

HTML

<md-input-container style="max-width: 150px; width: 150">
  Helper:
  <md-select ng-model='vm.selectedHelpers' multiple>
    <md-select-header style="height: 25px">
      <md-button ng-click="closeSelectBox()">Close</md-button>
    </md-select-header>
    <md-option ng-repeat='item in vm.helpers' ng-value='item'>
      {{item.name}}
    </md-option>
  </md-select>
</md-input-container>

jsFiddle

Body:
SOLVED
Need only trigger click on md-backdrop

$("md-backdrop").trigger ("click")

Working Fiddle