问:
TYPO3 RealURL Language Domain Configuration
We have following sceneario:

The website has 3 Domains.

domain.de

domain.eu

domain.com.tr

TYPO3 is already setup for multilanguage and the IDs for the languages are:

default (de) = 0

en = 1

tr = 2

Could somebody give us the proper RealURL configuration for this?

答:
Follow solution makes the language detection by domains:</p>

```<code><?php
  $GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['realurl'] = [
    'www.domain.de' => [ /* main configuration */,
    'www.domain.eu' => 'www.domain.de',
    'www.domain.tr' => 'www.domain.de',
    '_DOMAINS' => [
      'encode' => [
        [
          'GETvar' => 'L',
          'value' => '0',
          'useConfiguration' => 'www.domain.de',
          'urlPrepend' => 'https://www.domain.de'
        ],
        [
          'GETvar' => 'L',
          'value' => '1',
          'useConfiguration' => 'www.domain.eu',
          'urlPrepend' => 'https://www.domain.eu'
        ],
        [
          'GETvar' => 'L',
          'value' => '2',
          'useConfiguration' => 'www.domain.tr',
          'urlPrepend' => 'https://www.domain.tr'
        ]
      ],
      'decode' => [
        'www.domain.de' => [
          'GETvars' => [
            'L' => '',
          ],
          'useConfiguration' => 'www.domain.de',
        ],
        'www.domain.eu'  => [
          'GETvars' => [
            'L' => '1',
          ],
          'useConfiguration' => 'www.domain.eu',
        ],
        'www.domain.tr' => [
          'GETvars' => [
            'L' => '2',
          ],
          'useConfiguration' => 'www.domain.tr',
        ]
      ]
    ];
</code>```

Body:
Follow solution makes the language detection by domains:

<?php
  $GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['realurl'] = [
    'www.domain.de' => [ /* main configuration */,
    'www.domain.eu' => 'www.domain.de',
    'www.domain.tr' => 'www.domain.de',
    '_DOMAINS' => [
      'encode' => [
        [
          'GETvar' => 'L',
          'value' => '0',
          'useConfiguration' => 'www.domain.de',
          'urlPrepend' => 'https://www.domain.de'
        ],
        [
          'GETvar' => 'L',
          'value' => '1',
          'useConfiguration' => 'www.domain.eu',
          'urlPrepend' => 'https://www.domain.eu'
        ],
        [
          'GETvar' => 'L',
          'value' => '2',
          'useConfiguration' => 'www.domain.tr',
          'urlPrepend' => 'https://www.domain.tr'
        ]
      ],
      'decode' => [
        'www.domain.de' => [
          'GETvars' => [
            'L' => '',
          ],
          'useConfiguration' => 'www.domain.de',
        ],
        'www.domain.eu'  => [
          'GETvars' => [
            'L' => '1',
          ],
          'useConfiguration' => 'www.domain.eu',
        ],
        'www.domain.tr' => [
          'GETvars' => [
            'L' => '2',
          ],
          'useConfiguration' => 'www.domain.tr',
        ]
      ]
    ];


来源: stackexchange

问:
BizTalk 2013 R2 Large DB Log File
I have this alert on my client staging server :

Total DB Space Used  for DTA DB "BizTalkDTADb" on Biztalk Server
  1024619.49 (Large size on DTA db can impact also MsgBox Db performance, check Tables size and if 'DTA Purge and Archive' job is running)

DTA DB DATA File size : 2314 MB

DTA DB LOGFile size : 1022306 MB

My DTA purge JOB is configured to only purge without archive, but even after the purge/shrink LOG file, the size not decrease. Have you an idea?

答:
Info from elsewhere, OP is using an unsupported backup process.  Here's the Answer:

So...this is not supported and will not work.  You must use the BackupBizTalkServer job.

Regarding DBA's, the BizTalk Databases and SQL Server are part of the BizTalk product and must be managed by the BizTalk Administrators.  I'm going to assume you've never tried to recover your BizTalk Group since there is a distinct possibility that the backups they have been taking are not useful.

Additionally, you must stop any non-BizTalk maintenance jobs running against the BizTalk databases.  They are not supported and likely to cause problems.

So, your solution is to stop the custom, unsupported, backup process, then properly configure ALL the BizTalk Agent Jobs, including BackupBizTalk Server.

I fully expect the DBA to object but keep in mind, they caused this problem by not properly backing up BizTalk Server.

ContentLicense: CC BY-SA 3.0

Title: BizTalk 2013 R2 Large DB Log File


问:
Confusion with string pointers
```<code>#include<stdio.h>
int main()
{
    switch(*(1+"AB" "CD"+1))
    {
        case 'A':printf("A is here");
            break;
        case 'B':printf("B is here");
            break;
        case 'C':printf("C is here");
            break;
        case 'D':printf("D is here");
            break;
    }
}
</code>```

The output is: C is here.

Can anyone explain this to me its confusing me.

答:
In C, adjacent string literals, such as "AB" "CD", are concatenated. (This is a convenience that allows long strings to be easily broken up over multiple lines and enables certain features such as macros like PRIx64 in <inttypes.h> to work.) The result is "ABCD".

A string literal is an array of characters. In most circumstances, an array is automatically converted to a pointer to its first element. (The exceptions are in contexts where you want the actual array, such as applying sizeof.) So "ABCD" becomes a pointer to the A character.

When one is added to a pointer (to an element in an array), the result points to the next element in the array. So 1+"ABCD" points to the B. And 1+"ABCD"+1 points to the C.

Then the * operator produces the object the pointer points to, so *(1+"ABCD"+1) is the C character, whose value is C.

Title: Confusion with string pointers

Body:
#include<stdio.h>
int main()
{
    switch(*(1+"AB" "CD"+1))
    {
        case 'A':printf("A is here");
            break;
        case 'B':printf("B is here");
            break;
        case 'C':printf("C is here");
            break;
        case 'D':printf("D is here");
            break;
    }
}

The output is: C is here.

Can anyone explain this to me its confusing me.


问:
How to fail a jenkins job based on a condition
I use Jmeter to validate functional test for our API's. I have created an HTML file which contains the total number of tests executed and the passing/failure ones. This is a customized report.

Can I set a condition such that the build fails if there is a single failure in the report?

Please not that I have already tried performance plugin. But my assertion here is to see if the test case fails or passes and not the reponse/throughtput time.

Not sure if there is a plugin which will enable me to read the HTML and then fail the report if it sees a failing test case.

答:
I was having a similar issue with Jenkins and JMeter.  Here's what I did:

Install this plugin: https://wiki.jenkins.io/display/JENKINS/Log+Parser+Plugin

for your logParserfile, add this:

error /FAILED/

Create a BeanShell Assertion for each sampler you are testing that contains something like this:

String testscenario = "TEST SCENARIO: ";
String requestName = "getRequest";
String ver = "${My_ver}";
String respData = new String(ResponseData);

if (respData.contains("OK"))
{
    log.info(testscenario+"Passed. "+requestName+" version ="+ver);
    print(testscenario+"Passed. "+requestName+" version ="+ver);

} else
{
    log.error(testscenario+"*FAILED. "+requestName);

    print(testscenario+"*FAILED. "+requestName);

}

When your Jenkins job runs and anything fails, the FAILED log entry will show


问:
Constructor uses the mock object, how do I test a method in isolation?
I have a class that looks like this:

```<code>class MyClass {

  private IDependency dep;

  public MyClass(IDependency dep) {
    this.dep = dep;
    this.dep.Reset();
  }

  public void Clear() {
    this.dep.Reset();
  }
}
</code>```

How do I test that the Reset method gets called properly in the Clear method while ignoring what the constructor does?

My Moq test looks like this:

```<code>MockRepository mocks = new MockRepository(MockBehavior.Default);
var dep = mocks.Create<IDependency>();

dep.Setup(s => s.Reset());

MyClass myclass = new MyClass(dep.Object);
myclass.Clear():

state.Verify(s => s.Reset(), Times.Exactly(1));
</code>```

It fails because Reset has been called twice (once in the constructor, and once in the Clear method).

答: You can use reflection to set the private field dep to your mocked object. Then just call the Clear method and test the dependency call.</p>

ContentLicense: CC BY-SA 2.5

Body:
I have a class that looks like this:

class MyClass {

  private IDependency dep;

  public MyClass(IDependency dep) {
    this.dep = dep;
    this.dep.Reset();
  }

  public void Clear() {
    this.dep.Reset();
  }
}

How do I test that the Reset method gets called properly in the Clear method while ignoring what the constructor does?

My Moq test looks like this:

MockRepository mocks = new MockRepository(MockBehavior.Default);
var dep = mocks.Create<IDependency>();

dep.Setup(s => s.Reset());

MyClass myclass = new MyClass(dep.Object);
myclass.Clear():

state.Verify(s => s.Reset(), Times.Exactly(1));

It fails because Reset has been called twice (once in the constructor, and once in the Clear method).


问:
ID type mismatch when trying to get
Was just testing my code earlier this morning, and found something I cannot seems to resolve.

My SKU class has a custom ID generator(assinged) to take a String:

```<code>static mapping = {
    id generator: 'assigned', name: 'sku'
}
</code>```

I created a SKU object with ID: "1234445"  (Normally my SKU id is a mixture of dashes letters and numbers, but just for testing purposes I used a number as String)

Now whenever I try to do an SKU.get("1234445"), I get the following Error:

Provided id of the wrong type

Expected: class java.lang.String, got class java.lang.Long

Obviously I provided a String, somehow it's treating it as a Long when .get is performed, hence causing the error.

Any ideas on how to resolve this besides not using a String that looks like a number for SKU.id (Sku.sku in my case)?

答:
Sorry for the thread necromancy, but I encountered the same problem recently. As it turns out (thanks to @Peter for the solution) you can workaround the issue by defining String id in addition to the String sku. The following is a little ugly but works:

```<code>class Sku {
    String id
    String sku
    static mapping = {
        id name: 'sku', generator: 'assigned'
    }
}
</code>```

Then in a Spock test:

```<code>when:
(new Sku(sku: sku)).save()

then:
Sku.get(sku)

where:
sku << ['12345', 'f00-b4r']
</code>```

Title: ID type mismatch when trying to get

Body:
Was just testing my code earlier this morning, and found something I cannot seems to resolve.

My SKU class has a custom ID generator(assinged) to take a String:

static mapping = {
    id generator: 'assigned', name: 'sku'
}

I created a SKU object with ID: "1234445"  (Normally my SKU id is a mixture of dashes letters and numbers, but just for testing purposes I used a number as String)

Now whenever I try to do an SKU.get("1234445"), I get the following Error:

Provided id of the wrong type

Expected: class java.lang.String, got class java.lang.Long

Obviously I provided a String, somehow it's treating it as a Long when .get is performed, hence causing the error.

Any ideas on how to resolve this besides not using a String that looks like a number for SKU.id (Sku.sku in my case)?

Body:
Sorry for the thread necromancy, but I encountered the same problem recently. As it turns out (thanks to @Peter for the solution) you can workaround the issue by defining String id in addition to the String sku. The following is a little ugly but works:

class Sku {
    String id
    String sku
    static mapping = {
        id name: 'sku', generator: 'assigned'
    }
}

Then in a Spock test:

when:
(new Sku(sku: sku)).save()

then:
Sku.get(sku)

where:
sku << ['12345', 'f00-b4r']


问:
Ionic 3 : Close modal with phone's back button
I try to override the phone's back button in my Ionic App.

This code permit me to open a modal to close the App if I'm not in a page, else close the page.

But this doesn't allow me to close an opened modal. How can I detect if I'm in a modal to close it ?

```<code>platform.registerBackButtonAction(() => {

      let nav = app.getActiveNav();
      let activeView: ViewController = nav.getActive();
      console.log(activeView);

      if(activeView != null){
        if(nav.canGoBack()) {
          activeView.dismiss();
        } else{
          let alert = this.alertCtrl.create({
            title: this.pdataManager.translate.get("close-app"),
            message: this.pdataManager.translate.get("sure-want-leave"),
            buttons: [
              {
                text: this.pdataManager.translate.get("no"),
                handler: () => {
                  this.presentedAlert = false;
                },
                role: 'cancel',
              },
              {
                text: this.pdataManager.translate.get("yes"),
                handler: () => {
                  this.presentedAlert = false;
                  this.platform.exitApp();
                }
              }
            ]
          });
          if(!this.presentedAlert) {
            alert.present();
            this.presentedAlert = true;
          }
        }
      }
    });
  }
</code>```

答:
You can give page name to your modal and you can access it from anywhere in app. Try this..

```<code>import { App } from 'ionic-angular';

    constructor(public app: App){

    }

        platform.registerBackButtonAction(() => {

              let nav = this.app.getActiveNav();
              let view = nav.getActive().instance.pageName;

              if (view == YOU_PAGE_NAME) {
                //You are in modal
              } else {
                //You are not in modal
              }
        });
</code>```

Inside your modal

```<code>pageName = 'YOU_PAGE_NAME';
</code>```

Body:
I try to override the phone's back button in my Ionic App.

This code permit me to open a modal to close the App if I'm not in a page, else close the page.

But this doesn't allow me to close an opened modal. How can I detect if I'm in a modal to close it ?

platform.registerBackButtonAction(() => {

      let nav = app.getActiveNav();
      let activeView: ViewController = nav.getActive();
      console.log(activeView);

      if(activeView != null){
        if(nav.canGoBack()) {
          activeView.dismiss();
        } else{
          let alert = this.alertCtrl.create({
            title: this.pdataManager.translate.get("close-app"),
            message: this.pdataManager.translate.get("sure-want-leave"),
            buttons: [
              {
                text: this.pdataManager.translate.get("no"),
                handler: () => {
                  this.presentedAlert = false;
                },
                role: 'cancel',
              },
              {
                text: this.pdataManager.translate.get("yes"),
                handler: () => {
                  this.presentedAlert = false;
                  this.platform.exitApp();
                }
              }
            ]
          });
          if(!this.presentedAlert) {
            alert.present();
            this.presentedAlert = true;
          }
        }
      }
    });
  }

Body:
You can give page name to your modal and you can access it from anywhere in app. Try this..

import { App } from 'ionic-angular';

    constructor(public app: App){

    }

        platform.registerBackButtonAction(() => {

              let nav = this.app.getActiveNav();
              let view = nav.getActive().instance.pageName;

              if (view == YOU_PAGE_NAME) {
                //You are in modal
              } else {
                //You are not in modal
              }
        });

Inside your modal

pageName = 'YOU_PAGE_NAME';


问:
Inconsistent accessibility: parameter
I am new to C# and I am trying now to develop my first Windows Forms Application.

```<code> public partial class AddCourse : Form
 {
    Course course;
    public AddCourse(Course course)
    {
        this.course = course;
        InitializeComponent();
    }
</code>```

The problem here is that I get an error.

Error  CS0051  Inconsistent accessibility: parameter type 'Course' is less accessible than method 'AddCourse.AddCourse(Course)'

I know that this usually happens when a private variable is being called in a public method. But in my example I just do not know where the problem is.

I do have a sample code that is similar to this one and it runs just fine.

Anyone who can tell me what I am missing?

答:
Most likely your class isnt public</p>

```<code>public class Course {
...
}
</code>```

Title: Inconsistent accessibility: parameter

Body:
I am new to C# and I am trying now to develop my first Windows Forms Application.

 public partial class AddCourse : Form
 {
    Course course;
    public AddCourse(Course course)
    {
        this.course = course;
        InitializeComponent();
    }

The problem here is that I get an error.

Error  CS0051  Inconsistent accessibility: parameter type 'Course' is less accessible than method 'AddCourse.AddCourse(Course)'

I know that this usually happens when a private variable is being called in a public method. But in my example I just do not know where the problem is.

I do have a sample code that is similar to this one and it runs just fine.

Anyone who can tell me what I am missing?

Body:
Most likely your class isnt public

public class Course {
...
}


问:
Iterating with a jquery.().each and for loop fails
I am trying to get data from two objects and to avoid the (this) keyword to collide I thought using an each and for loop with the two objects would work. But I cant make them cooperate properly. The frustrating thing is I get now errors in the console. My Code:

```<code>var times = {
  startTimes: [{
    start: '10:00'
  }, {
    start: '11:00'
  }, {
    start: '12:00'
  }],
  endTimes: [{
    end: '10:00'
  }, {
    end: '11:00'
  }, {
    end: '12:00'
  }]
}
var items = [];
jQuery(obj).each(function() {
  if (this.ID === parseInt(inputID)) {

    for (var i in times) {
      var item = {
        id: this.ID,
        start: times.startTimes[i].start,
        end: times.endTimes[i].end
      }
      items.push(item);
    }

  }
});
</code>```

What I am doing wrong? Any suggestions?

答:
.each() is a function of jQuery object, from official docs found here: .each()

Description: Iterate over a jQuery object, executing a function for
  each matched element.

And:

When called it iterates over the DOM elements that are part of the
  jQuery object.

And you are calling it on something that is surely not made of DOM objects.

You could use what has been suggested in the comments or opt for vanilla here:

```<code>    arr.forEach(function callback(currentValue, index, array) {
       //your iterator
    }[, thisArg]);
</code>```

See the documentation: forEach()

Also, logic inside seems weird to me, what are you trying to achieve here?

Body:
I am trying to get data from two objects and to avoid the (this) keyword to collide I thought using an each and for loop with the two objects would work. But I cant make them cooperate properly. The frustrating thing is I get now errors in the console. My Code:

var times = {
  startTimes: [{
    start: '10:00'
  }, {
    start: '11:00'
  }, {
    start: '12:00'
  }],
  endTimes: [{
    end: '10:00'
  }, {
    end: '11:00'
  }, {
    end: '12:00'
  }]
}
var items = [];
jQuery(obj).each(function() {
  if (this.ID === parseInt(inputID)) {

    for (var i in times) {
      var item = {
        id: this.ID,
        start: times.startTimes[i].start,
        end: times.endTimes[i].end
      }
      items.push(item);
    }

  }
});

What I am doing wrong? Any suggestions?

Body:
.each() is a function of jQuery object, from official docs found here: .each()

Description: Iterate over a jQuery object, executing a function for
  each matched element.

And:

When called it iterates over the DOM elements that are part of the
  jQuery object.

And you are calling it on something that is surely not made of DOM objects.

You could use what has been suggested in the comments or opt for vanilla here:

    arr.forEach(function callback(currentValue, index, array) {
       //your iterator
    }[, thisArg]);

See the documentation: forEach()

Also, logic inside seems weird to me, what are you trying to achieve here?


问:
Java read Properties file that is in same package as the class
I'm stuck in this for almost an hour so please help me.

I'm using netbeans and under my Sources Packages I have a package called com.cmsv1.properties. Inside this package I have 1 java class and .properties file. Called config.java and config.properties.

I've tried so many solutions I got from the internet but nothing works. I always get nullPointerException.

The following are the solutions i've tried:

```<code>try
          {
              Properties prop = new Properties();
              InputStream is = config.class.getResourceAsStream("config.properties");
          }
        catch (Exception e)
          {
              System.out.println("got error");
          }
</code>```

another is:

```<code>try
          {
              Properties prop = new Properties();
              InputStream input = config.class.getClassLoader().getResourceAsStream("config.properties");
              prop.load(input);
          }
        catch (Exception e)
          {
              System.out.println("got error");
          }
</code>```

And a couple more solutions. Please tell me how can I do this. Remember both of my java class and .properties file are in the same package. Thanks in advance.

答:
If your compiler is compiling the properties file into your jar, this should work:</p>

```<code>this.getClass().getResourceAsStream("config.properties");
</code>```

Body:
I'm stuck in this for almost an hour so please help me.

I'm using netbeans and under my Sources Packages I have a package called com.cmsv1.properties. Inside this package I have 1 java class and .properties file. Called config.java and config.properties.

I've tried so many solutions I got from the internet but nothing works. I always get nullPointerException.

The following are the solutions i've tried:

try
          {
              Properties prop = new Properties();
              InputStream is = config.class.getResourceAsStream("config.properties");
          }
        catch (Exception e)
          {
              System.out.println("got error");
          }

another is:

try
          {
              Properties prop = new Properties();
              InputStream input = config.class.getClassLoader().getResourceAsStream("config.properties");
              prop.load(input);
          }
        catch (Exception e)
          {
              System.out.println("got error");
          }

And a couple more solutions. Please tell me how can I do this. Remember both of my java class and .properties file are in the same package. Thanks in advance.

Body:
If your compiler is compiling the properties file into your jar, this should work:

this.getClass().getResourceAsStream("config.properties");


答:
You need to make the type Course public; i.e.

```<code>public class Course {...}
</code>```

If a public method on a public type takes parameters: all of those parameters must be public. Otherwise callers can't possibly understand the API.

Title: Inconsistent accessibility: parameter

Body:
You need to make the type Course public; i.e.

public class Course {...}

If a public method on a public type takes parameters: all of those parameters must be public. Otherwise callers can't possibly understand the API.


问:
App works fine on iPhone/ iPod but crashes on iPad (even simulator)
```<code>#5  0x0298261c in _objc_terminate
#6  0x9532515a in __cxxabiv1::__terminate
#7  0x9532519a in std::terminate
#8  0x95325298 in __cxa_throw
#9  0x029823d8 in objc_exception_throw
#10 0x028677e1 in -[NSException raise]
#11 0x0005e0e0 in _NSSetUsingKeyValueSetter
#12 0x0005df1e in -[NSObject(NSKeyValueCoding) setValue:forKey:]
#13 0x0031e1e1 in -[UIView(CALayerDelegate) setValue:forKey:]
#14 0x004fc09f in -[UIRuntimeOutletConnection connect]
#15 0x027eac75 in -[NSArray makeObjectsPerformSelector:]
#16 0x004faae4 in -[UINib instantiateWithOptions:owner:loadingResourcesFromBundle:]
#17 0x004fcad9 in -[NSBundle(NSBundleAdditions) loadNibNamed:owner:options:]
#18 0x002f3272 in -[UIApplication _loadMainNibFile]
#19 0x002f4754 in -[UIApplication _runWithURL:payload:launchOrientation:]
#20 0x002fad3e in -[UIApplication handleEvent:withNewEvent:]
#21 0x002f64f7 in -[UIApplication sendEvent:]
#22 0x002fe1d8 in _UIApplicationHandleEvent
#23 0x030fb17c in PurpleEventCallback
#24 0x027b789c in CFRunLoopRunSpecific
#25 0x027b68a8 in CFRunLoopRunInMode
#26 0x002f4221 in -[UIApplication _run]
#27 0x002fc372 in UIApplicationMain
</code>```

In the App, the Main Window  is a  Navigation controller and it works fine on iPod/iPhone. Its even live on the iTunes store. But when i launch the app as an iPad simulator, it crashes with SIGABRT even before it can launch the view.

It seems like a problem with my xib files and I verified the parameters but could not find  the cause.

SDK: 4.1
iPad Simulator: 3.2

答:
Loading an iOS 4 specific item from a Nib, an iAd banner for example, would give this type of error.

You can upgrade to the latest version of Xcode with the iPad simulator running iOS 4.2.  Then your final application would have to require iOS 4 or later.

Alternatively, you can make an iOS 3.2 compatible Nib, and load that version when running on less than iOS 4.  You'll have to write some code to check at runtime and then choose the appropriate Nib.

Body:
#5  0x0298261c in _objc_terminate
#6  0x9532515a in __cxxabiv1::__terminate
#7  0x9532519a in std::terminate
#8  0x95325298 in __cxa_throw
#9  0x029823d8 in objc_exception_throw
#10 0x028677e1 in -[NSException raise]
#11 0x0005e0e0 in _NSSetUsingKeyValueSetter
#12 0x0005df1e in -[NSObject(NSKeyValueCoding) setValue:forKey:]
#13 0x0031e1e1 in -[UIView(CALayerDelegate) setValue:forKey:]
#14 0x004fc09f in -[UIRuntimeOutletConnection connect]
#15 0x027eac75 in -[NSArray makeObjectsPerformSelector:]
#16 0x004faae4 in -[UINib instantiateWithOptions:owner:loadingResourcesFromBundle:]
#17 0x004fcad9 in -[NSBundle(NSBundleAdditions) loadNibNamed:owner:options:]
#18 0x002f3272 in -[UIApplication _loadMainNibFile]
#19 0x002f4754 in -[UIApplication _runWithURL:payload:launchOrientation:]
#20 0x002fad3e in -[UIApplication handleEvent:withNewEvent:]
#21 0x002f64f7 in -[UIApplication sendEvent:]
#22 0x002fe1d8 in _UIApplicationHandleEvent
#23 0x030fb17c in PurpleEventCallback
#24 0x027b789c in CFRunLoopRunSpecific
#25 0x027b68a8 in CFRunLoopRunInMode
#26 0x002f4221 in -[UIApplication _run]
#27 0x002fc372 in UIApplicationMain

In the App, the Main Window  is a  Navigation controller and it works fine on iPod/iPhone. Its even live on the iTunes store. But when i launch the app as an iPad simulator, it crashes with SIGABRT even before it can launch the view.

It seems like a problem with my xib files and I verified the parameters but could not find  the cause.

SDK: 4.1
iPad Simulator: 3.2


问:
Lightbox CSS conflict
I had lightbox on my site and it was working fine.  I updated the pages with Dreamweaver CS6 to a Fluid grid with a side navigation bar so the site would be more mobile friendly.  The result is that my lightbox images are distorted  and the frame is missing from one side.  When scrolling through the images they will increase in size by a fraction and distortion will lessen.  I figure there is a CSS conflict and I can't figure it out.  Web page is located here,

http://www.crawfordcountyhistoricalsociety.org/Pages/Indians.html

答: U should remove this style, max-width:100% and padding: 10px.

Title: Lightbox CSS conflict


问:
Is it normal to experience large overhead using the 1:1 threading that comes in the standard library?
While working through learning Rust, a friend asked me to see what kind of performance I could get out of Rust for generating the first 1 million prime numbers both single-threaded and multi-threaded. After trying several implementations, I'm just stumped. Here is the kind of performance that I'm seeing:

rust_primes --threads 8 --verbose --count 1000000
Options { verbose: true, count: 1000000, threads: 8 }
Non-concurrent using while (15485863): 2.814 seconds.
Concurrent using mutexes (15485863): 876.561 seconds.
Concurrent using channels (15485863): 798.217 seconds.
```

<p>Without overloading the question with too much code, here are the methods responsible for each of the benchmarks:</p>

```fn non_concurrent(options: &Options) {
    let mut count = 0;
    let mut current = 0;

    let ts = Instant::now();
    while count < options.count {
        if is_prime(current) {
            count += 1;
        }
        current += 1;
    }
    let d = ts.elapsed();
    println!("Non-concurrent using while ({}): {}.{} seconds.", current - 1, d.as_secs(), d.subsec_nanos() / 1_000_000);
}

fn concurrent_mutex(options: &Options) {
    let count = Arc::new(Mutex::new(0));
    let highest = Arc::new(Mutex::new(0));

    let mut cc = 0;
    let mut current = 0;

    let ts = Instant::now();

    while cc < options.count {
        let mut handles = vec![];
        for x in current..(current + options.threads) {
            let count = Arc::clone(&count);
            let highest = Arc::clone(&highest);
            let handle = thread::spawn(move || {
                if is_prime(x) {
                    let mut c = count.lock().unwrap();
                    let mut h = highest.lock().unwrap();
                    *c += 1;
                    if x > *h {
                        *h = x;
                    }
                }
            });
            handles.push(handle);
        }

        for handle in handles {
            handle.join().unwrap();
        }

        cc = *count.lock().unwrap();
        current += options.threads;
    }

    let d = ts.elapsed();
    println!("Concurrent using mutexes ({}): {}.{} seconds.", *highest.lock().unwrap(), d.as_secs(), d.subsec_nanos() / 1_000_000);
}

fn concurrent_channel(options: &Options) {
    let mut count = 0;
    let mut current = 0;
    let mut highest = 0;

    let ts = Instant::now();

    while count < options.count {
        let (tx, rx) = mpsc::channel();

        for x in current..(current + options.threads) {
            let txc = mpsc::Sender::clone(&tx);

            thread::spawn(move || {
                if is_prime(x) {
                    txc.send(x).unwrap();
                }
            });
        }

        drop(tx);

        for message in rx {
            count += 1;

            if message > highest && count <= options.count {
                highest = message;
            }
        }

        current += options.threads;
    }

    let d = ts.elapsed();
    println!("Concurrent using channels ({}): {}.{} seconds.", highest, d.as_secs(), d.subsec_nanos() / 1_000_000);
}
```

<p>Am I doing something wrong, or is this normal performance with the 1:1 threading that comes in the standard library?</p>

<p>Here is a MCVE that shows the same problem. I didn't limit the number of threads it starts up at once here like I did in the code above. The point is, threading seems to have a very significant overhead unless I'm doing something horribly wrong.</p>

```use std::thread;
use std::time::Instant;
use std::sync::{Mutex, Arc};
use std::time::Duration;

fn main() {
    let iterations = 100_000;
    non_threaded(iterations);
    threaded(iterations);
}

fn threaded(iterations: u32) {
    let tx = Instant::now();
    let counter = Arc::new(Mutex::new(0));
    let mut handles = vec![];

    for _ in 0..iterations {
        let counter = Arc::clone(&counter);
        let handle = thread::spawn(move || {
            let mut num = counter.lock().unwrap();
            *num = test(*num);
        });
        handles.push(handle);
    }

    for handle in handles {
        handle.join().unwrap();
    }
    let d = tx.elapsed();

    println!("Threaded in {}.", dur_to_string(d));
}

fn non_threaded(iterations: u32) {
    let tx = Instant::now();
    let mut _q = 0;
    for x in 0..iterations {
        _q = test(x + 1);
    }

    let d = tx.elapsed();
    println!("Non-threaded in {}.", dur_to_string(d));
}

fn dur_to_string(d: Duration) -> String {
    let mut s = d.as_secs().to_string();
    s.push_str(".");
    s.push_str(&(d.subsec_nanos() / 1_000_000).to_string());
    s
}

fn test(x: u32) -> u32 {
    x
}
```

<p>Here are the results of this on my machine:</p>

<pre class="lang-none prettyprint-override"><code>Non-threaded in 0.9.
Threaded in 5.785.
</code>```

答:
threading seems to have a very significant overhead

It's not the general concept of "threading", it's the concept of creating and destroying lots of threads.

By default in Rust 1.22.1, each spawned thread allocates 2MiB of memory to use as stack space. In the worst case, your MCVE could allocate ~200GiB of RAM. In reality, this is unlikely to happen as some threads will exit, memory will be reused, etc. I only saw it use ~400MiB.

On top of that, there is overhead involved with inter-thread communication (Mutex, channels, Atomic*) compared to intra-thread variables. Some kind of locking needs to be performed to ensure that all threads see the same data. "Embarrassingly parallel" algorithms tend to not have a lot of communication required. There are also different amounts of time required for different communication primitives. Atomic variables tend to be faster than others in many cases, but aren't as widely usable.

Then there's compiler optimizations to account for. Non-threaded code is way easier to optimize compared to threaded code. For example, running your code in release mode shows:

Non-threaded in 0.0.
Threaded in 142.775.
```

<p>That's right, the non-threaded code took <strong>no time</strong>. The compiler can see through the code and realizes that nothing actually happens and removes it all. I don't know how you got 5 seconds for the threaded code as opposed to the 2+ minutes I saw.</p>

<hr>

<p>Switching to a threadpool will reduce a lot of the unneeded creation of threads. We can also use a threadpool that provides <em>scoped threads</em>, which allows us to avoid the <code>Arc</code> as well:</p>

```extern crate scoped_threadpool;

use scoped_threadpool::Pool;

fn threaded(iterations: u32) {
    let tx = Instant::now();
    let counter = Mutex::new(0);

    let mut pool = Pool::new(8);

    pool.scoped(|scope| {
        for _ in 0..iterations {
            scope.execute(|| {
                let mut num = counter.lock().unwrap();
                *num = test(*num);
            });
        }
    });
    let d = tx.elapsed();

    println!("Threaded in {}.", dur_to_string(d));
}
```

<pre class="lang-none prettyprint-override"><code>Non-threaded in 0.0.
Threaded in 0.675.
</code>```

As with most pieces of programming, it's crucial to understand the tools you have and to use them appropriately.

Body:
While working through learning Rust, a friend asked me to see what kind of performance I could get out of Rust for generating the first 1 million prime numbers both single-threaded and multi-threaded. After trying several implementations, I'm just stumped. Here is the kind of performance that I'm seeing:

rust_primes --threads 8 --verbose --count 1000000
Options { verbose: true, count: 1000000, threads: 8 }
Non-concurrent using while (15485863): 2.814 seconds.
Concurrent using mutexes (15485863): 876.561 seconds.
Concurrent using channels (15485863): 798.217 seconds.

Without overloading the question with too much code, here are the methods responsible for each of the benchmarks:

fn non_concurrent(options: &Options) {
    let mut count = 0;
    let mut current = 0;

    let ts = Instant::now();
    while count < options.count {
        if is_prime(current) {
            count += 1;
        }
        current += 1;
    }
    let d = ts.elapsed();
    println!("Non-concurrent using while ({}): {}.{} seconds.", current - 1, d.as_secs(), d.subsec_nanos() / 1_000_000);
}

fn concurrent_mutex(options: &Options) {
    let count = Arc::new(Mutex::new(0));
    let highest = Arc::new(Mutex::new(0));

    let mut cc = 0;
    let mut current = 0;

    let ts = Instant::now();

    while cc < options.count {
        let mut handles = vec![];
        for x in current..(current + options.threads) {
            let count = Arc::clone(&count);
            let highest = Arc::clone(&highest);
            let handle = thread::spawn(move || {
                if is_prime(x) {
                    let mut c = count.lock().unwrap();
                    let mut h = highest.lock().unwrap();
                    *c += 1;
                    if x > *h {
                        *h = x;
                    }
                }
            });
            handles.push(handle);
        }

        for handle in handles {
            handle.join().unwrap();
        }

        cc = *count.lock().unwrap();
        current += options.threads;
    }

    let d = ts.elapsed();
    println!("Concurrent using mutexes ({}): {}.{} seconds.", *highest.lock().unwrap(), d.as_secs(), d.subsec_nanos() / 1_000_000);
}

fn concurrent_channel(options: &Options) {
    let mut count = 0;
    let mut current = 0;
    let mut highest = 0;

    let ts = Instant::now();

    while count < options.count {
        let (tx, rx) = mpsc::channel();

        for x in current..(current + options.threads) {
            let txc = mpsc::Sender::clone(&tx);

            thread::spawn(move || {
                if is_prime(x) {
                    txc.send(x).unwrap();
                }
            });
        }

        drop(tx);

        for message in rx {
            count += 1;

            if message > highest && count <= options.count {
                highest = message;
            }
        }

        current += options.threads;
    }

    let d = ts.elapsed();
    println!("Concurrent using channels ({}): {}.{} seconds.", highest, d.as_secs(), d.subsec_nanos() / 1_000_000);
}

Am I doing something wrong, or is this normal performance with the 1:1 threading that comes in the standard library?

Here is a MCVE that shows the same problem. I didn't limit the number of threads it starts up at once here like I did in the code above. The point is, threading seems to have a very significant overhead unless I'm doing something horribly wrong.

use std::thread;
use std::time::Instant;
use std::sync::{Mutex, Arc};
use std::time::Duration;

fn main() {
    let iterations = 100_000;
    non_threaded(iterations);
    threaded(iterations);
}

fn threaded(iterations: u32) {
    let tx = Instant::now();
    let counter = Arc::new(Mutex::new(0));
    let mut handles = vec![];

    for _ in 0..iterations {
        let counter = Arc::clone(&counter);
        let handle = thread::spawn(move || {
            let mut num = counter.lock().unwrap();
            *num = test(*num);
        });
        handles.push(handle);
    }

    for handle in handles {
        handle.join().unwrap();
    }
    let d = tx.elapsed();

    println!("Threaded in {}.", dur_to_string(d));
}

fn non_threaded(iterations: u32) {
    let tx = Instant::now();
    let mut _q = 0;
    for x in 0..iterations {
        _q = test(x + 1);
    }

    let d = tx.elapsed();
    println!("Non-threaded in {}.", dur_to_string(d));
}

fn dur_to_string(d: Duration) -> String {
    let mut s = d.as_secs().to_string();
    s.push_str(".");
    s.push_str(&(d.subsec_nanos() / 1_000_000).to_string());
    s
}

fn test(x: u32) -> u32 {
    x
}

Here are the results of this on my machine:

Non-threaded in 0.9.
Threaded in 5.785.

Body:
threading seems to have a very significant overhead

It's not the general concept of "threading", it's the concept of creating and destroying lots of threads.

By default in Rust 1.22.1, each spawned thread allocates 2MiB of memory to use as stack space. In the worst case, your MCVE could allocate ~200GiB of RAM. In reality, this is unlikely to happen as some threads will exit, memory will be reused, etc. I only saw it use ~400MiB.

On top of that, there is overhead involved with inter-thread communication (Mutex, channels, Atomic*) compared to intra-thread variables. Some kind of locking needs to be performed to ensure that all threads see the same data. "Embarrassingly parallel" algorithms tend to not have a lot of communication required. There are also different amounts of time required for different communication primitives. Atomic variables tend to be faster than others in many cases, but aren't as widely usable.

Then there's compiler optimizations to account for. Non-threaded code is way easier to optimize compared to threaded code. For example, running your code in release mode shows:

Non-threaded in 0.0.
Threaded in 142.775.

That's right, the non-threaded code took no time. The compiler can see through the code and realizes that nothing actually happens and removes it all. I don't know how you got 5 seconds for the threaded code as opposed to the 2+ minutes I saw.

Switching to a threadpool will reduce a lot of the unneeded creation of threads. We can also use a threadpool that provides scoped threads, which allows us to avoid the Arc as well:

extern crate scoped_threadpool;

use scoped_threadpool::Pool;

fn threaded(iterations: u32) {
    let tx = Instant::now();
    let counter = Mutex::new(0);

    let mut pool = Pool::new(8);

    pool.scoped(|scope| {
        for _ in 0..iterations {
            scope.execute(|| {
                let mut num = counter.lock().unwrap();
                *num = test(*num);
            });
        }
    });
    let d = tx.elapsed();

    println!("Threaded in {}.", dur_to_string(d));
}

Non-threaded in 0.0.
Threaded in 0.675.

As with most pieces of programming, it's crucial to understand the tools you have and to use them appropriately.


问:
Toggle class on click body
I know lot of questions something like this are also in Stackoverflow. Here is a bit of Jquery problem. I have added toggle class Jquery function, and the same class should be remove when click anywhere on the body. Its working now, but I no need toggle that class when we click inside of the input text field.

Code:

var removeClass = true;
$(".btn-search").click(function() {
  $(".input-search").toggleClass('expanded');
  removeClass = false;
});
$("html").click(function() {
  if (removeClass) {
    $(".input-search").removeClass('expanded');
  }
  removeClass = true;
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
  background: #eee;
}

.col-search {
  padding: 13px 8px 8px 0;
  position: relative;
  width: 80%;
}

.input-search {
  width: 220px;
  height: 34px;
  max-width: 0;
  padding: 5px 10px;
  transition: all .2s ease;
  position: absolute;
  top: 13px;
  bottom: 13px;
  right: 46px;
  border: 0;
  box-sizing: border-box;
  opacity: 0;
}

.input-search.expanded {
  max-width: 220px;
  opacity: 1;
}

.btn-search {
  position: absolute;
  right: 0;
  width: 38px;
  height: 34px;
  border: 0;
  background: #333;
  color:#fff;
}</code>```

  <input class="input-search" type="search" placeholder="Search" />
  <input type="button" class="btn-search" value="click">

```

JS Fiddle: https://jsfiddle.net/vishnuprasadps/3a84p6h0/

答:
Just alter your JS with event on the input with return value
https://jsfiddle.net/fcdo7kyh/</p>

```<code>    var removeClass = true;
$(".btn-search").click(function() {
  $(".input-search").toggleClass('expanded');
  removeClass = false;
});
$(".input-search").click(function() {
  return false;
});

$("html").click(function() {
  if (removeClass) {
    $(".input-search").removeClass('expanded');
  }
  removeClass = true;
});
</code>```

Title: Toggle class on click body

Body:
I know lot of questions something like this are also in Stackoverflow. Here is a bit of Jquery problem. I have added toggle class Jquery function, and the same class should be remove when click anywhere on the body. Its working now, but I no need toggle that class when we click inside of the input text field.

Code:

var removeClass = true;
$(".btn-search").click(function() {
  $(".input-search").toggleClass('expanded');
  removeClass = false;
});
$("html").click(function() {
  if (removeClass) {
    $(".input-search").removeClass('expanded');
  }
  removeClass = true;
});

body {
  background: #eee;
}

.col-search {
  padding: 13px 8px 8px 0;
  position: relative;
  width: 80%;
}

.input-search {
  width: 220px;
  height: 34px;
  max-width: 0;
  padding: 5px 10px;
  transition: all .2s ease;
  position: absolute;
  top: 13px;
  bottom: 13px;
  right: 46px;
  border: 0;
  box-sizing: border-box;
  opacity: 0;
}

.input-search.expanded {
  max-width: 220px;
  opacity: 1;
}

.btn-search {
  position: absolute;
  right: 0;
  width: 38px;
  height: 34px;
  border: 0;
  background: #333;
  color:#fff;
}

  <input class="input-search" type="search" placeholder="Search" />
  <input type="button" class="btn-search" value="click">

JS Fiddle: https://jsfiddle.net/vishnuprasadps/3a84p6h0/

Body:
Just alter your JS with event on the input with return value
https://jsfiddle.net/fcdo7kyh/

    var removeClass = true;
$(".btn-search").click(function() {
  $(".input-search").toggleClass('expanded');
  removeClass = false;
});
$(".input-search").click(function() {
  return false;
});

$("html").click(function() {
  if (removeClass) {
    $(".input-search").removeClass('expanded');
  }
  removeClass = true;
});


问:
bash find filenames with the same last four character
I'd like to write a script that will execute a command that finds every set of files that have the same last four characters.

So for example, given a directory with these files,

```<code>$ ls -1
GH010119.MP4
GH010120.MP4
GH010126.MP4
GH010127.MP4
GH020119.MP4
GH020126.MP4
GH020127.MP4
GH030119.MP4
GH030126.MP4
</code>```

I'd like my script to make out these groups:

```<code>GH010119.MP4
GH020119.MP4
GH030119.MP4

GH010126.MP4
GH020126.MP4
GH030126.MP4

GH010127.MP4
GH020127.MP4

GH010120.MP4
</code>```

My current solution is to make out each group manually using: find . -name "*0119*", so I'd also like to know if the script I'd have to come up with won't be overly complex in comparison....

答:
You can extract the groupings with something like

```<code>printf '%s\n' *.MP4 | sed 's/.*\(........\)$/\1/' | sort -u
</code>```

With the extension .MP4 factored in, which is part of the file name no matter how you look at it, this extracts the last eight characters, and removes any duplicates.

Doing it in Awk might be a bit more efficient.

```<code>awk 'FNR == 1 { n = substr(FILENAME, length(FILENAME)-7);
    if (seen[n]++ == 0) print n; nextfile }' *.MP4
</code>```

Body:
I'd like to write a script that will execute a command that finds every set of files that have the same last four characters.

So for example, given a directory with these files,

$ ls -1
GH010119.MP4
GH010120.MP4
GH010126.MP4
GH010127.MP4
GH020119.MP4
GH020126.MP4
GH020127.MP4
GH030119.MP4
GH030126.MP4

I'd like my script to make out these groups:

GH010119.MP4
GH020119.MP4
GH030119.MP4

GH010126.MP4
GH020126.MP4
GH030126.MP4

GH010127.MP4
GH020127.MP4

GH010120.MP4

My current solution is to make out each group manually using: find . -name "*0119*", so I'd also like to know if the script I'd have to come up with won't be overly complex in comparison....

Body:
You can extract the groupings with something like

printf '%s\n' *.MP4 | sed 's/.*\(........\)$/\1/' | sort -u

With the extension .MP4 factored in, which is part of the file name no matter how you look at it, this extracts the last eight characters, and removes any duplicates.

Doing it in Awk might be a bit more efficient.

awk 'FNR == 1 { n = substr(FILENAME, length(FILENAME)-7);
    if (seen[n]++ == 0) print n; nextfile }' *.MP4


问:
Play several MP3 sounds Simultaneously
Is it possible to play several MP3 sounds Simultaneously with AVAudioPlayer?</p>

答: Yes. It says so in the documentation.</p>

Title: Play several MP3 sounds Simultaneously

Body: Yes. It says so in the documentation.


问:
C++ template function to split string to array
I read a text file which contains lines each line contains data separated by delimiters like spaces or commas , I have a function which split a string to array but I want to make it a template to get different types like floats or integers beside string, I made two functions one for split to strings and the the other to floats

```<code>template<class T>
void split(const std::string &s, char delim, std::vector<T>& result) {
    std::stringstream ss(s);
    std::string item;
    while (std::getline(ss, item, delim)) {
        T f = static_cast<T>(item.c_str());
        result.push_back(f);
    }
}

void fSplit(const std::string &s, char delim, std::vector<GLfloat>& result) {
    std::stringstream ss(s);
    std::string item;
    while (std::getline(ss, item, delim)) {
        GLfloat f = atof(item.c_str());
        result.push_back(f);
    }
}
</code>```

the template function works fine with strings, in the other function I use atof(item.c_str()) to get the float value from string, when I use the template function with floats I get invalid cast from type 'const char*' to type 'float'

so how could I make the casting in the template function?

答:
You cannot do:

```<code>T f = static_cast<T>(item.c_str());
</code>```

In your case, you could declare a template, e.g. from_string<T>, and replace the line with:

```<code>T f = from_string<T>(item);
</code>```

The you would implement it with something like:

```<code>// Header
template<typename T>
T from_string(const std::string &str);

// Implementations
template<>
int from_string(const std::string &str)
{
    return std::stoi(str);
}

template<>
double from_string(const std::string &str)
{
    return std::stod(str);
}

// Add implementations for all the types that you want to support...
</code>```

Body:
I read a text file which contains lines each line contains data separated by delimiters like spaces or commas , I have a function which split a string to array but I want to make it a template to get different types like floats or integers beside string, I made two functions one for split to strings and the the other to floats

template<class T>
void split(const std::string &s, char delim, std::vector<T>& result) {
    std::stringstream ss(s);
    std::string item;
    while (std::getline(ss, item, delim)) {
        T f = static_cast<T>(item.c_str());
        result.push_back(f);
    }
}

void fSplit(const std::string &s, char delim, std::vector<GLfloat>& result) {
    std::stringstream ss(s);
    std::string item;
    while (std::getline(ss, item, delim)) {
        GLfloat f = atof(item.c_str());
        result.push_back(f);
    }
}

the template function works fine with strings, in the other function I use atof(item.c_str()) to get the float value from string, when I use the template function with floats I get invalid cast from type 'const char*' to type 'float'

so how could I make the casting in the template function?

Body:
You cannot do:

T f = static_cast<T>(item.c_str());

In your case, you could declare a template, e.g. from_string<T>, and replace the line with:

T f = from_string<T>(item);

The you would implement it with something like:

// Header
template<typename T>
T from_string(const std::string &str);

// Implementations
template<>
int from_string(const std::string &str)
{
    return std::stoi(str);
}

template<>
double from_string(const std::string &str)
{
    return std::stod(str);
}

// Add implementations for all the types that you want to support...


答:
You could use the strtof function (http://en.cppreference.com/w/cpp/string/byte/strtof)

so something like this

```<code>GLfloat f = std::strtof (item.c_str(), nullptr);
</code>```

Title: C++ template function to split string to array

Body:
You could use the strtof function (http://en.cppreference.com/w/cpp/string/byte/strtof)

so something like this

GLfloat f = std::strtof (item.c_str(), nullptr);


问:
iPhone X status bar height
I have developed an app without autoLayout or interface-builder, all by code. It runs ok in all iPhones except iPhone X where the top bar stays under the new black thing in the middle.

It's possible to get that height by code, so I can shift my Navigationbar that height down and all runs normal ?

The solutions I see, they use auto layout.

I just want the get the distance to shift it down..

答:
You can always get the status bar height with or without status bar hidden by:

```<code>UIApplication.shared.keyWindow!.safeAreaInsets.top
</code>```

and the home screen indicator

```<code>UIApplication.shared.keyWindow!.safeAreaInsets.bottom
</code>```

If it's landscape the value would change

and safeAreaLayoutGuide is there also

Title: iPhone X status bar height

Body:
You can always get the status bar height with or without status bar hidden by:

UIApplication.shared.keyWindow!.safeAreaInsets.top

and the home screen indicator

UIApplication.shared.keyWindow!.safeAreaInsets.bottom

If it's landscape the value would change

and safeAreaLayoutGuide is there also


答:
Make sure to check the event wasn't triggered by the input you want to exclude using event.target

This also doesn't interfere with other events that might be bound to the input itself.

var removeClass = true;
$(".btn-search").click(function() {
  $(".input-search").toggleClass('expanded');
  removeClass = false;
});
$("html").click(function() {
  var searchInput = $(".input-search");
  if (removeClass && event.target != searchInput[0]) {
    searchInput.removeClass('expanded');
  }
  removeClass = true;
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
  background: #eee;
}

.col-search {
  padding: 13px 8px 8px 0;
  position: relative;
  width: 80%;
}

.input-search {
  width: 220px;
  height: 34px;
  max-width: 0;
  padding: 5px 10px;
  transition: all .2s ease;
  position: absolute;
  top: 13px;
  bottom: 13px;
  right: 46px;
  border: 0;
  box-sizing: border-box;
  opacity: 0;
}

.input-search.expanded {
  max-width: 220px;
  opacity: 1;
}

.btn-search {
  position: absolute;
  right: 0;
  width: 38px;
  height: 34px;
  border: 0;
  background: #333;
  color:#fff;
}</code>```

  <input class="input-search" type="search" placeholder="Search" />
  <input type="button" class="btn-search" value="click">

```

Title: Toggle class on click body

Body:
Make sure to check the event wasn't triggered by the input you want to exclude using event.target

This also doesn't interfere with other events that might be bound to the input itself.

var removeClass = true;
$(".btn-search").click(function() {
  $(".input-search").toggleClass('expanded');
  removeClass = false;
});
$("html").click(function() {
  var searchInput = $(".input-search");
  if (removeClass && event.target != searchInput[0]) {
    searchInput.removeClass('expanded');
  }
  removeClass = true;
});

body {
  background: #eee;
}

.col-search {
  padding: 13px 8px 8px 0;
  position: relative;
  width: 80%;
}

.input-search {
  width: 220px;
  height: 34px;
  max-width: 0;
  padding: 5px 10px;
  transition: all .2s ease;
  position: absolute;
  top: 13px;
  bottom: 13px;
  right: 46px;
  border: 0;
  box-sizing: border-box;
  opacity: 0;
}

.input-search.expanded {
  max-width: 220px;
  opacity: 1;
}

.btn-search {
  position: absolute;
  right: 0;
  width: 38px;
  height: 34px;
  border: 0;
  background: #333;
  color:#fff;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<div class="col-search">
  <input class="input-search" type="search" placeholder="Search" />
  <input type="button" class="btn-search" value="click">
</div>


问:
Error message when trying to compare data from Textbox to data from database
I'm trying to make a login page where I take the Password and Email from a SQL Server database. I want to compare the password and the Email.

```<code>private void buttoninloggen_Click(object sender, EventArgs e)
{
    using (SqlConnection connection = new SqlConnection(connectionstring))
    {
        connection.Open();

        string emailinlog = textBoxEmailLogin.Text;
        string passwordinlog = textBoxPasswordLogin.Text;
        string vergelijken = "select * from Account where Email = @email and Password = @password";

        SqlDataAdapter adapter = new SqlDataAdapter(vergelijken, connection);

        MessageBox.Show("tot hier is t goed");

        using (SqlCommand ophalen = new SqlCommand(vergelijken, connection))
        {
            ophalen.Parameters.AddWithValue("@email", emailinlog);
            ophalen.Parameters.AddWithValue("@password", passwordinlog);

            DataTable tafel = new DataTable();
            adapter.Fill(tafel);

            if (tafel.Rows.Count > 0)
            {
                MessageBox.Show("ingelogd");
            }
        }
    }
}
</code>```

I get this error message:

System.Data.SqlClient.SqlException: 'Must declare the scalar variable "@email".'

What am I doing wrong?

答:
Your code is wrong. You define an SqlDataAdapter with the query and connection but then do nothing else with it before trying to use it to fill the DataTable. It has no idea what the values for @email or @password are because you never tell it.

Your code should look like this:

```<code>private void buttoninloggen_Click(object sender, EventArgs e)
{
    using (SqlConnection connection = new SqlConnection(connectionstring))
    {
        connection.Open();
        string emailinlog = textBoxEmailLogin.Text;
        string passwordinlog = textBoxPasswordLogin.Text;
        string vergelijken = "select * from Account where Email = @email and Password = @password";

        // Moved the 'SqlDataAdapter' further down
        // SqlDataAdapter adapter = new SqlDataAdapter(vergelijken, connection);

        MessageBox.Show("tot hier is t goed");
        using (SqlCommand ophalen = new SqlCommand(vergelijken, connection))
        {
            ophalen.Parameters.AddWithValue("@email", emailinlog);
            ophalen.Parameters.AddWithValue("@password", passwordinlog);
            DataTable tafel = new DataTable();

            // SqlDataAdapter is now here
            // As it has been passed the SqlCommand it understands the parameters
            // Wrapped in using statement for disposal
            using (SqlDataAdapter adapter = new SqlDataAdapter(ophalen))
            {
                adapter.Fill(tafel);
                if (tafel.Rows.Count > 0)
                {
                    MessageBox.Show("ingelogd");
                }
            }
        }
    }
}
</code>```

Body:
I'm trying to make a login page where I take the Password and Email from a SQL Server database. I want to compare the password and the Email.

private void buttoninloggen_Click(object sender, EventArgs e)
{
    using (SqlConnection connection = new SqlConnection(connectionstring))
    {
        connection.Open();

        string emailinlog = textBoxEmailLogin.Text;
        string passwordinlog = textBoxPasswordLogin.Text;
        string vergelijken = "select * from Account where Email = @email and Password = @password";

        SqlDataAdapter adapter = new SqlDataAdapter(vergelijken, connection);

        MessageBox.Show("tot hier is t goed");

        using (SqlCommand ophalen = new SqlCommand(vergelijken, connection))
        {
            ophalen.Parameters.AddWithValue("@email", emailinlog);
            ophalen.Parameters.AddWithValue("@password", passwordinlog);

            DataTable tafel = new DataTable();
            adapter.Fill(tafel);

            if (tafel.Rows.Count > 0)
            {
                MessageBox.Show("ingelogd");
            }
        }
    }
}

I get this error message:

System.Data.SqlClient.SqlException: 'Must declare the scalar variable "@email".'

What am I doing wrong?

Body:
Your code is wrong. You define an SqlDataAdapter with the query and connection but then do nothing else with it before trying to use it to fill the DataTable. It has no idea what the values for @email or @password are because you never tell it.

Your code should look like this:

private void buttoninloggen_Click(object sender, EventArgs e)
{
    using (SqlConnection connection = new SqlConnection(connectionstring))
    {
        connection.Open();
        string emailinlog = textBoxEmailLogin.Text;
        string passwordinlog = textBoxPasswordLogin.Text;
        string vergelijken = "select * from Account where Email = @email and Password = @password";

        // Moved the 'SqlDataAdapter' further down
        // SqlDataAdapter adapter = new SqlDataAdapter(vergelijken, connection);

        MessageBox.Show("tot hier is t goed");
        using (SqlCommand ophalen = new SqlCommand(vergelijken, connection))
        {
            ophalen.Parameters.AddWithValue("@email", emailinlog);
            ophalen.Parameters.AddWithValue("@password", passwordinlog);
            DataTable tafel = new DataTable();

            // SqlDataAdapter is now here
            // As it has been passed the SqlCommand it understands the parameters
            // Wrapped in using statement for disposal
            using (SqlDataAdapter adapter = new SqlDataAdapter(ophalen))
            {
                adapter.Fill(tafel);
                if (tafel.Rows.Count > 0)
                {
                    MessageBox.Show("ingelogd");
                }
            }
        }
    }
}


问:
Expression of type list(object) doesn't conform to expected list scala
Supposedly I have the following

```<code>case class test {
                   a:string
                   b: string
                   c: Int
                   d: Int }

var temp = List(test("lol","lel",1,2))
var total = List(test)

total = total:::temp //this doesn't work because temp is of type [test] while total is of type [test.type]
</code>```

I do not understand the difference.
The reason I want to use this is that I want to have a running list where elements will be conditionally added in a loop.
So in this instance, total should initially an empty list which takes test objects. How do I do this?

Any feedback is appreciated!

答:
When you do this:

var total = List(test)

You are not initializing the object test, that's why the type of the list is Test.type, you are only creating a list of a template for an object.

When you do this instead:
var temp = List(test("lol","lel",1,2))

Yo have the object instantiated from a template (a class, in this case, Test) so the type of temp is List[Temp].

So, if you do something like:

val template = Test
Then the type of t is Test.type

And you can instantiate an object Test from template like this:

val instantiated = template("lol","lel",1,2)

As you see in your example, the total variable is just a list of templates from where you can instantiate objects while the temp variable is a list of objects of type Test.

To create an empty list of objects of type Test you just have to do:

val t: List[Test] = List.empty

Then you can add any object (of type Test) to this list

Body:
Supposedly I have the following

case class test {
                   a:string
                   b: string
                   c: Int
                   d: Int }

var temp = List(test("lol","lel",1,2))
var total = List(test)

total = total:::temp //this doesn't work because temp is of type [test] while total is of type [test.type]

I do not understand the difference.
The reason I want to use this is that I want to have a running list where elements will be conditionally added in a loop.
So in this instance, total should initially an empty list which takes test objects. How do I do this?

Any feedback is appreciated!


问:
webpack failing to import npm package
I've got a very simple webpack config

```<code>const HtmlWebpackPlugin = require("html-webpack-plugin");

module.exports = {
  entry: "./scripts/app.ts",
  output: {
    filename: "./www/scripts/appBundle.js",
  },
  resolve: {
    extensions: [".ts", ".js"]
  },
  devServer: {
    contentBase: './www'
  },
  module: {
    rules: [
      {
        test: /\.tsx?$/,
        use: [
          {
            loader: "ts-loader",
            options: {
              configFile: "scripts/tsconfig.json"
            }
          }
        ]
      }
    ]
  },
  plugins: [
    new HtmlWebpackPlugin({
      template: './www/index.ejs'
    })
  ],
  devtool: "source-map"
};
</code>```

I'm importing an npm package (nouislider), build works fine but when I run the app I get an error (noUiSlider is undefined).

I've set up a debug on chrome to try and find out what's happening - when I inspect the import I see an error - ReferenceError: noUiSlider is not defined at eval but when I inspect the actual execution line the debugger does recognize the import.

The execution still fails as the import is not recognized.

So far I've tried to add the babel-loader thinking it might be failing there, but I'm getting the same error.

Any idea what I'm missing?

答:
try adding something similar to 'babel-present-env' dependency to compile ES2015+ down to ES5. Looking at your config could you try changing your ts rule to this: </p>

```<code>{
  test: /\.ts(x?)$/,
  exclude: /node_modules/,
  use: [
    {
      loader: 'babel-loader',
      options: {
        presets:['env']
      }
    },
    {
      loader: 'ts-loader'
    }
  ]
}
</code>```

Title: webpack failing to import npm package

Body:
I've got a very simple webpack config

const HtmlWebpackPlugin = require("html-webpack-plugin");

module.exports = {
  entry: "./scripts/app.ts",
  output: {
    filename: "./www/scripts/appBundle.js",
  },
  resolve: {
    extensions: [".ts", ".js"]
  },
  devServer: {
    contentBase: './www'
  },
  module: {
    rules: [
      {
        test: /\.tsx?$/,
        use: [
          {
            loader: "ts-loader",
            options: {
              configFile: "scripts/tsconfig.json"
            }
          }
        ]
      }
    ]
  },
  plugins: [
    new HtmlWebpackPlugin({
      template: './www/index.ejs'
    })
  ],
  devtool: "source-map"
};

I'm importing an npm package (nouislider), build works fine but when I run the app I get an error (noUiSlider is undefined).

I've set up a debug on chrome to try and find out what's happening - when I inspect the import I see an error - ReferenceError: noUiSlider is not defined at eval but when I inspect the actual execution line the debugger does recognize the import.

The execution still fails as the import is not recognized.

So far I've tried to add the babel-loader thinking it might be failing there, but I'm getting the same error.

Any idea what I'm missing?

Body:
try adding something similar to 'babel-present-env' dependency to compile ES2015+ down to ES5. Looking at your config could you try changing your ts rule to this:

{
  test: /\.ts(x?)$/,
  exclude: /node_modules/,
  use: [
    {
      loader: 'babel-loader',
      options: {
        presets:['env']
      }
    },
    {
      loader: 'ts-loader'
    }
  ]
}


问:
Micro app router map->via with collections?
I'm setting up a Phalcon app using the Micro class.  I'm setting up my router to use the Collection class so that I can use a controller to split up the functionality and keep it fairly contained.

Now, what I'd like to do is have a route that handles both GET and POST.  With the normal micro app setup it looks pretty easy with $app->add(…)->via(['GET', 'POST']);.  However, the collections class offers a map method but nothing like a via.

Does anyone know the best way to achieve what I'm trying to do?  Code in the router looks simply like:

```<code><?php
    use Phalcon\Mvc\Micro\Collection;

    $login = new Collection();
    $login->setHandler('Service\Controllers\LoginController', true);
    $login->setPrefix('/login');
    $login->post('/basic', 'usernameAction');
    $login->map('/social/{oauthProvider}', 'socialAction')->via(['GET', 'POST']);

    $app->mount($login);
</code>```

(NB: this is just an included file, so auto-loading, defining $app and so on if fine, just in another file.  It also includes the map/via combination that doesn't work just to highlight what I'm trying to do.)

Thanks!

答:
It turns out that up to 3.2 of Phalcon (which I'm using) it's can't be done as I detailed above.  A mapVia method has been added to 3.3.x.

See further details from the Phalcon forums where I also asked this question.

Body:
I'm setting up a Phalcon app using the Micro class.  I'm setting up my router to use the Collection class so that I can use a controller to split up the functionality and keep it fairly contained.

Now, what I'd like to do is have a route that handles both GET and POST.  With the normal micro app setup it looks pretty easy with $app->add(…)->via(['GET', 'POST']);.  However, the collections class offers a map method but nothing like a via.

Does anyone know the best way to achieve what I'm trying to do?  Code in the router looks simply like:

<?php
    use Phalcon\Mvc\Micro\Collection;

    $login = new Collection();
    $login->setHandler('Service\Controllers\LoginController', true);
    $login->setPrefix('/login');
    $login->post('/basic', 'usernameAction');
    $login->map('/social/{oauthProvider}', 'socialAction')->via(['GET', 'POST']);

    $app->mount($login);

(NB: this is just an included file, so auto-loading, defining $app and so on if fine, just in another file.  It also includes the map/via combination that doesn't work just to highlight what I'm trying to do.)

Thanks!


问:
Rails: Catch a request in a scope when the request doesn't match anything in the scope
Let's take the following router  :

```<code>Rails.application.routes.draw do
  scope ":locale", locale: /en|nl/ do
    get "/:slug", to: "pages#prefixed_action", constraints: { slug: /.*/ }
  end

  root to: "pages#simple_action"
  get "/:slug", to: "pages#simple_action", constraints: { slug: /.*/ }
end
</code>```

If the request specifies a locale, the scope catches it and forwards it to pages#prefixed_action. If not the request is forwarded topages#simple_action.

My issue is that if I enter localhost:3000/en in the browser, it won't be catched by the scope. How can I arrange that ?

Edit1: I'd like the request to be routed to "pages#prefixed_action"

Edit2: added a root declaration in the code sample

答:
One of the possibilities is to specify root inside the scope:

```<code>scope ":locale", locale: /en|nl/ do
  root 'pages#prefixed_action'
  get "/:slug", to: "pages#prefixed_action", constraints: { slug: /.*/ }
end
</code>```

Body:
Let's take the following router  :

Rails.application.routes.draw do
  scope ":locale", locale: /en|nl/ do
    get "/:slug", to: "pages#prefixed_action", constraints: { slug: /.*/ }
  end

  root to: "pages#simple_action"
  get "/:slug", to: "pages#simple_action", constraints: { slug: /.*/ }
end

If the request specifies a locale, the scope catches it and forwards it to pages#prefixed_action. If not the request is forwarded topages#simple_action.

My issue is that if I enter localhost:3000/en in the browser, it won't be catched by the scope. How can I arrange that ?

Edit1: I'd like the request to be routed to "pages#prefixed_action"

Edit2: added a root declaration in the code sample

Body:
One of the possibilities is to specify root inside the scope:

scope ":locale", locale: /en|nl/ do
  root 'pages#prefixed_action'
  get "/:slug", to: "pages#prefixed_action", constraints: { slug: /.*/ }
end


问:
Check if exist and create
I try generate and save uncial slug for title in DB.

```<code>                $feed->friendlyUrl()->make([
                'url' => str_slug($feed->name),
                'action' => "feeds/{$feed->id}",
                'complicated' => false,
                'page_type_id' => PageType::TYPE_INDIVIDUAL_FEED_PAGE,
            ]);
</code>```

How check if such field in url exist? And if exist save:

```<code>'url' => str_slug($feed->name,"-1"),
</code>```

I think:

```<code>  if (FriendlyUrl::whereUrl(str_slug($feed->name))){
            $feed->friendlyUrl()->make([
                'url' => str_slug($feed->name),
                'action' => "feeds/{$feed->id}",
                'complicated' => false,
                'page_type_id' => PageType::TYPE_INDIVIDUAL_FEED_PAGE,
            ]);} else {
                $feed->friendlyUrl()->make([
                    'url' => str_slug($feed->name),
                    'action' => "feeds/{$feed->id}-1",
                    'complicated' => false,
                    'page_type_id' => PageType::TYPE_INDIVIDUAL_FEED_PAGE,
            };
            break;
</code>```

But it not clean and what if such url - str_slug($feed->name,"-1") already exists?

答:
Try this -

```<code>$FriendlyUrl = FriendlyUrl::firstOrNew(array('url' => str_slug($feed->name)));
$FriendlyUrl->action = "feeds/{$feed->id}";
$FriendlyUrl->complicated = false;
$FriendlyUrl->page_type_id = PageType::TYPE_INDIVIDUAL_FEED_PAGE;
$FriendlyUrl->save();
</code>```

Reference -
Insert a new record if not exist and update if exist, laravel eloquent

Title: Check if exist and create

Body:
I try generate and save uncial slug for title in DB.

                $feed->friendlyUrl()->make([
                'url' => str_slug($feed->name),
                'action' => "feeds/{$feed->id}",
                'complicated' => false,
                'page_type_id' => PageType::TYPE_INDIVIDUAL_FEED_PAGE,
            ]);

How check if such field in url exist? And if exist save:

'url' => str_slug($feed->name,"-1"),

I think:

  if (FriendlyUrl::whereUrl(str_slug($feed->name))){
            $feed->friendlyUrl()->make([
                'url' => str_slug($feed->name),
                'action' => "feeds/{$feed->id}",
                'complicated' => false,
                'page_type_id' => PageType::TYPE_INDIVIDUAL_FEED_PAGE,
            ]);} else {
                $feed->friendlyUrl()->make([
                    'url' => str_slug($feed->name),
                    'action' => "feeds/{$feed->id}-1",
                    'complicated' => false,
                    'page_type_id' => PageType::TYPE_INDIVIDUAL_FEED_PAGE,
            };
            break;

But it not clean and what if such url - str_slug($feed->name,"-1") already exists?

Body:
Try this -

$FriendlyUrl = FriendlyUrl::firstOrNew(array('url' => str_slug($feed->name)));
$FriendlyUrl->action = "feeds/{$feed->id}";
$FriendlyUrl->complicated = false;
$FriendlyUrl->page_type_id = PageType::TYPE_INDIVIDUAL_FEED_PAGE;
$FriendlyUrl->save();

Reference -
Insert a new record if not exist and update if exist, laravel eloquent


问:
Testing web service deployment with Arquillian: context root is null
I want to deploy an enterprise application with a web service facade to glassfish with Arquillian. I am not very experienced in this thema.

I send the WebService and Interface codes with annotiations.

WebService Implementation:

```<code>@Stateless
@WebService(endpointInterface = "ena.access.ticketsservices.facade.ITicketsRoleMappingsFacade")
@DeclareRoles({ "User", "Guest", "ProjectAdmin", "Admin" })
public class TicketsRoleMappingsFacade implements ITicketsRoleMappingsFacade {
 ...
}
</code>```

Interface:

```<code>@WebService(name = "TicketsRoleMappingsFacade")
public interface ITicketsRoleMappingsFacade {

  @WebMethod
  @WebResult(name = "createProjectResult")
  public Project createProject(@WebParam(name = "createproject") Project project);
}
</code>```

And the following xml files are glassfish configuration files.

application.xml

```<code><?xml version="1.0" encoding="UTF-8"?>
<application
    version="6"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/application_6.xsd">

    <display-name>j2ee-ear</display-name>

    <module>
        <ejb>j2ee-ejb.jar</ejb>
    </module>

    <security-role>
        <role-name>User</role-name>
    </security-role>
    <security-role>
        <role-name>Guest</role-name>
    </security-role>
    <security-role>
        <role-name>ProjectAdmin</role-name>
    </security-role>
    <security-role>
        <role-name>Admin</role-name>
    </security-role>

    <library-directory>lib</library-directory>

</application>
</code>```

glassfish-application.xml:

```<code><?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE glassfish-application PUBLIC -//GlassFish.org//DTD GlassFish Application Server 3.1 Java EE Application 6.0//EN http://glassfish.org/dtds/glassfish-application_6_0-1.dtd>
<glassfish-application>

    <security-role-mapping>
        <role-name>User</role-name>
        <group-name>User</group-name>
    </security-role-mapping>
    <security-role-mapping>
        <role-name>Guest</role-name>
        <group-name>Guest</group-name>
    </security-role-mapping>
    <security-role-mapping>
        <role-name>ProjectAdmin</role-name>
        <group-name>ProjectAdmin</group-name>
    </security-role-mapping>
    <security-role-mapping>
        <role-name>Admin</role-name>
        <group-name>Admin</group-name>
    </security-role-mapping>
    <realm>someRealm</realm>
</glassfish-application>
</code>```

glassfish-ejb-jar.xml

```<code><?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE glassfish-ejb-jar PUBLIC -//GlassFish.org//DTD GlassFish Application Server 3.1 EJB 3.1//EN http://glassfish.org/dtds/glassfish-ejb-jar_3_1-1.dtd>
<glassfish-ejb-jar>

    <security-role-mapping>
        <role-name>User</role-name>
        <group-name>User</group-name>
    </security-role-mapping>
    <security-role-mapping>
        <role-name>Guest</role-name>
        <group-name>Guest</group-name>
    </security-role-mapping>
    <security-role-mapping>
        <role-name>ProjectAdmin</role-name>
        <group-name>ProjectAdmin</group-name>
    </security-role-mapping>
    <security-role-mapping>
        <role-name>Admin</role-name>
        <group-name>Admin</group-name>
    </security-role-mapping>
    <enterprise-beans>
        <ejb>
            <ejb-name>TicketsRoleMappingsFacade</ejb-name>
            <webservice-endpoint>
                <port-component-name>TicketsRoleMappingsFacade</port-component-name>
                <port-component-uri>/TicketsRoleMappingsFacade</port-component-uri>
            </webservice-endpoint>
        </ejb>
    </enterprise-beans>

</glassfish-ejb-jar>
</code>```

When I build ear file with ShrinkWrap and deploy  get the following lines in log servers log, so I think a part of deployment was succesfull:

```<code>[#|2013-08-03T17:23:57.322+0200|INFO|glassfish3.1.1|javax.enterprise.webservices.org.glassfish.webservices|_ThreadID=17;_ThreadName=Thread-2;|WS00019: EJB Endpoint deployed j2ee-ear  listening at address at http://localhost:9999/TicketsRoleMappingsFacadeService/TicketsRoleMappingsFacade|#]
</code>```

But I also get the following exception in Arquillian:

```<code>java.lang.IllegalArgumentException: contextRoot must not be null
    at org.jboss.arquillian.container.spi.client.protocol.metadata.Servlet.<init>(Servlet.java:48)
    at org.jboss.arquillian.container.glassfish.clientutils.GlassFishClientService.resolveWebModuleSubComponents(GlassFishClientService.java:357)
    at org.jboss.arquillian.container.glassfish.clientutils.GlassFishClientService.doDeploy(GlassFishClientService.java:227)
    at org.jboss.arquillian.container.glassfish.CommonGlassFishManager.deploy(CommonGlassFishManager.java:101)
    at org.jboss.arquillian.container.glassfish.remote_3_1.GlassFishRestDeployableContainer.deploy(GlassFishRestDeployableContainer.java:71)
    at org.jboss.arquillian.container.impl.client.container.ContainerDeployController$3.call(ContainerDeployController.java:161)
    at org.jboss.arquillian.container.impl.client.container.ContainerDeployController$3.call(ContainerDeployController.java:128)
    at org.jboss.arquillian.container.impl.client.container.ContainerDeployController.executeOperation(ContainerDeployController.java:271)
    at org.jboss.arquillian.container.impl.client.container.ContainerDeployController.deploy(ContainerDeployController.java:127)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at org.jboss.arquillian.core.impl.ObserverImpl.invoke(ObserverImpl.java:94)
    at org.jboss.arquillian.core.impl.EventContextImpl.invokeObservers(EventContextImpl.java:99)
    at org.jboss.arquillian.core.impl.EventContextImpl.proceed(EventContextImpl.java:81)
    at
....
</code>```

I don't have any .war file for this test setup how can I specify the contextRoot for my web service?

答:
If you don't have a WAR(web application) you theoretically would not need the application.xml. My suggestion, try to delete it.

The successful deployment of the application in glassfish does not mean it will work in Arquillian. Arquillian has some issues with file name and context-root (I had this issue with an WAR file)

An EAR, according to JavaEE 6 Documentation, usually is used to bind WARs and EJBs. So, in theory, if you do not have a WAR you don't exactly need an EAR. You can deploy the EJB directly.

Body:
I want to deploy an enterprise application with a web service facade to glassfish with Arquillian. I am not very experienced in this thema.

I send the WebService and Interface codes with annotiations.

WebService Implementation:

@Stateless
@WebService(endpointInterface = "ena.access.ticketsservices.facade.ITicketsRoleMappingsFacade")
@DeclareRoles({ "User", "Guest", "ProjectAdmin", "Admin" })
public class TicketsRoleMappingsFacade implements ITicketsRoleMappingsFacade {
 ...
}

Interface:

@WebService(name = "TicketsRoleMappingsFacade")
public interface ITicketsRoleMappingsFacade {

  @WebMethod
  @WebResult(name = "createProjectResult")
  public Project createProject(@WebParam(name = "createproject") Project project);
}

And the following xml files are glassfish configuration files.

application.xml

<?xml version="1.0" encoding="UTF-8"?>
<application
    version="6"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/application_6.xsd">

    <display-name>j2ee-ear</display-name>

    <module>
        <ejb>j2ee-ejb.jar</ejb>
    </module>

    <security-role>
        <role-name>User</role-name>
    </security-role>
    <security-role>
        <role-name>Guest</role-name>
    </security-role>
    <security-role>
        <role-name>ProjectAdmin</role-name>
    </security-role>
    <security-role>
        <role-name>Admin</role-name>
    </security-role>

    <library-directory>lib</library-directory>

</application>

glassfish-application.xml:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE glassfish-application PUBLIC -//GlassFish.org//DTD GlassFish Application Server 3.1 Java EE Application 6.0//EN http://glassfish.org/dtds/glassfish-application_6_0-1.dtd>
<glassfish-application>

    <security-role-mapping>
        <role-name>User</role-name>
        <group-name>User</group-name>
    </security-role-mapping>
    <security-role-mapping>
        <role-name>Guest</role-name>
        <group-name>Guest</group-name>
    </security-role-mapping>
    <security-role-mapping>
        <role-name>ProjectAdmin</role-name>
        <group-name>ProjectAdmin</group-name>
    </security-role-mapping>
    <security-role-mapping>
        <role-name>Admin</role-name>
        <group-name>Admin</group-name>
    </security-role-mapping>
    <realm>someRealm</realm>
</glassfish-application>

glassfish-ejb-jar.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE glassfish-ejb-jar PUBLIC -//GlassFish.org//DTD GlassFish Application Server 3.1 EJB 3.1//EN http://glassfish.org/dtds/glassfish-ejb-jar_3_1-1.dtd>
<glassfish-ejb-jar>

    <security-role-mapping>
        <role-name>User</role-name>
        <group-name>User</group-name>
    </security-role-mapping>
    <security-role-mapping>
        <role-name>Guest</role-name>
        <group-name>Guest</group-name>
    </security-role-mapping>
    <security-role-mapping>
        <role-name>ProjectAdmin</role-name>
        <group-name>ProjectAdmin</group-name>
    </security-role-mapping>
    <security-role-mapping>
        <role-name>Admin</role-name>
        <group-name>Admin</group-name>
    </security-role-mapping>
    <enterprise-beans>
        <ejb>
            <ejb-name>TicketsRoleMappingsFacade</ejb-name>
            <webservice-endpoint>
                <port-component-name>TicketsRoleMappingsFacade</port-component-name>
                <port-component-uri>/TicketsRoleMappingsFacade</port-component-uri>
            </webservice-endpoint>
        </ejb>
    </enterprise-beans>

</glassfish-ejb-jar>

When I build ear file with ShrinkWrap and deploy  get the following lines in log servers log, so I think a part of deployment was succesfull:

[#|2013-08-03T17:23:57.322+0200|INFO|glassfish3.1.1|javax.enterprise.webservices.org.glassfish.webservices|_ThreadID=17;_ThreadName=Thread-2;|WS00019: EJB Endpoint deployed j2ee-ear  listening at address at http://localhost:9999/TicketsRoleMappingsFacadeService/TicketsRoleMappingsFacade|#]

But I also get the following exception in Arquillian:

java.lang.IllegalArgumentException: contextRoot must not be null
    at org.jboss.arquillian.container.spi.client.protocol.metadata.Servlet.<init>(Servlet.java:48)
    at org.jboss.arquillian.container.glassfish.clientutils.GlassFishClientService.resolveWebModuleSubComponents(GlassFishClientService.java:357)
    at org.jboss.arquillian.container.glassfish.clientutils.GlassFishClientService.doDeploy(GlassFishClientService.java:227)
    at org.jboss.arquillian.container.glassfish.CommonGlassFishManager.deploy(CommonGlassFishManager.java:101)
    at org.jboss.arquillian.container.glassfish.remote_3_1.GlassFishRestDeployableContainer.deploy(GlassFishRestDeployableContainer.java:71)
    at org.jboss.arquillian.container.impl.client.container.ContainerDeployController$3.call(ContainerDeployController.java:161)
    at org.jboss.arquillian.container.impl.client.container.ContainerDeployController$3.call(ContainerDeployController.java:128)
    at org.jboss.arquillian.container.impl.client.container.ContainerDeployController.executeOperation(ContainerDeployController.java:271)
    at org.jboss.arquillian.container.impl.client.container.ContainerDeployController.deploy(ContainerDeployController.java:127)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at org.jboss.arquillian.core.impl.ObserverImpl.invoke(ObserverImpl.java:94)
    at org.jboss.arquillian.core.impl.EventContextImpl.invokeObservers(EventContextImpl.java:99)
    at org.jboss.arquillian.core.impl.EventContextImpl.proceed(EventContextImpl.java:81)
    at
....

I don't have any .war file for this test setup how can I specify the contextRoot for my web service?


问:
Android Studio Multi-Windows for One Project
I'm wondering if anyone knows how to open two windows of Android Studio with both having the same project. I know you can drag tabs out, but that allows you to only edit that one file. I want two fully-featured windows with each being able to see the Project Files/Structure.

I don't want to just split the editor, I want a separate window.

I want two of these windows, with both "looking" at the same project:

I don't want another one of these windows, as I can't view the project structure and change that, and it's hard to change it to a different file in this view:

答: Just drag the tab outside the current window.</p>


问:
Powershell: TextBlock in Runspace – Add Inline with fontstyles
I have a problem with powershell and styling a part of Text in a TextBlock.

I use a function to push text to a runspace window and a TextBlock in it, which works fine.

```<code>Function Update-Log {
    Param (
        $Content,
        $type = "Black"
    )
    $syncHash.Window.Dispatcher.invoke(
        [action]{$syncHash.log_txt.Foreground = $type; $syncHash.log_txt.Inlines.Add($Content); },
        "Normal"
    )
}
</code>```

Even the change of color works without problems. But now I would like to mark individual words bold. I have tried a pragmatic approach:

```<code>Update-Log "Here is some <bold>bold</bold> text."
</code>```

Unfortunately this did not work. Can you help me to find a solution for this problem?

答:
You need to capitalize bold:</p>

```<code>Update-Log "Here is some <Bold>bold</Bold> text."
</code>```

Body:
I have a problem with powershell and styling a part of Text in a TextBlock.

I use a function to push text to a runspace window and a TextBlock in it, which works fine.

Function Update-Log {
    Param (
        $Content,
        $type = "Black"
    )
    $syncHash.Window.Dispatcher.invoke(
        [action]{$syncHash.log_txt.Foreground = $type; $syncHash.log_txt.Inlines.Add($Content); },
        "Normal"
    )
}

Even the change of color works without problems. But now I would like to mark individual words bold. I have tried a pragmatic approach:

Update-Log "Here is some <bold>bold</bold> text."

Unfortunately this did not work. Can you help me to find a solution for this problem?

Body:
You need to capitalize bold:

Update-Log "Here is some <Bold>bold</Bold> text."


Title: bash find filenames with the same last four character

Body:
I'd like to write a script that will execute a command that finds every set of files that have the same last four characters.

So for example, given a directory with these files,

$ ls -1
GH010119.MP4
GH010120.MP4
GH010126.MP4
GH010127.MP4
GH020119.MP4
GH020126.MP4
GH020127.MP4
GH030119.MP4
GH030126.MP4

I'd like my script to make out these groups:

GH010119.MP4
GH020119.MP4
GH030119.MP4

GH010126.MP4
GH020126.MP4
GH030126.MP4

GH010127.MP4
GH020127.MP4

GH010120.MP4

My current solution is to make out each group manually using: find . -name "*0119*", so I'd also like to know if the script I'd have to come up with won't be overly complex in comparison....

Body:
With perl

perl -e 'for (glob("*")){$f{$1}.="$&\n" if /.*(.{4}).MP4/}print "$_\n" for (values %f)'
GH010126.MP4
GH020126.MP4
GH030126.MP4

GH010120.MP4

GH010119.MP4
GH020119.MP4
GH030119.MP4

GH010127.MP4
GH020127.MP4


问:
MySQL connection with VB.NET via internet!
While connecting to mysql via VB.NET, I'm getting the following problem. What can be the solution or what am i missing???

Host '113.199.138.240' is not allowed to connect to this MySQL server

答:
There is a number of reasons you may not be allowed to connect:

Use port 3306 to connect

Check that your MySQL allows external connections

Check if local or remote firewalls prevent you from connecting.

In order to connect you need privileges:

```<code>grant 'privilege_type' on 'databasename'.* to '<user>'@'%' identified by 'password';
</code>```

Body:
There is a number of reasons you may not be allowed to connect:

Use port 3306 to connect

Check that your MySQL allows external connections

Check if local or remote firewalls prevent you from connecting.

In order to connect you need privileges:

grant 'privilege_type' on 'databasename'.* to '<user>'@'%' identified by 'password';