问:
How can I make a div span multiple rows and columns in a grid?
Building off of a previous question, I'm trying to add bigger blocks to my grid layout. In the last question, I needed to have a div span multiple rows. The problem now is that I need a div to span multiple rows and columns.

If I have a five-element row, how could I put bigger elements in the middle of it? (as float puts it naturally on the side).

Here's an example snippet:

#wrapper{
  width: 516px;
}
.block{
  display: inline-block;
  width: 90px;
  height: 50px;
  margin: 5px;
  background-color: red;
}
.bigger{
  height: 110px;
}
.larger{
  height: 110px;
  width: 190px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="wrapper">
  <div class="block"></div>
  <div class="block bigger"></div>
  <div class="block"></div>
  <div class="block"></div>
  <div class="block"></div>
  <div class="block"></div>
  <div class="block larger"></div>
  <div class="block"></div>
  <div class="block"></div>
  <div class="block"></div>
  <div class="block"></div>
</div></code>```

I don't want to use display: grid for the wrapper element, as Can I Use states this is a pretty on-the-edge technology right now. I was hoping for a non-grid, non-table solution.

Here's what I would like to have from the snippet above

答:
Keeping your HTML as-is, the layout is not natively possible with flexbox. This is primarily because of the 2 x 2 box occupying the third and fourth columns. The closest you can get is this:

#wrapper{
  display: flex;
  flex-direction: column;
  flex-wrap: wrap;
  align-content: flex-start;
  height: 180px;
  width: 516px;
}
.block {
  width: 90px;
  flex: 0 0 50px;
  margin: 5px;
  background-color: red;
}
.bigger{
  flex-basis: 110px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="wrapper">
  <div class="block"></div>
  <div class="block"></div>
  <div class="block"></div>
  <div class="block bigger"></div>
  <div class="block"></div>
  <div class="block"></div>
  <div class="block bigger"></div>
  <div class="block"></div>
  <div class="block bigger"></div>
  <div class="block"></div>
  <div class="block"></div>
  <div class="block"></div>
</div></code>```

As you can see, the big box is broken up between columns.

As mentioned in the other post you referenced, since you have fixed heights on your child elements (.block), we can determine the height of the container (.wrapper).

By knowing the height of the container, the layout above can be achieved using flex-direction: column and flex-wrap: wrap.

A fixed height on the container serves as a breakpoint, telling flex items where to wrap.

Alternatively, if you can add containers, then the layout is easy. Just create four nested flex containers to hold columns 1, 2, 3-4 and 5, and you're done.

#wrapper {
  display: flex;
  width: 516px;
}

section {
  display: flex;
  flex-direction: column;
}

.block {
  width: 90px;
  height: 50px;
  margin: 5px;
  background-color: red;
}

.bigger {
  flex-basis: 110px;
}

section:nth-child(3) {
  flex-direction: row;
  flex-wrap: wrap;
  flex: 0 0 200px;
}

section:nth-child(3)>.block:last-child {
  flex: 0 0 190px;
  height: 110px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="wrapper">
  <section>
    <div class="block"></div>
    <div class="block"></div>
    <div class="block"></div>
  </section>
  <section>
    <div class="block bigger"></div>
    <div class="block"></div>
  </section>
  <section>
    <div class="block"></div>
    <div class="block"></div>
    <div class="block"></div>
  </section>
  <section>
    <div class="block"></div>
    <div class="block"></div>
    <div class="block"></div>
  </section>
</div></code>```

Otherwise, see this post for more details and other options:

Is it possible for flex items to align tightly to the items above them?

Body:
Building off of a previous question, I'm trying to add bigger blocks to my grid layout. In the last question, I needed to have a div span multiple rows. The problem now is that I need a div to span multiple rows and columns.

If I have a five-element row, how could I put bigger elements in the middle of it? (as float puts it naturally on the side).

Here's an example snippet:

#wrapper{
  width: 516px;
}
.block{
  display: inline-block;
  width: 90px;
  height: 50px;
  margin: 5px;
  background-color: red;
}
.bigger{
  height: 110px;
}
.larger{
  height: 110px;
  width: 190px;
}

I don't want to use display: grid for the wrapper element, as Can I Use states this is a pretty on-the-edge technology right now. I was hoping for a non-grid, non-table solution.

Here's what I would like to have from the snippet above

Body:
Keeping your HTML as-is, the layout is not natively possible with flexbox. This is primarily because of the 2 x 2 box occupying the third and fourth columns. The closest you can get is this:

#wrapper{
  display: flex;
  flex-direction: column;
  flex-wrap: wrap;
  align-content: flex-start;
  height: 180px;
  width: 516px;
}
.block {
  width: 90px;
  flex: 0 0 50px;
  margin: 5px;
  background-color: red;
}
.bigger{
  flex-basis: 110px;
}

<div id="wrapper">
  <div class="block"></div>
  <div class="block"></div>
  <div class="block"></div>
  <div class="block bigger"></div>
  <div class="block"></div>
  <div class="block"></div>
  <div class="block bigger"></div>
  <div class="block"></div>
  <div class="block bigger"></div>
  <div class="block"></div>
  <div class="block"></div>
  <div class="block"></div>
</div>

As you can see, the big box is broken up between columns.

As mentioned in the other post you referenced, since you have fixed heights on your child elements (.block), we can determine the height of the container (.wrapper).

By knowing the height of the container, the layout above can be achieved using flex-direction: column and flex-wrap: wrap.

A fixed height on the container serves as a breakpoint, telling flex items where to wrap.

Alternatively, if you can add containers, then the layout is easy. Just create four nested flex containers to hold columns 1, 2, 3-4 and 5, and you're done.

#wrapper {
  display: flex;
  width: 516px;
}

section {
  display: flex;
  flex-direction: column;
}

.block {
  width: 90px;
  height: 50px;
  margin: 5px;
  background-color: red;
}

.bigger {
  flex-basis: 110px;
}

section:nth-child(3) {
  flex-direction: row;
  flex-wrap: wrap;
  flex: 0 0 200px;
}

section:nth-child(3)>.block:last-child {
  flex: 0 0 190px;
  height: 110px;
}

<div id="wrapper">
  <section>
    <div class="block"></div>
    <div class="block"></div>
    <div class="block"></div>
  </section>
  <section>
    <div class="block bigger"></div>
    <div class="block"></div>
  </section>
  <section>
    <div class="block"></div>
    <div class="block"></div>
    <div class="block"></div>
  </section>
  <section>
    <div class="block"></div>
    <div class="block"></div>
    <div class="block"></div>
  </section>
</div>

Otherwise, see this post for more details and other options:

Is it possible for flex items to align tightly to the items above them?


来源: stackexchange

问:
main storyboard with custom rootVievController doesn't call vc's init
I'm new to iOS programming, so don't be rude)
I create my view controller and connected it to Main.storyboard in appDelegate. It works.

```<code>- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
    TestViewController *vc = [storyboard instantiateViewControllerWithIdentifier:@"TestViewController"];
    [self.window setRootViewController:vc];

    return YES;
}
</code>```

In TestViewController.m in init put some data to NSArray, but it doesn't execute.

```<code>- (instancetype) init {
    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:[NSBundle mainBundle]];

    self = [storyboard instantiateViewControllerWithIdentifier:@"SMKQuizViewController"]; ...
</code>```

I tried just init and initWithNib, but both don't work.
What i'm doing wrong?

答:
When you load a ViewController from storyboard init will not get called instead you can put your code in

```<code>override func awakeFromNib() {
    super.awakeFromNib()
    self.yourArray = ["ABCD","EFGH"] //initialize ur array
}
</code>```

And if you are hell bent on writing init :) You can use

```<code>required init?(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)
    self.yourArray = ["ABCD","EFGH"] //initialize ur array
}
</code>```

EDIT:

init in Objective-C

```<code>- (instancetype)initWithCoder:(NSCoder *)coder
{
    self = [super initWithCoder:coder];
    if (self) {
        //initialize your array here :)
    }
    return self;
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm new to iOS programming, so don't be rude)
I create my view controller and connected it to Main.storyboard in appDelegate. It works.

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
    TestViewController *vc = [storyboard instantiateViewControllerWithIdentifier:@"TestViewController"];
    [self.window setRootViewController:vc];

    return YES;
}

In TestViewController.m in init put some data to NSArray, but it doesn't execute.

- (instancetype) init {
    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:[NSBundle mainBundle]];

    self = [storyboard instantiateViewControllerWithIdentifier:@"SMKQuizViewController"]; ...

I tried just init and initWithNib, but both don't work.
What i'm doing wrong?

Body:
When you load a ViewController from storyboard init will not get called instead you can put your code in

override func awakeFromNib() {
    super.awakeFromNib()
    self.yourArray = ["ABCD","EFGH"] //initialize ur array
}

And if you are hell bent on writing init :) You can use

required init?(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)
    self.yourArray = ["ABCD","EFGH"] //initialize ur array
}

EDIT:

init in Objective-C

- (instancetype)initWithCoder:(NSCoder *)coder
{
    self = [super initWithCoder:coder];
    if (self) {
        //initialize your array here :)
    }
    return self;
}


问:
Values error: Boolean types not allowed (at 'android:windowBackground' with value 'true')
I modified the values.xml files, and I accidentally put "true" in this part of code:

```<code> <item name="android:windowBackground"> true </item>
</code>```

I tried to change "true" to other variables, but always returns "true"

and this error:

Error:(2002, 47) Boolean types not allowed (at 'android:windowBackground' with value 'true').

Error:Execution failed for task ':app:processDebugResources'.
com.android.ide.common.process.ProcessException: Failed to execute aapt

And the values.xml file is on ( /app/build/intermediates/res/merged/debug/values ) folder.

Sorry fo my bad Englih.

答:
Simply modify the styles.xml file located in the path app\src\main\res\values

```<code><item name="android:windowBackground">@color/red</item>
</code>```

Something like above. Replace the red color with any preferable color of yours. Use the path I've mentioned above to modify the styles.xml file, the path you're pointing to is an intermediate build path and changes in that file won't affect your project because it is an auto generated file.

Body:
I modified the values.xml files, and I accidentally put "true" in this part of code:

 <item name="android:windowBackground"> true </item>

I tried to change "true" to other variables, but always returns "true"

and this error:

Error:(2002, 47) Boolean types not allowed (at 'android:windowBackground' with value 'true').

Error:Execution failed for task ':app:processDebugResources'.
com.android.ide.common.process.ProcessException: Failed to execute aapt

And the values.xml file is on ( /app/build/intermediates/res/merged/debug/values ) folder.

Sorry fo my bad Englih.

Body:
Simply modify the styles.xml file located in the path app\src\main\res\values

<item name="android:windowBackground">@color/red</item>

Something like above. Replace the red color with any preferable color of yours. Use the path I've mentioned above to modify the styles.xml file, the path you're pointing to is an intermediate build path and changes in that file won't affect your project because it is an auto generated file.


问:
didRegisterForRemoteNotificationsWithDeviceToken is not called in Xcode 8
I build my app on Xcode 8 with iOS 10 SDK.
didRegisterForRemoteNotificationsWithDeviceToken is not called for iOS 9.3 device, hence iOS 9.3 and bellow devices unable to receive push notifications.
But iOS 10 devices can receive push.
If i build the same app on Xcode 7.3 with iOS 9.3 SDK, then iOS 9 devices can receive push.
So, Im sure that all my settings should be correct.

This is my implementation :

```<code>// Push notification
if( SYSTEM_VERSION_LESS_THAN( @"10.0" ) )
{
    if([application respondsToSelector:@selector(registerUserNotificationSettings:)])
    {
        UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:(UIUserNotificationTypeAlert | UIUserNotificationTypeBadge | UIUserNotificationTypeSound) categories:nil];
        [[UIApplication sharedApplication] registerUserNotificationSettings:settings];
        [[UIApplication sharedApplication] registerForRemoteNotifications];

    }
    else
    {
        [[UIApplication sharedApplication] registerForRemoteNotificationTypes: (UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound)];
    }

}
else
{
    UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
    center.delegate = self;
    [center requestAuthorizationWithOptions:(UNAuthorizationOptionSound | UNAuthorizationOptionAlert | UNAuthorizationOptionBadge) completionHandler:^(BOOL granted, NSError * _Nullable error)
     {
         if( !error )
         {
             [[UIApplication sharedApplication] registerForRemoteNotifications];
         }

     }];
}

- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {

NSString * tokenAsString = [[[deviceToken description]
                             stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"<>"]]
                            stringByReplacingOccurrencesOfString:@" " withString:@""];

}

- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {

DLog(@"app didFailToRegisterForRemoteNotificationsWithError: %@", error.description);
}
</code>```

答:
You need to call registerForNotifications method from didFinishLaunchingWithOptions.</p>

```<code> func registerForNotifications(){
        if #available(iOS 10.0, *) {
            let center = UNUserNotificationCenter.current()
            center.delegate = self
            center.requestAuthorization(options:[.alert,.sound,.badge]) { (granted, error) in
                if granted{
                    UIApplication.shared.registerForRemoteNotifications()
                }else{
                    print("Notification permission denied.")

                }
            }

        } else {
            // For iOS 9 and Below
            let type: UIUserNotificationType = [.alert,.sound,.badge];
            let setting = UIUserNotificationSettings(types: type, categories: nil);
            UIApplication.shared.registerUserNotificationSettings(setting);
            UIApplication.shared.registerForRemoteNotifications()
        }
    }

 func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
        let token = String(format: "%@", deviceToken as CVarArg).trimmingCharacters(in: CharacterSet(charactersIn: "<>")).replacingOccurrences(of: " ", with: "")
        print(token)
    }

extension AppDelegate : UNUserNotificationCenterDelegate{
    @available(iOS 10.0, *)
    func userNotificationCenter(_ center: UNUserNotificationCenter,  willPresent notification: UNNotification, withCompletionHandler   completionHandler: @escaping (_ options:   UNNotificationPresentationOptions) -> Void) {
        print("Handle push from foreground”)

        let info = ((notification.request.content.userInfo as NSDictionary).value(forKey: "aps") as! NSDictionary)
        if let type = info.value(forKey: "type") as? Int{
            if type == 0 {   // notification arrive
                handlePush(apsDict: (notification.request.content.userInfo as NSDictionary))
            }
        }
    }
    @available(iOS 10.0, *)
    func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
        print("Handle push from background or closed")

        let info = ((response.notification.request.content.userInfo as NSDictionary).value(forKey: "aps") as! NSDictionary)
        if let type = info.value(forKey: "type") as? Int{
            if type == 0 {   // notification arrive
                handlePush(apsDict: (response.notification.request.content.userInfo as NSDictionary))
            }
        }
    }
}
</code>```

Body:
I build my app on Xcode 8 with iOS 10 SDK.
didRegisterForRemoteNotificationsWithDeviceToken is not called for iOS 9.3 device, hence iOS 9.3 and bellow devices unable to receive push notifications.
But iOS 10 devices can receive push.
If i build the same app on Xcode 7.3 with iOS 9.3 SDK, then iOS 9 devices can receive push.
So, Im sure that all my settings should be correct.

This is my implementation :

// Push notification
if( SYSTEM_VERSION_LESS_THAN( @"10.0" ) )
{
    if([application respondsToSelector:@selector(registerUserNotificationSettings:)])
    {
        UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:(UIUserNotificationTypeAlert | UIUserNotificationTypeBadge | UIUserNotificationTypeSound) categories:nil];
        [[UIApplication sharedApplication] registerUserNotificationSettings:settings];
        [[UIApplication sharedApplication] registerForRemoteNotifications];

    }
    else
    {
        [[UIApplication sharedApplication] registerForRemoteNotificationTypes: (UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound)];
    }

}
else
{
    UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
    center.delegate = self;
    [center requestAuthorizationWithOptions:(UNAuthorizationOptionSound | UNAuthorizationOptionAlert | UNAuthorizationOptionBadge) completionHandler:^(BOOL granted, NSError * _Nullable error)
     {
         if( !error )
         {
             [[UIApplication sharedApplication] registerForRemoteNotifications];
         }

     }];
}

- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {

NSString * tokenAsString = [[[deviceToken description]
                             stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"<>"]]
                            stringByReplacingOccurrencesOfString:@" " withString:@""];

}

- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {

DLog(@"app didFailToRegisterForRemoteNotificationsWithError: %@", error.description);
}

Body:
You need to call registerForNotifications method from didFinishLaunchingWithOptions.

 func registerForNotifications(){
        if #available(iOS 10.0, *) {
            let center = UNUserNotificationCenter.current()
            center.delegate = self
            center.requestAuthorization(options:[.alert,.sound,.badge]) { (granted, error) in
                if granted{
                    UIApplication.shared.registerForRemoteNotifications()
                }else{
                    print("Notification permission denied.")

                }
            }

        } else {
            // For iOS 9 and Below
            let type: UIUserNotificationType = [.alert,.sound,.badge];
            let setting = UIUserNotificationSettings(types: type, categories: nil);
            UIApplication.shared.registerUserNotificationSettings(setting);
            UIApplication.shared.registerForRemoteNotifications()
        }
    }

 func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
        let token = String(format: "%@", deviceToken as CVarArg).trimmingCharacters(in: CharacterSet(charactersIn: "<>")).replacingOccurrences(of: " ", with: "")
        print(token)
    }

extension AppDelegate : UNUserNotificationCenterDelegate{
    @available(iOS 10.0, *)
    func userNotificationCenter(_ center: UNUserNotificationCenter,  willPresent notification: UNNotification, withCompletionHandler   completionHandler: @escaping (_ options:   UNNotificationPresentationOptions) -> Void) {
        print("Handle push from foreground”)

        let info = ((notification.request.content.userInfo as NSDictionary).value(forKey: "aps") as! NSDictionary)
        if let type = info.value(forKey: "type") as? Int{
            if type == 0 {   // notification arrive
                handlePush(apsDict: (notification.request.content.userInfo as NSDictionary))
            }
        }
    }
    @available(iOS 10.0, *)
    func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
        print("Handle push from background or closed")

        let info = ((response.notification.request.content.userInfo as NSDictionary).value(forKey: "aps") as! NSDictionary)
        if let type = info.value(forKey: "type") as? Int{
            if type == 0 {   // notification arrive
                handlePush(apsDict: (response.notification.request.content.userInfo as NSDictionary))
            }
        }
    }
}


问:
wsadmin adminApp.update java.net.UnknownHostException Full-Qualified-Hostname
Try to deploy an EAR file to WebSphere enterprise app, over a SOAP connection.

the command line:

```<code>call wsadmin -conntype SOAP -host %WAS_HOST% -port %WAS_PORT% -user %WAS_USER% -password !WAS_PASSWORD! -lang jython -c "AdminApp.update('%APP_NAME%', 'app', '[ -operation update -contents %EAR_FILE% -usedefaultbindings -defaultbinding.virtual.host default_host -nopreCompileJSPs -installed.ear.destination $(APP_INSTALL_ROOT)/%WAS_HOST%Network -distributeApp -nouseMetaDataFromBinary -nodeployejb -createMBeansForResources -noreloadEnabled -deployws -validateinstall warn -noprocessEmbeddedConfig -filepermission .*\.dll=755#.*\.so=755#.*\.a=755#.*\.sl=755 -noallowDispatchRemoteInclude -noallowServiceRemoteInclude -asyncRequestDispatchType DISABLED -nouseAutoLink -MapModulesToServers [[ %MODULE_NAME% %WAR_FILE%,WEB-INF/web.xml WebSphere:cell=%WAS_HOST%Network,cluster=%CLUSTER%+WebSphere:cell=%WAS_HOST%Network,node=%WEB_NODE%,server=%WEB_NODE% ]]]' )"
</code>```

is issued from a build machine that is on windows. where WAS_HOST=MySrvrA.mycomp.com

when running this command, I got

WASX7209I: Connected to process "dmgr" on node eagnmncom0cbbManager using SOAP connector;  The type of process is: DeploymentManager
  WASX7015E: Exception running command: "AdminApp.update ...

  ....

  exception information:
  com.ibm.websphere.management.filetransfer.client.TransferFailedException
  java.net.UnknownHostException: java.net.UnknownHostException: MySrvrA

the WebSphere App server is on Linux, and the /etc/hosts file has the contents:

IP-Address  Full-Qualified-Hostname  Short-Hostname

#

127.0.0.1       localhost

special IPv6 addresses ::1     localhost       ipv6-localhost ipv6-loopback

fe00::0 ipv6-localnet

ff00::0 ipv6-mcastprefix ff02::1 ipv6-allnodes ff02::2 ipv6-allrouters
  ff02::3 ipv6-allhosts

56.xxx.xxx.xxx     MySrvrA.mycomp.com  MySrvrA

this server can be accessible over the internet via the Full-Qualified-Hostname only.

To trouble shoot, I have

1) run a command of

```<code>call wsadmin -conntype SOAP -host %WAS_HOST% -port %WAS_PORT% -user %WAS_USER% -password !WAS_PASSWORD! -lang jython -c "print Help.help()"
</code>```

this works, and it should prove that the connection from the build machine to the WAS server is good.

2) to further prove that the AdminApp.update and its resolved parameters works, I have run the AppAdmin.update in its entirety:

```<code>AdminApp.update('%APP_NAME%', 'app', '[ -operation update -contents %EAR_FILE% -usedefaultbindings -defaultbinding.virtual.host default_host -nopreCompileJSPs -installed.ear.destination $(APP_INSTALL_ROOT)/%WAS_HOST%Network -distributeApp -nouseMetaDataFromBinary -nodeployejb -createMBeansForResources -noreloadEnabled -deployws -validateinstall warn -noprocessEmbeddedConfig -filepermission .*\.dll=755#.*\.so=755#.*\.a=755#.*\.sl=755 -noallowDispatchRemoteInclude -noallowServiceRemoteInclude -asyncRequestDispatchType DISABLED -nouseAutoLink -MapModulesToServers [[ %MODULE_NAME% %WAR_FILE%,WEB-INF/web.xml WebSphere:cell=%WAS_HOST%Network,cluster=%CLUSTER%+WebSphere:cell=%WAS_HOST%Network,node=%WEB_NODE%,server=%WEB_NODE% ]]]' )
</code>```

directly on the WAS server. it works, and should prove the AdminApp.update and it's options and parameters are good.

it seems to me that over a SOAP deployment, AdminApp.update truncated the WAS_HOST and does not use the Full-Qualified-Hostname.

What I am doing wrong, and how can I resolve this?

I have another machine set that are accessible from the Internet via the Short-Hostname, the same command line works perfectly over SOAP connector.

答:
It turns out that a security restriction causes the issue.

The target WAS server is in DMZ .com, while the build machine is in the blue .xxx, file transfer from .xxx to .com is not allowed based on the security policies of the organization.

After adding the target WAS servers into the C:\Windows\System32\Drivers\etc\hosts of the build machine, the deployment goes successfully.

Body:
Try to deploy an EAR file to WebSphere enterprise app, over a SOAP connection.

the command line:

call wsadmin -conntype SOAP -host %WAS_HOST% -port %WAS_PORT% -user %WAS_USER% -password !WAS_PASSWORD! -lang jython -c "AdminApp.update('%APP_NAME%', 'app', '[ -operation update -contents %EAR_FILE% -usedefaultbindings -defaultbinding.virtual.host default_host -nopreCompileJSPs -installed.ear.destination $(APP_INSTALL_ROOT)/%WAS_HOST%Network -distributeApp -nouseMetaDataFromBinary -nodeployejb -createMBeansForResources -noreloadEnabled -deployws -validateinstall warn -noprocessEmbeddedConfig -filepermission .*\.dll=755#.*\.so=755#.*\.a=755#.*\.sl=755 -noallowDispatchRemoteInclude -noallowServiceRemoteInclude -asyncRequestDispatchType DISABLED -nouseAutoLink -MapModulesToServers [[ %MODULE_NAME% %WAR_FILE%,WEB-INF/web.xml WebSphere:cell=%WAS_HOST%Network,cluster=%CLUSTER%+WebSphere:cell=%WAS_HOST%Network,node=%WEB_NODE%,server=%WEB_NODE% ]]]' )"

is issued from a build machine that is on windows. where WAS_HOST=MySrvrA.mycomp.com

when running this command, I got

WASX7209I: Connected to process "dmgr" on node eagnmncom0cbbManager using SOAP connector;  The type of process is: DeploymentManager
  WASX7015E: Exception running command: "AdminApp.update ...

  ....

  exception information:
  com.ibm.websphere.management.filetransfer.client.TransferFailedException
  java.net.UnknownHostException: java.net.UnknownHostException: MySrvrA

the WebSphere App server is on Linux, and the /etc/hosts file has the contents:

IP-Address  Full-Qualified-Hostname  Short-Hostname

#

127.0.0.1       localhost

special IPv6 addresses ::1     localhost       ipv6-localhost ipv6-loopback

fe00::0 ipv6-localnet

ff00::0 ipv6-mcastprefix ff02::1 ipv6-allnodes ff02::2 ipv6-allrouters
  ff02::3 ipv6-allhosts

56.xxx.xxx.xxx     MySrvrA.mycomp.com  MySrvrA

this server can be accessible over the internet via the Full-Qualified-Hostname only.

To trouble shoot, I have

1) run a command of

call wsadmin -conntype SOAP -host %WAS_HOST% -port %WAS_PORT% -user %WAS_USER% -password !WAS_PASSWORD! -lang jython -c "print Help.help()"

this works, and it should prove that the connection from the build machine to the WAS server is good.

2) to further prove that the AdminApp.update and its resolved parameters works, I have run the AppAdmin.update in its entirety:

AdminApp.update('%APP_NAME%', 'app', '[ -operation update -contents %EAR_FILE% -usedefaultbindings -defaultbinding.virtual.host default_host -nopreCompileJSPs -installed.ear.destination $(APP_INSTALL_ROOT)/%WAS_HOST%Network -distributeApp -nouseMetaDataFromBinary -nodeployejb -createMBeansForResources -noreloadEnabled -deployws -validateinstall warn -noprocessEmbeddedConfig -filepermission .*\.dll=755#.*\.so=755#.*\.a=755#.*\.sl=755 -noallowDispatchRemoteInclude -noallowServiceRemoteInclude -asyncRequestDispatchType DISABLED -nouseAutoLink -MapModulesToServers [[ %MODULE_NAME% %WAR_FILE%,WEB-INF/web.xml WebSphere:cell=%WAS_HOST%Network,cluster=%CLUSTER%+WebSphere:cell=%WAS_HOST%Network,node=%WEB_NODE%,server=%WEB_NODE% ]]]' )

directly on the WAS server. it works, and should prove the AdminApp.update and it's options and parameters are good.

it seems to me that over a SOAP deployment, AdminApp.update truncated the WAS_HOST and does not use the Full-Qualified-Hostname.

What I am doing wrong, and how can I resolve this?

I have another machine set that are accessible from the Internet via the Short-Hostname, the same command line works perfectly over SOAP connector.


问:
PHP geoplugin php error
i added the plugin from geoplugin.com to my page, i activated my domain, but in my errorlog i get errors all the time like this:

```<code>[20-Mar-2013 11:17:13 CET] PHP Warning: file_get_contents(http://www.geoplugin.net/php.gp?ip=157.55.34.183&base_currency=USD) [<a href='function.file-get-contents'>function.file-get-contents</a>]: failed to open stream: HTTP request failed! HTTP/1.1 403 Forbidden
 in /wwwroot.wwwnew/templates/geo/geoplugin.class.php on line 105
</code>```

How can i solve this problem?

答:
If geoplugin.net was responding perfectly, then stopped, then you have
  gone over the free lookup limit of 120 requests per minute.

We automatically block all requests coming from an IP or a domain name
  if the number of requests exceeds 120 lookups per minute. This is
  explained in our Acceptable Use Policy. This block comes in the form
  of a HTTP/1.1 403 Forbidden reply from geoplugin.net

This block is automatically removed 1 hour after the last time your
  server stopped sending more than 120 requests a minute.

- GeoPlugin FaQ

If you need more than 120 requests per minute, you have to whitelist your domain (it's paid).

Title: PHP geoplugin php error

Body:
i added the plugin from geoplugin.com to my page, i activated my domain, but in my errorlog i get errors all the time like this:

[20-Mar-2013 11:17:13 CET] PHP Warning: file_get_contents(http://www.geoplugin.net/php.gp?ip=157.55.34.183&base_currency=USD) [function.file-get-contents]: failed to open stream: HTTP request failed! HTTP/1.1 403 Forbidden
 in /wwwroot.wwwnew/templates/geo/geoplugin.class.php on line 105

How can i solve this problem?


问:
Read File and store element as array Scala
I am new to Scala and this is the first time I'm using it. I want to read in a textfile with with two columns of numbers and store each column items in a separate list or array that will have to be cast as integer. For example the textfile looks like this:

```<code>1 2
2 3
3 4
4 5
1 6
6 7
7 8
8 9
6 10
</code>```

I want to separate the two columns so that each column is stored in its on list or array.

答:
Here is one possible way of doing this:</p>

```<code>val file: String = ??? // path to .txt in String format
val source = Source.fromFile(file)

scala> val columnsTogether = source.getLines.map { line =>
  val nums = line.split(" ") // creating an array of just the 'numbers'
  (nums.head, nums.last) // assumes every line has TWO numbers only
}.toList
columnsTogether: List[(String, String)] = List((1,2), (2,3), (3,4), (4,5), (1,6), (6,7), (7,8), (8,9), (6,10))

scala> columnsTogether.map(_._1.toInt)
res0: List[Int] = List(1, 2, 3, 4, 1, 6, 7, 8, 6)

scala> columnsTogether.map(_._2.toInt)
res1: List[Int] = List(2, 3, 4, 5, 6, 7, 8, 9, 10)
</code>```

Body:
I am new to Scala and this is the first time I'm using it. I want to read in a textfile with with two columns of numbers and store each column items in a separate list or array that will have to be cast as integer. For example the textfile looks like this:

1 2
2 3
3 4
4 5
1 6
6 7
7 8
8 9
6 10

I want to separate the two columns so that each column is stored in its on list or array.

Body:
Here is one possible way of doing this:

val file: String = ??? // path to .txt in String format
val source = Source.fromFile(file)

scala> val columnsTogether = source.getLines.map { line =>
  val nums = line.split(" ") // creating an array of just the 'numbers'
  (nums.head, nums.last) // assumes every line has TWO numbers only
}.toList
columnsTogether: List[(String, String)] = List((1,2), (2,3), (3,4), (4,5), (1,6), (6,7), (7,8), (8,9), (6,10))

scala> columnsTogether.map(_._1.toInt)
res0: List[Int] = List(1, 2, 3, 4, 1, 6, 7, 8, 6)

scala> columnsTogether.map(_._2.toInt)
res1: List[Int] = List(2, 3, 4, 5, 6, 7, 8, 9, 10)


问:
PHP Session Variable not showing prior to unset being called
Basically I have the following code which is currently working fine as expected:

```<code>if ( isset($_SESSION['message']) )
    {
    echo '<p class="user_message">'.$_SESSION['message'].'</p>';

    //unset( $_SESSION['message'] );
    }
</code>```

As you can see the unset()  has been commented out. What I want to do is unset the session message after it has echo'd out. However when I run this code without the comments, the session variable is not echo'd out at all?

Many thanks in advance.

EDIT:

Thanks for responding, however this solution does not work and returns the same result as my original attempt. Here is the code which defines the session message:

```<code>$_SESSION['message'] = "";

// We know user email exists if the rows returned are more than 0
if ( $result->num_rows > 0 ) {

$_SESSION['message'] = $_SESSION['message'].'User with this email already         exists!<br />';

 }
// Validate email address
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {

$_SESSION['message'] = $_SESSION['message'].'Email address is invalid, please try again!<br />';

}
// Validate Referral code
if ( $refby != "" ) {
if ( (count_digit($refby) > 0 && count_digit($refby) < 6) || count_digit($refby) > 6 ) {
        $_SESSION['message'] = $_SESSION['message'].'Referral code is invalid!<br />';
} elseif ( !is_numeric($refby) ) {
        $_SESSION['message'] = $_SESSION['message'].'Referral code is invalid!<br />';
}
</code>```

}

```<code> // Validate password length
if ( count_digit($_POST['password']) < 6 ) {

$_SESSION['message'] = $_SESSION['message'].'Password invalid, must be more than 6 characters!<br />';
</code>```

}

```<code>// Validate password confirmed
if ( $_POST['password'] != $_POST['confirm_password'] ) {

$_SESSION['message'] = $_SESSION['message'].'Your passwords do not match!<br     />';
</code>```

}

```<code> if ( count_digit($num1)>2 || count_digit($num2)>2 || count_digit($num3)>2 ||       count_digit($num4)>2 || count_digit($num5)>2 ) {

$_SESSION['message'] = $_SESSION['message'].'Please select your lucky    numbers!<br />';
 }

if ( $_SESSION['message'] != "" ) {
header("location: #register_content");
</code>```

however, I dont understand how the code works perfectly prior to unsetting the session variable? even though the contents are echo'd prior to the session variable being unset?

Many thanks

答:
So for anyone interested.

This occurs because the script continues to run, not really sure how it works but basically once the session variable is removed, the script can no longer refer to it.

Once the session variable is unset in the script, exit(0); is required. This resolves the problem and the session variable is unset, however the script still echo's out the contents of the session variable prior to it being unset.

Body:
Basically I have the following code which is currently working fine as expected:

if ( isset($_SESSION['message']) )
    {
    echo '
'.$_SESSION['message'].'
';

    //unset( $_SESSION['message'] );
    }

As you can see the unset()  has been commented out. What I want to do is unset the session message after it has echo'd out. However when I run this code without the comments, the session variable is not echo'd out at all?

Many thanks in advance.

EDIT:

Thanks for responding, however this solution does not work and returns the same result as my original attempt. Here is the code which defines the session message:

$_SESSION['message'] = "";

// We know user email exists if the rows returned are more than 0
if ( $result->num_rows > 0 ) {

$_SESSION['message'] = $_SESSION['message'].'User with this email already         exists!
';

 }
// Validate email address
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {

$_SESSION['message'] = $_SESSION['message'].'Email address is invalid, please try again!
';

}
// Validate Referral code
if ( $refby != "" ) {
if ( (count_digit($refby) > 0 && count_digit($refby) < 6) || count_digit($refby) > 6 ) {
        $_SESSION['message'] = $_SESSION['message'].'Referral code is invalid!
';
} elseif ( !is_numeric($refby) ) {
        $_SESSION['message'] = $_SESSION['message'].'Referral code is invalid!
';
}

}

 // Validate password length
if ( count_digit($_POST['password']) < 6 ) {

$_SESSION['message'] = $_SESSION['message'].'Password invalid, must be more than 6 characters!
';

}

// Validate password confirmed
if ( $_POST['password'] != $_POST['confirm_password'] ) {

$_SESSION['message'] = $_SESSION['message'].'Your passwords do not match!
';

}

 if ( count_digit($num1)>2 || count_digit($num2)>2 || count_digit($num3)>2 ||       count_digit($num4)>2 || count_digit($num5)>2 ) {

$_SESSION['message'] = $_SESSION['message'].'Please select your lucky    numbers!
';
 }

if ( $_SESSION['message'] != "" ) {
header("location: #register_content");

however, I dont understand how the code works perfectly prior to unsetting the session variable? even though the contents are echo'd prior to the session variable being unset?

Many thanks


答:
```<code><?
print_r(getDatesFromRange( '2010-10-01', '2010-10-05' ));

function getDatesFromRange($startDate, $endDate)
{
    $return = array($startDate);
    $start = $startDate;
    $i=1;
    if (strtotime($startDate) < strtotime($endDate))
    {
       while (strtotime($start) < strtotime($endDate))
        {
            $start = date('Y-m-d', strtotime($startDate.'+'.$i.' days'));
            $return[] = $start;
            $i++;
        }
    }

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

ContentLicense: CC BY-SA 2.5

Title: PHP: Return all dates between two dates in an array

Body:
Expected Input:

getDatesFromRange( '2010-10-01', '2010-10-05' );

Expected Output:

Array( '2010-10-01', '2010-10-02', '2010-10-03', '2010-10-04', '2010-10-05' )


问:
Android ImageView won't load on CustomList with ViewHolder
I have a custom list view which I recently upgraded to use View Holder. Right now the project works fine but the images in the two Image Views don't show on the screen.

This two black icons appear "transparent" but work if I click them.

This is the layout:

```<code>  <?xml version="1.0" encoding="UTF-8"?>

    <LinearLayout xmlns:tools="http://schemas.android.com/tools"
        android:layout_height="match_parent"
    android:layout_width="match_parent"
    android:orientation="vertical"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:android="http://schemas.android.com/apk/res/android">

    <RelativeLayout
        android:layout_height="match_parent"
        android:layout_width="match_parent">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="horizontal">

            <ImageView
                android:id="@+id/imgInfo"
                android:layout_width="50dp"
                android:layout_height="50dp"
                android:layout_alignParentLeft="true"
                android:layout_alignParentStart="true"
                android:layout_alignParentTop="true"
                android:layout_marginTop="12dp"
                android:layout_weight="0.04"
                android:visibility="visible"
                app:srcCompat="@drawable/details64" />

            <LinearLayout
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentTop="true"
                android:layout_toEndOf="@+id/imgInfo"
                android:layout_toLeftOf="@+id/imgEdit"
                android:layout_toRightOf="@+id/imgInfo"
                android:layout_weight="0.24"
                android:orientation="vertical">

                <TextView
                    android:id="@+id/txtChamado"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:textAlignment="center"
                    android:textColor="@android:color/background_dark"
                    android:textSize="25sp" />

                <TextView
                    android:id="@+id/txtSolicitante"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:textAlignment="center"
                    android:textColor="@android:color/background_dark"
                    android:textSize="15sp" />

                <TextView
                    android:id="@+id/txtItemDeCatalogo"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:textAlignment="center"
                    android:textColor="@android:color/background_dark"
                    android:textSize="15sp" />
            </LinearLayout>

            <ImageView
                android:id="@+id/imgEdit"
                android:layout_width="50dp"
                android:layout_height="50dp"
                android:layout_alignParentEnd="true"
                android:layout_alignParentRight="true"
                android:layout_marginTop="12dp"
                android:layout_weight="0.03"
                android:contentDescription=""
                app:srcCompat="@drawable/pencil64" />
        </LinearLayout>

    </RelativeLayout>

</LinearLayout>
</code>```

This is the code snippet:

```<code> @Override
    public View getView(final int position, View view, final ViewGroup parent) {

        View convertView;
        ViewHolder holder;

        if (view == null) {
            convertView = LayoutInflater.from(context).inflate(R.layout.customized_list_view, parent, false);
            holder = new ViewHolder(convertView);
            convertView.setTag(holder);
        }else{
            convertView = view;
            holder = (ViewHolder) convertView.getTag();
        }

        //  Object declaration
        final Sette setteData = getItem(position);

        //region Put the Tasks values to the textviews
        // Get me two strings, one with the older value and one with the newest
            String oldChamado = holder.txtChamado.getText().toString();
            String newChamado = setteData.getChamado();
            // Do not repeat the string in the textview
            if (!(oldChamado.equals(newChamado))) {
                holder.txtChamado.setText(newChamado);
            }
     //region Click Listener for the button that leads to Approvals Activity
        if (!aBoolean) {
            holder.imgEdit.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {

                    chamadoClicked = setteData.getChamado();
                    solicitanteClicked = setteData.getSolicitante();
                    itemDeCatalogoClicked = setteData.getItemDeCatalogo();
                    id = setteData.getId();

                    Intent intent = new Intent(context.getApplicationContext(), ApprovalsActivity.class);
                    intent.putExtra("Id", id);
                    intent.putExtra("chamadoClicked", chamadoClicked);
                    intent.putExtra("solicitanteClicked", solicitanteClicked);
                    intent.putExtra("itemDeCatalogoClicked", itemDeCatalogoClicked);
                    context.startActivity(intent);
                }
            });
        }
        //endregion
 return convertView;
    }// END METHOD
</code>```

ViewHolder (which I got from an internet example):

```<code>  public class ViewHolder {
    TextView txtChamado;
    TextView txtSolicitante;
    TextView txtItemDeCatalogo;
    ImageView imgInfo, imgEdit;
    Typeface bebasKai;
    Typeface london;

    public ViewHolder(View view){
        bebasKai = Typeface.createFromAsset(context.getAssets(), "fonts/bebaskai.otf");
        london = Typeface.createFromAsset(context.getAssets(), "fonts/london.ttf");
        txtChamado = (TextView) view.findViewById(R.id.txtChamado);
        txtChamado.setTypeface(bebasKai);
        txtSolicitante = (TextView) view.findViewById(R.id.txtSolicitante);
        txtSolicitante.setTypeface(london);
        txtItemDeCatalogo = (TextView) view.findViewById(R.id.txtItemDeCatalogo);
        txtItemDeCatalogo.setTypeface(london);
        imgEdit = (ImageView) view.findViewById(R.id.imgEdit);
        imgInfo = (ImageView) view.findViewById(R.id.imgInfo);
    }
}
</code>```

I tried clean, rebuild, download the project from BitBucket again, reinstall the app from scratch on my phone, invalidade cache/restart and check the code.

Am I missing something obvious here?

**EDIT:**Thank you SaNtoRiaN, I knew it was something simple that I was missing.

答: Change app:srcCompat attribute in your ImageView to android:src to view your images properly. To know more about the difference, check this answer.

Body:
I have a custom list view which I recently upgraded to use View Holder. Right now the project works fine but the images in the two Image Views don't show on the screen.

This two black icons appear "transparent" but work if I click them.

This is the layout:

  <?xml version="1.0" encoding="UTF-8"?>

    <LinearLayout xmlns:tools="http://schemas.android.com/tools"
        android:layout_height="match_parent"
    android:layout_width="match_parent"
    android:orientation="vertical"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:android="http://schemas.android.com/apk/res/android">

    <RelativeLayout
        android:layout_height="match_parent"
        android:layout_width="match_parent">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="horizontal">

            <ImageView
                android:id="@+id/imgInfo"
                android:layout_width="50dp"
                android:layout_height="50dp"
                android:layout_alignParentLeft="true"
                android:layout_alignParentStart="true"
                android:layout_alignParentTop="true"
                android:layout_marginTop="12dp"
                android:layout_weight="0.04"
                android:visibility="visible"
                app:srcCompat="@drawable/details64" />

            <LinearLayout
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentTop="true"
                android:layout_toEndOf="@+id/imgInfo"
                android:layout_toLeftOf="@+id/imgEdit"
                android:layout_toRightOf="@+id/imgInfo"
                android:layout_weight="0.24"
                android:orientation="vertical">

                <TextView
                    android:id="@+id/txtChamado"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:textAlignment="center"
                    android:textColor="@android:color/background_dark"
                    android:textSize="25sp" />

                <TextView
                    android:id="@+id/txtSolicitante"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:textAlignment="center"
                    android:textColor="@android:color/background_dark"
                    android:textSize="15sp" />

                <TextView
                    android:id="@+id/txtItemDeCatalogo"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:textAlignment="center"
                    android:textColor="@android:color/background_dark"
                    android:textSize="15sp" />
            </LinearLayout>

            <ImageView
                android:id="@+id/imgEdit"
                android:layout_width="50dp"
                android:layout_height="50dp"
                android:layout_alignParentEnd="true"
                android:layout_alignParentRight="true"
                android:layout_marginTop="12dp"
                android:layout_weight="0.03"
                android:contentDescription=""
                app:srcCompat="@drawable/pencil64" />
        </LinearLayout>

    </RelativeLayout>

</LinearLayout>

This is the code snippet:

 @Override
    public View getView(final int position, View view, final ViewGroup parent) {

        View convertView;
        ViewHolder holder;

        if (view == null) {
            convertView = LayoutInflater.from(context).inflate(R.layout.customized_list_view, parent, false);
            holder = new ViewHolder(convertView);
            convertView.setTag(holder);
        }else{
            convertView = view;
            holder = (ViewHolder) convertView.getTag();
        }

        //  Object declaration
        final Sette setteData = getItem(position);

        //region Put the Tasks values to the textviews
        // Get me two strings, one with the older value and one with the newest
            String oldChamado = holder.txtChamado.getText().toString();
            String newChamado = setteData.getChamado();
            // Do not repeat the string in the textview
            if (!(oldChamado.equals(newChamado))) {
                holder.txtChamado.setText(newChamado);
            }
     //region Click Listener for the button that leads to Approvals Activity
        if (!aBoolean) {
            holder.imgEdit.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {

                    chamadoClicked = setteData.getChamado();
                    solicitanteClicked = setteData.getSolicitante();
                    itemDeCatalogoClicked = setteData.getItemDeCatalogo();
                    id = setteData.getId();

                    Intent intent = new Intent(context.getApplicationContext(), ApprovalsActivity.class);
                    intent.putExtra("Id", id);
                    intent.putExtra("chamadoClicked", chamadoClicked);
                    intent.putExtra("solicitanteClicked", solicitanteClicked);
                    intent.putExtra("itemDeCatalogoClicked", itemDeCatalogoClicked);
                    context.startActivity(intent);
                }
            });
        }
        //endregion
 return convertView;
    }// END METHOD

ViewHolder (which I got from an internet example):

  public class ViewHolder {
    TextView txtChamado;
    TextView txtSolicitante;
    TextView txtItemDeCatalogo;
    ImageView imgInfo, imgEdit;
    Typeface bebasKai;
    Typeface london;

    public ViewHolder(View view){
        bebasKai = Typeface.createFromAsset(context.getAssets(), "fonts/bebaskai.otf");
        london = Typeface.createFromAsset(context.getAssets(), "fonts/london.ttf");
        txtChamado = (TextView) view.findViewById(R.id.txtChamado);
        txtChamado.setTypeface(bebasKai);
        txtSolicitante = (TextView) view.findViewById(R.id.txtSolicitante);
        txtSolicitante.setTypeface(london);
        txtItemDeCatalogo = (TextView) view.findViewById(R.id.txtItemDeCatalogo);
        txtItemDeCatalogo.setTypeface(london);
        imgEdit = (ImageView) view.findViewById(R.id.imgEdit);
        imgInfo = (ImageView) view.findViewById(R.id.imgInfo);
    }
}

I tried clean, rebuild, download the project from BitBucket again, reinstall the app from scratch on my phone, invalidade cache/restart and check the code.

Am I missing something obvious here?

**EDIT:**Thank you SaNtoRiaN, I knew it was something simple that I was missing.


问:
Merge two rows into one and sum a column
THIS IS NOT ASKING HOW TO USE SUM() AND GROUP BY

I have two rows in tableA

```<code>ID VALUE
1  100
1  200
</code>```

I want tableA:

```<code>ID VALUE
1  300
</code>```

Note that I want to

delete the original two records in tableA

and replace them by the new record in tableA

Is this related to merge function?

I only want to work on tableA, don't want to create any new tables.

答:
How about MERGE:

```<code>;with cte as (
    select t.*,
    row_number() over (partition by id order by id) as rn,
    sum(value) over (partition by id) as total_value
    from your_table t
)
merge into cte as t
using cte as t2
on (
    t.id = t2.id
    and t.rn = t2.rn
    and t.rn = 1
)
when matched then update set t.value = t2.total_value
when not matched by source then delete;
</code>```

Demo

Body:
THIS IS NOT ASKING HOW TO USE SUM() AND GROUP BY

I have two rows in tableA

ID VALUE
1  100
1  200

I want tableA:

ID VALUE
1  300

Note that I want to

delete the original two records in tableA

and replace them by the new record in tableA

Is this related to merge function?

I only want to work on tableA, don't want to create any new tables.

Body:
How about MERGE:

;with cte as (
    select t.*,
    row_number() over (partition by id order by id) as rn,
    sum(value) over (partition by id) as total_value
    from your_table t
)
merge into cte as t
using cte as t2
on (
    t.id = t2.id
    and t.rn = t2.rn
    and t.rn = 1
)
when matched then update set t.value = t2.total_value
when not matched by source then delete;

Demo


问:
How do you track hosting / domain / SSL certificate expiry dates for customers?
Not a programming question per se, but interesting for people who do commercial web development.

How do you track all of your clients' hosting, domain registration, and SSL certificate expiry dates?

Do you just keep a spreadsheet or is there some useful piece of software for this?

I've searched extensively and can't find a usable piece of software and am tempted to write something.  With 100+ customers to manage, and with hosting and domain names spread across several hosting companies and registrars, my ad hoc means are failing.

答:
You can use a service like https://IsItWorking.info to track domain registration, and SSL certificate expiry.

You can set when you want to get notifications (e.g. 60 days before expiry) and it can notify you by email, slack or pushover.

(full disclosure: I wrote it!)

OwnerDisplayName: Quog


问:
How do I alert the latitude in this Google Maps javascript?
As you can see, there is a line in there that does an alert. It's "undefined".  Whereas if I just alert results[0].geometry.location, it alerts (41.321, 41.556).

I just want to alert it and set it (as an int) to one of my id_lat and id_longs...

```<code>$("#geocodesubmit").click(function(){
        $("#id_lat").val("");
        $("#id_long").val("");
        var address = $("#addressinput").val();
        geocoder.geocode( { 'address': address}, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            $("#badlocation_holder").hide();
            $("#map_canvas").show();
            $("#map_canvas_holder").show().css("background-color", "#E6E6FA").animate({"background-color":"#f5f5f5"}, 800);
            ;
            var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
            map.setCenter(results[0].geometry.location);

            alert(results[0].geometry.location[1]); //this is undefined.

            $("#id_lat").val(results[0].geometry.location[0]);
            $("#id_long").val(results[0].geometry.location[1]);

            var marker = new google.maps.Marker({
                map: map,
                position: results[0].geometry.location,
                draggable:true
            });
          } else {
              $("#map_canvas_holder").hide();
              $("#badlocation_holder").show().css("background-color","#F08080").animate(
              {"background-color":"#f5f5f5"},800);
          }
        });
        return false;
    });
</code>```

答:
If you look at the API, location isn't an array (that's the main issue here), it's a property, so .location is the correct way to access it, not .location[0].

The official documentation is a bit hard to find for specific types, but here are updated docs on that location (a LatLng type):

The toString() is what you're getting in an alert (lat, long), there's also .lat() for latitude and .lng() for longitude, like this:

```<code>alert(results[0].geometry.location.lat());
alert(results[0].geometry.location.lng());
</code>```

Body:
As you can see, there is a line in there that does an alert. It's "undefined".  Whereas if I just alert results[0].geometry.location, it alerts (41.321, 41.556).

I just want to alert it and set it (as an int) to one of my id_lat and id_longs...

$("#geocodesubmit").click(function(){
        $("#id_lat").val("");
        $("#id_long").val("");
        var address = $("#addressinput").val();
        geocoder.geocode( { 'address': address}, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            $("#badlocation_holder").hide();
            $("#map_canvas").show();
            $("#map_canvas_holder").show().css("background-color", "#E6E6FA").animate({"background-color":"#f5f5f5"}, 800);
            ;
            var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
            map.setCenter(results[0].geometry.location);

            alert(results[0].geometry.location[1]); //this is undefined.

            $("#id_lat").val(results[0].geometry.location[0]);
            $("#id_long").val(results[0].geometry.location[1]);

            var marker = new google.maps.Marker({
                map: map,
                position: results[0].geometry.location,
                draggable:true
            });
          } else {
              $("#map_canvas_holder").hide();
              $("#badlocation_holder").show().css("background-color","#F08080").animate(
              {"background-color":"#f5f5f5"},800);
          }
        });
        return false;
    });

Body:
If you look at the API, location isn't an array (that's the main issue here), it's a property, so .location is the correct way to access it, not .location[0].

The official documentation is a bit hard to find for specific types, but here are updated docs on that location (a LatLng type):

The toString() is what you're getting in an alert (lat, long), there's also .lat() for latitude and .lng() for longitude, like this:

alert(results[0].geometry.location.lat());
alert(results[0].geometry.location.lng());


问:
Exploration graphics in h2o
To whom may it concern,

Is it possible to plot an exploratory variable versus the target in h2o? I want to know whether it is possible to carry out basic data exploration in h2o, or whether it is not designed for that.

Many thanks in advance,
Kere

答:
the main plotting functionality for an H2O frame is for histograms (hist() in python and h2o.hist() in R).

Within Flow you can do basic data exploration if you import your dataframe, then click on inspect and then, next to the hyperlinked columns, you'll see a plot button which will let you get bar charts of counts for example and other plot types.

You can also easily convert single columns you want to plot into a pandas or R dataframe with
H2OFrame.as_data_frame() in python
as.data.frame.H2OFrame in R and then use the native python and R plotting methods

Title: Exploration graphics in h2o


问:
Draw canvas shape
I need to draw the following canvas shape. I can't figure out how to make it. I tried to use lineTo() but I'm having a hard time positioning those line segments. Moreover it doesn't take a curve shape.

The <canvas> size should be equal to 600x450. Thanks in advance.

答:
You can use method bezierCurveTo():

The CanvasRenderingContext2D.bezierCurveTo() method of the Canvas 2D API adds a cubic Bézier curve to the path. It requires three points. The first two points are control points and the third one is the end point. The starting point is the last point in the current path, which can be changed using moveTo() before creating the Bézier curve.

Here is a basic example:

const canvas = document.getElementById("opCanvas");
const ctx = canvas.getContext('2d');
ctx.beginPath();
ctx.lineWidth =5;
ctx.strokeStyle ='orange';
ctx.moveTo(150,0);
ctx.bezierCurveTo(0,125,300,175,150,300);
ctx.stroke();```
<pre class="snippet-code-html lang-html prettyprint-override"><code><canvas id ="opCanvas" width="600" height ="450"></code>```

Here is a helper tool for doing that: http://www.victoriakirst.com/beziertool/

Title: Draw canvas shape

Body:
You can use method bezierCurveTo():

The CanvasRenderingContext2D.bezierCurveTo() method of the Canvas 2D API adds a cubic Bézier curve to the path. It requires three points. The first two points are control points and the third one is the end point. The starting point is the last point in the current path, which can be changed using moveTo() before creating the Bézier curve.

Here is a basic example:

const canvas = document.getElementById("opCanvas");
const ctx = canvas.getContext('2d');
ctx.beginPath();
ctx.lineWidth =5;
ctx.strokeStyle ='orange';
ctx.moveTo(150,0);
ctx.bezierCurveTo(0,125,300,175,150,300);
ctx.stroke();

<canvas id ="opCanvas" width="600" height ="450">

Here is a helper tool for doing that: http://www.victoriakirst.com/beziertool/


问:
How to find unused images in an Xcode project?
Has anyone a one-line to find unused images in an Xcode project? (Assuming all the files are referenced by name in code or the project files - no code generated file names.)

These files tend to build up over the life of a project and it can be hard to tell if it's safe to delete any given png.

答: You can try FauxPas App for Xcode. It is really good in findings the missing images and a lot of other issues/ violations related to Xcode project.</p>

ContentLicense: CC BY-SA 4.0


问:
Saving and comparing SQLCe .sdf files in C#
I have a desktop WPF/MVVM application that will need to save/persist scientific data to a SQLCe database using Entity Framework.

The requirements are that the user should be able to save/export/open files as if they were simple word/excel/txt files meaning that just because the system saves to a database, this should be hidden from the user. The user needs to be able to share these "save files (really just a .sdf) with others so that they can import someone elses "save file" into their desktop client instance and compare his results to someone elses results.

I am trying to find out how I can abstract away the fact that there is a database being used for storage while at the same time allowing the freedom of using a open file dialog (for example) to enable the user to export his data file so others can import it into another instance of the desktop application.

There is also the need to compare two or more sets of data against each other. This could manifest as one user comparing his data in the .sdf db against another set of data in a .sdf file from another user.

Any ideas on how to approach this are appreciated.

答:
The Entity Framework allows you to work with databases including SQL CE files (currently using it for SQL CE files myself):
https://msdn.microsoft.com/en-us/library/aa937723(v=vs.113).aspx

The connection string contains the file path, so when you use the Open Dialog, you'll retrieve the path and pass it to your context which opens the database connection.

I use Code First which allows you to write C# configuration files that define the database structure (see the link above)

There are some complications with using SQLCE, such as multi-threading (the EF is not inherently thread-safe), and detaching / re-attaching entities.

For comparison between files, I would imagine that you can just create two contexts and write methods to loop through and compare entities across the two.  The slightly tricky parts will be what constitutes a match (is it the ID, matching properties or also child entities) and what to do for new entities.  Not terribly difficult but may require some thought.

I also use the Repository Pattern, which abstracts away operations such as CRUD operations.  This allows you to use multiple file formats or switch formats later on down the road.  For instance, I may switch to XML in the future.


问:
spring-boot secutiry - invoked method after authorizating user
I need to set some thing in context (more exactly it is database context holder) after successfull authentication user. I have properly configured spring-security. Credentials are passed by headers (but here It doesn't matter). Sequent requestsa are augmented by SESSION ID.

Everything is fine, I need only to implement some function which is automatically invoked immediately after acceptance of the request as authorized.

How to do it ?

答:
When an authentication successfully completes, Spring Security will fire a AuthenticationSuccessEvent event. You just need to register an event listener to listen to that event and provide a callback which will be executed after this event being fired:

```<code>@Component
class SuccessfulAuthenticationListener implements ApplicationListener<AuthenticationSuccessEvent> {
    @Override
    public void onApplicationEvent(AuthenticationSuccessEvent event) {
        // Put the function which is automatically invoked immediately
        // after acceptance of the request as authorized.
    }
}
</code>```

In order to intercept every authorized request, just register a plain filter and check that if user is authenticated or not:

```<code>@Component
class AuthorizedRequestFilter extends OncePerRequestFilter {
    @Override
    protected void doFilterInternal(HttpServletRequest request,
                                    HttpServletResponse response,
                                    FilterChain filterChain) throws ServletException, IOException {

        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication != null && authentication.isAuthenticated()) {
            // do whatever is necessary
        }

        filterChain.doFilter(request, response);
    }
}
</code>```

Body:
When an authentication successfully completes, Spring Security will fire a AuthenticationSuccessEvent event. You just need to register an event listener to listen to that event and provide a callback which will be executed after this event being fired:

@Component
class SuccessfulAuthenticationListener implements ApplicationListener<AuthenticationSuccessEvent> {
    @Override
    public void onApplicationEvent(AuthenticationSuccessEvent event) {
        // Put the function which is automatically invoked immediately
        // after acceptance of the request as authorized.
    }
}

In order to intercept every authorized request, just register a plain filter and check that if user is authenticated or not:

@Component
class AuthorizedRequestFilter extends OncePerRequestFilter {
    @Override
    protected void doFilterInternal(HttpServletRequest request,
                                    HttpServletResponse response,
                                    FilterChain filterChain) throws ServletException, IOException {

        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication != null && authentication.isAuthenticated()) {
            // do whatever is necessary
        }

        filterChain.doFilter(request, response);
    }
}


问:
XAMPP relative URLs working on WordPress home but not pages
I have a testing site at tektonpress.piconmedia.com that is working correctly.

I'm having some problems with relative URLs and images on a local version.

I installed XAMPP, restored a copy of the database to my local machine, and copied FTP files over. After updating wp-config.php, just about everything is working correctly. That includes images that use relative URLs in my stylesheets.

My problem is with some images that I try to load through HTML. They display correctly on the home page, but not from other pages.

For example, the following HTML works on localhost/tektonpress/ but not localhost/tektonpress/editing/:

```<code><img src="resources/img/logo-white.png" alt="Tekton Press logo">
</code>```

Here's an example when the image doesn't work:

Example from page

The image in question is located at C:\xampp\htdocs\tektonpress\resources\img\logo-white.png

When I hover over the URL while inspecting the element in Chrome, here's what I see:

One layer too deep

I tried adding a slash to the front of the path, like so:

```<code><img src="/resources/img/logo-white.png" alt="Tekton Press logo">
</code>```

Unfortunately, the page ends up looking for the image at /localhost/resources/img/logo-white.png.

I've spent several hours on this with no luck. I thought I'd finally found a simple (but potentially maintenance-heavy) solution at stackoverflow.com/questions/7823260/xampp-relative-urls-not-working-correctly, but just ended up with a server error.

Here's the contents of my .htaccess file:

```<code><IfModule mod_rewrite.c>

RewriteEngine On

RewriteBase /tektonpress/

RewriteRule ^index\.php$ - [L]

RewriteCond %{REQUEST_FILENAME} !-f

RewriteCond %{REQUEST_FILENAME} !-d

RewriteRule . /tektonpress/index.php [L]

</IfModule>
</code>```

Any suggestions?

答:
Try using get_template_directory_uri().'/resources/img/logo-white.png'

It should work. As I am assuming resources is in the base of your theme directory.

Body:
I have a testing site at tektonpress.piconmedia.com that is working correctly.

I'm having some problems with relative URLs and images on a local version.

I installed XAMPP, restored a copy of the database to my local machine, and copied FTP files over. After updating wp-config.php, just about everything is working correctly. That includes images that use relative URLs in my stylesheets.

My problem is with some images that I try to load through HTML. They display correctly on the home page, but not from other pages.

For example, the following HTML works on localhost/tektonpress/ but not localhost/tektonpress/editing/:

Here's an example when the image doesn't work:

Example from page

The image in question is located at C:\xampp\htdocs\tektonpress\resources\img\logo-white.png

When I hover over the URL while inspecting the element in Chrome, here's what I see:

One layer too deep

I tried adding a slash to the front of the path, like so:

Unfortunately, the page ends up looking for the image at /localhost/resources/img/logo-white.png.

I've spent several hours on this with no luck. I thought I'd finally found a simple (but potentially maintenance-heavy) solution at stackoverflow.com/questions/7823260/xampp-relative-urls-not-working-correctly, but just ended up with a server error.

Here's the contents of my .htaccess file:

<IfModule mod_rewrite.c>

RewriteEngine On

RewriteBase /tektonpress/

RewriteRule ^index\.php$ - [L]

RewriteCond %{REQUEST_FILENAME} !-f

RewriteCond %{REQUEST_FILENAME} !-d

RewriteRule . /tektonpress/index.php [L]

</IfModule>

Any suggestions?


问:
Insert page number with text in footer aspose word java
I want to insert page number in footer alongside with text, but when footer contains some text, page number and text in footer switch places.
I am doing this while converting document from html to word using aspose words java library.
Text in footer is sent from html and I just want to add page number.

Code for add page number in footer:

```<code>log.debug("Add page number");
DocumentBuilder builder = new DocumentBuilder(doc);

// Insert PAGE field into the footer
builder.moveToHeaderFooter(HeaderFooterType.FOOTER_PRIMARY);
builder.insertField("PAGE", null);
builder.write("/");
builder.insertField("NUMPAGES", null);
</code>```

Also, is there any way to replace whole text in footer?

答:
You can add page numbers and text together in footer using table as following:

```<code>DocumentBuilder builder = new DocumentBuilder(doc);
// Insert PAGE field into the footer
builder.moveToHeaderFooter(HeaderFooterType.FOOTER_PRIMARY);
builder.startTable();
// Clear table borders
builder.getCellFormat().clearFormatting();
builder.insertCell();
// Set first cell to 1/3 of the page width.
builder.getCellFormat().setPreferredWidth(
PreferredWidth.fromPercent(100 / 3));
// Insert page numbering text here.
// It uses PAGE and NUMPAGES fields to auto calculate current page
// number and total number of pages.
builder.insertField("PAGE", null);
builder.write("/");
builder.insertField("NUMPAGES", null);
// Align this text to the left.
builder.getCurrentParagraph().getParagraphFormat()
.setAlignment(ParagraphAlignment.LEFT);
builder.insertCell();
// Set the second cell to 2/3 of the page width.
builder.getCellFormat().setPreferredWidth(
PreferredWidth.fromPercent(100 * 2 / 3));
builder.write("(C) 2017 Aspose Pty Ltd. All rights reserved.");
// Align this text to the right.
builder.getCurrentParagraph().getParagraphFormat()
.setAlignment(ParagraphAlignment.RIGHT);
builder.endRow();
builder.endTable();
</code>```

To replace whole text of footer you may access the footer, clear all text and add new contents as following:

```<code>DocumentBuilder builder = new DocumentBuilder(doc);
Section currentSection = builder.getCurrentSection();
com.aspose.words.HeaderFooter primaryHeader =  currentSection.getHeadersFooters().getByHeaderFooterType(HeaderFooterType.FOOTER_PRIMARY);
primaryHeader.getParagraphs().clear();
...
</code>```

I am Tilal Ahmad, developer evangelist at Aspose.

Body:
I want to insert page number in footer alongside with text, but when footer contains some text, page number and text in footer switch places.
I am doing this while converting document from html to word using aspose words java library.
Text in footer is sent from html and I just want to add page number.

Code for add page number in footer:

log.debug("Add page number");
DocumentBuilder builder = new DocumentBuilder(doc);

// Insert PAGE field into the footer
builder.moveToHeaderFooter(HeaderFooterType.FOOTER_PRIMARY);
builder.insertField("PAGE", null);
builder.write("/");
builder.insertField("NUMPAGES", null);

Also, is there any way to replace whole text in footer?

Body:
You can add page numbers and text together in footer using table as following:

DocumentBuilder builder = new DocumentBuilder(doc);
// Insert PAGE field into the footer
builder.moveToHeaderFooter(HeaderFooterType.FOOTER_PRIMARY);
builder.startTable();
// Clear table borders
builder.getCellFormat().clearFormatting();
builder.insertCell();
// Set first cell to 1/3 of the page width.
builder.getCellFormat().setPreferredWidth(
PreferredWidth.fromPercent(100 / 3));
// Insert page numbering text here.
// It uses PAGE and NUMPAGES fields to auto calculate current page
// number and total number of pages.
builder.insertField("PAGE", null);
builder.write("/");
builder.insertField("NUMPAGES", null);
// Align this text to the left.
builder.getCurrentParagraph().getParagraphFormat()
.setAlignment(ParagraphAlignment.LEFT);
builder.insertCell();
// Set the second cell to 2/3 of the page width.
builder.getCellFormat().setPreferredWidth(
PreferredWidth.fromPercent(100 * 2 / 3));
builder.write("(C) 2017 Aspose Pty Ltd. All rights reserved.");
// Align this text to the right.
builder.getCurrentParagraph().getParagraphFormat()
.setAlignment(ParagraphAlignment.RIGHT);
builder.endRow();
builder.endTable();

To replace whole text of footer you may access the footer, clear all text and add new contents as following:

DocumentBuilder builder = new DocumentBuilder(doc);
Section currentSection = builder.getCurrentSection();
com.aspose.words.HeaderFooter primaryHeader =  currentSection.getHeadersFooters().getByHeaderFooterType(HeaderFooterType.FOOTER_PRIMARY);
primaryHeader.getParagraphs().clear();
...

I am Tilal Ahmad, developer evangelist at Aspose.


问:
Android - Drag and Drop - Animation shadow to destination
I want to animate a ShadowView to some coordinates (to destination view).

I'm using D&D and if user drops (DragEvent.ACTION_DROP) then the view in some area I want to animate the view (from the drop location) to some destination view.

I don't want to animate view from the source location but want to do from the DROP location.

I tried a lot of things but nothing works. How can I get access to the ShadowView? This also not working:

```<code>EventDragShadowBuilder.getView()
</code>```

I think TranslateAnimation should work for this but I need access to the "shadow" view during the D&D.

Image:

答:
One possible thing could be

once the drag event has finished, you can move the "view" to the location of the drop and then you can start an animation to move the view from the dropped location to the destination.

Keep in mind here the drag shadow is not being animated but the view itself is being animated.

Body:
I want to animate a ShadowView to some coordinates (to destination view).

I'm using D&D and if user drops (DragEvent.ACTION_DROP) then the view in some area I want to animate the view (from the drop location) to some destination view.

I don't want to animate view from the source location but want to do from the DROP location.

I tried a lot of things but nothing works. How can I get access to the ShadowView? This also not working:

EventDragShadowBuilder.getView()

I think TranslateAnimation should work for this but I need access to the "shadow" view during the D&D.

Image:


问:
Is this string Base64? How can I tell what is the encoding used?
This is a puzzle to me and I am really annoyed that I cannot solve it! So, if anyone has some free time I would like to here some suggestions on how to solve it!

I use a software that stores the password in an oracle database. The password field is of type Varchar2(100 char). It seems to me that the software encodes the passwords and stores the encoded string in the database.

My password is '1234' and the encoded string is 'cRDtpNCeBiql5KOQsKVyrA0sAiA='. All the passwords in the database are 28 characters long.

The puzzle that I have assigned to myself is to find the encoding and/or encryption of the string. My first check was on Base64

So here is my first test in python (idle):

```<code>>>> import base64
>>> encoded = 'cRDtpNCeBiql5KOQsKVyrA0sAiA='
>>> decoded = base64.b64decode(encoded)
>>> decoded
'q\x10\xed\xa4\xd0\x9e\x06*\xa5\xe4\xa3\x90\xb0\xa5r\xac\r,\x02 '
>>> print decoded
qíﾤО*ﾥ䣐ﾰﾥrﾬ
</code>```

,

Here is my second test:

```<code>>>> myString = '1234'
>>> encoded = base64.b64encode(myString)
>>> encoded
'MTIzNA=='
>>> decoded = base64.b64decode('MTIzNA==')
>>> decoded
'1234'
</code>```

So, my first thought is that this is not Base64 encoded. After I checked wikipedia (https://en.wikipedia.org/wiki/Base64) it seems that Base64 encoded strings are not of fixed size. My second thought is that the string was encrypted and then encoded into Base64 and that is why I get the weird-looking decoded string.

Any ideas?

答:
While len(decoded) = 20 then I guess that this is Base64 encoded SHA1 hash.

You can create such coded passwords by:

```<code>import hashlib
import base64
passwd = '1234'
hp = base64.b64encode(hashlib.sha1(passwd).digest())
print hp
print len(hp)
</code>```

As for such storing passwords: it is not very good while many crackers can use "rainbow" tables with precomputed MD5, SHA1 and other hashes and they can get password based on such hash. To prevent it "salt" should be used: hash(salt+passwd), such salt can be random string saved in database per user or for example user login (something that never can be changed).

Body:
This is a puzzle to me and I am really annoyed that I cannot solve it! So, if anyone has some free time I would like to here some suggestions on how to solve it!

I use a software that stores the password in an oracle database. The password field is of type Varchar2(100 char). It seems to me that the software encodes the passwords and stores the encoded string in the database.

My password is '1234' and the encoded string is 'cRDtpNCeBiql5KOQsKVyrA0sAiA='. All the passwords in the database are 28 characters long.

The puzzle that I have assigned to myself is to find the encoding and/or encryption of the string. My first check was on Base64

So here is my first test in python (idle):

>>> import base64
>>> encoded = 'cRDtpNCeBiql5KOQsKVyrA0sAiA='
>>> decoded = base64.b64decode(encoded)
>>> decoded
'q\x10\xed\xa4\xd0\x9e\x06*\xa5\xe4\xa3\x90\xb0\xa5r\xac\r,\x02 '
>>> print decoded
qíﾤО*ﾥ䣐ﾰﾥrﾬ

,

Here is my second test:

>>> myString = '1234'
>>> encoded = base64.b64encode(myString)
>>> encoded
'MTIzNA=='
>>> decoded = base64.b64decode('MTIzNA==')
>>> decoded
'1234'

So, my first thought is that this is not Base64 encoded. After I checked wikipedia (https://en.wikipedia.org/wiki/Base64) it seems that Base64 encoded strings are not of fixed size. My second thought is that the string was encrypted and then encoded into Base64 and that is why I get the weird-looking decoded string.

Any ideas?

Body:
While len(decoded) = 20 then I guess that this is Base64 encoded SHA1 hash.

You can create such coded passwords by:

import hashlib
import base64
passwd = '1234'
hp = base64.b64encode(hashlib.sha1(passwd).digest())
print hp
print len(hp)

As for such storing passwords: it is not very good while many crackers can use "rainbow" tables with precomputed MD5, SHA1 and other hashes and they can get password based on such hash. To prevent it "salt" should be used: hash(salt+passwd), such salt can be random string saved in database per user or for example user login (something that never can be changed).


问:
AttributeError for exception subprocess.TimeoutExpired
I have a python3 code that uses subprocess exception TimeoutExpired, but I need this to run on python2. My code is a simple try and except subprocess.TimeoutExpired but it is only available on python3. I apologise for the simplicity of the question. What can I do about this?</p>

答: The timeout feature is available on Python 2.x via the subprocess32 backport of the 3.2+ subprocess module. You can get the module here


问:
Bootstrap background images grid
I'm starting with bootstrap, learning tutorials, etc. I want to build a page with only images (many) forming a background, with no borders and space between them. Kind of mosaic.

Have tried many things, including some tutorial bootstrap grid system but I didnt found a clue.

I've found some jQuery stuff, but using bootstrap would be a plus. Could it be responsive?

```<code><div class="container">
  <div class="row">
    <div class="col-lg-6">
      <img src="http://www.streetartutopia.com/wp-content/uploads/2012/11/Street-Art-by-David-Walker-in-London-England.jpg" class="img-responsive" alt="Responsive image">
     </div>
   </div>
 </div>
</code>```

答:
This worked for me, this should give a line of 6 images tight together.
Could be for two images "col-md-6" or three with "col-md-4".
Its important to make css for "#image-div .col-md-2" or "#image-div .row" so as to not effect these classes in other grids in the page only within #image-div or whatever you call it.

CSS PART

```<code><style>
    #image-div .row{
      margin-top:0px ;
      margin-bottom:0px ;
      margin-left:0px ;
      margin-right:0px ;
      padding-top:0px ;
      padding-bottom:0px ;
      padding-left:0px ;
      padding-right:0px ;
    }
    #image-div .col-md-2{
      margin-top:0px ;
      margin-bottom:0px ;
      margin-left:0px ;
      margin-right:0px ;
      padding-top:0px ;
      padding-bottom:0px ;
      padding-left:0px ;
      padding-right:0px ;
    }

  </style>
</code>```

HTML PART

```<code>   <div class="row">
        <div class="col-md-2">image.jpg</div>
        <div class="col-md-2">image.jpg</div>
        <div class="col-md-2">image.jpg</div>
        <div class="col-md-2">image.jpg</div>
        <div class="col-md-2">image.jpg</div>
        <div class="col-md-2">image.jpg</div>
   </div>
</code>```

Title: Bootstrap background images grid

Body:
This worked for me, this should give a line of 6 images tight together.
Could be for two images "col-md-6" or three with "col-md-4".
Its important to make css for "#image-div .col-md-2" or "#image-div .row" so as to not effect these classes in other grids in the page only within #image-div or whatever you call it.

CSS PART

<style>
    #image-div .row{
      margin-top:0px ;
      margin-bottom:0px ;
      margin-left:0px ;
      margin-right:0px ;
      padding-top:0px ;
      padding-bottom:0px ;
      padding-left:0px ;
      padding-right:0px ;
    }
    #image-div .col-md-2{
      margin-top:0px ;
      margin-bottom:0px ;
      margin-left:0px ;
      margin-right:0px ;
      padding-top:0px ;
      padding-bottom:0px ;
      padding-left:0px ;
      padding-right:0px ;
    }

  </style>

HTML PART

   <div class="row">
        <div class="col-md-2">image.jpg</div>
        <div class="col-md-2">image.jpg</div>
        <div class="col-md-2">image.jpg</div>
        <div class="col-md-2">image.jpg</div>
        <div class="col-md-2">image.jpg</div>
        <div class="col-md-2">image.jpg</div>
   </div>


问:
What are some Servlet Container pros and cons for a Solr installation?
The SolrInstall wiki page lists seven different server / Servlet Containers compatible with Solr:

Tomcat

Jetty

Resin

JBoss

WebSphere

Weblogic

Glassfish

I'm sure that "best" is subjective, so I'll just say my criteria are: easiest to set up, best for search performance with a smallish, infrequently-updated dataset, and with the fewest number of gotchas.

Jetty and Tomcat both have apt-get solr packages, so they're clearly the frontrunners for some.  Jetty is used in the demo install, but there's some notes that Jetty has some difficulties handling Unicode in some cases.  Tomcat is a common choice but my understanding is that it's not as lightweight and has a lot of features not needed by Solr.

Is it worth considering any of the others?  Are there some important pro's and cons I should be aware of?

答:
Following Solr5, Solr should be used as a blackbox.

https://cwiki.apache.org/confluence/display/solr/Major+Changes+from+Solr+4+to+Solr+5

http://grokbase.com/t/lucene/solr-user/15772hc1jd/jetty-in-solr-5-2-0

As of Solr6, it is still using Jetty but Solr developers may make their own application server mechanism in the future. Solr should be used as a service, and not as a war anymore.


问:
Java Enums, JPA and Postgres enums - How do I make them work together?
We have a postgres DB with postgres enums. We are starting to build JPA into our application. We also have Java enums which mirror the postgres enums. Now the big question is how to get JPA to understand Java enums on one side and postgres enums on the other? The Java side should be fairly easy but I'm not sure how to do the postgres side.</p>

答:
I've actually been using a simpler way than the one with PGObject and Converters. Since in Postgres enums are converted quite naturally to-from text you just need to let it do what it does best. I'll borrow Arjan's example of moods, if he doesn't mind:

The enum type in Postgres:

```<code>CREATE TYPE mood AS ENUM ('sad', 'ok', 'happy');
</code>```

The class and enum in Java:

```<code>public @Entity class Person {

  public static enum Mood {sad, ok, happy};

  @Enumerated(EnumType.STRING)
  Mood mood;
</code>```

}

That @Enumerated tag says that serialization/deserialization of the enum should be done in text. Without it, it uses int, which is more troublesome than anything.

At this point you have two options. You either:

Add stringtype=unspecified to the connection string, as explained in JDBC connection parameters.This lets Postgres guess the right-side type and convert everything adequately, since it receives something like 'enum = unknown', which is an expression it already knows what to do with (feed the ? value to the left-hand type deserialiser). This is the preferred option, as it should work for all simple UDTs such as enums in one go.

```<code>jdbc:postgresql://localhost:5432/dbname?stringtype=unspecified
</code>```

Or:

Create an implicit conversion from varchar to the enum in the database. So in this second case the database receives some assignment or comparison like 'enum = varchar' and it finds a rule in its internal catalog saying that it can pass the right-hand value through the serialization function of varchar followed by the deserialization function of the enum. That's more steps than should be needed; and having too many implicit casts in the catalog can cause arbitrary queries to have ambiguous interpretations, so use it sparingly. The cast creation is:

CREATE CAST (CHARACTER VARYING as mood) WITH INOUT AS IMPLICIT;

Should work with just that.

Body:
I've actually been using a simpler way than the one with PGObject and Converters. Since in Postgres enums are converted quite naturally to-from text you just need to let it do what it does best. I'll borrow Arjan's example of moods, if he doesn't mind:

The enum type in Postgres:

CREATE TYPE mood AS ENUM ('sad', 'ok', 'happy');

The class and enum in Java:

public @Entity class Person {

  public static enum Mood {sad, ok, happy};

  @Enumerated(EnumType.STRING)
  Mood mood;

}

That @Enumerated tag says that serialization/deserialization of the enum should be done in text. Without it, it uses int, which is more troublesome than anything.

At this point you have two options. You either:

Add stringtype=unspecified to the connection string, as explained in JDBC connection parameters.This lets Postgres guess the right-side type and convert everything adequately, since it receives something like 'enum = unknown', which is an expression it already knows what to do with (feed the ? value to the left-hand type deserialiser). This is the preferred option, as it should work for all simple UDTs such as enums in one go.

jdbc:postgresql://localhost:5432/dbname?stringtype=unspecified

Or:

Create an implicit conversion from varchar to the enum in the database. So in this second case the database receives some assignment or comparison like 'enum = varchar' and it finds a rule in its internal catalog saying that it can pass the right-hand value through the serialization function of varchar followed by the deserialization function of the enum. That's more steps than should be needed; and having too many implicit casts in the catalog can cause arbitrary queries to have ambiguous interpretations, so use it sparingly. The cast creation is:

CREATE CAST (CHARACTER VARYING as mood) WITH INOUT AS IMPLICIT;

Should work with just that.


问:
How do I identify language of a text document in Java?
Is there an existing Java library that could tell me whether a String contains English language text or not (e.g. I need to be able to distinguish French or Italian text -- the function needs to return false for French and Italian, and true for English)?</p>

答: Here's an interesting blog post that discusses this concept. The examples are in Scala, but you should be able to apply the same general concepts to Java.</p>

OwnerDisplayName: anonymous coward

LastEditorDisplayName: Neil Coffey

OwnerDisplayName: mipadi


问:
Downloading files from the most recent directory with wget or curl
I have the following, particular situation: FTP server at ftp://ftp.sanger.ac.uk/pub/gencode/Gencode_mouse/ contains directories with various versions of mouse genome sequences (M1-M13). I would like to be able to tell wget or curl to enter the most recent (i.e. newest) directory, without having to manually check which one that is, so that I can download the newest versions of files that I need for my work using a bash script/oneliner, without having to check the latest version number beforehand.

So, something like:

```<code>wget ftp://ftp.sanger.ac.uk/pub/gencode/Gencode_mouse/release_M**(newest)**/*.primary_assembly.genome.fa.gz
</code>```

I don't know how to pass the (newest) part to wget or curl.

答:
I'm not sure if this is what you are looking for but here,</p>

```<code>#! /bin/bash
##
# Get latest version
LATEST=$(curl -s4 ftp://ftp.sanger.ac.uk/pub/gencode/Gencode_mouse/ | grep -Eo 'release_M[0-9]+' | sort -nrt M -k2,2 | head -n 1)

# Download from latest folder but only if match pattern
wget -r -A '*.primary_assembly.genome.fa.gz' "ftp://ftp.sanger.ac.uk/pub/gencode/Gencode_mouse/$LATEST/"
</code>```

Body:
I have the following, particular situation: FTP server at ftp://ftp.sanger.ac.uk/pub/gencode/Gencode_mouse/ contains directories with various versions of mouse genome sequences (M1-M13). I would like to be able to tell wget or curl to enter the most recent (i.e. newest) directory, without having to manually check which one that is, so that I can download the newest versions of files that I need for my work using a bash script/oneliner, without having to check the latest version number beforehand.

So, something like:

wget ftp://ftp.sanger.ac.uk/pub/gencode/Gencode_mouse/release_M**(newest)**/*.primary_assembly.genome.fa.gz

I don't know how to pass the (newest) part to wget or curl.

Body:
I'm not sure if this is what you are looking for but here,

#! /bin/bash
##
# Get latest version
LATEST=$(curl -s4 ftp://ftp.sanger.ac.uk/pub/gencode/Gencode_mouse/ | grep -Eo 'release_M[0-9]+' | sort -nrt M -k2,2 | head -n 1)

# Download from latest folder but only if match pattern
wget -r -A '*.primary_assembly.genome.fa.gz' "ftp://ftp.sanger.ac.uk/pub/gencode/Gencode_mouse/$LATEST/"


问:
lightgallery library + lg-thumbnail plugin
I'm trying to setup lightgallery with lg-thumbnail plugin in a WordPress installation.

https://sachinchoolur.github.io/lightGallery/docs/api.html

https://sachinchoolur.github.io/lightGallery/docs/api.html#lg-thumbnial

Lightgallery alone seems to work without problems (so, HTML markup and enqueued script is OK) with this JS init:

```<code>    $(document).ready(function() {
        $("#gallery-1").lightGallery();
    });
</code>```

So, my next step is to include lg-thumbnail plugin. After enqueue plugin JS I add thumbnail:true:

```<code>    $(document).ready(function() {
        $("#gallery-1").lightGallery({
          thumbnail:true
        });
    });
</code>```

But nothing happens. There is no errors in the console. Seems like there is no lg-thumbnail plugin present at all.

But, script is in its place:

What am I doing wrong?
How can I diagnose the problem?
Thank you!

答:
Sorry about that, everything works fine, including thumbnail plugin. I was worng with what was the plugin function. I thought that this plugin acts on the thumbnails before lightbox was launched, but actually insert thumbnails in the lightbox after it is launched.

My apologies.

Body:
I'm trying to setup lightgallery with lg-thumbnail plugin in a WordPress installation.

https://sachinchoolur.github.io/lightGallery/docs/api.html

https://sachinchoolur.github.io/lightGallery/docs/api.html#lg-thumbnial

Lightgallery alone seems to work without problems (so, HTML markup and enqueued script is OK) with this JS init:

    $(document).ready(function() {
        $("#gallery-1").lightGallery();
    });

So, my next step is to include lg-thumbnail plugin. After enqueue plugin JS I add thumbnail:true:

    $(document).ready(function() {
        $("#gallery-1").lightGallery({
          thumbnail:true
        });
    });

But nothing happens. There is no errors in the console. Seems like there is no lg-thumbnail plugin present at all.

But, script is in its place:

What am I doing wrong?
How can I diagnose the problem?
Thank you!


问:
Ajax ignores html validation
```<code>$('#addProduct').click(function (e) {
        $('#qty').attr('required', 'required');
        $('#product_id').attr('required', 'required');
        e.preventDefault();

var product_id = $('#product_id').val();
        var data = $("#editOrderContent").serializeArray();
        data.push(addProduct);

    $.ajax({
        type: 'POST',
        dataType: 'JSON',
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        },
        url: $('#editOrderContent').attr('action'),
        data: data,

        success: function (html) {
            if (html.error) {
                $('.wrap_result')
                    .text(html.error)
                    .fadeIn(500).delay(3000).fadeOut(500);
            }
            else if (html.success) {
                $('#summary').before(html.tdProduct);
                $('#summary_qty').text(html.summaries['qty']);
                $('#summary_price').text(html.summaries['price'] + ' $.');
                $('#summary_sum').text(html.summaries['sum'] + ' $.');
                $('#product_id').val('');
                $('#qty').val(1);
            }
        }
    });
});
</code>```

These 2 fields has required attributes but ajax still completing even with empty values in these fields, also ajax ignores min value of #qty field

Why is this happening?

答: Use $('#formid').valid() method before making ajax request read more about .valid()

Title: Ajax ignores html validation

Body:
$('#addProduct').click(function (e) {
        $('#qty').attr('required', 'required');
        $('#product_id').attr('required', 'required');
        e.preventDefault();

var product_id = $('#product_id').val();
        var data = $("#editOrderContent").serializeArray();
        data.push(addProduct);

    $.ajax({
        type: 'POST',
        dataType: 'JSON',
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        },
        url: $('#editOrderContent').attr('action'),
        data: data,

        success: function (html) {
            if (html.error) {
                $('.wrap_result')
                    .text(html.error)
                    .fadeIn(500).delay(3000).fadeOut(500);
            }
            else if (html.success) {
                $('#summary').before(html.tdProduct);
                $('#summary_qty').text(html.summaries['qty']);
                $('#summary_price').text(html.summaries['price'] + ' $.');
                $('#summary_sum').text(html.summaries['sum'] + ' $.');
                $('#product_id').val('');
                $('#qty').val(1);
            }
        }
    });
});

These 2 fields has required attributes but ajax still completing even with empty values in these fields, also ajax ignores min value of #qty field

Why is this happening?