问:
How do detect that transaction has already been started?
I am using Zend_Db to insert some data inside a transaction. My function starts a transaction and then calls another method that also attempts to start a transaction and of course fails(I am using MySQL5). So, the question is - how do I detect that transaction has already been  started?
Here is a sample bit of code:

```<code>       try {
                    Zend_Registry::get('database')->beginTransaction();

                    $totals = self::calculateTotals($Cart);
                    $PaymentInstrument = new PaymentInstrument;
                    $PaymentInstrument->create();
                    $PaymentInstrument->validate();
                    $PaymentInstrument->save();

                    Zend_Registry::get('database')->commit();
                    return true;

            } catch(Zend_Exception $e) {
                    Bootstrap::$Log->err($e->getMessage());
                    Zend_Registry::get('database')->rollBack();
                    return false;
            }
</code>```

Inside PaymentInstrument::create there is another beginTransaction statement that produces the exception that says that transaction has already been started.

答: This discussion is fairly old. As some have pointed out, you can do it in your application. PHP has a method since version 5 >= 5.3.3 to know if you are in the middle of a transaction. PDP::inTransaction() returns true or false.  Link http://php.net/manual/en/pdo.intransaction.php </p>

Body:
I am using Zend_Db to insert some data inside a transaction. My function starts a transaction and then calls another method that also attempts to start a transaction and of course fails(I am using MySQL5). So, the question is - how do I detect that transaction has already been  started?
Here is a sample bit of code:

       try {
                    Zend_Registry::get('database')->beginTransaction();

                    $totals = self::calculateTotals($Cart);
                    $PaymentInstrument = new PaymentInstrument;
                    $PaymentInstrument->create();
                    $PaymentInstrument->validate();
                    $PaymentInstrument->save();

                    Zend_Registry::get('database')->commit();
                    return true;

            } catch(Zend_Exception $e) {
                    Bootstrap::$Log->err($e->getMessage());
                    Zend_Registry::get('database')->rollBack();
                    return false;
            }

Inside PaymentInstrument::create there is another beginTransaction statement that produces the exception that says that transaction has already been started.


来源: stackexchange

问:
Unable to click the element. Error: no such element: Unable to locate element:
I am practicing on flipkart.com. i am unable to click the product after the search result. The xpath is correct. I tried using scroll function,visible, find by partial linktext, wait, sleep still i am unable to do. Please find the below code.</p>

```<code>package Flipkart;

import org.openqa.selenium.By; import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

public class TC2
{
    public static void main(String[] args) throws InterruptedException
    {
        System.setProperty("webdriver.chrome.driver","C:\\Chrome\\chromedriver.exe");
        WebDriver driver = new ChromeDriver();
        driver.get("https://www.flipkart.com/");
        driver.findElement(By.name("q")).sendKeys("Bag");
        driver.findElement(By.xpath("html/body/div[1]/div/header/div[1]/div[2]/div/div/div[2]/form/div/div[2]/button")).click();
        driver.findElement(By.xpath(".//*[@id='container']/div/div[2]/div[2]/div/div[2]/div/div[3]/div[1]/div[1]/div[1]/div/a[2]")).click();
    }
}

  Error:
    Starting ChromeDriver 2.25.426923 (0390b88869384d6eb0d5d09729679f934aab9eed) on port 17575
    Only local connections are allowed.
    Exception in thread "main" org.openqa.selenium.NoSuchElementException: no such element: Unable to locate element: {"method":"xpath","selector":".//*[@id='container']/div/div[2]/div[2]/div/div[2]/div/div[3]/div[1]/div[1]/div[1]/div/a[2]"}
      (Session info: chrome=58.0.3029.81)
      (Driver info: chromedriver=2.25.426923 (0390b88869384d6eb0d5d09729679f934aab9eed),platform=Windows NT 10.0.14393 x86_64) (WARNING: The server did not provide any stacktrace information)
    Command duration or timeout: 76 milliseconds
    For documentation on this error, please visit: http://seleniumhq.org/exceptions/no_such_element.html
    Build info: version: 'unknown', revision: 'unknown', time: 'unknown'
    System info: host: 'D90T0CQ1', ip: '192.168.162.83', os.name: 'Windows 10', os.arch: 'amd64', os.version: '10.0', java.version: '1.8.0_102'
    Driver info: org.openqa.selenium.chrome.ChromeDriver
    Capabilities [{applicationCacheEnabled=false, rotatable=false, mobileEmulationEnabled=false, networkConnectionEnabled=false, chrome={chromedriverVersion=2.25.426923 (0390b88869384d6eb0d5d09729679f934aab9eed), userDataDir=C:\Users\SALUNK~1\AppData\Local\Temp\scoped_dir12552_16506}, takesHeapSnapshot=true, pageLoadStrategy=normal, databaseEnabled=false, handlesAlerts=true, hasTouchScreen=false, version=58.0.3029.81, platform=XP, browserConnectionEnabled=false, nativeEvents=true, acceptSslCerts=true, locationContextEnabled=true, webStorageEnabled=true, browserName=chrome, takesScreenshot=true, javascriptEnabled=true, cssSelectorsEnabled=true}]
    Session ID: a8c3432c9b1e8cce3365db9407fc310f
    *** Element info: {Using=xpath, value=.//*[@id='container']/div/div[2]/div[2]/div/div[2]/div/div[3]/div[1]/div[1]/div[1]/div/a[2]}
        at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
        at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
        at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
        at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
        at org.openqa.selenium.remote.ErrorHandler.createThrowable(ErrorHandler.java:206)
        at org.openqa.selenium.remote.ErrorHandler.throwIfResponseFailed(ErrorHandler.java:158)
        at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:678)
        at org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:363)
        at org.openqa.selenium.remote.RemoteWebDriver.findElementByXPath(RemoteWebDriver.java:500)
        at org.openqa.selenium.By$ByXPath.findElement(By.java:361)
        at org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:355)
        at Flipkart.TC2.main(TC2.java:15)
</code>```

答:
Final solution and I can't suggest more than this,

```<code>//openChromeBrowser();
    driver.get("https://www.flipkart.com/");
    driver.findElement(By.name("q")).sendKeys("Bag");
    driver.findElement(By.xpath("//form[@action='/search']/div/div[2]/button")).click();
    Thread.sleep(5000);
    driver.findElement(By.linkText("Puma PUMA Zipper Backpack 26 L Laptop Backpack")).click();
</code>```

1> Give some wait time and it works
2> Use LinkText for locators for any of the item shown.

And follow what @Monika Singhal has said for quick and efficient results in Automation.

ContentLicense: CC BY-SA 3.0

Body:
I am practicing on flipkart.com. i am unable to click the product after the search result. The xpath is correct. I tried using scroll function,visible, find by partial linktext, wait, sleep still i am unable to do. Please find the below code.

package Flipkart;

import org.openqa.selenium.By; import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

public class TC2
{
    public static void main(String[] args) throws InterruptedException
    {
        System.setProperty("webdriver.chrome.driver","C:\\Chrome\\chromedriver.exe");
        WebDriver driver = new ChromeDriver();
        driver.get("https://www.flipkart.com/");
        driver.findElement(By.name("q")).sendKeys("Bag");
        driver.findElement(By.xpath("html/body/div[1]/div/header/div[1]/div[2]/div/div/div[2]/form/div/div[2]/button")).click();
        driver.findElement(By.xpath(".//*[@id='container']/div/div[2]/div[2]/div/div[2]/div/div[3]/div[1]/div[1]/div[1]/div/a[2]")).click();
    }
}

  Error:
    Starting ChromeDriver 2.25.426923 (0390b88869384d6eb0d5d09729679f934aab9eed) on port 17575
    Only local connections are allowed.
    Exception in thread "main" org.openqa.selenium.NoSuchElementException: no such element: Unable to locate element: {"method":"xpath","selector":".//*[@id='container']/div/div[2]/div[2]/div/div[2]/div/div[3]/div[1]/div[1]/div[1]/div/a[2]"}
      (Session info: chrome=58.0.3029.81)
      (Driver info: chromedriver=2.25.426923 (0390b88869384d6eb0d5d09729679f934aab9eed),platform=Windows NT 10.0.14393 x86_64) (WARNING: The server did not provide any stacktrace information)
    Command duration or timeout: 76 milliseconds
    For documentation on this error, please visit: http://seleniumhq.org/exceptions/no_such_element.html
    Build info: version: 'unknown', revision: 'unknown', time: 'unknown'
    System info: host: 'D90T0CQ1', ip: '192.168.162.83', os.name: 'Windows 10', os.arch: 'amd64', os.version: '10.0', java.version: '1.8.0_102'
    Driver info: org.openqa.selenium.chrome.ChromeDriver
    Capabilities [{applicationCacheEnabled=false, rotatable=false, mobileEmulationEnabled=false, networkConnectionEnabled=false, chrome={chromedriverVersion=2.25.426923 (0390b88869384d6eb0d5d09729679f934aab9eed), userDataDir=C:\Users\SALUNK~1\AppData\Local\Temp\scoped_dir12552_16506}, takesHeapSnapshot=true, pageLoadStrategy=normal, databaseEnabled=false, handlesAlerts=true, hasTouchScreen=false, version=58.0.3029.81, platform=XP, browserConnectionEnabled=false, nativeEvents=true, acceptSslCerts=true, locationContextEnabled=true, webStorageEnabled=true, browserName=chrome, takesScreenshot=true, javascriptEnabled=true, cssSelectorsEnabled=true}]
    Session ID: a8c3432c9b1e8cce3365db9407fc310f
    *** Element info: {Using=xpath, value=.//*[@id='container']/div/div[2]/div[2]/div/div[2]/div/div[3]/div[1]/div[1]/div[1]/div/a[2]}
        at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
        at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
        at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
        at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
        at org.openqa.selenium.remote.ErrorHandler.createThrowable(ErrorHandler.java:206)
        at org.openqa.selenium.remote.ErrorHandler.throwIfResponseFailed(ErrorHandler.java:158)
        at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:678)
        at org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:363)
        at org.openqa.selenium.remote.RemoteWebDriver.findElementByXPath(RemoteWebDriver.java:500)
        at org.openqa.selenium.By$ByXPath.findElement(By.java:361)
        at org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:355)
        at Flipkart.TC2.main(TC2.java:15)

Body:
Final solution and I can't suggest more than this,

//openChromeBrowser();
    driver.get("https://www.flipkart.com/");
    driver.findElement(By.name("q")).sendKeys("Bag");
    driver.findElement(By.xpath("//form[@action='/search']/div/div[2]/button")).click();
    Thread.sleep(5000);
    driver.findElement(By.linkText("Puma PUMA Zipper Backpack 26 L Laptop Backpack")).click();

1> Give some wait time and it works
2> Use LinkText for locators for any of the item shown.

And follow what @Monika Singhal has said for quick and efficient results in Automation.


问:
Is Import-CSV useful for import of ;-separated code page 1252 files
When I use

```<code>Import-Csv $mycsvFile
</code>```

I get lines like

```<code>1;M�nchen;Bayern
</code>```

The 2 problems are, that it doesn't understand the ansi codepage (i.e. has no parameter -encoding default) and I didn't succesd in using the -del parameter to tell it to use the ; as separator. Any suggestions?

答:
There are 3 points to note to successfull use Import-CSV

the data has to include a line with headers or the headers must be supplied as parameter. Without either the errormessage isn't really helpfull

code page 1252 doesn't work, there is no -encoding parameter which offers default, as in similar other cmdlets.

After the first two points fullfiled, the -delimiter parameter works as described.
link text

I really thought about using gc and split to achieve my problem, where the data has about

20000 lines.

Here for demonstration I present a 1-line example:

Contents of DemoData.csv:

```<code>1;München;Bayern
</code>```

Contents of Import-DemoData.ps1

```<code>$header = "id","Ort","Land"
Import-CSV C:\mydata\DemoData.csv -del ';' -head $header
</code>```

Body:
When I use

Import-Csv $mycsvFile

I get lines like

1;M�nchen;Bayern

The 2 problems are, that it doesn't understand the ansi codepage (i.e. has no parameter -encoding default) and I didn't succesd in using the -del parameter to tell it to use the ; as separator. Any suggestions?

Body:
There are 3 points to note to successfull use Import-CSV

the data has to include a line with headers or the headers must be supplied as parameter. Without either the errormessage isn't really helpfull

code page 1252 doesn't work, there is no -encoding parameter which offers default, as in similar other cmdlets.

After the first two points fullfiled, the -delimiter parameter works as described.
link text

I really thought about using gc and split to achieve my problem, where the data has about

20000 lines.

Here for demonstration I present a 1-line example:

Contents of DemoData.csv:

1;München;Bayern

Contents of Import-DemoData.ps1

$header = "id","Ort","Land"
Import-CSV C:\mydata\DemoData.csv -del ';' -head $header

ContentLicense: CC BY-SA 2.5


问:
I'm trying to echo an image in a PHP variable in CodeIgniter
Hello I'm trying to echo an image on a view page in CodeIgniter but nothing is displayed on the page.

Here I'm making the variable:

```<code><?php $image = "<img src='../../images/stoel.jpg' alt='img' />";  ?>
</code>```

And here I'm trying to echo the image:

```<code><img src="<?php echo $image;?>">
</code>```

答:
Make sure your images out side of the application folder then you can do something like

```<code>application

images

images > stoel.jpg

system

index.php
</code>```

Use Base url from the url helper

```<code><img src="<?php echo base_url('images/stoel.jpg');?>" />
</code>```

Make sure you have set the base_url in config.php

```<code>$config['base_url'] = 'http://localhost/yourproject/';
</code>```

You can also use HTML Helper img();

Body:
Hello I'm trying to echo an image on a view page in CodeIgniter but nothing is displayed on the page.

Here I'm making the variable:

<?php $image = "";  ?>

And here I'm trying to echo the image:

<img src="<?php echo $image;?>">

Body:
Make sure your images out side of the application folder then you can do something like

application

images

images > stoel.jpg

system

index.php

Use Base url from the url helper

<img src="<?php echo base_url('images/stoel.jpg');?>" />

Make sure you have set the base_url in config.php

$config['base_url'] = 'http://localhost/yourproject/';

You can also use HTML Helper img();


问:
More elegant way to disable my LOG messages when unit testing?
Right now, in visual studio 2017, I'm trying to unit test my code using google's testing framework gtest. I'm coding in C++. The problem I'm having is I want to be able to disable my LOG and assert macros for my debug build when unit testing by I'm not sure how to do this properly. This is currently how I have my macros setup:

```<code>#if (DEBUG)

#define RUNTIME_ASSERT \
    BOOST_ASSERT_MSG

#define COMPILETIME_ASSERT(expr, msg) \
    static_assert(expr, msg)

#define LOG(...) \
    do { fprintf_s(stderr, __VA_ARGS__); } while (0)

#else
#define NDEBUG
#define RUNTIME_ASSERT
#define COMPILETIME_ASSERT(expr, msg)
#define LOG(...) ((void)0)
#endif
</code>```

My solution consists of two projects, my actual application (a video game project) and a unit test project which takes my game project as a lib to run the tests.

I've tried creating another build configuration like "Debug unit test" though I couldn't quite get things to work and it seems like a sloppy way of doing things as then I would have to keep maintaining changes to both debug and debug unit testing build configurations. Any other suggestions?

答:
The conditional LOG macro is OK - this is pretty standard (apart from the fact that you're using a non-standard Microsoft extension to fprintf, but whatever).

There is one potential problem, which is that your unit test will never exercise your log statements. So, you can potentially have a runtime bug in your LOG arguments, which the preprocessor will hide from testing.

The more reliable solution is to have the logging stream defined somewhere rather than hardcoding stderr, and then overriding that to a null stream in your unit test setup (or redirect stderr - I'm not sure what the Windows equivalent of /dev/null is). This way, the arguments to LOG are still evaluated, and the formatting is still done, but you still don't see the logging.

You don't need to do anything for static_assert (because if they ever fail in your test code when they would pass in non-test code ... you're probably not testing the right thing anyway).

You don't need to do anything special for BOOST_ASSERT_MSG either, as that's already disabled by NDEBUG.

Body:
Right now, in visual studio 2017, I'm trying to unit test my code using google's testing framework gtest. I'm coding in C++. The problem I'm having is I want to be able to disable my LOG and assert macros for my debug build when unit testing by I'm not sure how to do this properly. This is currently how I have my macros setup:

#if (DEBUG)

#define RUNTIME_ASSERT \
    BOOST_ASSERT_MSG

#define COMPILETIME_ASSERT(expr, msg) \
    static_assert(expr, msg)

#define LOG(...) \
    do { fprintf_s(stderr, __VA_ARGS__); } while (0)

#else
#define NDEBUG
#define RUNTIME_ASSERT
#define COMPILETIME_ASSERT(expr, msg)
#define LOG(...) ((void)0)
#endif

My solution consists of two projects, my actual application (a video game project) and a unit test project which takes my game project as a lib to run the tests.

I've tried creating another build configuration like "Debug unit test" though I couldn't quite get things to work and it seems like a sloppy way of doing things as then I would have to keep maintaining changes to both debug and debug unit testing build configurations. Any other suggestions?


问:
How to use a shell variable inside sed when doing "d" command?
In my bash, I wish to delete lines from 1 to ${number}, like this:

```<code>number=10
sed '1,${number}d' myfile
</code>```

It failed with syntax error.
I also tried "\${number}", '"$number"', neithers works

I changed to double quote, it works under command line, but not inside bash script file. How to make it work?

答:
Please use double quotes instead of single quotes while running sed this way.
Read here for Difference between single and double quotes</p>

Body:
In my bash, I wish to delete lines from 1 to ${number}, like this:

number=10
sed '1,${number}d' myfile

It failed with syntax error.
I also tried "\${number}", '"$number"', neithers works

I changed to double quote, it works under command line, but not inside bash script file. How to make it work?


问:
ClassCastException in JMS ConnectionFactory lookup in JNDI
I am new to Queues. I had setup my queue in JBOSS 5.1 EAP and now while trying to inject in tho the queue am getting a ClassCastException (in lookup of JNDI), I use flex on my front end and use Spring framework for flex. When injected into the queue using quartz job it runs well and good. The quartz job is a separate project and has nothing to do with flex and spring.

I read over some where that this could be a jar issue, I had JMS jars in my spring and i tried removing, replacing all types of jars, no luck.

```<code>        // Step 1. Create an initial context to perform the JNDI lookup.

        InputStream in = this.getClass().getResourceAsStream(
                "/clv2.properties");
        Properties configProp = new Properties();
        configProp.load(in);
        IpAddress = configProp.getProperty("ipaddress");
        port = configProp.getProperty("port");
        inQueueName = configProp.getProperty("inQueueName");
        Properties props = new Properties();
        props.setProperty("java.naming.factory.initial",
                "org.jnp.interfaces.NamingContextFactory");
        props.setProperty("java.naming.factory.url.pkgs",
                "org.jboss.naming");
        // props.setProperty("java.naming.provider.url", host + ":" + port);
        props.setProperty("java.naming.provider.url", "localhost" + ":"
                + 1099);
        // props.setProperty("java.naming.provider.url",
        // "16.181.233.61:1399");
        initialContext = new InitialContext(props);

        // Step 3. Perform a lookup on the Connection Factory
        QueueConnectionFactory cf = (QueueConnectionFactory) initialContext
                .lookup("/ConnectionFactory");
        Queue queue = (Queue) initialContext
                .lookup(/* "/queue/CLVInboundQueue" */inQueueName);
        // Step 4.Create a JMS Connection
        connection = (QueueConnection) cf.createConnection();

        // Step 5. Create a JMS Session
        session = (QueueSession) connection.createSession(false,
                Session.AUTO_ACKNOWLEDGE);

        // Step 6. Create a JMS Message Producer
        // MessageProducer producer = session.createProducer(queue);
        QueueSender queueSender = session.createSender(queue);
        TextMessage textMessage = session.createTextMessage(message);
        textMessage.setLongProperty("Rejected_Message_ID",
                rejected_Message_Id);
        /*
         * BufferedReader reader = new BufferedReader(new
         * InputStreamReader(ClassLoader.class.getResourceAsStream(file)));
         * StringBuilder sb = new StringBuilder(); String line = null;
         *
         *
         * while ((line = reader.readLine()) != null) { sb.append(line +
         * "\n"); } String announcementmsg = sb.toString();
         */
        commonlogger.info(textMessage);
        connection.start();
        // producer.send(session.createTextMessage(announcementmsg));
        queueSender.send(textMessage);
</code>```

This is my piece of coding to inject into the queue. I get the Exception in "//Step 3. Perform a lookup on the Connection Factory" and this is my stack trace.

```<code>09:22:20,730 ERROR [STDERR] java.lang.ClassCastException: org.jboss.jms.client.JBossConnectionFactory cannot be cast to javax.jms.QueueConnectionFactory
09:22:20,731 ERROR [STDERR]     at com.cat.clv.util.InQueueReinjectMessage.sendMessage(InQueueReinjectMessage.java:63)
09:22:20,731 ERROR [STDERR]     at com.cat.clv.util.RejectedMessageReinject.reProcessedMessage(RejectedMessageReinject.java:65)
09:22:20,731 ERROR [STDERR]     at com.cat.clv.service.ReinjectMessagesServiceImpl.reinjectRejectedMessages(ReinjectMessagesServiceImpl.java:106)
09:22:20,731 ERROR [STDERR]     at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
09:22:20,731 ERROR [STDERR]     at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
09:22:20,732 ERROR [STDERR]     at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
09:22:20,732 ERROR [STDERR]     at java.lang.reflect.Method.invoke(Unknown Source)
09:22:20,732 ERROR [STDERR]     at flex.messaging.services.remoting.adapters.JavaAdapter.invoke(JavaAdapter.java:421)
09:22:20,732 ERROR [STDERR]     at flex.messaging.services.RemotingService.serviceMessage(RemotingService.java:183)
09:22:20,732 ERROR [STDERR]     at flex.messaging.MessageBroker.routeMessageToService(MessageBroker.java:1503)
</code>```

答:
Getting classCast Exception at lookup :
classcastexception: weblogic.jms.client.JMSconnectionFactory cannot be cast to javax.jms.QueueConnectionFactory

initialContext = new InitialContext(props);

```<code>    // Step 3. Perform a lookup on the Connection Factory
    QueueConnectionFactory cf = (QueueConnectionFactory) initialContext
            .lookup("/ConnectionFactory");
    Queue queue = (Queue) initialContext
            .lookup(/* "/queue/CLVInboundQueue" */inQueueName);
    // Step 4.Create a JMS Connection
    connection = (QueueConnection) cf.createConnection();

    // Step 5. Create a JMS Session
    session = (QueueSession) connection.createSession(false,
            Session.AUTO_ACKNOWLEDGE);

    // Step 6. Create a JMS Message Producer
    // MessageProducer producer = session.createProducer(queue);
    QueueSender queueSender = session.createSender(queue);
    TextMessage textMessage = session.createTextMessage(message);
    textMessage.setLongProperty("Rejected_Message_ID",
            rejected_Message_Id);
    /*
     * BufferedReader reader = new BufferedReader(new
     * InputStreamReader(ClassLoader.class.getResourceAsStream(file)));
     * StringBuilder sb = new StringBuilder(); String line = null;
     *
     *
     * while ((line = reader.readLine()) != null) { sb.append(line +
     * "\n"); } String announcementmsg = sb.toString();
     */
    commonlogger.info(textMessage);
    connection.start();
    // producer.send(session.createTextMessage(announcementmsg));
    queueSender.send(textMessage);
</code>```

Body:
I am new to Queues. I had setup my queue in JBOSS 5.1 EAP and now while trying to inject in tho the queue am getting a ClassCastException (in lookup of JNDI), I use flex on my front end and use Spring framework for flex. When injected into the queue using quartz job it runs well and good. The quartz job is a separate project and has nothing to do with flex and spring.

I read over some where that this could be a jar issue, I had JMS jars in my spring and i tried removing, replacing all types of jars, no luck.

        // Step 1. Create an initial context to perform the JNDI lookup.

        InputStream in = this.getClass().getResourceAsStream(
                "/clv2.properties");
        Properties configProp = new Properties();
        configProp.load(in);
        IpAddress = configProp.getProperty("ipaddress");
        port = configProp.getProperty("port");
        inQueueName = configProp.getProperty("inQueueName");
        Properties props = new Properties();
        props.setProperty("java.naming.factory.initial",
                "org.jnp.interfaces.NamingContextFactory");
        props.setProperty("java.naming.factory.url.pkgs",
                "org.jboss.naming");
        // props.setProperty("java.naming.provider.url", host + ":" + port);
        props.setProperty("java.naming.provider.url", "localhost" + ":"
                + 1099);
        // props.setProperty("java.naming.provider.url",
        // "16.181.233.61:1399");
        initialContext = new InitialContext(props);

        // Step 3. Perform a lookup on the Connection Factory
        QueueConnectionFactory cf = (QueueConnectionFactory) initialContext
                .lookup("/ConnectionFactory");
        Queue queue = (Queue) initialContext
                .lookup(/* "/queue/CLVInboundQueue" */inQueueName);
        // Step 4.Create a JMS Connection
        connection = (QueueConnection) cf.createConnection();

        // Step 5. Create a JMS Session
        session = (QueueSession) connection.createSession(false,
                Session.AUTO_ACKNOWLEDGE);

        // Step 6. Create a JMS Message Producer
        // MessageProducer producer = session.createProducer(queue);
        QueueSender queueSender = session.createSender(queue);
        TextMessage textMessage = session.createTextMessage(message);
        textMessage.setLongProperty("Rejected_Message_ID",
                rejected_Message_Id);
        /*
         * BufferedReader reader = new BufferedReader(new
         * InputStreamReader(ClassLoader.class.getResourceAsStream(file)));
         * StringBuilder sb = new StringBuilder(); String line = null;
         *
         *
         * while ((line = reader.readLine()) != null) { sb.append(line +
         * "\n"); } String announcementmsg = sb.toString();
         */
        commonlogger.info(textMessage);
        connection.start();
        // producer.send(session.createTextMessage(announcementmsg));
        queueSender.send(textMessage);

This is my piece of coding to inject into the queue. I get the Exception in "//Step 3. Perform a lookup on the Connection Factory" and this is my stack trace.

09:22:20,730 ERROR [STDERR] java.lang.ClassCastException: org.jboss.jms.client.JBossConnectionFactory cannot be cast to javax.jms.QueueConnectionFactory
09:22:20,731 ERROR [STDERR]     at com.cat.clv.util.InQueueReinjectMessage.sendMessage(InQueueReinjectMessage.java:63)
09:22:20,731 ERROR [STDERR]     at com.cat.clv.util.RejectedMessageReinject.reProcessedMessage(RejectedMessageReinject.java:65)
09:22:20,731 ERROR [STDERR]     at com.cat.clv.service.ReinjectMessagesServiceImpl.reinjectRejectedMessages(ReinjectMessagesServiceImpl.java:106)
09:22:20,731 ERROR [STDERR]     at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
09:22:20,731 ERROR [STDERR]     at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
09:22:20,732 ERROR [STDERR]     at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
09:22:20,732 ERROR [STDERR]     at java.lang.reflect.Method.invoke(Unknown Source)
09:22:20,732 ERROR [STDERR]     at flex.messaging.services.remoting.adapters.JavaAdapter.invoke(JavaAdapter.java:421)
09:22:20,732 ERROR [STDERR]     at flex.messaging.services.RemotingService.serviceMessage(RemotingService.java:183)
09:22:20,732 ERROR [STDERR]     at flex.messaging.MessageBroker.routeMessageToService(MessageBroker.java:1503)

Body:
Getting classCast Exception at lookup :
classcastexception: weblogic.jms.client.JMSconnectionFactory cannot be cast to javax.jms.QueueConnectionFactory

initialContext = new InitialContext(props);

    // Step 3. Perform a lookup on the Connection Factory
    QueueConnectionFactory cf = (QueueConnectionFactory) initialContext
            .lookup("/ConnectionFactory");
    Queue queue = (Queue) initialContext
            .lookup(/* "/queue/CLVInboundQueue" */inQueueName);
    // Step 4.Create a JMS Connection
    connection = (QueueConnection) cf.createConnection();

    // Step 5. Create a JMS Session
    session = (QueueSession) connection.createSession(false,
            Session.AUTO_ACKNOWLEDGE);

    // Step 6. Create a JMS Message Producer
    // MessageProducer producer = session.createProducer(queue);
    QueueSender queueSender = session.createSender(queue);
    TextMessage textMessage = session.createTextMessage(message);
    textMessage.setLongProperty("Rejected_Message_ID",
            rejected_Message_Id);
    /*
     * BufferedReader reader = new BufferedReader(new
     * InputStreamReader(ClassLoader.class.getResourceAsStream(file)));
     * StringBuilder sb = new StringBuilder(); String line = null;
     *
     *
     * while ((line = reader.readLine()) != null) { sb.append(line +
     * "\n"); } String announcementmsg = sb.toString();
     */
    commonlogger.info(textMessage);
    connection.start();
    // producer.send(session.createTextMessage(announcementmsg));
    queueSender.send(textMessage);


问:
appium how to override capabilities
Any ideas on the following.

My standard capabilities are set to open my native application.

```<code>capabilities.setCapability("app", app.getAbsolutePath());
</code>```

This is defined in a method with @BeforeMethod annotation (TestNG)

I have one specific test I want to start in Chrome. How can I acheive this ? Can I override in some way the capabilities for one specific test ?

答:
```<code><suite name="Suite" parallel="none">
<test name="Test1">
    <parameter name="Device" value="ABCD" />
    <parameter name="Port" value="4723" />
        <classes>
            <class name="" />
            <methods>

            </methods>
        </classes>
    </test>
</suite>

use following annotations on your desired capability method and pass them in desired capability
@BeforeTest / @Beforemethod / @Beforeclass
@Parameters({"Device","Port"})
public void desiredcapability(string Device,string Port)
{

}
</code>```

Title: appium how to override capabilities

Body:
Any ideas on the following.

My standard capabilities are set to open my native application.

capabilities.setCapability("app", app.getAbsolutePath());

This is defined in a method with @BeforeMethod annotation (TestNG)

I have one specific test I want to start in Chrome. How can I acheive this ? Can I override in some way the capabilities for one specific test ?


问:
how to use both Groovy-defined and OS system variable in a multi-line shell script within Jenkins Groovy
I need to access Groovy-defined variables (e.g. var1) in a multi-line shell script in Jenkins. I need to use double-quote """ in sh. (I refer to here)

But I also need to read and change os system variable (e.g. aws_api_key) too. It needs to use single-quote ''' in sh and use \ to escape dollar $ sign. (I refer to here)

How can I use both of them? any help will be much appreciated.

e.g.

```<code>node ("Jenkins-Test-Slave") {
stage ("hello world") {
    echo 'Hello World'
}

def var1="bin"
stage ("test") {
    withEnv(["aws_api_key='define in withEnv'","service_url=''"]) {
        echo var1
        sh '''
            echo the groovy data var1 is "${var1}",'\${var1}',\$var1,${var1},var1!!!
            echo default value of aws_api_key is \$aws_api_key
            aws_api_key='changed in shell'
            echo new value of aws_api_key is \$aws_api_key

            export newvar='newxxx'
            echo the new var value is \$newvar
        '''
    }
}
}
</code>```

The result is:

```<code>+ echo the groovy data var1 is ,${var1},,,var1!!!
the groovy data var1 is ,${var1},,,var1!!!
+ echo default value of aws_api_key is 'define in withEnv'
default value of aws_api_key is 'define in withEnv'
+ aws_api_key=changed in shell
+ echo new value of aws_api_key is changed in shell
new value of aws_api_key is changed in shell
+ export newvar=newxxx
+ echo the new var value is newxxx
the new var value is newxxx
</code>```

答:
Instead of multi-line String (''') use multi-line GString (""") to make string interpolation work, then ${var1} will be interpolated as expected:

```<code>sh """
    echo the groovy data var1 is "${var1}",'\${var1}',\$var1,${var1},var1!!!
    echo default value of aws_api_key is \$aws_api_key
    aws_api_key='changed in shell'
    echo new value of aws_api_key is \$aws_api_key

    export newvar='newxxx'
    echo the new var value is \$newvar
"""
</code>```

Body:
I need to access Groovy-defined variables (e.g. var1) in a multi-line shell script in Jenkins. I need to use double-quote """ in sh. (I refer to here)

But I also need to read and change os system variable (e.g. aws_api_key) too. It needs to use single-quote ''' in sh and use \ to escape dollar $ sign. (I refer to here)

How can I use both of them? any help will be much appreciated.

e.g.

node ("Jenkins-Test-Slave") {
stage ("hello world") {
    echo 'Hello World'
}

def var1="bin"
stage ("test") {
    withEnv(["aws_api_key='define in withEnv'","service_url=''"]) {
        echo var1
        sh '''
            echo the groovy data var1 is "${var1}",'\${var1}',\$var1,${var1},var1!!!
            echo default value of aws_api_key is \$aws_api_key
            aws_api_key='changed in shell'
            echo new value of aws_api_key is \$aws_api_key

            export newvar='newxxx'
            echo the new var value is \$newvar
        '''
    }
}
}

The result is:

+ echo the groovy data var1 is ,${var1},,,var1!!!
the groovy data var1 is ,${var1},,,var1!!!
+ echo default value of aws_api_key is 'define in withEnv'
default value of aws_api_key is 'define in withEnv'
+ aws_api_key=changed in shell
+ echo new value of aws_api_key is changed in shell
new value of aws_api_key is changed in shell
+ export newvar=newxxx
+ echo the new var value is newxxx
the new var value is newxxx

Body:
Instead of multi-line String (''') use multi-line GString (""") to make string interpolation work, then ${var1} will be interpolated as expected:

sh """
    echo the groovy data var1 is "${var1}",'\${var1}',\$var1,${var1},var1!!!
    echo default value of aws_api_key is \$aws_api_key
    aws_api_key='changed in shell'
    echo new value of aws_api_key is \$aws_api_key

    export newvar='newxxx'
    echo the new var value is \$newvar
"""


问:
Can't use ssh git repositories after SierraOS update
I updated my macbook to latest Sierra OS with all security updates. Since then my Intellij can't operate with remote git repositories using ssh. It works (fetch, pull, push) when using https version of remote repository. Git also works on terminal with ssh repositories or https repositories. In Intellij settings, I tried to switch Native or Built-in executable and tests says it works fine.

But when I try to pull changes from git@github.com:company/repo.git in Intellij it doesn't work and says Could not read from remote repository

答:
Your private is key is probably locked. Try inputting this into a terminal window to unlock it:

ssh-add -K

Not sure if that will permeate through to IntelliJ though, otherwise try to unlock your private key from within IntelliJ. I don't use IntelliJ, so I am not familiar with how to do it there.


问:
Click on bootstrap dropdown element and change the value
This is the dropdwon

```<code><div class="col-md-6">
             <div class="dropdown">
                <input  type="text" data-toggle="dropdown" id="search-input" class="form-control">
                <ul class="dropdown-menu" id="employee-list">
                  <!--filled by ajax -->
                </ul>
              </div>
        </div>
</code>```

and I get the list with aand itry to get the click event but nothing its done

```<code>$(document).ready( function(){
    $('#search-input').keyup(function(e){
        if($(this).val().length >= 3 /*&& e.which != 8*/ ){
            get_users($(this).val());
        }
    });

    $(".dropdown-menu li a").click(function(){
        alert('aaaa');
    });
});
</code>```

Ineed to click a list element and set the text of the input with the text of the clicked element but I can't handle the click event

```<code>function get_users($text){
    $.ajax({
      url: "asociate_ci.php",
      method: 'get',
      data: {
        'text': $text ,
        'option':'get_users'
      }
    })
      .done(function( response ) {
        var employees = JSON.parse(response);
        //console.dir(employees);
        $('#employee-list').empty();
        $.each(employees, function(){
            //console.log(this.last_name);
            $('#employee-list').append("<li ><a class='employee-li'>"+this.last_name+"</a></li>");
        });
        $('#search-input').focus();
      });
}
</code>```

答:
jquery handlers on present elements they work fine,
but the new elements are not binded to those handlers so thats why we need to use the .on() method.

Change your click event like below:

```<code>$('.dropdown-menu').on('click', 'a', function(){
   alert('aaaa');
});
</code>```

Body:
This is the dropdwon

                <input  type="text" data-toggle="dropdown" id="search-input" class="form-control">

and I get the list with aand itry to get the click event but nothing its done

$(document).ready( function(){
    $('#search-input').keyup(function(e){
        if($(this).val().length >= 3 /*&& e.which != 8*/ ){
            get_users($(this).val());
        }
    });

    $(".dropdown-menu li a").click(function(){
        alert('aaaa');
    });
});

Ineed to click a list element and set the text of the input with the text of the clicked element but I can't handle the click event

function get_users($text){
    $.ajax({
      url: "asociate_ci.php",
      method: 'get',
      data: {
        'text': $text ,
        'option':'get_users'
      }
    })
      .done(function( response ) {
        var employees = JSON.parse(response);
        //console.dir(employees);
        $('#employee-list').empty();
        $.each(employees, function(){
            //console.log(this.last_name);
            $('#employee-list').append("
"+this.last_name+"
");
        });
        $('#search-input').focus();
      });
}

Body:
jquery handlers on present elements they work fine,
but the new elements are not binded to those handlers so thats why we need to use the .on() method.

Change your click event like below:

$('.dropdown-menu').on('click', 'a', function(){
   alert('aaaa');
});


问:
Parser/split const char* in c++
I tried to find a solution but I did not find anything that solved my question.

I have a C++ program that receive a const char* variable (filedata) and the size (filesize). The contents of this variable is a csv format. Each field is separated by ';'. The content is also dynamic, and may have more or less content, since this variable represents a set of logs. There is also a delimiter \n to represent the line break.

Example 1 of filedata:

```<code>const char* filedata =
    "1496843100;2017-06-07 13:45:00;000002D8;2800;0x23000CCD.VARIABLE67\n"
    "1496843100;2017-06-07 13:45:00;000002D9;2800;0x23000CCD.VARIABLE68";
</code>```

Example 2 of fildedata:

```<code>const char* filedata =
    "1496843100;2017-06-07 13:45:00;000002D8;2800;0x23000CCD.VARIABLE67\n"
    "1496843100;2017-06-07 13:45:00;000002D9;2800;0x23000CCD.VARIABLE68\n"
    "1496843100;2017-06-07 13:45:00;000002DA;2800;0x23000CCD.VARIABLE69";
</code>```

If you see the example 1 only have 2 lines, and the example 2 have 3 lines. I never know how many lines I have. I can have 2, 3, 200, 1000, etc. lines and the filedata variable save all content.

So my objective is to receive this filedata variable (I also have access to filesize) and for each line I need to parse the field 1 and 2 (timestamp and the data in normal format).

Expected output (for the example 2):

```<code>1496843100 2017-06-07 13:45:00
1496843100 2017-06-07 13:45:00
1496843100 2017-06-07 13:45:00
</code>```

In example 2 I have 3 lines, so I need to iterate all lines and for each line parse the specific fields, very similar to the output.
After this i pick each parser fields and save to object list (This part is already implemented. I'm just having trouble parsing filedata.

答:
Fast solution :
You can use similar method to explode() function from PHP. Here is answer how to create explode function in C++ enter link description here. Probably you will have to modify answered code to take standard C string as input.

Then if you will have own explode() function version, you can do something like  std::vector<std::string> lines = explode(filedata,'\n').

Next step will be for each lines element do std::vector<std::string> line_elements = explode(lines[i], ';'). Then you will have each separate field and you can print/parse what do you want.

Title: Parser/split const char* in c++

Body:
I tried to find a solution but I did not find anything that solved my question.

I have a C++ program that receive a const char* variable (filedata) and the size (filesize). The contents of this variable is a csv format. Each field is separated by ';'. The content is also dynamic, and may have more or less content, since this variable represents a set of logs. There is also a delimiter \n to represent the line break.

Example 1 of filedata:

const char* filedata =
    "1496843100;2017-06-07 13:45:00;000002D8;2800;0x23000CCD.VARIABLE67\n"
    "1496843100;2017-06-07 13:45:00;000002D9;2800;0x23000CCD.VARIABLE68";

Example 2 of fildedata:

const char* filedata =
    "1496843100;2017-06-07 13:45:00;000002D8;2800;0x23000CCD.VARIABLE67\n"
    "1496843100;2017-06-07 13:45:00;000002D9;2800;0x23000CCD.VARIABLE68\n"
    "1496843100;2017-06-07 13:45:00;000002DA;2800;0x23000CCD.VARIABLE69";

If you see the example 1 only have 2 lines, and the example 2 have 3 lines. I never know how many lines I have. I can have 2, 3, 200, 1000, etc. lines and the filedata variable save all content.

So my objective is to receive this filedata variable (I also have access to filesize) and for each line I need to parse the field 1 and 2 (timestamp and the data in normal format).

Expected output (for the example 2):

1496843100 2017-06-07 13:45:00
1496843100 2017-06-07 13:45:00
1496843100 2017-06-07 13:45:00

In example 2 I have 3 lines, so I need to iterate all lines and for each line parse the specific fields, very similar to the output.
After this i pick each parser fields and save to object list (This part is already implemented. I'm just having trouble parsing filedata.


问:
iOS 5.0 Check if NSString contains Emoji characters
I have an iOS 5 application that allows users to enter username with international keyboards.
I want to check if the input (NSString *) contains an emoji character or not.

Disabling emoji keyboard is not an option (Using UIKeyboardTypeASCIICapable as it disables some of the international keyboards).

I tried  this. But it does not detect some of the characters like these.

Is there a good way to solve this problem?

答:
To iOS 10 and below, you should check if the unicode if between the following values.</p>

```<code>if ((0x1d000 <= uc && uc <= 0x1f77f) || (0x1f900 <= 0x1f9ff)) {
     //is emoji
}
</code>```

Body:
To iOS 10 and below, you should check if the unicode if between the following values.

if ((0x1d000 <= uc && uc <= 0x1f77f) || (0x1f900 <= 0x1f9ff)) {
     //is emoji
}


问:
Calling SharePoint with HttpClient PostAsync() results into forbidden response
I am trying to send HttpClient PostAsync() request to company's internal sharepoint site but its returning response with forbidden error. I have all necessary access permission for site to load and have also passed required headers to the HttpClient object.

Here is code snippet.

```<code>HttpClient client = new System.Net.Http.HttpClient (new HttpClientHandler { UseDefaultCredentials = true });

client.BaseAddress = new Uri (string.Format (API_URL, p_siteNumber));
client.DefaultRequestHeaders.Accept.Add (new MediaTypeWithQualityHeaderValue (@"application/atom+xml"));
client.DefaultRequestHeaders.TryAddWithoutValidation ("Accept-Encoding", "gzip, deflate");
client.DefaultRequestHeaders.TryAddWithoutValidation ("Accept-Language", "en-US, en;q=0.8, hi;q=0.6");
client.DefaultRequestHeaders.TryAddWithoutValidation ("User-Agent", "Mozilla/5.0 (Windows NT 6.2; WOW64; rv:19.0) Gecko/20100101 Firefox/19.0");
client.DefaultRequestHeaders.TryAddWithoutValidation ("Accept-Charset", "ISO-8859-1");

HttpResponseMessage httpResponse = await client.PostAsync (urlHttpPost, new StringContent (string.Empty));

string response = await httpResponse.Content.ReadAsStringAsync ();
</code>```

Can anyone help me with this?
Thanks in advance.

答:
I ran into the same problem I wanted to send the file and some string contents with it.

so below code helped me!!

```<code>using (var client = new HttpClient())
        {
            //client.DefaultRequestHeaders.Add("User-Agent", "CBS Brightcove API Service");
            string authorization = GenerateBase64();
            client.DefaultRequestHeaders.Add("Authorization", authorization);

            using (var content = new MultipartFormDataContent())
            {

                string fileName = Path.GetFileName(textBox1.Text);

                //Content-Disposition: form-data; name="json"
                var stringContent = new StringContent(InstancePropertyObject);
                stringContent.Headers.Remove("Content-Type");
                stringContent.Headers.Add("Content-Type", "application/json");
                stringContent.Headers.Add("Content-Disposition", "form-data; name=\"instance\"");
                content.Add(stringContent, "instance");

                var fileContent = new ByteArrayContent(filecontent);
                fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
                {
                    FileName = fileName
                };
                content.Add(fileContent);

                var result = client.PostAsync(targetURL, content).Result;
            }
        }
</code>```

Body:
I am trying to send HttpClient PostAsync() request to company's internal sharepoint site but its returning response with forbidden error. I have all necessary access permission for site to load and have also passed required headers to the HttpClient object.

Here is code snippet.

HttpClient client = new System.Net.Http.HttpClient (new HttpClientHandler { UseDefaultCredentials = true });

client.BaseAddress = new Uri (string.Format (API_URL, p_siteNumber));
client.DefaultRequestHeaders.Accept.Add (new MediaTypeWithQualityHeaderValue (@"application/atom+xml"));
client.DefaultRequestHeaders.TryAddWithoutValidation ("Accept-Encoding", "gzip, deflate");
client.DefaultRequestHeaders.TryAddWithoutValidation ("Accept-Language", "en-US, en;q=0.8, hi;q=0.6");
client.DefaultRequestHeaders.TryAddWithoutValidation ("User-Agent", "Mozilla/5.0 (Windows NT 6.2; WOW64; rv:19.0) Gecko/20100101 Firefox/19.0");
client.DefaultRequestHeaders.TryAddWithoutValidation ("Accept-Charset", "ISO-8859-1");

HttpResponseMessage httpResponse = await client.PostAsync (urlHttpPost, new StringContent (string.Empty));

string response = await httpResponse.Content.ReadAsStringAsync ();

Can anyone help me with this?
Thanks in advance.

Body:
I ran into the same problem I wanted to send the file and some string contents with it.

so below code helped me!!

using (var client = new HttpClient())
        {
            //client.DefaultRequestHeaders.Add("User-Agent", "CBS Brightcove API Service");
            string authorization = GenerateBase64();
            client.DefaultRequestHeaders.Add("Authorization", authorization);

            using (var content = new MultipartFormDataContent())
            {

                string fileName = Path.GetFileName(textBox1.Text);

                //Content-Disposition: form-data; name="json"
                var stringContent = new StringContent(InstancePropertyObject);
                stringContent.Headers.Remove("Content-Type");
                stringContent.Headers.Add("Content-Type", "application/json");
                stringContent.Headers.Add("Content-Disposition", "form-data; name=\"instance\"");
                content.Add(stringContent, "instance");

                var fileContent = new ByteArrayContent(filecontent);
                fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
                {
                    FileName = fileName
                };
                content.Add(fileContent);

                var result = client.PostAsync(targetURL, content).Result;
            }
        }


问:
How to overlap layouts/views within LinearLayout?
I would like to create layout that looks like this:

Layout1and Layout2 are some layouts of any kind, nested in a parent LinearLayout. The LinearLayout is necessary to give both child layouts a 50% height by using layout_weight.

The red squares should be Buttons which overlap both Layout1and Layout2 and are centered between the two layouts.

Of course this could achived by using RelativeLayout as parent instead but then I would loose the possibility to use layout_weight...

If I keep using LinearLayout, it seems to be impossible to let the buttons overlap the two other layouts.

Furthermore the buttons cannot be siblings of the two layouts but need to be nested inside a common container layout that takes care of the horizontal positioning (e.g. a LinearLayout with horizontal orientation).

Any idea how to solve this?

I already tried to place the buttons inside Layout1 (or Layout2), place them below the bottom and use android:clipChildren=false, but this had no effect. The button where simple cut in half.

Edit:
Splitting the height between the two layouts 50/50 is just one version. Another view uses the same basic layout but splits the height 70/30 between the two layouts. The buttons should always be centered between the two layouts. Sorry for not pointing this out earlier.

Layout Code:

```<code><!-- parent/root layout -->
<LinearLayout
    ...
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    ... >

    <!-- Layout1 -->
    <LinearLayout
        android:layout_weight="1"
        ... />

    <!-- Buttons -->
    <LinearLayout
        android:orientation="horizontal"
        ... >

        <Button ... />
        <Button ... />
        <Button ... />

    </LinearLayout>

    <!-- Layout2 -->
    <LinearLayout
        android:layout_weight="1"
        ... />

</LinearLayout>
</code>```

答:
Here, this is the solution using only Linearlayout.

Key point is: button is consist of two part. Half top and Half bottom. And minus margin means half of your button's height.

But, please do not use this code. Use GuideLine of ConstraintLayout. It has percentage option, so you can implement almost evert layout you want.

```<code><LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/activity_test"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight="0.5"
        android:background="#d3d3d3">

        <ImageView
            android:id="@+id/imageView1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="bottom"
            android:layout_marginBottom="-25dp"
            android:layout_weight="1"
            android:src="@mipmap/ic_launcher"/>

        <ImageView
            android:id="@+id/imageView2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="bottom"
            android:layout_marginBottom="-25dp"
            android:layout_weight="1"
            android:src="@mipmap/ic_launcher"/>

        <ImageView
            android:id="@+id/imageView3"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="bottom"
            android:layout_marginBottom="-25dp"
            android:layout_weight="1"
            android:src="@mipmap/ic_launcher"/>

    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight="0.5"
        android:background="#Ed1c24">

        <ImageView
            android:id="@+id/imageView4"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="top"
            android:layout_marginTop="-25dp"
            android:layout_weight="1"
            android:src="@mipmap/ic_launcher"/>

        <ImageView
            android:id="@+id/imageView5"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="top"
            android:layout_marginTop="-25dp"
            android:layout_weight="1"
            android:src="@mipmap/ic_launcher"/>

        <ImageView
            android:id="@+id/imageView6"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="top"
            android:layout_marginTop="-25dp"
            android:layout_weight="1"
            android:src="@mipmap/ic_launcher"/>
    </LinearLayout>

</LinearLayout>
</code>```

Body:
I would like to create layout that looks like this:

Layout1and Layout2 are some layouts of any kind, nested in a parent LinearLayout. The LinearLayout is necessary to give both child layouts a 50% height by using layout_weight.

The red squares should be Buttons which overlap both Layout1and Layout2 and are centered between the two layouts.

Of course this could achived by using RelativeLayout as parent instead but then I would loose the possibility to use layout_weight...

If I keep using LinearLayout, it seems to be impossible to let the buttons overlap the two other layouts.

Furthermore the buttons cannot be siblings of the two layouts but need to be nested inside a common container layout that takes care of the horizontal positioning (e.g. a LinearLayout with horizontal orientation).

Any idea how to solve this?

I already tried to place the buttons inside Layout1 (or Layout2), place them below the bottom and use android:clipChildren=false, but this had no effect. The button where simple cut in half.

Edit:
Splitting the height between the two layouts 50/50 is just one version. Another view uses the same basic layout but splits the height 70/30 between the two layouts. The buttons should always be centered between the two layouts. Sorry for not pointing this out earlier.

Layout Code:

<LinearLayout
    ...
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    ... >

    <LinearLayout
        android:layout_weight="1"
        ... />

    <LinearLayout
        android:orientation="horizontal"
        ... >

        <Button ... />
        <Button ... />
        <Button ... />

    </LinearLayout>

    <LinearLayout
        android:layout_weight="1"
        ... />

</LinearLayout>

Body:
Here, this is the solution using only Linearlayout.

Key point is: button is consist of two part. Half top and Half bottom. And minus margin means half of your button's height.

But, please do not use this code. Use GuideLine of ConstraintLayout. It has percentage option, so you can implement almost evert layout you want.

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/activity_test"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight="0.5"
        android:background="#d3d3d3">

        <ImageView
            android:id="@+id/imageView1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="bottom"
            android:layout_marginBottom="-25dp"
            android:layout_weight="1"
            android:src="@mipmap/ic_launcher"/>

        <ImageView
            android:id="@+id/imageView2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="bottom"
            android:layout_marginBottom="-25dp"
            android:layout_weight="1"
            android:src="@mipmap/ic_launcher"/>

        <ImageView
            android:id="@+id/imageView3"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="bottom"
            android:layout_marginBottom="-25dp"
            android:layout_weight="1"
            android:src="@mipmap/ic_launcher"/>

    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight="0.5"
        android:background="#Ed1c24">

        <ImageView
            android:id="@+id/imageView4"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="top"
            android:layout_marginTop="-25dp"
            android:layout_weight="1"
            android:src="@mipmap/ic_launcher"/>

        <ImageView
            android:id="@+id/imageView5"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="top"
            android:layout_marginTop="-25dp"
            android:layout_weight="1"
            android:src="@mipmap/ic_launcher"/>

        <ImageView
            android:id="@+id/imageView6"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="top"
            android:layout_marginTop="-25dp"
            android:layout_weight="1"
            android:src="@mipmap/ic_launcher"/>
    </LinearLayout>

</LinearLayout>


问:
With... End With vs Using in VB.NET
I just found out that like C#, VB.NET also has the using keyword.

Until now I thought it didn't have it (stupid of me, I know...) and did stuff like this instead:

```<code>With New OleDbConnection(MyConnectionString)
   ' Do stuff
End With
</code>```

What are the implications of this compared to doing it with a using statement like this

```<code>Using cn as New OleDBConnection(MyConnectionString)
    With cn
        ' Do stuff with cn
    End With
End using
</code>```

UPDATE:

I should add that I am familiar with what the using statement does in that it disposes of the object when the construct is exited.

However, as far as I understand the With New ... construct will have the object mark the object as ready for garbage collection when it goes out of scope.

So my question really is, is the only difference the fact that with using I will release the memory right away, whereas with the With construct it will be released whenever the GC feels like it? Or am I missing something bigger here?

Are there any best practice implications? Should I go and rewrite all the code with I used With New MyDisposableObject() ... End With as Using o as New MyDisposableObject()?

答:
Using connection...  End Using : Be careful !!!
This statement will close your database connection !

In the middle of a module or form(s), i.e.adding or updating records, this will close the connection.  When you try to do another operation in that module you will receive a database error. For connections, I no longer use it.  You can use the Try... End Try wihthouth the Using statement.

I open the connection upon entry to the module and close it it upon exit.  That solves the problem.

Title: With... End With vs Using in VB.NET

Body:
I just found out that like C#, VB.NET also has the using keyword.

Until now I thought it didn't have it (stupid of me, I know...) and did stuff like this instead:

With New OleDbConnection(MyConnectionString)
   ' Do stuff
End With

What are the implications of this compared to doing it with a using statement like this

Using cn as New OleDBConnection(MyConnectionString)
    With cn
        ' Do stuff with cn
    End With
End using

UPDATE:

I should add that I am familiar with what the using statement does in that it disposes of the object when the construct is exited.

However, as far as I understand the With New ... construct will have the object mark the object as ready for garbage collection when it goes out of scope.

So my question really is, is the only difference the fact that with using I will release the memory right away, whereas with the With construct it will be released whenever the GC feels like it? Or am I missing something bigger here?

Are there any best practice implications? Should I go and rewrite all the code with I used With New MyDisposableObject() ... End With as Using o as New MyDisposableObject()?


问:
django rest framework RetrieveUpdateAPIView
I come from Vietnam.

I want to update User by Django Rest FrameWork. I can update User by 'pk'. But I can't update User by 'username'. I hope that everyone help me. Thank you so much.

serializers.py

```<code>class UserDetailSerializer(serializers.ModelSerializer):
    url_update = serializers.HyperlinkedIdentityField(view_name='api:UserUpdateAPIView', lookup_field='username')
    class Meta:
        model = User
        fields = ('url_update', 'username', 'email', 'user_permissions', 'is_staff', 'groups', 'last_login')

class UserUpdateSerialier(serializers.ModelSerializer):
    password = serializers.CharField(
        style={'input_type': 'password'}
    )
    class Meta:
        model = User
        fields = ('pk', 'username', 'password')

    def update(self, instance, validated_data):
        instance.username = validated_data.get('username', instance.username)
        instance.set_password(validated_data.get('password', instance.password))
        instance.save()
        return instance
</code>```

views.py

```<code>class UserDetailAPIView(generics.RetrieveAPIView):
    permission_classes = (permissions.IsAdminUser,)
    serializer_class = UserDetailSerializer
    #queryset = User.objects.all()
    lookup_field = 'username'
    def get_object(self):
        username = self.kwargs["username"]
        return get_object_or_404(User, username=username)

class UserUpdateAPIView(generics.RetrieveUpdateAPIView):
    permission_classes = (permissions.IsAdminUser,)
    #queryset = User.objects.all()
    serializer_class = UserUpdateSerialier

    def get_object(self):
        username = self.kwargs["username"]
        return get_object_or_404(User, username=username)

    def put(self, request, *args, **kwargs):
        return self.update(request, *args, **kwargs)
</code>```

urls.py

```<code>url(r'^$', views.UserListAPIView.as_view(), name='UserListAPIView'),
url(r'^(?P<username>.*)/$', views.UserDetailAPIView.as_view(), name='UserDetailAPIView'),
url(r'^(?P<username>.*)/update/$', views.UserUpdateAPIView.as_view(), name='UserUpdateAPIView'),
</code>```

HTTP 404 Not Found

Allow: GET, HEAD, OPTIONS

Content-Type: application/json

Vary: Accept

{
      "detail": "Not found."
  }

答:
Try editing your view like this,</p>

```<code>class UserUpdateAPIView(generics.RetrieveUpdateAPIView):
    permission_classes = (permissions.IsAdminUser,)
    serializer_class = UserUpdateSerialier
    lookup_field = 'username'

    def get_object(self):
        username = self.kwargs["username"]
        return get_object_or_404(User, username=username)

    def put(self, request, *args, **kwargs):
        return self.update(request, *args, **kwargs)
</code>```

Body:
I come from Vietnam.

I want to update User by Django Rest FrameWork. I can update User by 'pk'. But I can't update User by 'username'. I hope that everyone help me. Thank you so much.

serializers.py

class UserDetailSerializer(serializers.ModelSerializer):
    url_update = serializers.HyperlinkedIdentityField(view_name='api:UserUpdateAPIView', lookup_field='username')
    class Meta:
        model = User
        fields = ('url_update', 'username', 'email', 'user_permissions', 'is_staff', 'groups', 'last_login')

class UserUpdateSerialier(serializers.ModelSerializer):
    password = serializers.CharField(
        style={'input_type': 'password'}
    )
    class Meta:
        model = User
        fields = ('pk', 'username', 'password')

    def update(self, instance, validated_data):
        instance.username = validated_data.get('username', instance.username)
        instance.set_password(validated_data.get('password', instance.password))
        instance.save()
        return instance

views.py

class UserDetailAPIView(generics.RetrieveAPIView):
    permission_classes = (permissions.IsAdminUser,)
    serializer_class = UserDetailSerializer
    #queryset = User.objects.all()
    lookup_field = 'username'
    def get_object(self):
        username = self.kwargs["username"]
        return get_object_or_404(User, username=username)

class UserUpdateAPIView(generics.RetrieveUpdateAPIView):
    permission_classes = (permissions.IsAdminUser,)
    #queryset = User.objects.all()
    serializer_class = UserUpdateSerialier

    def get_object(self):
        username = self.kwargs["username"]
        return get_object_or_404(User, username=username)

    def put(self, request, *args, **kwargs):
        return self.update(request, *args, **kwargs)

urls.py

url(r'^$', views.UserListAPIView.as_view(), name='UserListAPIView'),
url(r'^(?P<username>.*)/$', views.UserDetailAPIView.as_view(), name='UserDetailAPIView'),
url(r'^(?P<username>.*)/update/$', views.UserUpdateAPIView.as_view(), name='UserUpdateAPIView'),

HTTP 404 Not Found

Allow: GET, HEAD, OPTIONS

Content-Type: application/json

Vary: Accept

{
      "detail": "Not found."
  }

Body:
Try editing your view like this,

class UserUpdateAPIView(generics.RetrieveUpdateAPIView):
    permission_classes = (permissions.IsAdminUser,)
    serializer_class = UserUpdateSerialier
    lookup_field = 'username'

    def get_object(self):
        username = self.kwargs["username"]
        return get_object_or_404(User, username=username)

    def put(self, request, *args, **kwargs):
        return self.update(request, *args, **kwargs)


问:
How can I replace image with javascript?
My view like this :

```<code><li id="thumbnail-view" class="count-photo">
    <div class="thumbnail">
        <img src="{{ asset('img/thumbs/'.$photo) }}" alt="">
        <a href="javascript:" class="thumbnail-check"><span class="fa fa-check-circle"></span></a>
        <ul class="list-inline list-edit">
            ...
        </ul>
    </div>
</li>
</code>```

My javascript like this :

```<code>var photo = 'flower.jpg';
var res = `<img src="{{ asset('img/thumbs/'+photo) }}" alt="">`
$('#thumbnail-view img').html(res);
</code>```

If the javascript code executed, I want to change the image

I try like that, but it does not work

How can I do it?

答:
Don't set the inner HTML of an image, set its src property.

```<code>$('#thumbnail-view img').prop("src", "{{ asset('img/thumbs/') }}"+photo);
</code>```

Sidenote: if this is in a .js file then your template engine probably will not process the asset tag so you need to hardcode the path or grab it from elsewhere.

```<code>$('#thumbnail-view img').prop("src", "/assets/img/thumbs/"+photo);
</code>```

Body:
My view like this :

            ...

My javascript like this :

var photo = 'flower.jpg';
var res = `<img src="{{ asset('img/thumbs/'+photo) }}" alt="">`
$('#thumbnail-view img').html(res);

If the javascript code executed, I want to change the image

I try like that, but it does not work

How can I do it?

Body:
Don't set the inner HTML of an image, set its src property.

$('#thumbnail-view img').prop("src", "{{ asset('img/thumbs/') }}"+photo);

Sidenote: if this is in a .js file then your template engine probably will not process the asset tag so you need to hardcode the path or grab it from elsewhere.

$('#thumbnail-view img').prop("src", "/assets/img/thumbs/"+photo);


问:
How to Access 64bit DLLs from Java?
I use JDK (64 bit) and am using the JNA library to access a DLL. However this dll is in C: \ Windows \ SysWWOW64, so it is 64bit. How do I access it?
My processor is: 64bits. My JDK is 64bits. My DLL is 64bits.

My Program:

```<code> LibraryMethods libMethods = (LibraryMethods) Native.loadLibrary("msxfs.dll", LibraryMethods.class);
</code>```

My JNA Interface:

```<code>import com.sun.jna.Library;

public interface LibraryMethods extends Library{

     public short WFSStartUp(int dwVersionsRequired, String lpWFSVersion);

}
</code>```

Error:

```<code>java.lang.UnsatisfiedLinkError: %1 is not a valid Win32 application.
</code>```

答:
If the library is in SysWoW64 then it is 32 bits not 64.

So you need to use JDK 32 bits to load the DLL.

You can find more info about SysWow64 in this question

Title: How to Access 64bit DLLs from Java?

Body:
I use JDK (64 bit) and am using the JNA library to access a DLL. However this dll is in C: \ Windows \ SysWWOW64, so it is 64bit. How do I access it?
My processor is: 64bits. My JDK is 64bits. My DLL is 64bits.

My Program:

 LibraryMethods libMethods = (LibraryMethods) Native.loadLibrary("msxfs.dll", LibraryMethods.class);

My JNA Interface:

import com.sun.jna.Library;

public interface LibraryMethods extends Library{

     public short WFSStartUp(int dwVersionsRequired, String lpWFSVersion);

}

Error:

java.lang.UnsatisfiedLinkError: %1 is not a valid Win32 application.


问:
Trying to install library 'quantmod' in R
I'm trying to download library 'quantmod' in R:

```<code>install.packages("quantmod")
</code>```

console:

```<code>The downloaded source packages are in
‘/tmp/RtmpwSKGIl/downloaded_packages’
</code>```

then:

```<code>library("quantmod", lib.loc="/tmp/RtmpwSKGIl/downloaded_packages")
</code>```

console:

```<code>Error in library("quantmod", lib.loc = "/tmp/RtmpwSKGIl/downloaded_packages") :
  there is no package called ‘quantmod’
</code>```

What is the problem?

答:
I get no problem when I try to load this package.

Have you tried to provide R the full name path to your package file directory ?
C:/Users/...

Is your R version up to date ? Try to check if you have the latest, I tried and it worked with :

R 3.3.3

If you are a Windows or MAC user you might want to force the download of the package from source to binary, this can be done by setting the right options in the install.packages command:

options(install.packages.check.source = "no")

https://stat.ethz.ch/R-manual/R-devel/library/utils/html/install.packages.html

Body:
I'm trying to download library 'quantmod' in R:

install.packages("quantmod")

console:

The downloaded source packages are in
‘/tmp/RtmpwSKGIl/downloaded_packages’

then:

library("quantmod", lib.loc="/tmp/RtmpwSKGIl/downloaded_packages")

console:

Error in library("quantmod", lib.loc = "/tmp/RtmpwSKGIl/downloaded_packages") :
  there is no package called ‘quantmod’

What is the problem?


问:
How to clear memory and disk cache for images loaded using Kingfisherin UITableView?
I need to free all the memory occupied by images fetched using Kingfisher. I have a UITableView that store a lot of images and has the Load More feature also.

I tried these measures.

In viewDidLoad() I am setting the cache size.

```<code>let cache = KingfisherManager.sharedManager.cache
cache.maxMemoryCost = 50 * 1024 * 1024
// Set max disk cache to 50 mb. Default is no limit.
cache.maxDiskCacheSize = 50 * 1024 * 1024
// Set max disk cache to duration to 3 days, Default is 1 week.
cache.maxCachePeriodInSecond = 60 * 60 * 24 * 3
</code>```

In viewWillDisappear() I am clearing this.

```<code>cache.clearMemoryCache()
// Clear disk cache.
cache.clearDiskCache()
// Clean expired or size exceeded disk cache.
cache.cleanExpiredDiskCache()
</code>```

Still memory does not gets free as expected. Kindly correct me if I m missing something.

答:
On receiving memory warning I cleared the cache and it worked fine for me now :

```<code>override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
    cache.clearMemoryCache()
    cache.clearDiskCache()
    cache.cleanExpiredDiskCache()
}
</code>```

Update for Swift 4 :

```<code>override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
    KingfisherManager.shared.cache.clearMemoryCache()
    KingfisherManager.shared.cache.clearDiskCache()
    KingfisherManager.shared.cache.cleanExpiredDiskCache()
}
</code>```

Body:
I need to free all the memory occupied by images fetched using Kingfisher. I have a UITableView that store a lot of images and has the Load More feature also.

I tried these measures.

In viewDidLoad() I am setting the cache size.

let cache = KingfisherManager.sharedManager.cache
cache.maxMemoryCost = 50 * 1024 * 1024
// Set max disk cache to 50 mb. Default is no limit.
cache.maxDiskCacheSize = 50 * 1024 * 1024
// Set max disk cache to duration to 3 days, Default is 1 week.
cache.maxCachePeriodInSecond = 60 * 60 * 24 * 3

In viewWillDisappear() I am clearing this.

cache.clearMemoryCache()
// Clear disk cache.
cache.clearDiskCache()
// Clean expired or size exceeded disk cache.
cache.cleanExpiredDiskCache()

Still memory does not gets free as expected. Kindly correct me if I m missing something.

Body:
On receiving memory warning I cleared the cache and it worked fine for me now :

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
    cache.clearMemoryCache()
    cache.clearDiskCache()
    cache.cleanExpiredDiskCache()
}

Update for Swift 4 :

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
    KingfisherManager.shared.cache.clearMemoryCache()
    KingfisherManager.shared.cache.clearDiskCache()
    KingfisherManager.shared.cache.cleanExpiredDiskCache()
}

ContentLicense: CC BY-SA 4.0


问:
JS input type date field, keep values selected after form submission
Is there a way for the  </p>

```<code><input type="date" id="from" class="mdl-textfield__input" name="from" value="{{moment date=d format='YYYY-MM-DD'}}" style="position:relative; float: left; width: 180px; bottom: 10px;"/>
</code>```

<p>field to remember selected value after form submission? </p>

答:
Use HTML5 with storage
   stored the value in a variable after clicking the submit button. you can do whatever you want with that variable</p>

```<code>localStorage.setItem("user_selected_date", value);
</code>```

Body:
Is there a way for the

<input type="date" id="from" class="mdl-textfield__input" name="from" value="{{moment date=d format='YYYY-MM-DD'}}" style="position:relative; float: left; width: 180px; bottom: 10px;"/>

field to remember selected value after form submission?

Body:
Use HTML5 with storage
   stored the value in a variable after clicking the submit button. you can do whatever you want with that variable

localStorage.setItem("user_selected_date", value);


答:
You should use like this:
$('#thumbnail-view img').attr('src','path/to/photo');

Title: How can I replace image with javascript?


问:
google shell programmatically download reviews from google play
so I have opened a google cloud platform account and would like to programmatically download my apps reviews from Google Play Store.
On a support.google.com page it says that I could do this with gsutil.
I tried the example code:

```<code>gsutil cp -r gs://pubsite_prod_rev_0123456789/reviews/reviews_com.example.app_2014* /your/local/directory
</code>```

Replacing the examples. But I cant get it to work. It says 'No URLs matched'

1) What do I do wrong?

2) I dont think this command programmatically downloads this report everyday, how would I do this?

Thanks

答:
This command would actually work. The problem was that I did not initiate gcloud and allowed my Google account access to my local machine.

So downloading gcloud, installing it and then initiate with gcloud init will do the trick.

Body:
so I have opened a google cloud platform account and would like to programmatically download my apps reviews from Google Play Store.
On a support.google.com page it says that I could do this with gsutil.
I tried the example code:

gsutil cp -r gs://pubsite_prod_rev_0123456789/reviews/reviews_com.example.app_2014* /your/local/directory

Replacing the examples. But I cant get it to work. It says 'No URLs matched'

1) What do I do wrong?

2) I dont think this command programmatically downloads this report everyday, how would I do this?

Thanks


问:
How to test a regex password in Python?
Using a regex in Python, how can I verify that a user's password is:

At least 8 characters

Must be restricted to, though does not specifically require any of:

uppercase letters: A-Z

lowercase letters: a-z

numbers: 0-9

any of the special characters: @#$%^&+=

Note, all the letter/number/special chars are optional.  I only want to verify that the password is at least 8 chars in length and is restricted to a letter/number/special char.  It's up to the user to pick a stronger / weaker password if they so choose.
So far what I have is:

```<code>import re
pattern = "^.*(?=.{8,})(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%^&+=]).*$"
password = raw_input("Enter string to test: ")
result = re.findall(pattern, password)
if (result):
    print "Valid password"
else:
    print "Password not valid"
</code>```

答:
This regex validate if the password:

uppercase letters: A-Z
-lowercase letters: a-z

numbers: 0-9

any of the
special characters: !@£$%^&*()_+={}?:~[]]+

```<code>re.compile(r'^.*(?=.{8,10})(?=.*[a-zA-Z])(?=.*?[A-Z])(?=.*\d)[a-zA-Z0-9!@£$%^&*()_+={}?:~\[\]]+$')
</code>```

Title: How to test a regex password in Python?

Body:
Using a regex in Python, how can I verify that a user's password is:

At least 8 characters

Must be restricted to, though does not specifically require any of:

uppercase letters: A-Z

lowercase letters: a-z

numbers: 0-9

any of the special characters: @#$%^&+=

Note, all the letter/number/special chars are optional.  I only want to verify that the password is at least 8 chars in length and is restricted to a letter/number/special char.  It's up to the user to pick a stronger / weaker password if they so choose.
So far what I have is:

import re
pattern = "^.*(?=.{8,})(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%^&+=]).*$"
password = raw_input("Enter string to test: ")
result = re.findall(pattern, password)
if (result):
    print "Valid password"
else:
    print "Password not valid"

Body:
This regex validate if the password:

uppercase letters: A-Z
-lowercase letters: a-z

numbers: 0-9

any of the
special characters: !@£$%^&*()_+={}?:~[]]+

re.compile(r'^.*(?=.{8,10})(?=.*[a-zA-Z])(?=.*?[A-Z])(?=.*\d)[a-zA-Z0-9!@£$%^&*()_+={}?:~\[\]]+$')


问:
laravel get the filename of all records od my database
I want to get from all of my records the value of the filename fields but i have this error. Can anyone help me?

My Code:

$acao = Acao::where('estado_id', '1');

              if($acao->count() >= 1) {

                $filename = $acao->imagem;

                $path = asset('images/acoes/'.$filename);

                return view ('CFAE.index', compact('path'))->withAcoes($acao);

              }else{

                return view ('CFAE.index')->withAcoes($acao);

              }

And the laravel show me this error:

Undefined property: Illuminate\Database\Eloquent\Builder::$imagem

答:
You should use the first() method to get an object:

```<code>$acao = Acao::where('estado_id', '1')->first();
</code>```

You do not use it, so you get an instance of Query Builder which doesn't have imagem property.

Also, to check if object is found or not, do this:

```<code>if (!is_null($acao)) {
</code>```

Body:
You should use the first() method to get an object:

$acao = Acao::where('estado_id', '1')->first();

You do not use it, so you get an instance of Query Builder which doesn't have imagem property.

Also, to check if object is found or not, do this:

if (!is_null($acao)) {


问:
Flash / Actionscript CPU profiler
Have you found such a tool and used it successfully?</p>

答:
I was also looking for a profiler for AS, but I wanted an freeware/open source solution that works with FlashDevelop and Flex SDK. I found none. So I wrote a simple python script and an even simpler AS class. The script essentially takes any AS file and adds profiling code (i.e. calls to measure the total runtime of that function with an accuracy of 1 ms - the resolution of the flash.utils.getTimer() call) to each function definition. The script sometimes makes mistakes, but these are usually easy to fix by hand. Then you need to add one more line manually: dump the profiling statistics somewhere at some point. This method is obviously far from accurate, but it nonetheless gives you good feel of bottlenecks in your code. I used it for a 100k file with success.

Here is the AS class:

```<code>package  {
    public class Profiler {
        private static var instance:Profiler;

        public static function get profiler():Profiler {
            if (!Profiler.instance) Profiler.instance = new Profiler;
            return Profiler.instance;
        }

        private var data:Object = {};

        public function profile(fn:String, dur:int):void {
            if (!data.hasOwnProperty(fn)) data[fn] = new Number(0);
            data[fn] += dur / 1000.0;
        }

        public function clear():void {
            data = { };
        }

        public function get stats():String {
            var st:String = "";
            for (var fn:String in data) {
                st += fn + ":\t" + data[fn] + "\n";
            }
            return st;
        }
    }
}
</code>```

And here is the python script that does the trick:

```<code>import sre, sys

rePOI = sre.compile(r'''\bclass\b|\bfunction\b|\breturn\b|["'/{}]''')
reFun = sre.compile(r'\bfunction\b\s*((?:[gs]et\s+)?\w*)\s*\(')
reCls = sre.compile(r'class\s+(\w+)[\s{]')
reStr = sre.compile(r'''(["'/]).*?(?<!\\)\1''')

def addProfilingCalls(body):
    stack = []
    pos = 0
    depth = 0
    retvar = 0
    klass = ""
    match = rePOI.search(body, pos)
    while match:
        poi = match.group(0)
        pos = match.start(0)
        endpos = match.end(0)

        if poi in '''"'/''':
            strm = reStr.match(body, pos)
            if strm and (poi != '/' or sre.search('[=(,]\s*$', body[:pos])):
                endpos = strm.end(0)

        elif poi == 'class':
            klass = reCls.match(body, pos).group(1)
            sys.stderr.write('class ' + klass + '\n')

        elif poi == 'function':
            fname = reFun.match(body, pos)
            if fname.group(1):
                fname = klass + '.' + fname.group(1)
            else:
                lastf = stack[-1]
                lastf['anon'] += 1
                fname = lastf['name'] + '.anon' + str(lastf['anon'])
            sys.stderr.write('function ' + fname + '\n')
            stack.append({'name':fname, 'depth':depth, 'anon':0})

            brace = body.find('{', pos) + 1
            line = "\nvar __start__:int = flash.utils.getTimer();"
            body = body[:brace] + line + body[brace:]
            depth += 1
            endpos = brace + len(line)

        elif poi == '{':
            depth += 1

        elif poi == 'return':
            lastf = stack[-1]
            semicolon = body.find(';', pos) + 1
            if sre.match('return\s*;', body[pos:]):
                line = "{ Profiler.profiler.profile('" + lastf['name'] + \
                       "', flash.utils.getTimer() - __start__); return; }"
            else:
                retvar += 1
                line = "{ var __ret" + str(retvar) + "__:* =" + body[pos+6:semicolon] + \
                       "\nProfiler.profiler.profile('" + lastf['name'] + \
                       "', flash.utils.getTimer() - __start__); return __ret" + str(retvar) + "__; }"
            body = body[:pos] + line + body[semicolon:]
            endpos = pos + len(line)

        elif poi == '}':
            depth -= 1
            if len(stack) > 0 and stack[-1]['depth'] == depth:
                lastf = stack.pop()
                line = "Profiler.profiler.profile('" + lastf['name'] + \
                    "', flash.utils.getTimer() - __start__);\n"
                body = body[:pos] + line + body[pos:]
                endpos += len(line)

        pos = endpos
        match = rePOI.search(body, pos)
    return body

def main():
    if len(sys.argv) >= 2: inf = open(sys.argv[1], 'rU')
    else: inf = sys.stdin
    if len(sys.argv) >= 3: outf = open(sys.argv[2], 'wU')
    else: outf = sys.stdout
    outf.write(addProfilingCalls(inf.read()))
    inf.close()
    outf.close()

if __name__ == "__main__":
    main()
</code>```

Feel free to use, distribute and modify both.

OwnerDisplayName: joeysim

Title: Flash / Actionscript CPU profiler

Body:
I was also looking for a profiler for AS, but I wanted an freeware/open source solution that works with FlashDevelop and Flex SDK. I found none. So I wrote a simple python script and an even simpler AS class. The script essentially takes any AS file and adds profiling code (i.e. calls to measure the total runtime of that function with an accuracy of 1 ms - the resolution of the flash.utils.getTimer() call) to each function definition. The script sometimes makes mistakes, but these are usually easy to fix by hand. Then you need to add one more line manually: dump the profiling statistics somewhere at some point. This method is obviously far from accurate, but it nonetheless gives you good feel of bottlenecks in your code. I used it for a 100k file with success.

Here is the AS class:

package  {
    public class Profiler {
        private static var instance:Profiler;

        public static function get profiler():Profiler {
            if (!Profiler.instance) Profiler.instance = new Profiler;
            return Profiler.instance;
        }

        private var data:Object = {};

        public function profile(fn:String, dur:int):void {
            if (!data.hasOwnProperty(fn)) data[fn] = new Number(0);
            data[fn] += dur / 1000.0;
        }

        public function clear():void {
            data = { };
        }

        public function get stats():String {
            var st:String = "";
            for (var fn:String in data) {
                st += fn + ":\t" + data[fn] + "\n";
            }
            return st;
        }
    }
}

And here is the python script that does the trick:

import sre, sys

rePOI = sre.compile(r'''\bclass\b|\bfunction\b|\breturn\b|["'/{}]''')
reFun = sre.compile(r'\bfunction\b\s*((?:[gs]et\s+)?\w*)\s*\(')
reCls = sre.compile(r'class\s+(\w+)[\s{]')
reStr = sre.compile(r'''(["'/]).*?(?<!\\)\1''')

def addProfilingCalls(body):
    stack = []
    pos = 0
    depth = 0
    retvar = 0
    klass = ""
    match = rePOI.search(body, pos)
    while match:
        poi = match.group(0)
        pos = match.start(0)
        endpos = match.end(0)

        if poi in '''"'/''':
            strm = reStr.match(body, pos)
            if strm and (poi != '/' or sre.search('[=(,]\s*$', body[:pos])):
                endpos = strm.end(0)

        elif poi == 'class':
            klass = reCls.match(body, pos).group(1)
            sys.stderr.write('class ' + klass + '\n')

        elif poi == 'function':
            fname = reFun.match(body, pos)
            if fname.group(1):
                fname = klass + '.' + fname.group(1)
            else:
                lastf = stack[-1]
                lastf['anon'] += 1
                fname = lastf['name'] + '.anon' + str(lastf['anon'])
            sys.stderr.write('function ' + fname + '\n')
            stack.append({'name':fname, 'depth':depth, 'anon':0})

            brace = body.find('{', pos) + 1
            line = "\nvar __start__:int = flash.utils.getTimer();"
            body = body[:brace] + line + body[brace:]
            depth += 1
            endpos = brace + len(line)

        elif poi == '{':
            depth += 1

        elif poi == 'return':
            lastf = stack[-1]
            semicolon = body.find(';', pos) + 1
            if sre.match('return\s*;', body[pos:]):
                line = "{ Profiler.profiler.profile('" + lastf['name'] + \
                       "', flash.utils.getTimer() - __start__); return; }"
            else:
                retvar += 1
                line = "{ var __ret" + str(retvar) + "__:* =" + body[pos+6:semicolon] + \
                       "\nProfiler.profiler.profile('" + lastf['name'] + \
                       "', flash.utils.getTimer() - __start__); return __ret" + str(retvar) + "__; }"
            body = body[:pos] + line + body[semicolon:]
            endpos = pos + len(line)

        elif poi == '}':
            depth -= 1
            if len(stack) > 0 and stack[-1]['depth'] == depth:
                lastf = stack.pop()
                line = "Profiler.profiler.profile('" + lastf['name'] + \
                    "', flash.utils.getTimer() - __start__);\n"
                body = body[:pos] + line + body[pos:]
                endpos += len(line)

        pos = endpos
        match = rePOI.search(body, pos)
    return body

def main():
    if len(sys.argv) >= 2: inf = open(sys.argv[1], 'rU')
    else: inf = sys.stdin
    if len(sys.argv) >= 3: outf = open(sys.argv[2], 'wU')
    else: outf = sys.stdout
    outf.write(addProfilingCalls(inf.read()))
    inf.close()
    outf.close()

if __name__ == "__main__":
    main()

Feel free to use, distribute and modify both.

OwnerDisplayName: David Hanak


问:
Knexjs PgSQL json query
I have a column in a Postgres that stores some JSON data. The JSON has no defined schema, but it should be possible to search all records that have some specified key.

I'm using KnexJS to build the queries and so far I came up with this:

```<code>tx.select('*').from('table')
.whereRaw('cast(data->>? as ?) = ?', [key, type, JSON.parse(value)]));
</code>```

But it's not working because I don't think it will be possible to specify the type.

Still, when I try to specify it manually like this:

```<code>tx.select('*').from('table')
.whereRaw('cast(data->>? as boolean) = ?', [key, JSON.parse(value)]));
</code>```

It still doesn't work! This is the log from the console when using DEBUG:knex:*

```<code>{ key: 'admin', value: 'true', type: 'boolean' }
  knex:tx trx1: Starting top level transaction +0ms
  knex:pool INFO pool postgresql:pg:client0 - dispense() clients=1 available=0 +2ms
  knex:client acquired connection from pool: __knexUid2 +38ms
  knex:query BEGIN; +2ms
  knex:bindings undefined +1ms
  knex:query select * from "contexts" where cast(data->>? as boolean) = ? +18ms
  knex:bindings [ 'admin', true ] +0ms
  knex:query COMMIT; +9ms
  knex:bindings undefined +0ms
  knex:tx trx1: releasing connection +6ms
  knex:client releasing connection to pool: __knexUid2 +1ms
  knex:pool INFO pool postgresql:pg:client0 - dispense() clients=0 available=1 +1ms
</code>```

Any ideas on how I can accomplish this?

thanks in advance!

答:
How bindings work:

First of all you need to know how binding work at the lib you use.

From the debug log you provided it shows that you value type as string:

```<code>key: 'admin', value: 'true', type: 'boolean'
</code>```

Therefore the first query and its actual SQL translation is:

```<code>// Your code:
tx.select('*').from('table')
.whereRaw('cast(data->>? as ?) = ?', [key, type, JSON.parse(value)]));

// Actual SQL:
SELECT * FROM "table" WHERE cast(data->>'admin' as 'boolean') = true;
</code>```

This provides clear syntax error that is visible in your Postgres logs also.

The second query (when you cast manually) fails because you kept 3 binding parameters while using only 2 and second parameter is by array order type instead of value:

```<code>// Your code:
tx.select('*').from('table')
.whereRaw('cast(data->>? as boolean) = ?', [key, JSON.parse(value)]));

// Actual SQL:
SELECT * FROM "table" WHERE cast(data->>'admin' as boolean) = 'undefined'
</code>```

Which naturally fails.

While you are at it, some SQL tips:

Postgres gives you few other options/styles how you can execute your query and here are some other examples (all giving same results):

```<code>// Casting with `=` s
SELECT * FROM table WHERE (data ->> 'admin')::boolean = TRUE            // finds all `true` values
SELECT * FROM table WHERE NOT ( (data ->> 'admin')::boolean = FALSE )   // finds all 'false' values

// Since every condition in WHERE ends up boolean you can avoid
// using `=` comparsion and shorten the code
SELECT * FROM table WHERE (data ->> 'admin')::boolean                   // finds all `true` values
SELECT * FROM table WHERE NOT ( (data ->> 'admin')::boolean )           // finds all 'false' values

// When using JSONB data type you can use `->` operator instead
SELECT * FROM table WHERE data -> 'admin' = 'true'                      // finds all `true` values
SELECT * FROM table WHERE NOT ( data -> 'admin' = 'false' )             // finds all 'false' values
</code>```

What style you prefer is totally up to your preference and I'm just pointing out how else you can do it :)

Hopefully, helps :)

Title: Knexjs PgSQL json query

Body:
I have a column in a Postgres that stores some JSON data. The JSON has no defined schema, but it should be possible to search all records that have some specified key.

I'm using KnexJS to build the queries and so far I came up with this:

tx.select('*').from('table')
.whereRaw('cast(data->>? as ?) = ?', [key, type, JSON.parse(value)]));

But it's not working because I don't think it will be possible to specify the type.

Still, when I try to specify it manually like this:

tx.select('*').from('table')
.whereRaw('cast(data->>? as boolean) = ?', [key, JSON.parse(value)]));

It still doesn't work! This is the log from the console when using DEBUG:knex:*

{ key: 'admin', value: 'true', type: 'boolean' }
  knex:tx trx1: Starting top level transaction +0ms
  knex:pool INFO pool postgresql:pg:client0 - dispense() clients=1 available=0 +2ms
  knex:client acquired connection from pool: __knexUid2 +38ms
  knex:query BEGIN; +2ms
  knex:bindings undefined +1ms
  knex:query select * from "contexts" where cast(data->>? as boolean) = ? +18ms
  knex:bindings [ 'admin', true ] +0ms
  knex:query COMMIT; +9ms
  knex:bindings undefined +0ms
  knex:tx trx1: releasing connection +6ms
  knex:client releasing connection to pool: __knexUid2 +1ms
  knex:pool INFO pool postgresql:pg:client0 - dispense() clients=0 available=1 +1ms

Any ideas on how I can accomplish this?

thanks in advance!

Body:
How bindings work:

First of all you need to know how binding work at the lib you use.

From the debug log you provided it shows that you value type as string:

key: 'admin', value: 'true', type: 'boolean'

Therefore the first query and its actual SQL translation is:

// Your code:
tx.select('*').from('table')
.whereRaw('cast(data->>? as ?) = ?', [key, type, JSON.parse(value)]));

// Actual SQL:
SELECT * FROM "table" WHERE cast(data->>'admin' as 'boolean') = true;

This provides clear syntax error that is visible in your Postgres logs also.

The second query (when you cast manually) fails because you kept 3 binding parameters while using only 2 and second parameter is by array order type instead of value:

// Your code:
tx.select('*').from('table')
.whereRaw('cast(data->>? as boolean) = ?', [key, JSON.parse(value)]));

// Actual SQL:
SELECT * FROM "table" WHERE cast(data->>'admin' as boolean) = 'undefined'

Which naturally fails.

While you are at it, some SQL tips:

Postgres gives you few other options/styles how you can execute your query and here are some other examples (all giving same results):

// Casting with `=` s
SELECT * FROM table WHERE (data ->> 'admin')::boolean = TRUE            // finds all `true` values
SELECT * FROM table WHERE NOT ( (data ->> 'admin')::boolean = FALSE )   // finds all 'false' values

// Since every condition in WHERE ends up boolean you can avoid
// using `=` comparsion and shorten the code
SELECT * FROM table WHERE (data ->> 'admin')::boolean                   // finds all `true` values
SELECT * FROM table WHERE NOT ( (data ->> 'admin')::boolean )           // finds all 'false' values

// When using JSONB data type you can use `->` operator instead
SELECT * FROM table WHERE data -> 'admin' = 'true'                      // finds all `true` values
SELECT * FROM table WHERE NOT ( data -> 'admin' = 'false' )             // finds all 'false' values

What style you prefer is totally up to your preference and I'm just pointing out how else you can do it :)

Hopefully, helps :)