问:
URLClassLoader finding X but not Y in same folder
General idea: I'm writing on a loader for java that allows dynamically reloading classes to allow for changing the implementation, without restarting the entire program to keep the main application running and minimize downtimes. Every external piece of code is grouped by "modules", each module has a main class with a "onEnable, postEnable, onDisable" entry/exit point and can consist of any amount of classes. To load a module, the class containing the entry point is specified, then loaded. I'll reference them as "modules" and "additional classes" in the following, "module" being the class containing the above mentioned functions by implementing the "public interface Module", "additional classes" refer to everything the module would use on runtime but isn't a Module by itself (e.g. we have a Module called "Car implements Module", and that module requires a class "Engine" to function -> "Car" is the module, "Engine" is an additional class")

Code of what I'm doing to load a module initially (name is a String containing the full classname including path, example given later):

```<code>Class<?> clazz = mainLoader.loadClass(name);
Module module = (Module) clazz.newInstance();
addLoadedModule(module);
enableLoadedModule(module);
</code>```

And here's how I reload the module when it's already existing, so that I can override the implementation. "m" is an instance of the current implementation of the Module that is supposed to be reloaded.

```<code>boolean differs = false;
Class<?> newClass = null;
try (URLClassLoader cl = new URLClassLoader(urls, mainLoader.getParent()))
{
    // Try to load the class and check if it differs from the already known one
    newClass = cl.loadClass(m.getClass().getName());
    differs = m.getClass() != newClass;
}
catch (IOException | ClassNotFoundException e)
{
    // Class couldn't be found, abort.
    e.printStackTrace();
    return;
}
if (!differs)
{
    // New class == old class -> no need to reload it
    return;
}
Module module = null;
try
{
    // Try to instantiate the class
    module = (Module) newClass.newInstance();
}
catch (InstantiationException | IllegalAccessException e)
{
    // Can't instantiate, abort
    e.printStackTrace();
    return;
}
// Check versions, only reload if the new implementation's version differs from the current one. Version is a custom annotation, don't worry about that; the version check works fine
Version oldVersion = m.getClass().getAnnotation(Version.class);
Version newVersion = module.getClass().getAnnotation(Version.class);
if (oldVersion.equals(newVersion))
{
    return;
}
// And if everything went well, disable and remove the old module from the list, then add and enable the new module.
disableModule(m);
modules.remove(m);
modules.put(module, false);
enableLoadedModule(module);
</code>```

This is the mainLoader, urls is an URL[] pointing to the location containing the external classes to load:

```<code>mainLoader = new URLClassLoader(urls, this.getClass().getClassLoader());
</code>```

The problem arises when I try to RE-load an implementation, that requires multiple classes:

Module of class A requires class B to function. This is what happens when I try to dynamically load, then reload class A:

load A -> "Sure, but I'll need B with it." -> automatically loads B -> "Here ya go, A works fine now."
reload A -> "Sure, but I'll need B with it." -> crashes because B couldn't be found

Both classes are located in the exact same folder, structure like this:

Class A implements Module: com/foo/bar/A.class

Class B: com/foo/bar/B.class

urls: ["com/foo/bar/"]

I call the function with load("com.foo.bar.A"), which works when attempting to load it the first time, but fails when trying to reload it as described above.

It works fine when trying to load a "single class module", the problem arises when the module relies on an additional external class. I tried using different classloaders to use as the parent for the URLClassLoader in the reloading process, those being the sysloader, Module.class.getClassLoader(), mainLoader (using that one, it won't ever find the new class definition because it already knows about it and therefor won't even attempt to load it from the drive again) and the mainLoader.getParent(), the classloader of the old module, and the parent of the modules classloader.

I'm probably just overseeing something obvious, but I can't figure out why it would manage to load the "extra" classes the first time, but fail when I reload the base class...

If you need any debug outputs or exact errors let me know, I replaced the debug outputs with comments explaining what does what so I got a fairly detailed log of what's happening when, but I didn't seem it to be necessary as it goes through the entire "check and then load" process just fine, it crashes when trying to enable the module. The "onEnable" method of the module requires the additional class B, that's where it fails. As I said, if you need the implementation of the classes A and B, Module, any other code or the debug outputs let me know and I'll add them in as requested.

答: The solution lies in the classloader being closed and deleted as soon as the loading of the initial class is done, due to the class loader being only existant in the try/catch clause. I solved the issue by storing the classloader in a map until a new implementation of the module is loaded, then I can discard the old loader and store the new one instead.</p>

Body:
General idea: I'm writing on a loader for java that allows dynamically reloading classes to allow for changing the implementation, without restarting the entire program to keep the main application running and minimize downtimes. Every external piece of code is grouped by "modules", each module has a main class with a "onEnable, postEnable, onDisable" entry/exit point and can consist of any amount of classes. To load a module, the class containing the entry point is specified, then loaded. I'll reference them as "modules" and "additional classes" in the following, "module" being the class containing the above mentioned functions by implementing the "public interface Module", "additional classes" refer to everything the module would use on runtime but isn't a Module by itself (e.g. we have a Module called "Car implements Module", and that module requires a class "Engine" to function -> "Car" is the module, "Engine" is an additional class")

Code of what I'm doing to load a module initially (name is a String containing the full classname including path, example given later):

Class<?> clazz = mainLoader.loadClass(name);
Module module = (Module) clazz.newInstance();
addLoadedModule(module);
enableLoadedModule(module);

And here's how I reload the module when it's already existing, so that I can override the implementation. "m" is an instance of the current implementation of the Module that is supposed to be reloaded.

boolean differs = false;
Class<?> newClass = null;
try (URLClassLoader cl = new URLClassLoader(urls, mainLoader.getParent()))
{
    // Try to load the class and check if it differs from the already known one
    newClass = cl.loadClass(m.getClass().getName());
    differs = m.getClass() != newClass;
}
catch (IOException | ClassNotFoundException e)
{
    // Class couldn't be found, abort.
    e.printStackTrace();
    return;
}
if (!differs)
{
    // New class == old class -> no need to reload it
    return;
}
Module module = null;
try
{
    // Try to instantiate the class
    module = (Module) newClass.newInstance();
}
catch (InstantiationException | IllegalAccessException e)
{
    // Can't instantiate, abort
    e.printStackTrace();
    return;
}
// Check versions, only reload if the new implementation's version differs from the current one. Version is a custom annotation, don't worry about that; the version check works fine
Version oldVersion = m.getClass().getAnnotation(Version.class);
Version newVersion = module.getClass().getAnnotation(Version.class);
if (oldVersion.equals(newVersion))
{
    return;
}
// And if everything went well, disable and remove the old module from the list, then add and enable the new module.
disableModule(m);
modules.remove(m);
modules.put(module, false);
enableLoadedModule(module);

This is the mainLoader, urls is an URL[] pointing to the location containing the external classes to load:

mainLoader = new URLClassLoader(urls, this.getClass().getClassLoader());

The problem arises when I try to RE-load an implementation, that requires multiple classes:

Module of class A requires class B to function. This is what happens when I try to dynamically load, then reload class A:

load A -> "Sure, but I'll need B with it." -> automatically loads B -> "Here ya go, A works fine now."
reload A -> "Sure, but I'll need B with it." -> crashes because B couldn't be found

Both classes are located in the exact same folder, structure like this:

Class A implements Module: com/foo/bar/A.class

Class B: com/foo/bar/B.class

urls: ["com/foo/bar/"]

I call the function with load("com.foo.bar.A"), which works when attempting to load it the first time, but fails when trying to reload it as described above.

It works fine when trying to load a "single class module", the problem arises when the module relies on an additional external class. I tried using different classloaders to use as the parent for the URLClassLoader in the reloading process, those being the sysloader, Module.class.getClassLoader(), mainLoader (using that one, it won't ever find the new class definition because it already knows about it and therefor won't even attempt to load it from the drive again) and the mainLoader.getParent(), the classloader of the old module, and the parent of the modules classloader.

I'm probably just overseeing something obvious, but I can't figure out why it would manage to load the "extra" classes the first time, but fail when I reload the base class...

If you need any debug outputs or exact errors let me know, I replaced the debug outputs with comments explaining what does what so I got a fairly detailed log of what's happening when, but I didn't seem it to be necessary as it goes through the entire "check and then load" process just fine, it crashes when trying to enable the module. The "onEnable" method of the module requires the additional class B, that's where it fails. As I said, if you need the implementation of the classes A and B, Module, any other code or the debug outputs let me know and I'll add them in as requested.


来源: stackexchange

问:
Appium, Cucumber and Junit how to run tests in parallel on multiple devices
Trying to execute my appium tests in parallel on multiple devices.

I currently can execute my test cases on one android device. After a chopping and changing I cannot get my tests to run in parallel.

Heres my current set up. Hoping to execute tests in parallel without the need for saucelabs or selenium grid.

Example of my Junit runner

```<code>@RunWith(Cucumber.class)
@CucumberOptions(plugin = {"json:target/cucumber.json", "pretty"}, features = {
    "src/test/resources/features/
},
    glue = "com.test.stepdefs")
public class RunCukesTest {

  private static AppiumDriverLocalService service;
  public static File file;

  @BeforeClass
  public static void startAppium() throws IOException {

    System.out.println("YOUR OS NAME : " + osName);

    String nodePath = null;
    String appiumPath = null;

    ServerArgument argument;

    if (osName.contains("mac")) {
//            mac paths
      nodePath = "/usr/local/bin/node";
      appiumPath = "/usr/local/lib/node_modules/appium/build/lib/main.js";

      service = AppiumDriverLocalService.buildService(new AppiumServiceBuilder()
                                                          .usingDriverExecutable(new File(nodePath))
                                                          .usingPort(4723)
                                                          .withArgument(GeneralServerFlag.LOG_LEVEL,
                                                                        "error")
                                                          .withAppiumJS(new File(appiumPath)));
    } else if (osName.contains("windows")) {

      service = AppiumDriverLocalService.buildDefaultService();

    } else if (osName.contains("linux")) {
//    linuxs path
      nodePath = System.getenv("PRODUCTION") + "/.linuxbrew/bin/node";
      appiumPath =
          System.getenv("PRODUCTION") + "/.linuxbrew/lib/node_modules/appium/build/lib/main.js";
      service = AppiumDriverLocalService.buildService(new AppiumServiceBuilder()
                                                          .usingDriverExecutable(new File(nodePath))
                                                          .usingPort(4723)
                                                          .withAppiumJS(new File(appiumPath)));
    }

    service.addOutPutStream(stream);
    service.start();
  }

  @AfterClass
  public static void stopAppium() {
    service.stop();
  }
</code>```

and an example of my

```<code>@Configuration
public class AppUtils {
    @Value("${explicit.wait}")
    public int explicitWaitTime;
    @Value("${implicit.wait}")
    public int implicitWaitTime;
    @Value("${default.wait}")
    public int defaultWaitTime;
    public String applicationName;
    public DesiredCapabilities capabilities;
    @Value("${appium.server.port}")
    private String appiumPort;
    @Value("${automation.instrumentation}")
    private String instrumentation;
    @Value("${browser.name}")
    private String browserName;
    @Value("${platform.name}")
    private String platformName;
    @Value("${device.name}")
    private String deviceName;
    @Value("${platform.version}")
    private String platformVersion;
    @Value("${new.command.timeout}")
    private String newCommandTimeout;
    @Value("${app.package}")
    private String appPackage;
    @Value("${device.ready.timeout}")
    private String deviceReadyTimeout;
    private URL serverUrl;
    private AppiumDriver<? extends MobileElement> driver;

    @Bean(destroyMethod = "quit")
    @Scope("cucumber-glue")
    public AndroidDriver getDriver() throws MalformedURLException {
        capabilities = new DesiredCapabilities();
        capabilities.setCapability(MobileCapabilityType.BROWSER_NAME, "Chrome");
        capabilities.setCapability(MobileCapabilityType.PLATFORM_VERSION, platformVersion);
        capabilities.setCapability(MobileCapabilityType.PLATFORM_NAME, platformName);
        capabilities.setCapability(MobileCapabilityType.DEVICE_NAME, deviceName);
        capabilities.setCapability(MobileCapabilityType.AUTOMATION_NAME, instrumentation);
        capabilities.setCapability("appPackage", "com.android.chrome"); //To be moved to properties
        capabilities.setCapability("appActivity", "com.google.android.apps.chrome.Main"); //To be moved to properties
        serverUrl = new URL("http://localhost:" + appiumPort + "/wd/hub");
//        LoggingPreferences logPrefs = new LoggingPreferences();
//        logPrefs.addPreferences()
//        capabilities.setCapability(CapabilityType.LOGGING_PREFS, logs);
        driver = new AndroidDriver(serverUrl, capabilities);

        driver.manage().timeouts().implicitlyWait(implicitWaitTime, TimeUnit.SECONDS);
        //driver.setLogLevel(Level.OFF);
        return (AndroidDriver) driver;
    }
}
</code>```

Cannot find any good documentation on this and would appreciated any help.

答: You should start another appium server instance listening on different port and then launch tests with this new server port capability.</p>

ContentLicense: CC BY-SA 3.0

Body:
Trying to execute my appium tests in parallel on multiple devices.

I currently can execute my test cases on one android device. After a chopping and changing I cannot get my tests to run in parallel.

Heres my current set up. Hoping to execute tests in parallel without the need for saucelabs or selenium grid.

Example of my Junit runner

@RunWith(Cucumber.class)
@CucumberOptions(plugin = {"json:target/cucumber.json", "pretty"}, features = {
    "src/test/resources/features/
},
    glue = "com.test.stepdefs")
public class RunCukesTest {

  private static AppiumDriverLocalService service;
  public static File file;

  @BeforeClass
  public static void startAppium() throws IOException {

    System.out.println("YOUR OS NAME : " + osName);

    String nodePath = null;
    String appiumPath = null;

    ServerArgument argument;

    if (osName.contains("mac")) {
//            mac paths
      nodePath = "/usr/local/bin/node";
      appiumPath = "/usr/local/lib/node_modules/appium/build/lib/main.js";

      service = AppiumDriverLocalService.buildService(new AppiumServiceBuilder()
                                                          .usingDriverExecutable(new File(nodePath))
                                                          .usingPort(4723)
                                                          .withArgument(GeneralServerFlag.LOG_LEVEL,
                                                                        "error")
                                                          .withAppiumJS(new File(appiumPath)));
    } else if (osName.contains("windows")) {

      service = AppiumDriverLocalService.buildDefaultService();

    } else if (osName.contains("linux")) {
//    linuxs path
      nodePath = System.getenv("PRODUCTION") + "/.linuxbrew/bin/node";
      appiumPath =
          System.getenv("PRODUCTION") + "/.linuxbrew/lib/node_modules/appium/build/lib/main.js";
      service = AppiumDriverLocalService.buildService(new AppiumServiceBuilder()
                                                          .usingDriverExecutable(new File(nodePath))
                                                          .usingPort(4723)
                                                          .withAppiumJS(new File(appiumPath)));
    }

    service.addOutPutStream(stream);
    service.start();
  }

  @AfterClass
  public static void stopAppium() {
    service.stop();
  }

and an example of my

@Configuration
public class AppUtils {
    @Value("${explicit.wait}")
    public int explicitWaitTime;
    @Value("${implicit.wait}")
    public int implicitWaitTime;
    @Value("${default.wait}")
    public int defaultWaitTime;
    public String applicationName;
    public DesiredCapabilities capabilities;
    @Value("${appium.server.port}")
    private String appiumPort;
    @Value("${automation.instrumentation}")
    private String instrumentation;
    @Value("${browser.name}")
    private String browserName;
    @Value("${platform.name}")
    private String platformName;
    @Value("${device.name}")
    private String deviceName;
    @Value("${platform.version}")
    private String platformVersion;
    @Value("${new.command.timeout}")
    private String newCommandTimeout;
    @Value("${app.package}")
    private String appPackage;
    @Value("${device.ready.timeout}")
    private String deviceReadyTimeout;
    private URL serverUrl;
    private AppiumDriver<? extends MobileElement> driver;

    @Bean(destroyMethod = "quit")
    @Scope("cucumber-glue")
    public AndroidDriver getDriver() throws MalformedURLException {
        capabilities = new DesiredCapabilities();
        capabilities.setCapability(MobileCapabilityType.BROWSER_NAME, "Chrome");
        capabilities.setCapability(MobileCapabilityType.PLATFORM_VERSION, platformVersion);
        capabilities.setCapability(MobileCapabilityType.PLATFORM_NAME, platformName);
        capabilities.setCapability(MobileCapabilityType.DEVICE_NAME, deviceName);
        capabilities.setCapability(MobileCapabilityType.AUTOMATION_NAME, instrumentation);
        capabilities.setCapability("appPackage", "com.android.chrome"); //To be moved to properties
        capabilities.setCapability("appActivity", "com.google.android.apps.chrome.Main"); //To be moved to properties
        serverUrl = new URL("http://localhost:" + appiumPort + "/wd/hub");
//        LoggingPreferences logPrefs = new LoggingPreferences();
//        logPrefs.addPreferences()
//        capabilities.setCapability(CapabilityType.LOGGING_PREFS, logs);
        driver = new AndroidDriver(serverUrl, capabilities);

        driver.manage().timeouts().implicitlyWait(implicitWaitTime, TimeUnit.SECONDS);
        //driver.setLogLevel(Level.OFF);
        return (AndroidDriver) driver;
    }
}

Cannot find any good documentation on this and would appreciated any help.


问:
What does `(c = *str) != 0` mean?
```<code>int equiv (char, char);
int nmatches(char *str, char comp) {
    char c;
    int n=0;
    while ((c = *str) != 0) {
       if (equiv(c,comp) != 0) n++;
      str++;
    }
    return (n);
}
</code>```

What does "(c = *str) != 0" actually mean?
Can someone please explain it to me or help give me the correct terms to search for an explanation myself?

答:
We are going through the str in the while loop and extract every char symbol in it until it is equal to zero - the main rule of the end of char string.

Here is 'for' loop equivalent:

```<code> for (int i = 0; i < strlen(str); ++i )
       std::cout << str[i];
</code>```

Title: What does `(c = *str) != 0` mean?

Body:
int equiv (char, char);
int nmatches(char *str, char comp) {
    char c;
    int n=0;
    while ((c = *str) != 0) {
       if (equiv(c,comp) != 0) n++;
      str++;
    }
    return (n);
}

What does "(c = *str) != 0" actually mean?
Can someone please explain it to me or help give me the correct terms to search for an explanation myself?

Body:
We are going through the str in the while loop and extract every char symbol in it until it is equal to zero - the main rule of the end of char string.

Here is 'for' loop equivalent:

 for (int i = 0; i < strlen(str); ++i )
       std::cout << str[i];


问:
How to read ctx.request.body in koa 2 (without body-parser)?
I want to read ctx.request.body from a post without body-parser middleware.

```<code>const Koa = require('koa');
const Router = require('koa-router');
const app = new Koa();
const router = new Router();
app.use(router.routes());

router.post('/publish', async (ctx, next) => {
  let msg = JSON.stringify(ctx.request.body);
  console.log(msg); //undefined
  console.log(ctx.request.body); //undefined
  console.log(ctx.req.body);  //undefined
});

app.listen(process.env.PORT);
</code>```

Using curl -X POST -H "Content-Type: application/json" -d '{"key":"val"}' 'http://localhost:8080/publish' I get 3 undefined.

How do I solve this problem? I know that koa can't parse req.body, but why doesn't JSON.stringify(ctx.request.body) work?

答:
JSON.stringify(ctx.request.body) does not work, because it only gets set if you use one of the available body parsers. So if you do not want to use body-parser (or any other body-parser middleware), you have to parse the body from req.body by yourself.

But honestly, why would you not want to use one of the existing solutions for your problem?

Body:
I want to read ctx.request.body from a post without body-parser middleware.

const Koa = require('koa');
const Router = require('koa-router');
const app = new Koa();
const router = new Router();
app.use(router.routes());

router.post('/publish', async (ctx, next) => {
  let msg = JSON.stringify(ctx.request.body);
  console.log(msg); //undefined
  console.log(ctx.request.body); //undefined
  console.log(ctx.req.body);  //undefined
});

app.listen(process.env.PORT);

Using curl -X POST -H "Content-Type: application/json" -d '{"key":"val"}' 'http://localhost:8080/publish' I get 3 undefined.

How do I solve this problem? I know that koa can't parse req.body, but why doesn't JSON.stringify(ctx.request.body) work?


问:
Deleting a value at a time by it's location which is separated by a comma in column of a mysql table
This is table that has all the skills which candidate can add to their profile in candidate table

And this is where candidate has added desired skills which is separated by comma,

Now i am stuck , problem is how can i delete those skills which i dont want anymore to be in my profile. This is separated by a comma that's why i am finding it delete individualy

```<code>$sql_r = "select expert_skills, inter_skills, beginner_skills
            from user_personal_details
            WHERE upd_user_id = '". $_SESSION["user_id"] ."'";

$skills_render = $this->model->execute_query_all($sql_r);

$arr1=explode(",",$skills_render['0']['expert_skills']);

$ty = array_keys($arr1);
$ty1 = array_values($arr1);

$location = $_POST['skill_location'];

echo $location;
</code>```

$location variable i.e skill id, i am taking from front end, how can i delete by location

答:
You should normalize your database.

Or for each delete action, update the entire value in skills.

if you want to remove one item individually, you need to update the field with new set of values.

you have 1,2,9,10,7,6,8 as expert_skills. if you need to remove 9 & 10 then you need to update it as 1,2,7,6,8.

I assume you don't have a delete screen but an update screen where you select/unselect the skills.

Body:
This is table that has all the skills which candidate can add to their profile in candidate table

And this is where candidate has added desired skills which is separated by comma,

Now i am stuck , problem is how can i delete those skills which i dont want anymore to be in my profile. This is separated by a comma that's why i am finding it delete individualy

$sql_r = "select expert_skills, inter_skills, beginner_skills
            from user_personal_details
            WHERE upd_user_id = '". $_SESSION["user_id"] ."'";

$skills_render = $this->model->execute_query_all($sql_r);

$arr1=explode(",",$skills_render['0']['expert_skills']);

$ty = array_keys($arr1);
$ty1 = array_values($arr1);

$location = $_POST['skill_location'];

echo $location;

$location variable i.e skill id, i am taking from front end, how can i delete by location


问:
How to get IPv4 address when using SOCKS over ssh
I'm using SOCKS5 over ssh. All works fine, however, when I check my public IP address, I see this is an IPv6 address (The machine I'm connecting to has both IPv4 and IPv6 addresses). If I understand this correctly this is the responsibility of sshd_config on the server I'm using for SOCKS, right? Is it possible somehow to force this to use IPv4 address?

答:
What you can try to do is force SSHD into the IPv4 only mode, by setting:

AddressFamily inet

in your sshd_config

AddressFamily

Specifies which address family should be used by sshd(8). Valid arguments are ''any'', ''inet'' (use IPv4 only), or ''inet6'' (use IPv6 only). The default is ''any''.

man sshd_config  (OpenSSH)


问:
Ambari Hive UTF-8 problems
Have a problem with cyrillic symbols at hive tables. Installed versions:

```<code>ambari-server 2.4.2.0-136
hive-2-5-3-0-37 1.2.1000.2.5.3.0-37
Ubuntu 14.04
</code>```

Whats the problem:

Set locale to ru_RU.UTF-8:

```<code>spark@hadoop:~$ locale
LANG=ru_RU.UTF-8
LANGUAGE=ru_RU:ru
LC_CTYPE="ru_RU.UTF-8"
LC_NUMERIC="ru_RU.UTF-8"
LC_TIME="ru_RU.UTF-8"
LC_COLLATE="ru_RU.UTF-8"
LC_MONETARY="ru_RU.UTF-8"
LC_MESSAGES="ru_RU.UTF-8"
LC_PAPER="ru_RU.UTF-8"
LC_NAME="ru_RU.UTF-8"
LC_ADDRESS="ru_RU.UTF-8"
LC_TELEPHONE="ru_RU.UTF-8"
LC_MEASUREMENT="ru_RU.UTF-8"
LC_IDENTIFICATION="ru_RU.UTF-8"
LC_ALL=ru_RU.UTF-8
</code>```

Connect to hive and create test table:

```<code>spark@hadoop:~$ beeline -n spark -u jdbc:hive2://spark@hadoop.domain.com:10000/

Connecting to enter code herejdbc:hive2://spark@hadoop.domain.com:10000/
Connected to: Apache Hive (version 1.2.1000.2.5.3.0-37)
Driver: Hive JDBC (version 1.2.1000.2.5.3.0-37)
Transaction isolation: TRANSACTION_REPEATABLE_READ
Beeline version 1.2.1000.2.5.3.0-37 by Apache Hive

0: jdbc:hive2://spark@hadoop.domain.com> CREATE TABLE `test`(`name` string) ROW FORMAT SERDE 'org.apache.hadoop.hive.serde2.lazy.LazySimpleSerDe' WITH SERDEPROPERTIES ( 'serialization.encoding'='UTF-8');
No rows affected (0,127 seconds)
</code>```

Insert cyrillic symbols:

```<code>0: jdbc:hive2://spark@hadoop.domain.com> insert into test values('привет');

INFO  : Tez session hasn't been created yet. Opening session
INFO  : Dag name: insert into test values('привет')(Stage-1)
INFO  :

INFO  : Status: Running (Executing on YARN cluster with App id application_1490211406894_2481)

INFO  : Map 1: -/-
INFO  : Map 1: 0/1
INFO  : Map 1: 0(+1)/1
INFO  : Map 1: 1/1
INFO  : Loading data to table default.test from hdfs://hadoop.domain.com:8020/apps/hive/warehouse/test/.hive-staging_hive_2017-03-23_13-41-46_215_3133047104896717605-116/-ext-10000
INFO  : Table default.test stats: [numFiles=1, numRows=1, totalSize=7, rawDataSize=6]
No rows affected (6,652 seconds)
</code>```

Select from table:

```<code>0: jdbc:hive2://spark@hadoop.domain.com> select * from test;
+------------+--+
| test.name  |
+------------+--+
| ?@825B     |
+------------+--+
1 row selected (0,162 seconds)
</code>```

I've read a lot of bugs at apache hive, tested unicode, utf-8, utf-16, some isos encodings with no luck.

Can somebody help me with that?

Thanks!

答:
Guys from Hortonwroks helped me with that issue. Seems that it's a bug.

https://community.hortonworks.com/answers/90989/view.html

https://issues.apache.org/jira/browse/HIVE-13983

Title: Ambari Hive UTF-8 problems

Body:
Have a problem with cyrillic symbols at hive tables. Installed versions:

ambari-server 2.4.2.0-136
hive-2-5-3-0-37 1.2.1000.2.5.3.0-37
Ubuntu 14.04

Whats the problem:

Set locale to ru_RU.UTF-8:

spark@hadoop:~$ locale
LANG=ru_RU.UTF-8
LANGUAGE=ru_RU:ru
LC_CTYPE="ru_RU.UTF-8"
LC_NUMERIC="ru_RU.UTF-8"
LC_TIME="ru_RU.UTF-8"
LC_COLLATE="ru_RU.UTF-8"
LC_MONETARY="ru_RU.UTF-8"
LC_MESSAGES="ru_RU.UTF-8"
LC_PAPER="ru_RU.UTF-8"
LC_NAME="ru_RU.UTF-8"
LC_ADDRESS="ru_RU.UTF-8"
LC_TELEPHONE="ru_RU.UTF-8"
LC_MEASUREMENT="ru_RU.UTF-8"
LC_IDENTIFICATION="ru_RU.UTF-8"
LC_ALL=ru_RU.UTF-8

Connect to hive and create test table:

spark@hadoop:~$ beeline -n spark -u jdbc:hive2://spark@hadoop.domain.com:10000/

Connecting to enter code herejdbc:hive2://spark@hadoop.domain.com:10000/
Connected to: Apache Hive (version 1.2.1000.2.5.3.0-37)
Driver: Hive JDBC (version 1.2.1000.2.5.3.0-37)
Transaction isolation: TRANSACTION_REPEATABLE_READ
Beeline version 1.2.1000.2.5.3.0-37 by Apache Hive

0: jdbc:hive2://spark@hadoop.domain.com> CREATE TABLE `test`(`name` string) ROW FORMAT SERDE 'org.apache.hadoop.hive.serde2.lazy.LazySimpleSerDe' WITH SERDEPROPERTIES ( 'serialization.encoding'='UTF-8');
No rows affected (0,127 seconds)

Insert cyrillic symbols:

0: jdbc:hive2://spark@hadoop.domain.com> insert into test values('привет');

INFO  : Tez session hasn't been created yet. Opening session
INFO  : Dag name: insert into test values('привет')(Stage-1)
INFO  :

INFO  : Status: Running (Executing on YARN cluster with App id application_1490211406894_2481)

INFO  : Map 1: -/-
INFO  : Map 1: 0/1
INFO  : Map 1: 0(+1)/1
INFO  : Map 1: 1/1
INFO  : Loading data to table default.test from hdfs://hadoop.domain.com:8020/apps/hive/warehouse/test/.hive-staging_hive_2017-03-23_13-41-46_215_3133047104896717605-116/-ext-10000
INFO  : Table default.test stats: [numFiles=1, numRows=1, totalSize=7, rawDataSize=6]
No rows affected (6,652 seconds)

Select from table:

0: jdbc:hive2://spark@hadoop.domain.com> select * from test;
+------------+--+
| test.name  |
+------------+--+
| ?@825B     |
+------------+--+
1 row selected (0,162 seconds)

I've read a lot of bugs at apache hive, tested unicode, utf-8, utf-16, some isos encodings with no luck.

Can somebody help me with that?

Thanks!


问:
GridView Header Click
I am trying to figure out how to point a Grid View Header Click to my Viewmodel

```<code> <ListView ItemsSource="{Binding UserProfileData}" GridViewColumnHeader.Click="Handle_Click">
       <ListView.View>
                <GridView>
                    <GridViewColumn DisplayMemberBinding="{Binding Name}" Header="User ID"/>
                    <GridViewColumn DisplayMemberBinding="{Binding LastUsed}" Header="Last Loaded"/>
                    <GridViewColumn DisplayMemberBinding="{Binding IsLoaded}" Header="Logged In"/>
                </GridView>
            </ListView.View>
        </ListView>
</code>```

GridViewColumnHeader.Click="Handle_Click" will push it to my MainWindow.xaml.cs but i want to have the click go to the DataContext of my MainWindow

```<code><Window.DataContext>
    <vm:MainWindowViewModel/>
</Window.DataContext>
</code>```

any ideas?

答:
You could use a style to bind the Command property of the GridViewColumnHeader to an ICommand source property of your view model. You could then pass the header string as the argument to the command:

```<code><ListView x:Name="test" ItemsSource="{Binding UserProfileData}">
    <ListView.Resources>
        <Style TargetType="GridViewColumnHeader">
            <Setter Property="Command" Value="{Binding YourCommandProperty}" />
            <Setter Property="CommandParameter" Value="{Binding Content, RelativeSource={RelativeSource Self}}" />
        </Style>
    </ListView.Resources>
    <ListView.View>
        <GridView>
            <GridViewColumn DisplayMemberBinding="{Binding Name}" Header="User ID"/>
            <GridViewColumn DisplayMemberBinding="{Binding LastUsed}" Header="Last Loaded"/>
            <GridViewColumn DisplayMemberBinding="{Binding IsLoaded}" Header="Logged In"/>
        </GridView>
    </ListView.View>
</ListView>
</code>```

Title: GridView Header Click

Body:
I am trying to figure out how to point a Grid View Header Click to my Viewmodel

 <ListView ItemsSource="{Binding UserProfileData}" GridViewColumnHeader.Click="Handle_Click">
       <ListView.View>
                <GridView>
                    <GridViewColumn DisplayMemberBinding="{Binding Name}" Header="User ID"/>
                    <GridViewColumn DisplayMemberBinding="{Binding LastUsed}" Header="Last Loaded"/>
                    <GridViewColumn DisplayMemberBinding="{Binding IsLoaded}" Header="Logged In"/>
                </GridView>
            </ListView.View>
        </ListView>

GridViewColumnHeader.Click="Handle_Click" will push it to my MainWindow.xaml.cs but i want to have the click go to the DataContext of my MainWindow

<Window.DataContext>
    <vm:MainWindowViewModel/>
</Window.DataContext>

any ideas?

Body:
You could use a style to bind the Command property of the GridViewColumnHeader to an ICommand source property of your view model. You could then pass the header string as the argument to the command:

<ListView x:Name="test" ItemsSource="{Binding UserProfileData}">
    <ListView.Resources>
        <Style TargetType="GridViewColumnHeader">
            <Setter Property="Command" Value="{Binding YourCommandProperty}" />
            <Setter Property="CommandParameter" Value="{Binding Content, RelativeSource={RelativeSource Self}}" />
        </Style>
    </ListView.Resources>
    <ListView.View>
        <GridView>
            <GridViewColumn DisplayMemberBinding="{Binding Name}" Header="User ID"/>
            <GridViewColumn DisplayMemberBinding="{Binding LastUsed}" Header="Last Loaded"/>
            <GridViewColumn DisplayMemberBinding="{Binding IsLoaded}" Header="Logged In"/>
        </GridView>
    </ListView.View>
</ListView>


答:
Confusingly,

while ((c = *str) != 0) {

is a tautology of the considerably easier to read

while (c = *str) {

This also has the effect of assigning the character at *str to c, and the loop will terminate once *str is \0; i.e. when the end of the string has been reached.

Assignments within conditionals such as the above can be confusing on first glance, (cf. the behaviour of the very different c == *str), but they are such a useful part of C and C++, you need to get used to them.

Title: What does `(c = *str) != 0` mean?


问:
How to invoke a function and pass parameter when you have function name as string?
How to invoke a function when you have function name as string? e.g.</p>

```<code>$scope.ExecuteFunction = function (func,val) {
  // here func="GetActivityInfo" and val="ERF000000000A6543"
  // How to Invoke function named in variable func and pass val as parameter ?
  // GetActivityInfo(val) to be invoked.
}

var GetActivityInfo = function (elementId) {
  // some code
};
</code>```

答:
You can use apply() or call() for achieving it,

var test = func.apply(test,val); this line should be added

Definition:

---> With call() or apply() you can set the value of this, and invoke a function as a new method of an existing object.

Difference between call() and apply():

---> call() takes the function arguments separately, and apply() takes the function arguments in an array.

<!DOCTYPE html>

```

Please run the above snippet

Body:
How to invoke a function when you have function name as string? e.g.

$scope.ExecuteFunction = function (func,val) {
  // here func="GetActivityInfo" and val="ERF000000000A6543"
  // How to Invoke function named in variable func and pass val as parameter ?
  // GetActivityInfo(val) to be invoked.
}

var GetActivityInfo = function (elementId) {
  // some code
};

Body:
You can use apply() or call() for achieving it,

var test = func.apply(test,val); this line should be added

Definition:

---> With call() or apply() you can set the value of this, and invoke a function as a new method of an existing object.

Difference between call() and apply():

---> call() takes the function arguments separately, and apply() takes the function arguments in an array.

<!DOCTYPE html>
<html>
<body>

<p id="demo"></p>

<script>
var myObject, myArray;
function myFunction(func,val) {
    var test = func.apply(test,val);
}
function myFunction2(val) {
    alert(val)
}
myObject = myFunction(myFunction2, ['myArray called using apply ']);      // Will return the value called from inside using `apply`
document.getElementById("demo").innerHTML = myObject;
</script>

</body>
</html>

Please run the above snippet


问:
Sum up every N elements of a list?
I have a list of numbers like this:

```<code>[ 0, 1, 2, 3, 4, 5, 6, 7 ]
</code>```

How to sum up every N (let's assume 2) elements in an elegant way and transform the list into:

```<code>[ 1, 5, 9, 13 ]
</code>```

edit:
I came up with the following solution:

```<code>    List<Double> input = Arrays.asList(0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0);
    List<Double> output = new ArrayList<>();

    int N = 2;
    IntStream.range(0, (input.size() + N - 1) / N)
            .mapToObj(i -> input.subList(i * N, Math.min(N * (i + 1), input.size())))
            .mapToDouble(l -> l.stream().mapToDouble(Double::doubleValue).sum())
            .forEach(output::add);

    System.out.println(output);
</code>```

It works, but I'm still looking for a more readable and simple one.

答:
I think most elegant way is using flatMap, so you avoid O(n²) complexity.
Here's an example:

```<code>public static class Helper {

    private final int chunkSize;
    private int index;
    private int sum;

    public Helper(int chunkSize) {
        this.chunkSize = chunkSize;
    }

    public Stream<Integer> set(int v) {
        index += 1;
        sum += v;

        ArrayList<Integer> ret = new ArrayList<>();
        if (index == chunkSize) {
            ret.add(sum);
            sum = 0;
            index = 0;
        }
        return ret.stream();
    }
}

public static void main(String[] args) {
    List<Integer> input = Arrays.asList(0, 1, 2, 3, 4, 5, 6, 7);
    Helper helper = new Helper(2);
    List<Integer> output = input.stream().flatMap(helper::set).collect(Collectors.toList());

    System.out.println(input);
    System.out.println(output);
}
</code>```

This will outputs:

```<code>[0, 1, 2, 3, 4, 5, 6, 7]
[1, 5, 9, 13]
</code>```

Title: Sum up every N elements of a list?

Body:
I have a list of numbers like this:

[ 0, 1, 2, 3, 4, 5, 6, 7 ]

How to sum up every N (let's assume 2) elements in an elegant way and transform the list into:

[ 1, 5, 9, 13 ]

edit:
I came up with the following solution:

    List<Double> input = Arrays.asList(0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0);
    List<Double> output = new ArrayList<>();

    int N = 2;
    IntStream.range(0, (input.size() + N - 1) / N)
            .mapToObj(i -> input.subList(i * N, Math.min(N * (i + 1), input.size())))
            .mapToDouble(l -> l.stream().mapToDouble(Double::doubleValue).sum())
            .forEach(output::add);

    System.out.println(output);

It works, but I'm still looking for a more readable and simple one.

Body:
I think most elegant way is using flatMap, so you avoid O(n²) complexity.
Here's an example:

public static class Helper {

    private final int chunkSize;
    private int index;
    private int sum;

    public Helper(int chunkSize) {
        this.chunkSize = chunkSize;
    }

    public Stream<Integer> set(int v) {
        index += 1;
        sum += v;

        ArrayList<Integer> ret = new ArrayList<>();
        if (index == chunkSize) {
            ret.add(sum);
            sum = 0;
            index = 0;
        }
        return ret.stream();
    }
}

public static void main(String[] args) {
    List<Integer> input = Arrays.asList(0, 1, 2, 3, 4, 5, 6, 7);
    Helper helper = new Helper(2);
    List<Integer> output = input.stream().flatMap(helper::set).collect(Collectors.toList());

    System.out.println(input);
    System.out.println(output);
}

This will outputs:

[0, 1, 2, 3, 4, 5, 6, 7]
[1, 5, 9, 13]


问:
Linq Group by to column
I have a list of items with a property code and I want to group by eventId and create a table representation where code values are transformed to columns.
Every triple (event, code,amount) is unique.

I want to transform this

```<code>eventId code  amount
  1      A     100
  1      B     101
  1      C     102
  2      A     103
  2      C     104
  3      B     105
  ....
</code>```

to this

```<code>eventId  A    B   C
 1      100  101 102
 2      103   0  104
 3       0   105  0
 ...

var table=from x in list
    group x by x.eventId into gr
    select new
           {
              eventId=gr.Key,
              ....
           }
</code>```

答:
You need to filter on grouped result and project in to anonymous object :</p>

```<code>var table=from x in list
    group x by x.eventId into gr
    select new
           {
              eventId=gr.Key,
              A = gr.Where(x=>x.code == "A").Sum(x=>x.amount),
              B = gr.Where(x=>x.code == "B").Sum(x=>x.amount),
              C = gr.Where(x=>x.code == "C").Sum(x=>x.amount)
           }
</code>```

Title: Linq Group by to column

Body:
I have a list of items with a property code and I want to group by eventId and create a table representation where code values are transformed to columns.
Every triple (event, code,amount) is unique.

I want to transform this

eventId code  amount
  1      A     100
  1      B     101
  1      C     102
  2      A     103
  2      C     104
  3      B     105
  ....

to this

eventId  A    B   C
 1      100  101 102
 2      103   0  104
 3       0   105  0
 ...

var table=from x in list
    group x by x.eventId into gr
    select new
           {
              eventId=gr.Key,
              ....
           }

Body:
You need to filter on grouped result and project in to anonymous object :

var table=from x in list
    group x by x.eventId into gr
    select new
           {
              eventId=gr.Key,
              A = gr.Where(x=>x.code == "A").Sum(x=>x.amount),
              B = gr.Where(x=>x.code == "B").Sum(x=>x.amount),
              C = gr.Where(x=>x.code == "C").Sum(x=>x.amount)
           }


问:
Copy Numbers from end of string
Here's something I can't get my head around and I would appreciate some help :)

At the moment I have fields on an Excel spreadsheet that have customer's addresses and phone numbers. However the phone numbers are at the end of each string in the address field e.g

Name,Address,Landline,Mobile

Johnson,2 Oxton Road Moreton CH45 9JB 07854213658 721 2569,

I need it to go to

Johnson,2 Oxton Road Moreton CH45 9JB,07854213658,721 2569

Any ideas? The phone numbers are always at the end of the string

I can also write in c# but I can't figure out where to start

Thanks in advance guys

答:
If you always have Address(space)Landline(space)mobile

and mobile always is ###(space)####.

Here's a way to do it with Excel.

```<code>A1: Johnson,2 Oxton Road Moreton CH45 9JB 07854213658 721 2569,
</code>```

You can get the number of spaces in the string: B1: =len(A1)-len(substitute(A1," ",""))

Here after, you can replace the correct spaces with commas, using substitute again:

```<code>C1: =substitute(A1," ",",",B1-2)
D1: =substitute(C1," ",",",B1-2)
</code>```

We're doing B1-2 in both, as the second space we want to replace has changed from the 7th to the 6th space.

You still need to remove the last comma, this could be done with: E1: =left(D1,len(D1)-1)

This can ofcourse all be nested:

```<code>B1: =left(substitute(substitute(A1," ",",",len(A1)-len(substitute(A1," ",""))-2)," ",",",len(A1)-len(substitute(A1," ",""))-2),len(A1)-1)
</code>```

Notice I'm just using the length of the old string, as the length shouldn't change when replacing two spaces with two commas.

Title: Copy Numbers from end of string

Body:
If you always have Address(space)Landline(space)mobile

and mobile always is ###(space)####.

Here's a way to do it with Excel.

A1: Johnson,2 Oxton Road Moreton CH45 9JB 07854213658 721 2569,

You can get the number of spaces in the string: B1: =len(A1)-len(substitute(A1," ",""))

Here after, you can replace the correct spaces with commas, using substitute again:

C1: =substitute(A1," ",",",B1-2)
D1: =substitute(C1," ",",",B1-2)

We're doing B1-2 in both, as the second space we want to replace has changed from the 7th to the 6th space.

You still need to remove the last comma, this could be done with: E1: =left(D1,len(D1)-1)

This can ofcourse all be nested:

B1: =left(substitute(substitute(A1," ",",",len(A1)-len(substitute(A1," ",""))-2)," ",",",len(A1)-len(substitute(A1," ",""))-2),len(A1)-1)

Notice I'm just using the length of the old string, as the length shouldn't change when replacing two spaces with two commas.


问:
Nginx doesn't recognize my Rails 3 application
I have set up nginx + REE + passenger on my Linode VPS, which has been running great for past six month, both for Rails 2.3.x and Sinatra applications.

However this week I tried to add Rails 3 application to the stack, and I keep on getting 404 Not Found. Logs show that nginx doesn't recognize Rails application and is trying to serve it as static.

```<code>2010/11/29 23:44:44 [error] 12464#0: *29 "/var/app/modelky/public/index.html"
is not found (2: No such file or directory), client: 90.177.23.122, server:
reedink.com, request: "GET / HTTP/1.1", host: "reedink.com"

2010/11/29 23:44:44 [error] 12464#0: *30 open() "/var/app/modelky/public/favicon.ico"
failed (2: No such file or directory), client: 90.177.23.122,
server: reedink.com, request: "GET /favicon.ico HTTP/1.1", host: "reedink.com"
</code>```

However, I'm using the same configuration as I use for all my other Rails 2.3.5 and Sinatra applications that works without any problems

```<code>server {
    listen 80;
    server_name www.reedink.com;
    rewrite ^(.*) http://reedink.com$1 permanent;
}

server {
    listen 80;
    server_name reedink.com;
    root /var/app/modelky/public;
    passenger_enabled on;
}
</code>```

From what I understand, Rails 3 should be rack compatible, so from the server's point of view, it's no different than any Sinatra application right?

答:
Looks like your request is not hitting Rails. I would try to:

put a static index.html in /var/app/modelky/public to see if it shows up

check if the Rails app is in the given path and restart nginx

prestart Passenger on that server and see how it reacts

To prestart Passenger:

```<code>http {
  server {
    listen 80;
    server_name www.reedink.com;
    rewrite ^(.*) http://reedink.com$1 permanent;
  }

  server {
    listen 80;
    server_name reedink.com;
    root /var/app/modelky/public;
    passenger_enabled on;
  }
passenger_pre_start http://reedink.com/;
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I have set up nginx + REE + passenger on my Linode VPS, which has been running great for past six month, both for Rails 2.3.x and Sinatra applications.

However this week I tried to add Rails 3 application to the stack, and I keep on getting 404 Not Found. Logs show that nginx doesn't recognize Rails application and is trying to serve it as static.

2010/11/29 23:44:44 [error] 12464#0: *29 "/var/app/modelky/public/index.html"
is not found (2: No such file or directory), client: 90.177.23.122, server:
reedink.com, request: "GET / HTTP/1.1", host: "reedink.com"

2010/11/29 23:44:44 [error] 12464#0: *30 open() "/var/app/modelky/public/favicon.ico"
failed (2: No such file or directory), client: 90.177.23.122,
server: reedink.com, request: "GET /favicon.ico HTTP/1.1", host: "reedink.com"

However, I'm using the same configuration as I use for all my other Rails 2.3.5 and Sinatra applications that works without any problems

server {
    listen 80;
    server_name www.reedink.com;
    rewrite ^(.*) http://reedink.com$1 permanent;
}

server {
    listen 80;
    server_name reedink.com;
    root /var/app/modelky/public;
    passenger_enabled on;
}

From what I understand, Rails 3 should be rack compatible, so from the server's point of view, it's no different than any Sinatra application right?

Body:
Looks like your request is not hitting Rails. I would try to:

put a static index.html in /var/app/modelky/public to see if it shows up

check if the Rails app is in the given path and restart nginx

prestart Passenger on that server and see how it reacts

To prestart Passenger:

http {
  server {
    listen 80;
    server_name www.reedink.com;
    rewrite ^(.*) http://reedink.com$1 permanent;
  }

  server {
    listen 80;
    server_name reedink.com;
    root /var/app/modelky/public;
    passenger_enabled on;
  }
passenger_pre_start http://reedink.com/;
}


问:
Odbc Connection - [ODBC Driver Manager] Data source name not found and no default driver specified
```<code>Public Sub Main()
    Dim connSource As New System.Data.Odbc.OdbcConnection

    Dim cmdSource As New System.Data.Odbc.OdbcCommand
    Dim cmdupdate As New System.Data.Odbc.OdbcCommand

    Dim connsql As System.Data.Odbc.OdbcConnection
    Dim cmdsql As System.Data.Odbc.OdbcCommand

    connsql = New System.Data.Odbc.OdbcConnection

    strsqlConnectionString = "Driver={ODBC Driver 11 for SQL Server};" & _
                             "Server=MyDatabaseServer;" & _
                             "DataBase=MyDatabase;" & _
                             "Trusted_Connection=Yes;"

    connsql.ConnectionString = strsqlConnectionString
    connsql.Open()

    cmdSource.Connection = connSource
    cmdupdate.Connection = connsql

    cmdsql = New System.Data.Odbc.OdbcCommand

    Dim m_strSourceExcelFileName As String
    m_strSourceExcelFileName = Dts.Variables("User::FileName").Value.ToString()
    Dim m_strSourceFilePath As String = "D:\Files\2017\"

    m_strConnSource = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + m_strSourceFilePath + "\" + m_strSourceExcelFileName + "; Extended Properties='Excel 12.0 Xml;HDR=NO'"

    connSource.ConnectionString = m_strConnSource
    connSource.Open()
</code>```

I have the above code snippet in an SSIS script task. The script task contains code to copy read data from excel to SQL Server 2014.

I'm getting the below error at last line 'connSource.Open()' in the snippet above.

ERROR [IM002] [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified

I can't seem to figure out what could be wrong with my connection string. I have AccessDatabaseEngine_x64.exe installed on the machine.

答:
To connect to Excel using ODBC, I use connection strings like:

Driver={Microsoft Excel Driver (*.xls, *.xlsx, *.xlsm, *.xlsb)};DBQ=E:\foo\excelTest.xls;

This works for the driver that comes with ACEODBC.DLL, with the Date 22.03.2010

Body:
Public Sub Main()
    Dim connSource As New System.Data.Odbc.OdbcConnection

    Dim cmdSource As New System.Data.Odbc.OdbcCommand
    Dim cmdupdate As New System.Data.Odbc.OdbcCommand

    Dim connsql As System.Data.Odbc.OdbcConnection
    Dim cmdsql As System.Data.Odbc.OdbcCommand

    connsql = New System.Data.Odbc.OdbcConnection

    strsqlConnectionString = "Driver={ODBC Driver 11 for SQL Server};" & _
                             "Server=MyDatabaseServer;" & _
                             "DataBase=MyDatabase;" & _
                             "Trusted_Connection=Yes;"

    connsql.ConnectionString = strsqlConnectionString
    connsql.Open()

    cmdSource.Connection = connSource
    cmdupdate.Connection = connsql

    cmdsql = New System.Data.Odbc.OdbcCommand

    Dim m_strSourceExcelFileName As String
    m_strSourceExcelFileName = Dts.Variables("User::FileName").Value.ToString()
    Dim m_strSourceFilePath As String = "D:\Files\2017\"

    m_strConnSource = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + m_strSourceFilePath + "\" + m_strSourceExcelFileName + "; Extended Properties='Excel 12.0 Xml;HDR=NO'"

    connSource.ConnectionString = m_strConnSource
    connSource.Open()

I have the above code snippet in an SSIS script task. The script task contains code to copy read data from excel to SQL Server 2014.

I'm getting the below error at last line 'connSource.Open()' in the snippet above.

ERROR [IM002] [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified

I can't seem to figure out what could be wrong with my connection string. I have AccessDatabaseEngine_x64.exe installed on the machine.


问:
Having trouble with --out cucumber
I'm currently investigating using cucumber's --out option to write my test results out to a file. However, I'm running into some difficulties, and can't find a lot of useful information about it online. I created a reports folder under my features folder, and put a file text.html in it, so it looks like this:

```<code>features
       -> reports
               -> test.html
</code>```

However, when I run

```<code>cucumber --tags @test --format html --out reports/test.html
</code>```

I get the error

```<code>Not a directory @ rb_sysopen - reports/test.html
Error creating formatter: html (Errno::ENOTDIR)
</code>```

If I just run

```<code>cucumber --tags @test --format html --out reports
</code>```

The test doesn't complain and goes and does its thing, but I can't find any report in reports. Any idea what I'm doing wrong? Thanks in advance.

答:
The path to the output folder is relative to the project root, not the features directory, so your directory structure should look like this:

```<code>features
reports
    -> test.html
</code>```

Move your reports directory into the project root and then you should see output being created.

Title: Having trouble with --out cucumber

Body:
I'm currently investigating using cucumber's --out option to write my test results out to a file. However, I'm running into some difficulties, and can't find a lot of useful information about it online. I created a reports folder under my features folder, and put a file text.html in it, so it looks like this:

features
       -> reports
               -> test.html

However, when I run

cucumber --tags @test --format html --out reports/test.html

I get the error

Not a directory @ rb_sysopen - reports/test.html
Error creating formatter: html (Errno::ENOTDIR)

If I just run

cucumber --tags @test --format html --out reports

The test doesn't complain and goes and does its thing, but I can't find any report in reports. Any idea what I'm doing wrong? Thanks in advance.

Body:
The path to the output folder is relative to the project root, not the features directory, so your directory structure should look like this:

features
reports
    -> test.html

Move your reports directory into the project root and then you should see output being created.


问:
How to make break after header in <data:post.snippet> in Blogger
I'm trying to make a simple line break between a header h2 and the first paragraph of a post in a <data:post.snippet> in Blogger.

This post kind of helps (How to increase character lengh in blogger snippet instead of using limited length, 'data:post.snippet'?), but I limited the amount of characters using this javascript code (https://groups.google.com/d/msg/bloggerdev/8jUR9uISmA0/J8dmGwACJDgJ) (I don't want to show <data:post.body> until the read more tag).

Is there a way to style the snippet to make a line break after a heading?

答:
You will need to utilize the new snippet operator introduced with new themes. It has an option to preserve the line breaks which are present in the actual post content. The code for the same will look like -

```<code><b:eval expr='snippet(data:post.body, {length: 450, linebreaks: true})' />
</code>```

This will process the data:post.body data tag and extract the first 450 characters from it while preserving the line breaks present in it.

For more detailed documentation of the snippet operator -

snippet(string, options)

Produces a short snippet from an HTML string.

options: Object specifying the snippeting options, which are:

links: boolean for whether to preserve anchors/links in the snippet.
Defaults to true.

linebreaks: boolean for whether to preserve linebreaks (tags) in the
snippet. Defaults to true.

ellipsis: boolean for whether to append an ellipsis (…) to the end of
the snippet. Defaults to true.

length: Number specifying the maximum length of the snippet.

Body:
You will need to utilize the new snippet operator introduced with new themes. It has an option to preserve the line breaks which are present in the actual post content. The code for the same will look like -

<b:eval expr='snippet(data:post.body, {length: 450, linebreaks: true})' />

This will process the data:post.body data tag and extract the first 450 characters from it while preserving the line breaks present in it.

For more detailed documentation of the snippet operator -

snippet(string, options)

Produces a short snippet from an HTML string.

options: Object specifying the snippeting options, which are:

links: boolean for whether to preserve anchors/links in the snippet.
Defaults to true.

linebreaks: boolean for whether to preserve linebreaks (tags) in the
snippet. Defaults to true.

ellipsis: boolean for whether to append an ellipsis (…) to the end of
the snippet. Defaults to true.

length: Number specifying the maximum length of the snippet.


问:
How to close window in vaadin?
I have got class MyCustomWindow which extends Window (com.vaadin.ui) from vaadin.
When you click some button MyCustomWindow will show.
Now I would like to add button to this window and when you push this buton it will close the window.
I have got problem what to use to remove this window.
I have found:

```<code>Window w = getWindow();
getApplication().removeWindow(w);
</code>```

or

```<code>Window w = this.findAncestor(Window.class);
w.close();
</code>```

But it doesn't work.
I would like to remove window from inside the class, not from outside, using "this"? Something like:

```<code>UI.getCurrent().removeWindow(this);
</code>```

I am using vaadin 7.
Can you help me?

答:
You could use this code to remove all windows.

```<code>for (Window window : UI.getCurrent().getWindows())
        {

            UI.getCurrent().removeWindow(window);
            window.close();
        }
</code>```

However if you already have reference to the window all you need is this:

```<code>UI.getCurrent().removeWindow(window);
</code>```

Title: How to close window in vaadin?

Body:
I have got class MyCustomWindow which extends Window (com.vaadin.ui) from vaadin.
When you click some button MyCustomWindow will show.
Now I would like to add button to this window and when you push this buton it will close the window.
I have got problem what to use to remove this window.
I have found:

Window w = getWindow();
getApplication().removeWindow(w);

or

Window w = this.findAncestor(Window.class);
w.close();

But it doesn't work.
I would like to remove window from inside the class, not from outside, using "this"? Something like:

UI.getCurrent().removeWindow(this);

I am using vaadin 7.
Can you help me?

Body:
You could use this code to remove all windows.

for (Window window : UI.getCurrent().getWindows())
        {

            UI.getCurrent().removeWindow(window);
            window.close();
        }

However if you already have reference to the window all you need is this:

UI.getCurrent().removeWindow(window);


问:
WPF Datagrid Multiple Selection without CTRL or Shift
The WPF Datagrid has two selection modes, Single or Extended. The WPF ListView has a third - Multiple. This mode allows you to click and select multiple rows without CTRL or Shift being held down. Anyone know how to do this for the datagrid?</p>

答:
Based on a previous article, i wrote a ("like") MVVM code:

Firstly add this to your main View:

```<code>  xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"
</code>```

The relevant part of View:

```<code>       <DataGrid
              Style="{StaticResource DataGridStyle}"
              ItemsSource="{Binding Results}"
              SelectionUnit="FullRow"
              SnapsToDevicePixels="True"
              SelectionMode="Extended">  <!--You can change selection mode with converter. It will work (i tested it.)-->
        <i:Interaction.Behaviors>
                         <utils:EventToCommandBehavior Command="{Binding TouchCommand}"
                                                  Event="PreviewTouchDown"
                                                  PassArguments="True"></utils:EventToCommandBehavior>
                        <utils:EventToCommandBehavior Command="{Binding MouseCommand}"
                                                  Event="PreviewMouseDown"
                                                  PassArguments="True"></utils:EventToCommandBehavior>
        </i:Interaction.Behaviors>
        <DataGrid.Resources>
            <Style TargetType="{x:Type DataGridRow}">
                <Setter Property="IsSelected"<Style.Triggers>
                    <Trigger Property="IsSelected" Value="True">
                        <Setter Property="Background">
                            <Setter.Value>
                                <SolidColorBrush>
                                    <SolidColorBrush.Color>
                                        <Color A="50" R="0" G="0" B="0" />
                                    </SolidColorBrush.Color>
                                </SolidColorBrush>
                            </Setter.Value>
                        </Setter>
                    </Trigger>
                </Style.Triggers>
            </Style>
          </DataGrid.Resources>
        <DataGrid.Columns>
         <!-- your columns -->
        </DataGrid.Columns>
       </DataGrid>
</code>```

More information about EventToCommandBehavior:
here

In this way, your ViewModel must implement these commands:

```<code>    //i skipped the TouchCommand definition because MouseCommand runs for touch on screen too.
    public RelayCommand<MouseButtonEventArgs> MouseCommand
    {
        get
        {
            return new RelayCommand<MouseButtonEventArgs>((e)=> {
                if (e.LeftButton == MouseButtonState.Pressed)
                {
                    //call this function from your utils/models
                    var row = FindTemplatedParentByVisualParent<DataGridRow>((FrameworkElement)e.OriginalSource,typeof(ICommandSource));
                    //add ICommanSource to parameters. (if actual cell contains button instead of data.) Its optional.
                    if(row!=null)
                    {
                        row.IsSelected = !row.IsSelected;
                        e.Handled = true;
                    }
                }
            });
        }
    }
</code>```

Finally implement a method (somewhere in Model) to find the row(s).

```<code>   public static T FindTemplatedParentByVisualParent<T>(FrameworkElement element,Type exceptionType = null) where T : class
    {
        if (element != null && (exceptionType == null || element.TemplatedParent == null || (exceptionType != null  && element.TemplatedParent !=null && !exceptionType.IsAssignableFrom(element.TemplatedParent.GetType()))))
        {
            Type type = typeof(T);
            if (type.IsInstanceOfType(element.TemplatedParent))
            {
                return (element.TemplatedParent as T);
            }
            else
            {
                return FindTemplatedParentByVisualParent<T>((FrameworkElement)VisualTreeHelper.GetParent(element));
            }
        }
        else
            return null;
    }
</code>```

This solution works for me perfectly so i hope it will help for you too.

ContentLicense: CC BY-SA 4.0

Body:
Based on a previous article, i wrote a ("like") MVVM code:

Firstly add this to your main View:

  xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"

The relevant part of View:

       <DataGrid
              Style="{StaticResource DataGridStyle}"
              ItemsSource="{Binding Results}"
              SelectionUnit="FullRow"
              SnapsToDevicePixels="True"
              SelectionMode="Extended">  <!--You can change selection mode with converter. It will work (i tested it.)-->
        <i:Interaction.Behaviors>
                         <utils:EventToCommandBehavior Command="{Binding TouchCommand}"
                                                  Event="PreviewTouchDown"
                                                  PassArguments="True"></utils:EventToCommandBehavior>
                        <utils:EventToCommandBehavior Command="{Binding MouseCommand}"
                                                  Event="PreviewMouseDown"
                                                  PassArguments="True"></utils:EventToCommandBehavior>
        </i:Interaction.Behaviors>
        <DataGrid.Resources>
            <Style TargetType="{x:Type DataGridRow}">
                <Setter Property="IsSelected"<Style.Triggers>
                    <Trigger Property="IsSelected" Value="True">
                        <Setter Property="Background">
                            <Setter.Value>
                                <SolidColorBrush>
                                    <SolidColorBrush.Color>
                                        <Color A="50" R="0" G="0" B="0" />
                                    </SolidColorBrush.Color>
                                </SolidColorBrush>
                            </Setter.Value>
                        </Setter>
                    </Trigger>
                </Style.Triggers>
            </Style>
          </DataGrid.Resources>
        <DataGrid.Columns>
         <!-- your columns -->
        </DataGrid.Columns>
       </DataGrid>

More information about EventToCommandBehavior:
here

In this way, your ViewModel must implement these commands:

    //i skipped the TouchCommand definition because MouseCommand runs for touch on screen too.
    public RelayCommand<MouseButtonEventArgs> MouseCommand
    {
        get
        {
            return new RelayCommand<MouseButtonEventArgs>((e)=> {
                if (e.LeftButton == MouseButtonState.Pressed)
                {
                    //call this function from your utils/models
                    var row = FindTemplatedParentByVisualParent<DataGridRow>((FrameworkElement)e.OriginalSource,typeof(ICommandSource));
                    //add ICommanSource to parameters. (if actual cell contains button instead of data.) Its optional.
                    if(row!=null)
                    {
                        row.IsSelected = !row.IsSelected;
                        e.Handled = true;
                    }
                }
            });
        }
    }

Finally implement a method (somewhere in Model) to find the row(s).

   public static T FindTemplatedParentByVisualParent<T>(FrameworkElement element,Type exceptionType = null) where T : class
    {
        if (element != null && (exceptionType == null || element.TemplatedParent == null || (exceptionType != null  && element.TemplatedParent !=null && !exceptionType.IsAssignableFrom(element.TemplatedParent.GetType()))))
        {
            Type type = typeof(T);
            if (type.IsInstanceOfType(element.TemplatedParent))
            {
                return (element.TemplatedParent as T);
            }
            else
            {
                return FindTemplatedParentByVisualParent<T>((FrameworkElement)VisualTreeHelper.GetParent(element));
            }
        }
        else
            return null;
    }

This solution works for me perfectly so i hope it will help for you too.


问:
Windows Powershell ISE Just Run First Line of Function Invoke Command ScriptBlock
This is my code snippet :

```<code>$s = New-PSSession -ComputerName dafwkn409c6c9 -Credential $mycreds

function Foo (){
    Get-ChildItem C:\
    Get-ChildItem d:\
}

function Foo1 (){
    Get-ChildItem d:\
}

Invoke-Command  -Session $s -ScriptBlock ${function:Foo}
Invoke-Command  -Session $s -ScriptBlock ${function:Foo1}
</code>```

Function Foo has 2 Line. Foo1 has 1 line.

But when I give my code to my friend, or I run my code at the server, the function Foo run all of lines.

This just happened my computer, my foo function just run first line.

Please suggest where to fix my powershell ISE.

Why my last code at function foo not called?

My DotNet 4.5 says no,

but when I install dotnet 4.5 this dialog says something

答:
Finally I update My PS Version, to version 5.1

It is because 5.0 bug's I guess. That article says :

v5 is a preview. It isn't done, and it isn't guaranteed bug-free. It
shouldn't be installed on production computers until it's officially
released.

v5 doesn't install 'side by side' with v3 or v4. You can't
run it with "-version 3" to "downgrade." Now, v5 shouldn't break
anything - something that runs in v3 or v4 should still work fine -
but there are no guarantees as it's a preview and not released code
at this stage.

Server software (Exchange, SharePoint, etc) often has
a hard dependency on a specific version of PowerShell. You need to
look into that before you install v5.

After installing v5, you might
not be able to cleanly uninstall and revert to a prior version.

The point is :

Generally speaking, v5 should be installed in a test virtual machine
  at the very least, not on a production computer. It's great to play
  with it, and you should absolutely log bugs and suggestions to
  http://connect.microsoft.com.

When I run this block of codes:

```<code>$s = New-PSSession -ComputerName dafwkn409c6c9 -Credential $mycreds

function Foo (){
    Get-ChildItem C:\
    Get-ChildItem d:\
}

Invoke-Command  -Session $s -ScriptBlock ${function:Foo}
</code>```

All of codes at function executed well.

Please beware with Powershell 5.0

Body:
This is my code snippet :

$s = New-PSSession -ComputerName dafwkn409c6c9 -Credential $mycreds

function Foo (){
    Get-ChildItem C:\
    Get-ChildItem d:\
}

function Foo1 (){
    Get-ChildItem d:\
}

Invoke-Command  -Session $s -ScriptBlock ${function:Foo}
Invoke-Command  -Session $s -ScriptBlock ${function:Foo1}

Function Foo has 2 Line. Foo1 has 1 line.

But when I give my code to my friend, or I run my code at the server, the function Foo run all of lines.

This just happened my computer, my foo function just run first line.

Please suggest where to fix my powershell ISE.

Why my last code at function foo not called?

My DotNet 4.5 says no,

but when I install dotnet 4.5 this dialog says something

Body:
Finally I update My PS Version, to version 5.1

It is because 5.0 bug's I guess. That article says :

v5 is a preview. It isn't done, and it isn't guaranteed bug-free. It
shouldn't be installed on production computers until it's officially
released.

v5 doesn't install 'side by side' with v3 or v4. You can't
run it with "-version 3" to "downgrade." Now, v5 shouldn't break
anything - something that runs in v3 or v4 should still work fine -
but there are no guarantees as it's a preview and not released code
at this stage.

Server software (Exchange, SharePoint, etc) often has
a hard dependency on a specific version of PowerShell. You need to
look into that before you install v5.

After installing v5, you might
not be able to cleanly uninstall and revert to a prior version.

The point is :

Generally speaking, v5 should be installed in a test virtual machine
  at the very least, not on a production computer. It's great to play
  with it, and you should absolutely log bugs and suggestions to
  http://connect.microsoft.com.

When I run this block of codes:

$s = New-PSSession -ComputerName dafwkn409c6c9 -Credential $mycreds

function Foo (){
    Get-ChildItem C:\
    Get-ChildItem d:\
}

Invoke-Command  -Session $s -ScriptBlock ${function:Foo}

All of codes at function executed well.

Please beware with Powershell 5.0


问:
One mouse press for several QGraphicsItem's in QT
I have a matrix of QGraphicsItem's in a QGraphicsScene and when I click an element it changes it's color. This is implemented with mousePressEvent(). I want to be able to click and hold and then move the cursor over other QGraphicsItem's and change their color too, hence trigger their mousePressEvent().

The problem is that due to mouse grabbing the first element I click "keeps" all the events and hoverEnterEvent() is not triggered. I tried adding ungrabMouse() to mousePressEvent() but that didn't help.

I guess one solution would be to make the QGraphicsitem's drag-able and use QT drag and drop functions for that. In fact I have this:

```<code>void dragEnterEvent(QGraphicsSceneDragDropEvent *event)
{
    changeColor();
}
</code>```

and when I drag some text from the application over the elements it works like I want it but not when I "drag" a QGrahphicsItem.

So is the only solution to make a QGraphicsItem dragable to be able to trigger events while hovering over them with a clicked mouse button?

答:
I found a solution myself. I added all my QGraphicsRectItem's to a QGraphicsItemGroup and implemented the events for this group. In Group::MouseMoveEvent() I check the position of the cursor and apply the event to its children. It looks like this:

```<code>void Group::mouseMoveEvent ( QGraphicsSceneMouseEvent * event )
{
    if (boundingRect().adjusted(0,0,-1,-1).contains(event->pos()))
    {
        if (CellCoordinate(event->pos()) != lastChangedCell_) {
            lastChangedCell_ = CellCoordinate(event->pos());
            modifyCell(CellCoordinate(event->pos()));
        }
    }
}
</code>```

If you have the same problem and need more info feel free to contact me.

Body:
I have a matrix of QGraphicsItem's in a QGraphicsScene and when I click an element it changes it's color. This is implemented with mousePressEvent(). I want to be able to click and hold and then move the cursor over other QGraphicsItem's and change their color too, hence trigger their mousePressEvent().

The problem is that due to mouse grabbing the first element I click "keeps" all the events and hoverEnterEvent() is not triggered. I tried adding ungrabMouse() to mousePressEvent() but that didn't help.

I guess one solution would be to make the QGraphicsitem's drag-able and use QT drag and drop functions for that. In fact I have this:

void dragEnterEvent(QGraphicsSceneDragDropEvent *event)
{
    changeColor();
}

and when I drag some text from the application over the elements it works like I want it but not when I "drag" a QGrahphicsItem.

So is the only solution to make a QGraphicsItem dragable to be able to trigger events while hovering over them with a clicked mouse button?

Body:
I found a solution myself. I added all my QGraphicsRectItem's to a QGraphicsItemGroup and implemented the events for this group. In Group::MouseMoveEvent() I check the position of the cursor and apply the event to its children. It looks like this:

void Group::mouseMoveEvent ( QGraphicsSceneMouseEvent * event )
{
    if (boundingRect().adjusted(0,0,-1,-1).contains(event->pos()))
    {
        if (CellCoordinate(event->pos()) != lastChangedCell_) {
            lastChangedCell_ = CellCoordinate(event->pos());
            modifyCell(CellCoordinate(event->pos()));
        }
    }
}

If you have the same problem and need more info feel free to contact me.


问:
IONIC:Unable to install phonegap-plugin-push in ios app
I am new with ionic framework.Currently i am working on ionic iOS app. when i install phonegap-plugin-push    i am getting error

```<code>Failed to install 'phonegap-plugin-push':undefined  Error: /Library/Ruby/Gems/2.0.0/gems/claide-1.0.1/lib/claide/command.rb:439:in `help!': [!] You cannot run CocoaPods as root. (CLAide::Help)
</code>```

i have searched it but no solution found yet!

答:
I also got same kind of problem. In my case I used sudo ionic platform add ios

This is worked well while building every plugins but phonegap-plugin-push.

phonegap-plugin-push is keep giving above error [!] You cannot run CocoaPods as root. (CLAide::Help)

Then I used ionic platform add ios without sudo This is the actual solution for this. But in this case It is keep giving me the permission related issue code EACCESS.

Then I used followings step to overcome that one.

sudo chown -R $USER /usr/local/

Again added cordoava and ionic

sudo npm install -g cordova

sudo npm install -g ionic

Other informations

phonegap-plugin-push version: 1.10.0

Cordova CLI: 6.5.0

Ionic CLI Version: 2.2.2

Node Version: v7.7.2

Xocde Version: Xcode 8.2.1

CocoaPods Version: 1.2.0

Hope this will help.

Body:
I am new with ionic framework.Currently i am working on ionic iOS app. when i install phonegap-plugin-push    i am getting error

Failed to install 'phonegap-plugin-push':undefined  Error: /Library/Ruby/Gems/2.0.0/gems/claide-1.0.1/lib/claide/command.rb:439:in `help!': [!] You cannot run CocoaPods as root. (CLAide::Help)

i have searched it but no solution found yet!


答:
This will work in Oracle versions from 9i:

```<code>select reference
       , modifieddate as startdate
       , lead ( modifieddate, 1, to_timestamp('9999-12-31 00:00:00.000', 'yyyy-mm-dd hh24:mi:ss.ff3'))
                 over (partition by reference order by modifieddate) as enddate
from your_table;
</code>```

Note that the windowing clause needs to sort by modifieddate to ensure the correct value.

Title: Complex SQL transformation

Body:
This is my source table

Reference   ModifiedDate
------------------------------------
1023175     2017-03-03 16:02:01.723
1023175     2017-03-07 07:59:49.283
1023175     2017-03-12 11:14:40.230

Ineed the following output

Reference   StartDate                 EndDate
---------------------------------------------
1023175   2017-03-03 16:02:01.723     2017-03-07 07:59:49.283
1023175   2017-03-07 07:59:49.283     2017-03-12 11:14:40.230
1023175   2017-03-12 11:14:40.230     9999-12-31 00:00:00.000 (last record should have this value)

Any suggestions on how this can be achieved?

Body:
This will work in Oracle versions from 9i:

select reference
       , modifieddate as startdate
       , lead ( modifieddate, 1, to_timestamp('9999-12-31 00:00:00.000', 'yyyy-mm-dd hh24:mi:ss.ff3'))
                 over (partition by reference order by modifieddate) as enddate
from your_table;

Note that the windowing clause needs to sort by modifieddate to ensure the correct value.


问:
Git and PhpStorm project play together
I am trying to understand how to work with Git and PhpStorm together.

Lets imagine situation, I have an APP in a local git repo in folder some_project, so in git meaning this is will be a working area .git folder inside with. In repository I have 2 branches master and develop which equal for this moment.

So now I implement some new future in my APP, to do this I am making new branch with name, say, new_future. After that I am checkout new_future and ready to go do some work.

Now, I faced with certain questions:

Where I must to create PhpStorm project? Do I need to create it in repository folder? Cause if I will create it in repo folder then while changing branch with checkout using GIT my project files will be changed, do I need this? And after all, if I will delete project using PhpStorm - I could delete my all repository! This is unacceptable!

So if I will create project in other folders out my repo then how I will get code from my branch new_future? How I will commit and so on? Cause my project will be out of SVC folder and to do this all I guess need to do is after some changes code in PhpStorm project manually copy it to folder some_project and then using GIT in that folder add changes and commit them.

Is this right to do this or there is other easy options?

So I think you got the idea what I am trying to know - some recipe of actions in this usual working case.

答:
First of all, PHPStorm have its own Git manager inside of it. You do not need to add, commit, merge and so on outside of PHPStorm, you can do all of it inside PHPStorm. By default you can find your Git actions in the top right corner of your screen, and you can see what branch you're on or switch branch in the bottom right corner.

So, if you don't like new files to be created in different branches, just create the project on the Master branch and then you switch or create new branches after that.

Secondly, if you don't want the PHPStorm project files (.idea/) to be part of your repository, you can simply use a .gitignore file to ignore any of those files when you add and commit.

Read more about ignoring files.

Personally I use PHPStorm in the following way:

Clone repository to local computer

Open new project, PHPStorm lets you select to create the project out of the existing source.

Handle all checkouts, merges, commits and pushes inside PHPStorm

I use a .gitignore file that make sure that the PHPStorm settings files are not included in the commits. You can find one here.

Title: Git and PhpStorm project play together


问:
How to decrease datatable row height in primefaces
I tried to decrease the height of the column by using following syntax:

```<code><p:column style="height:10px;">
</code>```

and the datatable row height won't decrease; it only increases if I set a bigger size.

Is there a way to make the height smaller than the default/existing one?

This is the exact code, that I'm using:

```<code><c:forEach var="column" items="#{dispoFillingPage.columnListAuftrag}">
                    <c:choose>
                        <c:when test="${column.dateColumn}">
                            <p:column id="#{column.id}" filterStyleClass="#{column.filterStyleClass}" headerText="#{column.title}" visible="#{column.visible}"
                                width="#{column.width}" filterBy="#{data[column.property]}" sortBy="#{data[column.property]}" field="#{column.property}"
                                filterFunction="#{standortPage.filterByDate}" filterMatchMode="contains" style="height:10px">
                                <f:attribute name="rtcCol" value="#{column}" />
                                <h:outputText value="#{data[column.property]}">
                                    <f:convertDateTime type="date" pattern="yyyy-MM-dd" />
                                </h:outputText>
                            </p:column>
                        </c:when>
                        <c:otherwise>
                            <p:column id="#{column.id}" filterStyleClass="#{column.filterStyleClass}" headerText="#{column.title}" field="#{column.property}"
                                visible="#{column.visible}" width="#{column.width}" filterBy="#{data[column.property]}" sortBy="#{data[column.property]}"
                                filterMatchMode="contains" style="height:10px;">
                                <f:attribute name="rtcCol" value="#{column}" />
                                <h:outputText value="#{data[column.property]}" />
                            </p:column>
                        </c:otherwise>
                    </c:choose>
                </c:forEach>
</code>```

I have to do this, because I have two datatables with 20 rows each and I have to make them fit in the screen, so that they are entirely visible to the user.

答:
I had to decrease the font-style of the datatable in order to decrease also the row height.

```<code><p:datatable style="font-size:8px">
</code>```

But this way I decrease the entire datatable.

Body:
I tried to decrease the height of the column by using following syntax:

and the datatable row height won't decrease; it only increases if I set a bigger size.

Is there a way to make the height smaller than the default/existing one?

This is the exact code, that I'm using:

<c:forEach var="column" items="#{dispoFillingPage.columnListAuftrag}">
                    <c:choose>
                        <c:when test="${column.dateColumn}">

                                <f:attribute name="rtcCol" value="#{column}" />
                                <h:outputText value="#{data[column.property]}">
                                    <f:convertDateTime type="date" pattern="yyyy-MM-dd" />
                                </h:outputText>

                        </c:when>
                        <c:otherwise>

                                <f:attribute name="rtcCol" value="#{column}" />
                                <h:outputText value="#{data[column.property]}" />

                        </c:otherwise>
                    </c:choose>
                </c:forEach>

I have to do this, because I have two datatables with 20 rows each and I have to make them fit in the screen, so that they are entirely visible to the user.

Body:
I had to decrease the font-style of the datatable in order to decrease also the row height.

<p:datatable style="font-size:8px">

But this way I decrease the entire datatable.


问:
How to rename data frame column by taking only the first value of the splitter string
I have the following data frame:

```<code>df <- structure(list(n.foldchange = c(2, 3, 5), s.foldchange = c(4,
0.2, 100.3)), .Names = c("n.foldchange", "s.foldchange"), row.names = c(NA,
-3L), class = "data.frame")
</code>```

Which looks like this:

```<code>  n.foldchange s.foldchange
1            2          4.0
2            3          0.2
3            5        100.3
</code>```

What I want to do is to rename the column by removing the value after ..
Yielding

```<code>             n            s
1            2          4.0
2            3          0.2
3            5        100.3
</code>```

How can I do that? (with tidyverse possible?)

答:
We can rename the names of columns using setnames with dplyr.

```<code>library(dplyr)
df %>%
 setnames(sub("\\..*", "", names(.)))

df

#  n     s
#1 2   4.0
#2 3   0.2
#3 5 100.3
</code>```

Body:
I have the following data frame:

df <- structure(list(n.foldchange = c(2, 3, 5), s.foldchange = c(4,
0.2, 100.3)), .Names = c("n.foldchange", "s.foldchange"), row.names = c(NA,
-3L), class = "data.frame")

Which looks like this:

  n.foldchange s.foldchange
1            2          4.0
2            3          0.2
3            5        100.3

What I want to do is to rename the column by removing the value after ..
Yielding

             n            s
1            2          4.0
2            3          0.2
3            5        100.3

How can I do that? (with tidyverse possible?)

Body:
We can rename the names of columns using setnames with dplyr.

library(dplyr)
df %>%
 setnames(sub("\\..*", "", names(.)))

df

#  n     s
#1 2   4.0
#2 3   0.2
#3 5 100.3


问:
Rest service with oauth2: Failed to find access token for token
I try to create spring rest service, whis is autenticated by my own oauth2 resources server. I created resource server:

```<code>@Configuration
@EnableResourceServer
protected static class ResourceServer extends ResourceServerConfigurerAdapter {

    @Autowired
    private TokenStore tokenStore;

    @Override
    public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
        resources.tokenStore(tokenStore).resourceId("mobileapp");
    }

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests().antMatchers("/api/shop /**").authenticated().and()
                .authorizeRequests().antMatchers("/auth/**").anonymous();
    }

}
</code>```

and authorization server:

```<code>@Configuration
@EnableAuthorizationServer
protected static class OAuth2Config extends AuthorizationServerConfigurerAdapter {

    @Autowired
    private AuthenticationManager auth;

    @Autowired
    private DataSource dataSource;

    @Autowired
    private BCryptPasswordEncoder passwordEncoder;

    @Bean
    public JdbcTokenStore tokenStore() {
        return new JdbcTokenStore(dataSource);
    }

    @Bean
    protected AuthorizationCodeServices authorizationCodeServices() {
        return new JdbcAuthorizationCodeServices(dataSource);
    }

    @Override
    public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
        security.passwordEncoder(passwordEncoder);
    }

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        endpoints
                .authorizationCodeServices(authorizationCodeServices())
                .authenticationManager(auth)
                .tokenStore(tokenStore())
                .approvalStoreDisabled();
    }

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients.jdbc(dataSource)
                .passwordEncoder(passwordEncoder);
                .withClient("mobile")
                .authorizedGrantTypes("password", "refresh_token")
                .authorities("ROLE_CLIENT")
                .scopes("read", "write", "trust")
                .autoApprove(true)
               .resourceIds("mobileapp")
                .secret("123456");
    }
</code>```

When I try to receive an access token from server, using curl:

curl -X POST -vu mobile:123456 http://localhost:8080/oauth/token -H
  "Accept: application/json" -d
  "password=test123&username=admin@gmail.com&grant_type=password&scope=read&client_secret=123456&client_id=mobile"

I get this error as a response message:

{"error":"server_error","error_description":"java.io.NotSerializableException:
  org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder"}

In tomcat logs there is also

o.s.s.o.p.token.store.JdbcTokenStore - Failed to find access token for
  token

EDIT:
Bean definition of password encoder:

```<code>@Bean
public BCryptPasswordEncoder passwordEncoder() {
    BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
    return bCryptPasswordEncoder;
}
</code>```

This bean is created in class, in which OAuth2Config and ResourceServer are declared.

I checked code and found out which table spring uses and the table is empty. My question is: should it be auto generated or there is a problem with my code?

Thanks in advance for help.

答:
Your model must have BCryptPasswordEncoder which is not serialized. Make it transient in your user bmodel.</p>

```<code>private transient BCryptPasswordEncoder passwordEncoder;
</code>```

Body:
I try to create spring rest service, whis is autenticated by my own oauth2 resources server. I created resource server:

@Configuration
@EnableResourceServer
protected static class ResourceServer extends ResourceServerConfigurerAdapter {

    @Autowired
    private TokenStore tokenStore;

    @Override
    public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
        resources.tokenStore(tokenStore).resourceId("mobileapp");
    }

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests().antMatchers("/api/shop /**").authenticated().and()
                .authorizeRequests().antMatchers("/auth/**").anonymous();
    }

}

and authorization server:

@Configuration
@EnableAuthorizationServer
protected static class OAuth2Config extends AuthorizationServerConfigurerAdapter {

    @Autowired
    private AuthenticationManager auth;

    @Autowired
    private DataSource dataSource;

    @Autowired
    private BCryptPasswordEncoder passwordEncoder;

    @Bean
    public JdbcTokenStore tokenStore() {
        return new JdbcTokenStore(dataSource);
    }

    @Bean
    protected AuthorizationCodeServices authorizationCodeServices() {
        return new JdbcAuthorizationCodeServices(dataSource);
    }

    @Override
    public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
        security.passwordEncoder(passwordEncoder);
    }

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        endpoints
                .authorizationCodeServices(authorizationCodeServices())
                .authenticationManager(auth)
                .tokenStore(tokenStore())
                .approvalStoreDisabled();
    }

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients.jdbc(dataSource)
                .passwordEncoder(passwordEncoder);
                .withClient("mobile")
                .authorizedGrantTypes("password", "refresh_token")
                .authorities("ROLE_CLIENT")
                .scopes("read", "write", "trust")
                .autoApprove(true)
               .resourceIds("mobileapp")
                .secret("123456");
    }

When I try to receive an access token from server, using curl:

curl -X POST -vu mobile:123456 http://localhost:8080/oauth/token -H
  "Accept: application/json" -d
  "password=test123&username=admin@gmail.com&grant_type=password&scope=read&client_secret=123456&client_id=mobile"

I get this error as a response message:

{"error":"server_error","error_description":"java.io.NotSerializableException:
  org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder"}

In tomcat logs there is also

o.s.s.o.p.token.store.JdbcTokenStore - Failed to find access token for
  token

EDIT:
Bean definition of password encoder:

@Bean
public BCryptPasswordEncoder passwordEncoder() {
    BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
    return bCryptPasswordEncoder;
}

This bean is created in class, in which OAuth2Config and ResourceServer are declared.

I checked code and found out which table spring uses and the table is empty. My question is: should it be auto generated or there is a problem with my code?

Thanks in advance for help.

Body:
Your model must have BCryptPasswordEncoder which is not serialized. Make it transient in your user bmodel.

private transient BCryptPasswordEncoder passwordEncoder;


问:
How can I get certain data from JSON using a JQuery ajax call?
I am making a small finance website as a project but I can't seem to figure out how to get specific data from the JSON that is on this Google Finance site. The code should get only the value associated with l but it gets all of the data instead.

```<code>$(document).ready(function(){
  $.ajax({
    url: 'http://finance.google.com/finance/info?client=ig&q=AMD',
    dataType: 'jsonp',
    data: { get_param: 'l' },
    success: function(json) {
        console.log(json);
    }

  });
});
</code>```

答:
```<code>$(document).ready(function(){
  $.ajax({
    url: 'http://finance.google.com/finance/info?client=ig&q=AMD',
    dataType: 'jsonp',
    success: function(json) {
        console.log(json[0]['l']);
    }
  });
});
</code>```

you don't need to send a data construct on this query because google did not handle it. all you need to do work with the complete json result in your success function and figure out what params you need to attach. this sample should do what you want if i understood your question right.

Body:
I am making a small finance website as a project but I can't seem to figure out how to get specific data from the JSON that is on this Google Finance site. The code should get only the value associated with l but it gets all of the data instead.

$(document).ready(function(){
  $.ajax({
    url: 'http://finance.google.com/finance/info?client=ig&q=AMD',
    dataType: 'jsonp',
    data: { get_param: 'l' },
    success: function(json) {
        console.log(json);
    }

  });
});

Body:
$(document).ready(function(){
  $.ajax({
    url: 'http://finance.google.com/finance/info?client=ig&q=AMD',
    dataType: 'jsonp',
    success: function(json) {
        console.log(json[0]['l']);
    }
  });
});

you don't need to send a data construct on this query because google did not handle it. all you need to do work with the complete json result in your success function and figure out what params you need to attach. this sample should do what you want if i understood your question right.