问:
Passing environment envariables inside webpack configuration
What I want to achieve is to set an BACKEND environment variable so our VueJS project will send request to the API of that host however it always return Unexpected token :.

Below is the current code of our config/dev.env.js and I'm a little stuck now

```<code>module.exports = {
  NODE_ENV: '"development"',
  HOST: process.env.BACKEND,
  NAME: '"Jaguar Dashboard"'
}
</code>```

I just want the process.env.BACKEND to have a value like 'http://example.com' and then our VueJS project will now start nicely. How can I solve this?

UPDATE

It is working when I do it like this:

module.exports = merge(prodEnv, {
  NODE_ENV: '"development"',
  HOST: 'http://example-0e1b-4a12-91ef-b853a47bab34.node.dockerapp.io:8000',
  NAME: 'Jaguar Dashboard'
})

When I try JSON.stringify(process.env), the error(Unexpected identifier) shows in this line:

eval("var merge = __webpack_require__(424)\nvar prodEnv = __webpack_require__(69)\n\nmodule.exports = merge(prodEnv, {\n  NODE_ENV: '\"development\"',\n  HOST: JSON.stringify(__webpack_require__.i({\"NODE_ENV\":\"development\",\"HOST\":\"http://example-0e1b-4a12-91ef-b853a47bab34.node.dockerapp.io:8000\",\"NAME\":Jaguar Dashboard}).BACKEND),\n  NAME: 'Jaguar Dashboard'\n})\n\n//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiMjU4LmpzIiwic291cmNlcyI6WyJ3ZWJwYWNrOi8vLy4vY29uZmlnL2Rldi5lbnYuanM/NzYxMiJdLCJzb3VyY2VzQ29udGVudCI6WyJ2YXIgbWVyZ2UgPSByZXF1aXJlKCd3ZWJwYWNrLW1lcmdlJylcbnZhciBwcm9kRW52ID0gcmVxdWlyZSgnLi9wcm9kLmVudicpXG5cbm1vZHVsZS5leHBvcnRzID0gbWVyZ2UocHJvZEVudiwge1xuICBOT0RFX0VOVjogJ1wiZGV2ZWxvcG1lbnRcIicsXG4gIEhPU1Q6IEpTT04uc3RyaW5naWZ5KHByb2Nlc3MuZW52LkJBQ0tFTkQpLFxuICBOQU1FOiAnSmFndWFyIERhc2hib2FyZCdcbn0pXG5cblxuXG4vLy8vLy8vLy8vLy8vLy8vLy9cbi8vIFdFQlBBQ0sgRk9PVEVSXG4vLyAuL2NvbmZpZy9kZXYuZW52LmpzXG4vLyBtb2R1bGUgaWQgPSAyNThcbi8vIG1vZHVsZSBjaHVua3MgPSA2MCJdLCJtYXBwaW5ncyI6IkFBQUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTsiLCJzb3VyY2VSb290IjoiIn0=\n//# sourceURL=webpack-internal:///258\n");

When I try '"'+process.env.BACKEND+'"', the error(Unexpected identifier) shows in this line:

eval("var merge = __webpack_require__(424)\nvar prodEnv = __webpack_require__(69)\n\nmodule.exports = merge(prodEnv, {\n  NODE_ENV: '\"development\"',\n  HOST: '\"'+__webpack_require__.i({\"NODE_ENV\":\"development\",\"HOST\":\"http://example-0e1b-4a12-91ef-b853a47bab34.node.dockerapp.io:8000\",\"NAME\":Jaguar Dashboard}).BACKEND+'\"',\n  NAME: 'Jaguar Dashboard'\n})\n\n//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiMjU4LmpzIiwic291cmNlcyI6WyJ3ZWJwYWNrOi8vLy4vY29uZmlnL2Rldi5lbnYuanM/NzYxMiJdLCJzb3VyY2VzQ29udGVudCI6WyJ2YXIgbWVyZ2UgPSByZXF1aXJlKCd3ZWJwYWNrLW1lcmdlJylcbnZhciBwcm9kRW52ID0gcmVxdWlyZSgnLi9wcm9kLmVudicpXG5cbm1vZHVsZS5leHBvcnRzID0gbWVyZ2UocHJvZEVudiwge1xuICBOT0RFX0VOVjogJ1wiZGV2ZWxvcG1lbnRcIicsXG4gIEhPU1Q6ICdcIicrcHJvY2Vzcy5lbnYuQkFDS0VORCsnXCInLFxuICBOQU1FOiAnSmFndWFyIERhc2hib2FyZCdcbn0pXG5cblxuXG4vLy8vLy8vLy8vLy8vLy8vLy9cbi8vIFdFQlBBQ0sgRk9PVEVSXG4vLyAuL2NvbmZpZy9kZXYuZW52LmpzXG4vLyBtb2R1bGUgaWQgPSAyNThcbi8vIG1vZHVsZSBjaHVua3MgPSA2MCJdLCJtYXBwaW5ncyI6IkFBQUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTsiLCJzb3VyY2VSb290IjoiIn0=\n//# sourceURL=webpack-internal:///258\n");

But for my successful code where I just defined a string, it shows the code below on that line:

eval("var merge = __webpack_require__(424)\nvar prodEnv = __webpack_require__(69)\n\nmodule.exports = merge(prodEnv, {\n  NODE_ENV: '\"development\"',\n  HOST: 'http://example-0e1b-4a12-91ef-b853a47bab34.node.dockerapp.io:8000',\n  NAME: 'Jaguar Dashboard'\n})\n\n//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiMjU4LmpzIiwic291cmNlcyI6WyJ3ZWJwYWNrOi8vLy4vY29uZmlnL2Rldi5lbnYuanM/NzYxMiJdLCJzb3VyY2VzQ29udGVudCI6WyJ2YXIgbWVyZ2UgPSByZXF1aXJlKCd3ZWJwYWNrLW1lcmdlJylcbnZhciBwcm9kRW52ID0gcmVxdWlyZSgnLi9wcm9kLmVudicpXG5cbm1vZHVsZS5leHBvcnRzID0gbWVyZ2UocHJvZEVudiwge1xuICBOT0RFX0VOVjogJ1wiZGV2ZWxvcG1lbnRcIicsXG4gIEhPU1Q6ICdodHRwOi8vZXhhbXBsZS5jb20nLFxuICBOQU1FOiAnSmFndWFyIERhc2hib2FyZCdcbn0pXG5cblxuXG4vLy8vLy8vLy8vLy8vLy8vLy9cbi8vIFdFQlBBQ0sgRk9PVEVSXG4vLyAuL2NvbmZpZy9kZXYuZW52LmpzXG4vLyBtb2R1bGUgaWQgPSAyNThcbi8vIG1vZHVsZSBjaHVua3MgPSA2MCJdLCJtYXBwaW5ncyI6IkFBQUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTsiLCJzb3VyY2VSb290IjoiIn0=\n//# sourceURL=webpack-internal:///258\n");

SCREENSHOTS OF THE CODES:

config/dev.env.js

build/webpack.base.conf.js

build/webpack.dev.conf.js

P.S.

All of these response happens when I npm run dev in our VueJS project

答:
You'll notice that the strings are wrapped in another pair of quotes. This is so strings aren't inserted as variables.

From the DefinePlugin docs

Note that because the plugin does a direct text replacement, the value
  given to it must include actual quotes inside of the string itself.
  Typically, this is done either with either alternate quotes, such as
  '"production"', or by using JSON.stringify('production').

You can do HOST: '"'+process.env.BACKEND+'"'

or

HOST: JSON.stringify(process.env.BACKEND) (more readable)

Body:
What I want to achieve is to set an BACKEND environment variable so our VueJS project will send request to the API of that host however it always return Unexpected token :.

Below is the current code of our config/dev.env.js and I'm a little stuck now

module.exports = {
  NODE_ENV: '"development"',
  HOST: process.env.BACKEND,
  NAME: '"Jaguar Dashboard"'
}

I just want the process.env.BACKEND to have a value like 'http://example.com' and then our VueJS project will now start nicely. How can I solve this?

UPDATE

It is working when I do it like this:

module.exports = merge(prodEnv, {
  NODE_ENV: '"development"',
  HOST: 'http://example-0e1b-4a12-91ef-b853a47bab34.node.dockerapp.io:8000',
  NAME: 'Jaguar Dashboard'
})

When I try JSON.stringify(process.env), the error(Unexpected identifier) shows in this line:

eval("var merge = __webpack_require__(424)\nvar prodEnv = __webpack_require__(69)\n\nmodule.exports = merge(prodEnv, {\n  NODE_ENV: '\"development\"',\n  HOST: JSON.stringify(__webpack_require__.i({\"NODE_ENV\":\"development\",\"HOST\":\"http://example-0e1b-4a12-91ef-b853a47bab34.node.dockerapp.io:8000\",\"NAME\":Jaguar Dashboard}).BACKEND),\n  NAME: 'Jaguar Dashboard'\n})\n\n//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiMjU4LmpzIiwic291cmNlcyI6WyJ3ZWJwYWNrOi8vLy4vY29uZmlnL2Rldi5lbnYuanM/NzYxMiJdLCJzb3VyY2VzQ29udGVudCI6WyJ2YXIgbWVyZ2UgPSByZXF1aXJlKCd3ZWJwYWNrLW1lcmdlJylcbnZhciBwcm9kRW52ID0gcmVxdWlyZSgnLi9wcm9kLmVudicpXG5cbm1vZHVsZS5leHBvcnRzID0gbWVyZ2UocHJvZEVudiwge1xuICBOT0RFX0VOVjogJ1wiZGV2ZWxvcG1lbnRcIicsXG4gIEhPU1Q6IEpTT04uc3RyaW5naWZ5KHByb2Nlc3MuZW52LkJBQ0tFTkQpLFxuICBOQU1FOiAnSmFndWFyIERhc2hib2FyZCdcbn0pXG5cblxuXG4vLy8vLy8vLy8vLy8vLy8vLy9cbi8vIFdFQlBBQ0sgRk9PVEVSXG4vLyAuL2NvbmZpZy9kZXYuZW52LmpzXG4vLyBtb2R1bGUgaWQgPSAyNThcbi8vIG1vZHVsZSBjaHVua3MgPSA2MCJdLCJtYXBwaW5ncyI6IkFBQUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTsiLCJzb3VyY2VSb290IjoiIn0=\n//# sourceURL=webpack-internal:///258\n");

When I try '"'+process.env.BACKEND+'"', the error(Unexpected identifier) shows in this line:

eval("var merge = __webpack_require__(424)\nvar prodEnv = __webpack_require__(69)\n\nmodule.exports = merge(prodEnv, {\n  NODE_ENV: '\"development\"',\n  HOST: '\"'+__webpack_require__.i({\"NODE_ENV\":\"development\",\"HOST\":\"http://example-0e1b-4a12-91ef-b853a47bab34.node.dockerapp.io:8000\",\"NAME\":Jaguar Dashboard}).BACKEND+'\"',\n  NAME: 'Jaguar Dashboard'\n})\n\n//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiMjU4LmpzIiwic291cmNlcyI6WyJ3ZWJwYWNrOi8vLy4vY29uZmlnL2Rldi5lbnYuanM/NzYxMiJdLCJzb3VyY2VzQ29udGVudCI6WyJ2YXIgbWVyZ2UgPSByZXF1aXJlKCd3ZWJwYWNrLW1lcmdlJylcbnZhciBwcm9kRW52ID0gcmVxdWlyZSgnLi9wcm9kLmVudicpXG5cbm1vZHVsZS5leHBvcnRzID0gbWVyZ2UocHJvZEVudiwge1xuICBOT0RFX0VOVjogJ1wiZGV2ZWxvcG1lbnRcIicsXG4gIEhPU1Q6ICdcIicrcHJvY2Vzcy5lbnYuQkFDS0VORCsnXCInLFxuICBOQU1FOiAnSmFndWFyIERhc2hib2FyZCdcbn0pXG5cblxuXG4vLy8vLy8vLy8vLy8vLy8vLy9cbi8vIFdFQlBBQ0sgRk9PVEVSXG4vLyAuL2NvbmZpZy9kZXYuZW52LmpzXG4vLyBtb2R1bGUgaWQgPSAyNThcbi8vIG1vZHVsZSBjaHVua3MgPSA2MCJdLCJtYXBwaW5ncyI6IkFBQUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTsiLCJzb3VyY2VSb290IjoiIn0=\n//# sourceURL=webpack-internal:///258\n");

But for my successful code where I just defined a string, it shows the code below on that line:

eval("var merge = __webpack_require__(424)\nvar prodEnv = __webpack_require__(69)\n\nmodule.exports = merge(prodEnv, {\n  NODE_ENV: '\"development\"',\n  HOST: 'http://example-0e1b-4a12-91ef-b853a47bab34.node.dockerapp.io:8000',\n  NAME: 'Jaguar Dashboard'\n})\n\n//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiMjU4LmpzIiwic291cmNlcyI6WyJ3ZWJwYWNrOi8vLy4vY29uZmlnL2Rldi5lbnYuanM/NzYxMiJdLCJzb3VyY2VzQ29udGVudCI6WyJ2YXIgbWVyZ2UgPSByZXF1aXJlKCd3ZWJwYWNrLW1lcmdlJylcbnZhciBwcm9kRW52ID0gcmVxdWlyZSgnLi9wcm9kLmVudicpXG5cbm1vZHVsZS5leHBvcnRzID0gbWVyZ2UocHJvZEVudiwge1xuICBOT0RFX0VOVjogJ1wiZGV2ZWxvcG1lbnRcIicsXG4gIEhPU1Q6ICdodHRwOi8vZXhhbXBsZS5jb20nLFxuICBOQU1FOiAnSmFndWFyIERhc2hib2FyZCdcbn0pXG5cblxuXG4vLy8vLy8vLy8vLy8vLy8vLy9cbi8vIFdFQlBBQ0sgRk9PVEVSXG4vLyAuL2NvbmZpZy9kZXYuZW52LmpzXG4vLyBtb2R1bGUgaWQgPSAyNThcbi8vIG1vZHVsZSBjaHVua3MgPSA2MCJdLCJtYXBwaW5ncyI6IkFBQUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTsiLCJzb3VyY2VSb290IjoiIn0=\n//# sourceURL=webpack-internal:///258\n");

SCREENSHOTS OF THE CODES:

config/dev.env.js

build/webpack.base.conf.js

build/webpack.dev.conf.js

P.S.

All of these response happens when I npm run dev in our VueJS project


来源: stackexchange

问:
CPU throttling in C++
I was just wondering if there is an elegant way to set the maximum CPU load for a particular thread doing intensive calculations.

Right now I have located the most time-consuming loop in the thread (it does only compression) and use GetTickCount() and Sleep() with hardcoded values. It makes sure that the loop continues for a certain period and then sleeps for a certain minimum time. It more or less does the job, i.e. guarantees that the thread will not use more than 50% of CPU.

However, behavior is dependent on the number of CPU cores (huge disadvantage) and simply ugly (smaller disadvantage).

Any ideas?

答:
The problem is it's not normal to want to leave the CPU idle while you have work to do. Normally you set a background task to IDLE priority, and let the OS handle scheduling it all the CPU time that isn't used by interactive tasks.

It sound to me like the problem is the watchdog process.

If your background task is CPU-bound then you want it to take all the unused CPU time for its task.

Maybe you should look at fixing the watchdog program?

ContentLicense: CC BY-SA 4.0

Title: CPU throttling in C++

OwnerDisplayName: Douglas

ContentLicense: CC BY-SA 2.5


问:
What is <?= in C++?

Possible Duplicate:

  C extension: <? and >? operators

Take a look at the top answer (by sclo) to problem D of this Google Code Jam. It's C++ code, it must have compiled, and it contains statements such as this one:

```<code>double& ret = F[mask][cur][b];
if(j==cur) {
  ret<?=f(tmp,j,b||bad[i])+M[cur][i];   // WTF is <?=   ???
}
</code>```

This doesn't compile in my Visual Studio 2008. What does the <?= mean?

答: It's simply not valid C++. < Might be less than, an open angle bracket for a template argument list, or the start of a digraph however non of those can be followed by ?, then =.

Title: What is <?= in C++?

Body:
Possible Duplicate:

  C extension: <? and >? operators

Take a look at the top answer (by sclo) to problem D of this Google Code Jam. It's C++ code, it must have compiled, and it contains statements such as this one:

double& ret = F[mask][cur][b];
if(j==cur) {
  ret<?=f(tmp,j,b||bad[i])+M[cur][i];   // WTF is <?=   ???
}

This doesn't compile in my Visual Studio 2008. What does the <?= mean?


问:
Removing object from parent environment using rm()
I am trying to remove an object from the parent environment.

```<code>rm_obj <- function(obj){
  a <-deparse(substitute(obj))
  print (a)
  print(ls(envir=sys.frame(-1)))
  rm(a,envir=sys.frame(-1))
}
> x<-c(1,2,3)
> rm_obj(x)
[1] "x"

[1] "rm_obj" "x"
Warning message:
In rm(a, envir = sys.frame(-1)) : object 'a' not found
</code>```

This will help clarify my misunderstanding regarding frames.

答:
The following code works for me.</p>

```<code>myEnv = new.env()
assign('xx', 5, envir=myEnv)
get('xx', envir=myEnv)
rm('xx', envir=myEnv)
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am trying to remove an object from the parent environment.

rm_obj <- function(obj){
  a <-deparse(substitute(obj))
  print (a)
  print(ls(envir=sys.frame(-1)))
  rm(a,envir=sys.frame(-1))
}
> x<-c(1,2,3)
> rm_obj(x)
[1] "x"

[1] "rm_obj" "x"
Warning message:
In rm(a, envir = sys.frame(-1)) : object 'a' not found

This will help clarify my misunderstanding regarding frames.

Body:
The following code works for me.

myEnv = new.env()
assign('xx', 5, envir=myEnv)
get('xx', envir=myEnv)
rm('xx', envir=myEnv)


问:
Disable SonarLint analysis during Debug build
Is it possible (in Visual Studio using SonarLint extension) to disable Sonar Analyzers during Debug build, but keep them enabled in Release build? The reason is that connecting the solution to SonarQube has drastically increased the build time.</p>

答:
I ended up modifying the .csproj files to remove the analyzers if I'm building the solution from within Visual Studio in Debug configuration. That way, sonarlint does not complain that rules are outdated, nor does it get affected by updates. I got the answer from here </p>

```<code><Target Name="DisableAnalyzersForVisualStudioBuild"
        BeforeTargets="CoreCompile"
        Condition="'$(BuildingInsideVisualStudio)' == 'True' And '$(BuildingProject)' == 'True' And '$(Configuration)' == 'Debug'">
  <!--
    Disable analyzers when building a project inside Visual Studio. Note that analyzer behavior for IntelliSense purposes is not altered by this.
  -->
  <ItemGroup>
    <Analyzer Remove="@(Analyzer)"/>
  </ItemGroup>
</Target>
</code>```

Body:
I ended up modifying the .csproj files to remove the analyzers if I'm building the solution from within Visual Studio in Debug configuration. That way, sonarlint does not complain that rules are outdated, nor does it get affected by updates. I got the answer from here

<Target Name="DisableAnalyzersForVisualStudioBuild"
        BeforeTargets="CoreCompile"
        Condition="'$(BuildingInsideVisualStudio)' == 'True' And '$(BuildingProject)' == 'True' And '$(Configuration)' == 'Debug'">
  <!--
    Disable analyzers when building a project inside Visual Studio. Note that analyzer behavior for IntelliSense purposes is not altered by this.
  -->
  <ItemGroup>
    <Analyzer Remove="@(Analyzer)"/>
  </ItemGroup>
</Target>


问:
Update Zero to One and One to Zero in SQL Server
I have a table with flag 0 and 1.

Please tell me how to update Zero to One and One to  Zero

```<code>DECLARE @a INT, @b INT

SELECT @a = number
FROM zerone
WHERE number = 0

SELECT @b = number
FROM zerone
WHERE number = 1

BEGIN
    IF @a = 0
        UPDATE zerone
        SET number = 1
        WHERE @a = 0
    ELSE IF @b = 1
        UPDATE zerone
        SET number = 0
        WHERE @b = 1
END
</code>```

This query is not working for me.

答:
you should also always consider NULL values in update operations and must explicitly filter them out

```<code>UPDATE zerone
SET number= case
              when 1 then 0
              when 0 then 1
             end
WHERE number in (0,1)
</code>```

Also your query will not work because you are assigning a single variable with a rows of data in the select statement.

```<code>SELECT @a = number
FROM zerone
WHERE number = 0
</code>```

This does not work like as you are expecting and will only assign @a with value either NULL(if there are no rows) or with 0 if there is a row. If there are multiple rows even then it will have a single value 0

Body:
I have a table with flag 0 and 1.

Please tell me how to update Zero to One and One to  Zero

DECLARE @a INT, @b INT

SELECT @a = number
FROM zerone
WHERE number = 0

SELECT @b = number
FROM zerone
WHERE number = 1

BEGIN
    IF @a = 0
        UPDATE zerone
        SET number = 1
        WHERE @a = 0
    ELSE IF @b = 1
        UPDATE zerone
        SET number = 0
        WHERE @b = 1
END

This query is not working for me.

Body:
you should also always consider NULL values in update operations and must explicitly filter them out

UPDATE zerone
SET number= case
              when 1 then 0
              when 0 then 1
             end
WHERE number in (0,1)

Also your query will not work because you are assigning a single variable with a rows of data in the select statement.

SELECT @a = number
FROM zerone
WHERE number = 0

This does not work like as you are expecting and will only assign @a with value either NULL(if there are no rows) or with 0 if there is a row. If there are multiple rows even then it will have a single value 0


问:
how to insert multiple lines in json array in database using php
I want to enter some details that included in JSON arrays to database.

Given below is my source code.

here is my data json array from the txt file

{

   "reader_name":"Biboy Pogi",
   "mac_address":"00:16:25:10:7E:85",
   "tag_reads":[

      {

         "antennaPort":1,
         "epc":"2015031687850100010105B5",
         "tid":"E280110520005A8B952F0886",
         "isHeartBeat":false
      }
   ]
}

{

   "reader_name":"Biboy Pogi",
   "mac_address":"00:16:25:10:7E:85",
   "tag_reads":[

      {

         "antennaPort":1,
         "epc":"2015031687850100010105B5",
         "tid":"E280110520005A8B952F0886",
         "isHeartBeat":false
      }
   ]
}

Body:
your json seems to be the problem.

try this:

[
  {
    "reader_name": "Biboy Pogi",
    "mac_address": "00:16:25:10:7E:85",
    "tag_reads": [
      {
        "antennaPort": 1,
        "epc": "2015031687850100010105B5",
        "tid": "E280110520005A8B952F0886",
        "isHeartBeat": false
      }
    ]
  },
  {
    "reader_name": "Biboy Pogi",
    "mac_address": "00:16:25:10:7E:85",
    "tag_reads": [
      {
        "antennaPort": 1,
        "epc": "2015031687850100010105B5",
        "tid": "E280110520005A8B952F0886",
        "isHeartBeat": false
      }
    ]
  }
]


问:
Multiple web.xml database connections in Maven Project
I am not completely new to Java, but I have recently learned about using a web.xml file to connect to a database.

It would be convenient to connect to the mySql I already have set, and a MSSql database within the same maven project.

I have researched this topic a bit, and haven't really found the answer I am looking for.

It isn't really helpful in terms of the question, but I have provided my web.xml as a code base if you would like to show me how this would be done.

Any help in the right direction would be appreciated.

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

<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
     version="3.1">

    <context-param>
        <param-name>db.driver.class</param-name>
        <param-value>com.mysql.jdbc.Driver</param-value>
    </context-param>
    <context-param>
        <param-name>db.url</param-name>
        <param-value>jdbc:mysql://localhost:3308/lib-1323</param-value>
    </context-param>
    <context-param>
        <param-name>db.username</param-name>
        <param-value>root</param-value>
    </context-param>
    <context-param>
        <param-name>db.password</param-name>
        <param-value>admin</param-value>
    </context-param>

    <session-config>
        <session-timeout>
            30
        </session-timeout>
    </session-config>
</web-app>
</code>```

答:
This can be done. I would do some research on Spring and hibernate.

I found this article which may help.

You would need the Microsoft SQL Dependency in your pom.xml, and the correct driver.

Hope this helps.

Body:
I am not completely new to Java, but I have recently learned about using a web.xml file to connect to a database.

It would be convenient to connect to the mySql I already have set, and a MSSql database within the same maven project.

I have researched this topic a bit, and haven't really found the answer I am looking for.

It isn't really helpful in terms of the question, but I have provided my web.xml as a code base if you would like to show me how this would be done.

Any help in the right direction would be appreciated.

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

<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
     version="3.1">

    <context-param>
        <param-name>db.driver.class</param-name>
        <param-value>com.mysql.jdbc.Driver</param-value>
    </context-param>
    <context-param>
        <param-name>db.url</param-name>
        <param-value>jdbc:mysql://localhost:3308/lib-1323</param-value>
    </context-param>
    <context-param>
        <param-name>db.username</param-name>
        <param-value>root</param-value>
    </context-param>
    <context-param>
        <param-name>db.password</param-name>
        <param-value>admin</param-value>
    </context-param>

    <session-config>
        <session-timeout>
            30
        </session-timeout>
    </session-config>
</web-app>


问:
Pass route data as query string by URL routing
I have injected country code in URL and now want to pass country code route data as query string by URL routing.

```<code>    routes.MapPageRoute(
        "Home",
        "{lang}",
        "~/Default.aspx?country={lang}"
    );
</code>```

But it is not working and throwing error.

So, how could I append route data mean my country code with Default.aspx?

答:
Well in your case, appending query string parameters directly in the file path has no effect on getting the country code value you want.

I think what you can do instead is to make country as part of the route values.

```<code>routes.MapPageRoute(
    "Home",
    "Home/{country}",
    "~/Default.aspx"
);
</code>```

So essentially, you will have a route like http://www.example.com/home/us, and the value us can be retrieved by calling Page.RouteData.Values["country"] in the code behind.

Body:
I have injected country code in URL and now want to pass country code route data as query string by URL routing.

    routes.MapPageRoute(
        "Home",
        "{lang}",
        "~/Default.aspx?country={lang}"
    );

But it is not working and throwing error.

So, how could I append route data mean my country code with Default.aspx?

Body:
Well in your case, appending query string parameters directly in the file path has no effect on getting the country code value you want.

I think what you can do instead is to make country as part of the route values.

routes.MapPageRoute(
    "Home",
    "Home/{country}",
    "~/Default.aspx"
);

So essentially, you will have a route like http://www.example.com/home/us, and the value us can be retrieved by calling Page.RouteData.Values["country"] in the code behind.


问:
What types of notifications can I use in admin-on-rest?
I use import { showNotification as showNotificationAction } from 'admin-on-rest';
I call it like showNotification(res.error.message, "warning") or showNotification(res.error.message, "info"). Which other types of messages can I use except info and warning?

答: This part is still not documented so you'll have to explore the source code: https://github.com/marmelab/admin-on-rest/blob/master/src/reducer/admin/notification.js#L8</p>


问:
Android studio :: Unable to see a source folder
I recently migrated my project to Android studio. I have placed all my library source folders under Application/library/src/main/java.

There is one folder named "rcs". I can see it in my windows explorer. But, I cannot see it in Android studio project view or any other views. And I can see that, wherever I refer the contents of this folder, I am seeing "Cannot resolve symbol" for this particular folder.

But I see those files are compiled and present in the "exploded-aar" folder of my application folder. Just that, they are not present in the project explorer.

Please input your suggestions. I don't have a classpath or .cvsignore or .gitignore.

答: If you are using new android studio, check this


答:
It's a gcc extension: C extension: <? and >? operators

Recent manuals say:

The G++ minimum and maximum operators (‘<?’ and ‘>?’) and their compound forms (‘<?=’) and ‘>?=’) have been deprecated and are now removed from G++. Code using these operators should be modified to use std::min and std::max instead...

Title: What is <?= in C++?


问:
How to stop labels from moving up when navigation bar disappears?
The layout in Xcode:

Output, in an iPhone 5s simulator once the navigation bar is removed:

Initially, at the start of this view, the navigation bar is required, but when I hit the record button, the navigation bar is to disappear, which it does. However, in doing so, it moves the timer labels up with it. How do I stop autolayout from moving the labels up?

Thanks.

答: Use Push function to navigate the first page to another and add navigation disappear Function to next page. It will work.</p>


问:
how to work with "process.stdin.on"?
I'm trying to understand process.stdin.

For example - I need to show array elements in console. And i should allow user choose which element will be shown.

I have code:

```<code>var arr = ['elem1','elem2','elem3','elem4','elem5'],
    lastIndx = arr.length-1;

showArrElem();

function showArrElem () {

  console.log('press number from 0 to ' + lastIndx +', or "q" to quit');

  process.stdin.on('readable', function (key) {
        var key = process.stdin.read();
        if (!process.stdin.isRaw) {
          process.stdin.setRawMode( true );
        } else {
          var i = String(key);
          if (i == 'q') {
            process.exit(0);
          } else {
            console.log('you press ' +i); // null
            console.log('e: ' +arr[i]);
            showArrElem();
          };
        };
  });

};
</code>```

Why the "i" is null when i type number a second time? How to use "process.stdin.on" correctly?

答:
This is typically how I get input when using stdin (node.js) This is the ES5 version, I don't use ES6 yet.

```<code>function processThis(input) {
  console.log(input);  //your code goes here
}

process.stdin.resume();
process.stdin.setEncoding("ascii");
_input = "";
process.stdin.on("data", function (input) {
  _input += input;
});

process.stdin.on("end", function () {
   processThis(_input);
});
</code>```

hope this helps.

Title: how to work with "process.stdin.on"?

Body:
I'm trying to understand process.stdin.

For example - I need to show array elements in console. And i should allow user choose which element will be shown.

I have code:

var arr = ['elem1','elem2','elem3','elem4','elem5'],
    lastIndx = arr.length-1;

showArrElem();

function showArrElem () {

  console.log('press number from 0 to ' + lastIndx +', or "q" to quit');

  process.stdin.on('readable', function (key) {
        var key = process.stdin.read();
        if (!process.stdin.isRaw) {
          process.stdin.setRawMode( true );
        } else {
          var i = String(key);
          if (i == 'q') {
            process.exit(0);
          } else {
            console.log('you press ' +i); // null
            console.log('e: ' +arr[i]);
            showArrElem();
          };
        };
  });

};

Why the "i" is null when i type number a second time? How to use "process.stdin.on" correctly?

Body:
This is typically how I get input when using stdin (node.js) This is the ES5 version, I don't use ES6 yet.

function processThis(input) {
  console.log(input);  //your code goes here
}

process.stdin.resume();
process.stdin.setEncoding("ascii");
_input = "";
process.stdin.on("data", function (input) {
  _input += input;
});

process.stdin.on("end", function () {
   processThis(_input);
});

hope this helps.


问:
Getting "No message available" error with Spring Boot + REST application
I have created demo Spring Boot project and implemented Restful services as shown here

```<code>@RestController
public class GreetingsController {
    @RequestMapping(value="/api/greetings", method=RequestMethod.GET, produces=MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<String> getGreetings(){
        return new ResponseEntity<String>("Hello World", HttpStatus.OK);
    }
}
</code>```

When I tried to invoke the service with Postman tool with url "http://localhost:8080/api/greetings" as request method GET, I am getting below error message

```<code>{
  "timestamp": 1449495844177,
  "status": 404,
  "error": "Not Found",
  "message": "No message available",
  "path": "/api/greetings"
}
</code>```

Per Spring Boot application, I don't have to configure the Spring Dispatcher servlet in web.xml.

Can someone help me to find out the missing point here?

答:
If you are using @SpringBootApplication alone, then make sure your rest service controller is in the same package like below -

```<code>com.testSpring->SpringBootApplication class
com.testSpring.controller->RestfulController classes
com.testSpring.model->Model classes
..etc
</code>```

If you are using @ComponentScan(basePackageClasses = UserController.class), then mention specific controller class names.

Body:
I have created demo Spring Boot project and implemented Restful services as shown here

@RestController
public class GreetingsController {
    @RequestMapping(value="/api/greetings", method=RequestMethod.GET, produces=MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<String> getGreetings(){
        return new ResponseEntity<String>("Hello World", HttpStatus.OK);
    }
}

When I tried to invoke the service with Postman tool with url "http://localhost:8080/api/greetings" as request method GET, I am getting below error message

{
  "timestamp": 1449495844177,
  "status": 404,
  "error": "Not Found",
  "message": "No message available",
  "path": "/api/greetings"
}

Per Spring Boot application, I don't have to configure the Spring Dispatcher servlet in web.xml.

Can someone help me to find out the missing point here?

Body:
If you are using @SpringBootApplication alone, then make sure your rest service controller is in the same package like below -

com.testSpring->SpringBootApplication class
com.testSpring.controller->RestfulController classes
com.testSpring.model->Model classes
..etc

If you are using @ComponentScan(basePackageClasses = UserController.class), then mention specific controller class names.


问:
Getting ExecuteBatch to execute faster
I'm trying to read a table from a sybase server, process the rows, and output the results to another table.  (Below is my code)

The code retrieves the table pretty fast and processes equally fast (get's to the part where it sends within 30 seconds).  But When I run execute batch it sits there for 20 minutes before finish (fyi, I have a table which I'm testing with 8400 rows).

Is there a more efficient way to do this?  I'm amenable as to how I can recieve or send the queries (I can create a new table, update a table, etc) -- I just don't know why this is so slow (I'm sure the data < 1 MB and I'm sure it doesn't take the SQL server 20 minutes to parse 8400 rows).  Any ideas?

Note:  The reason this is really bad for me is that I have to parse a table with 1.2 MM rows (this table I'm working with right now is a test table with 8400 rows)

```<code>    Connection conn = DriverManager.getConnection(conString, user, pass);

    String sql = "SELECT id,dateid,attr from user.fromtable";
    Statement st = conn.createStatement();
    ResultSet rs = st.executeQuery(sql);

    String sqlOut = "INSERT INTO user.mytabletest (id,attr,date,estEndtime) values (?,?,?,?)";
    PreparedStatement ps = conn.prepareStatement(sqlOut);

    int i=1;

    while(rs.next())
    {
        int date = rs.getInt("dateid");
        String attr = rs.getString("attr");
        String id = rs.getString("id");

        Time tt = getTime(date,attr);
        Timestamp ts = new Timestamp(tt.getTime());

        ps.setString(1, id);
        ps.setString(2, attr);
        ps.setInt(3, date);
        ps.setTimestamp(4, ts);
        ps.addBatch();

        if(i % 10000 == 0)
        {
            System.out.println(i);
            ps.executeBatch();
            conn.commit();
            ps.clearBatch();
        }

        i++;
    }
    System.out.println("sending "+(new Date()));
    int[] results = ps.executeBatch();
    System.out.println("committing "+(new Date()));
    conn.commit();
    System.out.println("done "+(new Date()));
</code>```

答:
Add ?rewriteBatchedStatements=true to the end of your JDBC url. It'll give you a serious performance improvement. Note that this is specific to MySql, won't have any effect with any other JDBC drivers.

Eg : jdbc:mysql://server:3306/db_name?rewriteBatchedStatements=true

It improved my performance by more than 15 times

Title: Getting ExecuteBatch to execute faster

Body:
I'm trying to read a table from a sybase server, process the rows, and output the results to another table.  (Below is my code)

The code retrieves the table pretty fast and processes equally fast (get's to the part where it sends within 30 seconds).  But When I run execute batch it sits there for 20 minutes before finish (fyi, I have a table which I'm testing with 8400 rows).

Is there a more efficient way to do this?  I'm amenable as to how I can recieve or send the queries (I can create a new table, update a table, etc) -- I just don't know why this is so slow (I'm sure the data < 1 MB and I'm sure it doesn't take the SQL server 20 minutes to parse 8400 rows).  Any ideas?

Note:  The reason this is really bad for me is that I have to parse a table with 1.2 MM rows (this table I'm working with right now is a test table with 8400 rows)

    Connection conn = DriverManager.getConnection(conString, user, pass);

    String sql = "SELECT id,dateid,attr from user.fromtable";
    Statement st = conn.createStatement();
    ResultSet rs = st.executeQuery(sql);

    String sqlOut = "INSERT INTO user.mytabletest (id,attr,date,estEndtime) values (?,?,?,?)";
    PreparedStatement ps = conn.prepareStatement(sqlOut);

    int i=1;

    while(rs.next())
    {
        int date = rs.getInt("dateid");
        String attr = rs.getString("attr");
        String id = rs.getString("id");

        Time tt = getTime(date,attr);
        Timestamp ts = new Timestamp(tt.getTime());

        ps.setString(1, id);
        ps.setString(2, attr);
        ps.setInt(3, date);
        ps.setTimestamp(4, ts);
        ps.addBatch();

        if(i % 10000 == 0)
        {
            System.out.println(i);
            ps.executeBatch();
            conn.commit();
            ps.clearBatch();
        }

        i++;
    }
    System.out.println("sending "+(new Date()));
    int[] results = ps.executeBatch();
    System.out.println("committing "+(new Date()));
    conn.commit();
    System.out.println("done "+(new Date()));


问:
Splitting HTML file doesn't work
I'm trying to build very simple web page (one page , spited into 2 parts, each part will have it's own html file):

Welcome.html & Welcome.css:

```<code><html>

    <head>
        <link rel="stylesheet" type="text/css" href="Welcome.css">
    </head>

    <body id="bodyTag">

     <script type = "text/javascript"  src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
      <script type = "text/javascript">
         $(document).ready(function(){

         });
      </script>

       <div id="top" w3-include-html="/Top.html">

       </div>

       <div id="bottom">
            bottom
        </div>

    </body>
</html>

#bottom {
    height: 50%;
    background-color: blue;
}

#top {
    height: 50%;
    background-color: orange;
}
</code>```

I want that Welcome.html file will get the top content from external html file

```<code>Top.html

<html>

  <head>
  </head>

  <body>
      Test -> TOP

  </body>
</html>
</code>```

But is seems that there is no request for Top.html file in the Node.js Log:

```<code>var express = require('express');
var app = express();
var fs = require('fs');
var bodyParser = require('body-parser');

app.use(bodyParser.json())

/*
 *  Home page
 */
app.get('/', function (req, res) {
   clearLogScreen();
   console.log("[/] Got request for '/'");
   res.sendFile( __dirname + '/Welcome.html');
})

app.get('/Welcome.css', function(req, res) {
  console.log("[/Welcome] Got request for 'Welcome.css'");
  res.sendFile(__dirname + "/" + "Welcome.css");
});

app.get('/Top', function(req, res) {
  console.log("[/Top] Got request for 'Welcome.top'");
  res.sendFile(__dirname + "/" + "Top.html");
});

/*
 *  Startup
 */
var server = app.listen(8081, function () {
   var host = server.address().address
   var port = server.address().port

   // start
   console.log("-----------------------------")
   console.log("Dirname: " + __dirname);
   console.log("App listening at http://%s:%s", host, port)
})
</code>```

I guess I'm missing something very easy, but can't find the mistake.

答: Kindly checkout templatesjs; It will help insert html inside another html.</p>

Title: Splitting HTML file doesn't work

Body:
I'm trying to build very simple web page (one page , spited into 2 parts, each part will have it's own html file):

Welcome.html & Welcome.css:

        <link rel="stylesheet" type="text/css" href="Welcome.css">

            bottom

#bottom {
    height: 50%;
    background-color: blue;
}

#top {
    height: 50%;
    background-color: orange;
}

I want that Welcome.html file will get the top content from external html file

Top.html

      Test -> TOP

But is seems that there is no request for Top.html file in the Node.js Log:

var express = require('express');
var app = express();
var fs = require('fs');
var bodyParser = require('body-parser');

app.use(bodyParser.json())

/*
 *  Home page
 */
app.get('/', function (req, res) {
   clearLogScreen();
   console.log("[/] Got request for '/'");
   res.sendFile( __dirname + '/Welcome.html');
})

app.get('/Welcome.css', function(req, res) {
  console.log("[/Welcome] Got request for 'Welcome.css'");
  res.sendFile(__dirname + "/" + "Welcome.css");
});

app.get('/Top', function(req, res) {
  console.log("[/Top] Got request for 'Welcome.top'");
  res.sendFile(__dirname + "/" + "Top.html");
});

/*
 *  Startup
 */
var server = app.listen(8081, function () {
   var host = server.address().address
   var port = server.address().port

   // start
   console.log("-----------------------------")
   console.log("Dirname: " + __dirname);
   console.log("App listening at http://%s:%s", host, port)
})

I guess I'm missing something very easy, but can't find the mistake.


问:
Inserting 2 rows, each to different tables where one row refrences the other's primary key
Hello folks
Checkout this scenario

Table 1 columns -> | table_1_id (pkey) | some_column | comments |

Table 2 columns -> | table_2_id (pkey) | some_other_column | table_1_id (fkey) | comments |

All primary keys are of type serial or auto number.
The 3rd column on Table 2 is an fk that references Table 1's primary key.

I would like to insert rows into both programmaticaly (from a c++ app)

Do i have to insert to table one then SELECT-query the entry's primary key then insert the Table 2 row with the pkey result?

Is there a more efficient way of handling this? Say using almost 2 queries?

答:
If you don't need the table_1_id value in your application, you can skip retrieving it completely:</p>

```<code>INSERT INTO table_1(cols...) VALUES(vals...)
INSERT INTO table_2(table_1_id, cols...) VALUES(currval('table_1_table_1_id_seq'), vals...)
</code>```

Body:
If you don't need the table_1_id value in your application, you can skip retrieving it completely:

INSERT INTO table_1(cols...) VALUES(vals...)
INSERT INTO table_2(table_1_id, cols...) VALUES(currval('table_1_table_1_id_seq'), vals...)


问:
Perl user input into SQL Like statement
Im trying to get user input and send it through to the SQL Like statement. But Im getting error: Can't call method "bind_param" on an undefined.
My Original code :

```<code>#!/usr/bin/perl
use DBI;
#use DBD::Oracle;
use strict;
use warnings;
use CGI;

print "Enter INCD number : ";

my $input = <>;
chomp $input;

my $DSN = 'driver={SQL Server};Server=ddsfs1; database=sdfds;TrustedConnection=Yes';
my $dbh = DBI->connect("dbi:ODBC:$DSN")
    #print "connected.."
    or die "$DBI::errstr\n";

my $query = $dbh->prepare("SELECT TOP 20 Id
      ,Created
      ,Updated
      ,Message
      FROM FrameworkDEV3.Log.Entry
     where Message  like ?
     and Created >= DATEADD(day, -10, GETDATE())
        order by Created desc");
$sth->bind_param(1, '%$input%');

print $sth;
$sth->execute;
#DBI::dump_results($sth);

while( my @data = $query->fetchrow_array())
{
    foreach(@data) {
    print "[$_]";
    }
    print "\n\n";
}

$sth->finish;
$dbh->disconnect;
#print "Connected..";
print "\n";
</code>```

Following code is fixed as per comments from Dave and Jim :

```<code>my $sth = $dbh->prepare("SELECT TOP 20 Id
      ,Created
      ,Updated
      ,Message
      FROM FrDEVsd.Log.Entry
     where Message  like ?
     and Created >= DATEADD(day, -10, GETDATE())
        order by Created desc");
  $sth->bind_param(1, "%$input%");
print $sth;
$sth->execute;
#DBI::dump_results($sth);
while( my @data = $sth->fetchrow_array())
{
    foreach(@data) {
    print "[$_]";
    }
    print "\n\n";
}

$sth->finish;
$dbh->disconnect;
</code>```

print "\n";

The error im getting now is

DBI::st=HASH(0x2a9a480)

答:
In your code:

```<code>my $query = $dbh->prepare("SELECT TOP 20 Id
      ,Created
      ,Updated
      ,Message
      FROM sdada.ada.asd
      where Message  like ?
      and Created >= DATEADD(day, -10, GETDATE())
      order by Created desc");
my $sth->bind_param(1, "%$input%");
</code>```

Notice the prepared statement is stored in a variable named $query, but you attempt to bind using $sth which was never set and is undefined.  That is what the error message was telling you.

Use the same variable name both places (and later when you execute the statement) to fix the problem.

Title: Perl user input into SQL Like statement

Body:
Im trying to get user input and send it through to the SQL Like statement. But Im getting error: Can't call method "bind_param" on an undefined.
My Original code :

#!/usr/bin/perl
use DBI;
#use DBD::Oracle;
use strict;
use warnings;
use CGI;

print "Enter INCD number : ";

my $input = <>;
chomp $input;

my $DSN = 'driver={SQL Server};Server=ddsfs1; database=sdfds;TrustedConnection=Yes';
my $dbh = DBI->connect("dbi:ODBC:$DSN")
    #print "connected.."
    or die "$DBI::errstr\n";

my $query = $dbh->prepare("SELECT TOP 20 Id
      ,Created
      ,Updated
      ,Message
      FROM FrameworkDEV3.Log.Entry
     where Message  like ?
     and Created >= DATEADD(day, -10, GETDATE())
        order by Created desc");
$sth->bind_param(1, '%$input%');

print $sth;
$sth->execute;
#DBI::dump_results($sth);

while( my @data = $query->fetchrow_array())
{
    foreach(@data) {
    print "[$_]";
    }
    print "\n\n";
}

$sth->finish;
$dbh->disconnect;
#print "Connected..";
print "\n";

Following code is fixed as per comments from Dave and Jim :

my $sth = $dbh->prepare("SELECT TOP 20 Id
      ,Created
      ,Updated
      ,Message
      FROM FrDEVsd.Log.Entry
     where Message  like ?
     and Created >= DATEADD(day, -10, GETDATE())
        order by Created desc");
  $sth->bind_param(1, "%$input%");
print $sth;
$sth->execute;
#DBI::dump_results($sth);
while( my @data = $sth->fetchrow_array())
{
    foreach(@data) {
    print "[$_]";
    }
    print "\n\n";
}

$sth->finish;
$dbh->disconnect;

print "\n";

The error im getting now is

DBI::st=HASH(0x2a9a480)

Body:
In your code:

my $query = $dbh->prepare("SELECT TOP 20 Id
      ,Created
      ,Updated
      ,Message
      FROM sdada.ada.asd
      where Message  like ?
      and Created >= DATEADD(day, -10, GETDATE())
      order by Created desc");
my $sth->bind_param(1, "%$input%");

Notice the prepared statement is stored in a variable named $query, but you attempt to bind using $sth which was never set and is undefined.  That is what the error message was telling you.

Use the same variable name both places (and later when you execute the statement) to fix the problem.


问:
How to center crop an image () in fluid width container
How do I get an image to stay centered when its fluid width (percentage based) container is too small to show the whole image?

How can I center the image inside it's container

This means it should show the middle of the image instead of the sides when container is too small.

答:
If you are anticipating that the image to be displayed will be so much longer than the display container, setting left: 100%; and margin-left: -200%; (from Bryce's answer) might not be enough to get the center part of the image. Just put a bigger percentage for both. Make sure that the other is half of the other though.</p>

```<code>left: 500%;
margin-left: -1000%;
</code>```

Title: How to center crop an image (<img>) in fluid width container

Body:
If you are anticipating that the image to be displayed will be so much longer than the display container, setting left: 100%; and margin-left: -200%; (from Bryce's answer) might not be enough to get the center part of the image. Just put a bigger percentage for both. Make sure that the other is half of the other though.

left: 500%;
margin-left: -1000%;


问:
getting data from localstorage in ngOnInit in Angular 4 but it reset its value on refresh
I am using localstorage to store data in it and retreiving from it in constructor, I want that check varaible retain its value on refresh of page and compare its value with the 0, after getting updated value if check == 0 then it should go inside that function.

I am stuck on it how this can be possible?

```<code>check=0;

ngOnInit() {

    if(this.check==0)
    {
        this.list =new Array();
        this.list.push("Purchase a ring for my beautiful wife","get new GALAXY Note 150","Complete kevin's work ASAP","Buy 2 dozen eggs","Get milk on my way to home");
        localStorage.setItem('list', JSON.stringify(this.list));
        this.check++;
        localStorage.setItem('incre', JSON.stringify(this.check));
    }

    this.check=JSON.parse( localStorage.getItem('incre'));
    this.list=JSON.parse( localStorage.getItem('list'));
}
</code>```

答:
If I understand your question correctly then  this.check=JSON.parse( localStorage.getItem('incre')); should be at the top of your constructor and then you should compare it in if block

Try this

```<code>check=0;
list = any[];

constructor() {

 this.check=JSON.parse( localStorage.getItem('incre'));
 if(this.check == undefined || this.check==0)
 {
  this.list =new Array();
  this.list.push("Purchase a ring for my beautiful wife","get new GALAXY Note 150","Complete kevin's work ASAP","Buy 2 dozen eggs","Get milk on my way to home");
  localStorage.setItem('list', JSON.stringify(this.list));
  this.check++;
  localStorage.setItem('incre', JSON.stringify(this.check));
 }

  this.list=JSON.parse( localStorage.getItem('list'));
}
</code>```

Body:
I am using localstorage to store data in it and retreiving from it in constructor, I want that check varaible retain its value on refresh of page and compare its value with the 0, after getting updated value if check == 0 then it should go inside that function.

I am stuck on it how this can be possible?

check=0;

ngOnInit() {

    if(this.check==0)
    {
        this.list =new Array();
        this.list.push("Purchase a ring for my beautiful wife","get new GALAXY Note 150","Complete kevin's work ASAP","Buy 2 dozen eggs","Get milk on my way to home");
        localStorage.setItem('list', JSON.stringify(this.list));
        this.check++;
        localStorage.setItem('incre', JSON.stringify(this.check));
    }

    this.check=JSON.parse( localStorage.getItem('incre'));
    this.list=JSON.parse( localStorage.getItem('list'));
}

Body:
If I understand your question correctly then  this.check=JSON.parse( localStorage.getItem('incre')); should be at the top of your constructor and then you should compare it in if block

Try this

check=0;
list = any[];

constructor() {

 this.check=JSON.parse( localStorage.getItem('incre'));
 if(this.check == undefined || this.check==0)
 {
  this.list =new Array();
  this.list.push("Purchase a ring for my beautiful wife","get new GALAXY Note 150","Complete kevin's work ASAP","Buy 2 dozen eggs","Get milk on my way to home");
  localStorage.setItem('list', JSON.stringify(this.list));
  this.check++;
  localStorage.setItem('incre', JSON.stringify(this.check));
 }

  this.list=JSON.parse( localStorage.getItem('list'));
}


问:
Why Spring Boot Application logs that it started twice after adding spring-cloud-bus dependency
This is simple code in my Spring boot application:

```<code>package com.maxxton.SpringBootHelloWorld;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class SpringBootHelloWorldApplication {

  public static void main(String[] args) {
    SpringApplication.run(SpringBootHelloWorldApplication.class, args);
  }
}
</code>```

And a ApplicationListener class to listen to ApplicationEvent:

```<code>package com.maxxton.SpringBootHelloWorld;

import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

@Component
public class Test implements ApplicationListener {

  @Override
  public void onApplicationEvent(ApplicationEvent event) {
    if (event.getClass().getSimpleName().equals("ApplicationReadyEvent")) {
      System.out.println("-------------------------------------");
      System.out.println(event.getClass().getSimpleName());
      System.out.println("-------------------------------------");
    }
  }
}
</code>```

build.gradle contains these dependencies:

```<code>dependencies {

    compile("org.springframework.boot:spring-boot-starter-amqp")
    compile("org.springframework.cloud:spring-cloud-starter-bus-amqp")

    compile('org.springframework.boot:spring-boot-starter-web')
    compile('org.springframework.boot:spring-boot-starter')
    compile("org.springframework.cloud:spring-cloud-starter")
    compile("org.springframework.cloud:spring-cloud-starter-security")
    compile("org.springframework.cloud:spring-cloud-starter-eureka")
    testCompile('org.springframework.boot:spring-boot-starter-test')
}
</code>```

Now, when I run this spring boot application, I see this log printed twice:

```<code>[main] c.m.S.SpringBootHelloWorldApplication : Started SpringBootHelloWorldApplication in ... seconds (JVM running for ...)
</code>```

Usually, this log get printed only once, but it get printed twice if I add these dependencies:

```<code>compile("org.springframework.boot:spring-boot-starter-amqp")
compile("org.springframework.cloud:spring-cloud-starter-bus-amqp")
</code>```

This is complete log:

```<code>2017-11-17 15:44:07.372  INFO 5976 --- [           main] o.s.c.support.GenericApplicationContext  : Refreshing org.springframework.context.support.GenericApplicationContext@31c7c281: startup date [Fri Nov 17 15:44:07 IST 2017]; root of context hierarchy
-------------------------------------
ApplicationReadyEvent
-------------------------------------
2017-11-17 15:44:07.403  INFO 5976 --- [           main] c.m.S.SpringBootHelloWorldApplication    : Started SpringBootHelloWorldApplication in 1.19 seconds (JVM running for 10.231)
2017-11-17 15:44:09.483  WARN 5976 --- [           main] o.s.amqp.rabbit.core.RabbitAdmin         : Failed to declare exchange: Exchange [name=springCloudBus, type=topic, durable=true, autoDelete=false, internal=false, arguments={}], continuing... org.springframework.amqp.AmqpConnectException: java.net.ConnectException: Connection refused: connect
2017-11-17 15:44:09.492  INFO 5976 --- [           main] o.s.integration.channel.DirectChannel    : Channel 'a-bootiful-client.springCloudBusOutput' has 1 subscriber(s).
2017-11-17 15:44:09.493  INFO 5976 --- [           main] o.s.c.support.DefaultLifecycleProcessor  : Starting beans in phase 0
2017-11-17 15:44:09.530  INFO 5976 --- [           main] o.s.i.endpoint.EventDrivenConsumer       : Adding {logging-channel-adapter:_org.springframework.integration.errorLogger} as a subscriber to the 'errorChannel' channel
2017-11-17 15:44:09.530  INFO 5976 --- [           main] o.s.i.channel.PublishSubscribeChannel    : Channel 'a-bootiful-client.errorChannel' has 1 subscriber(s).
2017-11-17 15:44:09.530  INFO 5976 --- [           main] o.s.i.endpoint.EventDrivenConsumer       : started _org.springframework.integration.errorLogger
2017-11-17 15:44:09.530  INFO 5976 --- [           main] o.s.c.support.DefaultLifecycleProcessor  : Starting beans in phase 2147482647
2017-11-17 15:44:09.539  INFO 5976 --- [           main] c.s.b.r.p.RabbitExchangeQueueProvisioner : declaring queue for inbound: springCloudBus.anonymous.kZ1vvxHaRfChKe1TncH-MQ, bound to: springCloudBus
2017-11-17 15:44:11.562  WARN 5976 --- [           main] o.s.amqp.rabbit.core.RabbitAdmin         : Failed to declare exchange: Exchange [name=springCloudBus, type=topic, durable=true, autoDelete=false, internal=false, arguments={}], continuing... org.springframework.amqp.AmqpConnectException: java.net.ConnectException: Connection refused: connect
2017-11-17 15:44:13.587  WARN 5976 --- [           main] o.s.amqp.rabbit.core.RabbitAdmin         : Failed to declare queue: Queue [name=springCloudBus.anonymous.kZ1vvxHaRfChKe1TncH-MQ, durable=false, autoDelete=true, exclusive=true, arguments={}], continuing... org.springframework.amqp.AmqpConnectException: java.net.ConnectException: Connection refused: connect
2017-11-17 15:44:15.611  WARN 5976 --- [           main] o.s.amqp.rabbit.core.RabbitAdmin         : Failed to declare binding: Binding [destination=springCloudBus.anonymous.kZ1vvxHaRfChKe1TncH-MQ, exchange=springCloudBus, routingKey=#], continuing... org.springframework.amqp.AmqpConnectException: java.net.ConnectException: Connection refused: connect
2017-11-17 15:44:17.662  INFO 5976 --- [           main] o.s.i.a.i.AmqpInboundChannelAdapter      : started inbound.springCloudBus.anonymous.kZ1vvxHaRfChKe1TncH-MQ
2017-11-17 15:44:17.662  INFO 5976 --- [           main] o.s.i.endpoint.EventDrivenConsumer       : Adding {message-handler:inbound.springCloudBus.default} as a subscriber to the 'bridge.springCloudBus' channel
2017-11-17 15:44:17.662  INFO 5976 --- [           main] o.s.i.endpoint.EventDrivenConsumer       : started inbound.springCloudBus.default
2017-11-17 15:44:17.663  INFO 5976 --- [           main] o.s.c.support.DefaultLifecycleProcessor  : Starting beans in phase 2147483647
2017-11-17 15:44:17.714  INFO 5976 --- [           main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8080 (http)
-------------------------------------
ApplicationReadyEvent
-------------------------------------
2017-11-17 15:44:17.717  INFO 5976 --- [           main] c.m.S.SpringBootHelloWorldApplication    : Started SpringBootHelloWorldApplication in 20.131 seconds (JVM running for 20.545)
</code>```

As you can see, ApplicationReadyEvent is happening twice.

Why is this happening?
Is there any way to avoid this?

答:
Are u using multiple binders rabbitmq configuration in your application.yml/.xml ?

If it's a yes, then u can try to exclude RabbitAutoConfiguration.

```<code>@EnableDiscoveryClient
@EnableAutoConfiguration(exclude = {RabbitAutoConfiguration.class})
@SpringBootApplication
public class SpringBootHelloWorldApplication {

  public static void main(String[] args) {
    SpringApplication.run(SpringBootHelloWorldApplication.class, args);
  }
}
</code>```

Body:
This is simple code in my Spring boot application:

package com.maxxton.SpringBootHelloWorld;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class SpringBootHelloWorldApplication {

  public static void main(String[] args) {
    SpringApplication.run(SpringBootHelloWorldApplication.class, args);
  }
}

And a ApplicationListener class to listen to ApplicationEvent:

package com.maxxton.SpringBootHelloWorld;

import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

@Component
public class Test implements ApplicationListener {

  @Override
  public void onApplicationEvent(ApplicationEvent event) {
    if (event.getClass().getSimpleName().equals("ApplicationReadyEvent")) {
      System.out.println("-------------------------------------");
      System.out.println(event.getClass().getSimpleName());
      System.out.println("-------------------------------------");
    }
  }
}

build.gradle contains these dependencies:

dependencies {

    compile("org.springframework.boot:spring-boot-starter-amqp")
    compile("org.springframework.cloud:spring-cloud-starter-bus-amqp")

    compile('org.springframework.boot:spring-boot-starter-web')
    compile('org.springframework.boot:spring-boot-starter')
    compile("org.springframework.cloud:spring-cloud-starter")
    compile("org.springframework.cloud:spring-cloud-starter-security")
    compile("org.springframework.cloud:spring-cloud-starter-eureka")
    testCompile('org.springframework.boot:spring-boot-starter-test')
}

Now, when I run this spring boot application, I see this log printed twice:

[main] c.m.S.SpringBootHelloWorldApplication : Started SpringBootHelloWorldApplication in ... seconds (JVM running for ...)

Usually, this log get printed only once, but it get printed twice if I add these dependencies:

compile("org.springframework.boot:spring-boot-starter-amqp")
compile("org.springframework.cloud:spring-cloud-starter-bus-amqp")

This is complete log:

2017-11-17 15:44:07.372  INFO 5976 --- [           main] o.s.c.support.GenericApplicationContext  : Refreshing org.springframework.context.support.GenericApplicationContext@31c7c281: startup date [Fri Nov 17 15:44:07 IST 2017]; root of context hierarchy
-------------------------------------
ApplicationReadyEvent
-------------------------------------
2017-11-17 15:44:07.403  INFO 5976 --- [           main] c.m.S.SpringBootHelloWorldApplication    : Started SpringBootHelloWorldApplication in 1.19 seconds (JVM running for 10.231)
2017-11-17 15:44:09.483  WARN 5976 --- [           main] o.s.amqp.rabbit.core.RabbitAdmin         : Failed to declare exchange: Exchange [name=springCloudBus, type=topic, durable=true, autoDelete=false, internal=false, arguments={}], continuing... org.springframework.amqp.AmqpConnectException: java.net.ConnectException: Connection refused: connect
2017-11-17 15:44:09.492  INFO 5976 --- [           main] o.s.integration.channel.DirectChannel    : Channel 'a-bootiful-client.springCloudBusOutput' has 1 subscriber(s).
2017-11-17 15:44:09.493  INFO 5976 --- [           main] o.s.c.support.DefaultLifecycleProcessor  : Starting beans in phase 0
2017-11-17 15:44:09.530  INFO 5976 --- [           main] o.s.i.endpoint.EventDrivenConsumer       : Adding {logging-channel-adapter:_org.springframework.integration.errorLogger} as a subscriber to the 'errorChannel' channel
2017-11-17 15:44:09.530  INFO 5976 --- [           main] o.s.i.channel.PublishSubscribeChannel    : Channel 'a-bootiful-client.errorChannel' has 1 subscriber(s).
2017-11-17 15:44:09.530  INFO 5976 --- [           main] o.s.i.endpoint.EventDrivenConsumer       : started _org.springframework.integration.errorLogger
2017-11-17 15:44:09.530  INFO 5976 --- [           main] o.s.c.support.DefaultLifecycleProcessor  : Starting beans in phase 2147482647
2017-11-17 15:44:09.539  INFO 5976 --- [           main] c.s.b.r.p.RabbitExchangeQueueProvisioner : declaring queue for inbound: springCloudBus.anonymous.kZ1vvxHaRfChKe1TncH-MQ, bound to: springCloudBus
2017-11-17 15:44:11.562  WARN 5976 --- [           main] o.s.amqp.rabbit.core.RabbitAdmin         : Failed to declare exchange: Exchange [name=springCloudBus, type=topic, durable=true, autoDelete=false, internal=false, arguments={}], continuing... org.springframework.amqp.AmqpConnectException: java.net.ConnectException: Connection refused: connect
2017-11-17 15:44:13.587  WARN 5976 --- [           main] o.s.amqp.rabbit.core.RabbitAdmin         : Failed to declare queue: Queue [name=springCloudBus.anonymous.kZ1vvxHaRfChKe1TncH-MQ, durable=false, autoDelete=true, exclusive=true, arguments={}], continuing... org.springframework.amqp.AmqpConnectException: java.net.ConnectException: Connection refused: connect
2017-11-17 15:44:15.611  WARN 5976 --- [           main] o.s.amqp.rabbit.core.RabbitAdmin         : Failed to declare binding: Binding [destination=springCloudBus.anonymous.kZ1vvxHaRfChKe1TncH-MQ, exchange=springCloudBus, routingKey=#], continuing... org.springframework.amqp.AmqpConnectException: java.net.ConnectException: Connection refused: connect
2017-11-17 15:44:17.662  INFO 5976 --- [           main] o.s.i.a.i.AmqpInboundChannelAdapter      : started inbound.springCloudBus.anonymous.kZ1vvxHaRfChKe1TncH-MQ
2017-11-17 15:44:17.662  INFO 5976 --- [           main] o.s.i.endpoint.EventDrivenConsumer       : Adding {message-handler:inbound.springCloudBus.default} as a subscriber to the 'bridge.springCloudBus' channel
2017-11-17 15:44:17.662  INFO 5976 --- [           main] o.s.i.endpoint.EventDrivenConsumer       : started inbound.springCloudBus.default
2017-11-17 15:44:17.663  INFO 5976 --- [           main] o.s.c.support.DefaultLifecycleProcessor  : Starting beans in phase 2147483647
2017-11-17 15:44:17.714  INFO 5976 --- [           main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8080 (http)
-------------------------------------
ApplicationReadyEvent
-------------------------------------
2017-11-17 15:44:17.717  INFO 5976 --- [           main] c.m.S.SpringBootHelloWorldApplication    : Started SpringBootHelloWorldApplication in 20.131 seconds (JVM running for 20.545)

As you can see, ApplicationReadyEvent is happening twice.

Why is this happening?
Is there any way to avoid this?

Body:
Are u using multiple binders rabbitmq configuration in your application.yml/.xml ?

If it's a yes, then u can try to exclude RabbitAutoConfiguration.

@EnableDiscoveryClient
@EnableAutoConfiguration(exclude = {RabbitAutoConfiguration.class})
@SpringBootApplication
public class SpringBootHelloWorldApplication {

  public static void main(String[] args) {
    SpringApplication.run(SpringBootHelloWorldApplication.class, args);
  }
}


问:
How to use method to output a random string from array?
How can I fix the code so my method compiles correctly to output a random string from the array I created into the main method?</p>

```<code>class Main
{
  public static void main (String[] args)
  {
   randomWord();
   System.out.println (random);
  }

  static String[] randomWord()
  {
    String[] randomWords = {"dog", "cat", "monkey"}
    String random = randomWords[(int)(Math.random() * randomWords.length)];
    return random;
  }
}
</code>```

答:
Your code needs 2 little modifications, and I'll explain each change and why.

Here is a working version after applying changes:

```<code>public class Main {

     public static void main(String[] args) {
     System.out.println(randomWord()); //randomWord() returns the random string which is directly printed
     }

     static String randomWord() {
     String[] randomWords = {"dog", "cat", "monkey"};
     return randomWords[(int) (Math.random() * randomWords.length)];
     }
}
</code>```

Tweaks made:

1- You are printing out variable 'random' which cannot be accessed in your main method since its a local variable to method 'randomWord()'

Code Modified to print the returned value of the 'randomWord()' method itself

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

2- 'randomWord()' is defined to return a String array, But in actuality you are returning a string variable 'random'

Code Modified to return a String in the definition

```<code> static String randomWord()
</code>```

Body:
How can I fix the code so my method compiles correctly to output a random string from the array I created into the main method?

class Main
{
  public static void main (String[] args)
  {
   randomWord();
   System.out.println (random);
  }

  static String[] randomWord()
  {
    String[] randomWords = {"dog", "cat", "monkey"}
    String random = randomWords[(int)(Math.random() * randomWords.length)];
    return random;
  }
}

Body:
Your code needs 2 little modifications, and I'll explain each change and why.

Here is a working version after applying changes:

public class Main {

     public static void main(String[] args) {
     System.out.println(randomWord()); //randomWord() returns the random string which is directly printed
     }

     static String randomWord() {
     String[] randomWords = {"dog", "cat", "monkey"};
     return randomWords[(int) (Math.random() * randomWords.length)];
     }
}

Tweaks made:

1- You are printing out variable 'random' which cannot be accessed in your main method since its a local variable to method 'randomWord()'

Code Modified to print the returned value of the 'randomWord()' method itself

 System.out.println(randomWord());

2- 'randomWord()' is defined to return a String array, But in actuality you are returning a string variable 'random'

Code Modified to return a String in the definition

 static String randomWord()


答:
Move this statement to the beginning of the constructor

constructor() {
   this.check=JSON.parse(localStorage.getItem('incre'));
   if(this.check==0)```

Title: getting data from localstorage in ngOnInit in Angular 4 but it reset its value on refresh


问:
Adding multiple action statements in drools fluent api
I am using fluent api to generate rules. I have a requirement to do multiple actions when a specific condition is satisfied. I can add multiple constraints in lhs. I need to know how I can add multiple rhs statements.

```<code>PackageDescrBuilder pkgDescrBuilder = DescrFactory.newPackage();
        pkgDescrBuilder.name("com.test.drools").getDescr();
        RuleDescrBuilder ruleBuilder = pkgDescrBuilder.newRule().name("droolsTest");
        CEDescrBuilder<RuleDescrBuilder, AndDescr> lhsBuilder = ruleBuilder.lhs();
        PatternDescrBuilder<CEDescrBuilder<RuleDescrBuilder, AndDescr>> patternBuilder = lhsBuilder.pattern("DroolClass").id("$droolClass", false);
        patternBuilder.constraint("nameObj.name matches \".*john.*\"").end();
        patternBuilder.constraint("nameObj.name == \"john snow\"").end();
        ruleBuilder.rhs("nameObj.gender = male").end();
</code>```

When I add one more rhs, It is over writing the existing one. I would need help to write multiple actions statements in rhs.

答:
```<code>StringBuilder sb = new StringBuilder();
sb.append( "int a = 1;" );
sb.append( "int b = 2;" );
ruleBuilder.rhs( sb.toString() ).end();
</code>```

Body:
I am using fluent api to generate rules. I have a requirement to do multiple actions when a specific condition is satisfied. I can add multiple constraints in lhs. I need to know how I can add multiple rhs statements.

PackageDescrBuilder pkgDescrBuilder = DescrFactory.newPackage();
        pkgDescrBuilder.name("com.test.drools").getDescr();
        RuleDescrBuilder ruleBuilder = pkgDescrBuilder.newRule().name("droolsTest");
        CEDescrBuilder<RuleDescrBuilder, AndDescr> lhsBuilder = ruleBuilder.lhs();
        PatternDescrBuilder<CEDescrBuilder<RuleDescrBuilder, AndDescr>> patternBuilder = lhsBuilder.pattern("DroolClass").id("$droolClass", false);
        patternBuilder.constraint("nameObj.name matches \".*john.*\"").end();
        patternBuilder.constraint("nameObj.name == \"john snow\"").end();
        ruleBuilder.rhs("nameObj.gender = male").end();

When I add one more rhs, It is over writing the existing one. I would need help to write multiple actions statements in rhs.


问:
Ionic 2 Geofence plugin not working in iOS
Ionic 2 Geofence plugin not working in iOS, though device log showing fence is registered and start tracking but transition not triggering on device,

pls help

答:
This is a known issue of the cordova-plugin-geofence

Apple won't let you deploy an app that is constantly looking for location, that would be a drain on resources.

The issue is when the app is minimized, IOS in an attempt to reduce load kills the Webview, once the app is opened again it takes a moment with the correct plugin to recover but by that time, the code fails to execute the transition.

a possible solution is to add parameters in the URL as a query string so that once the app does recover it can just grab the parameters and execute the trigger event.

This should resolve the issue. without to much of a major change even just an add-on function.

FYR


问:
debug app build failure after enabling proguard
```<code>Error:Execution failed for task
':app:transformClassesWithAndroidGradleClassShrinkerForDebug'.
Warnings found during shrinking, please use -dontwarn or -ignorewarnings to suppress them.
</code>```

How do i fix this?

PS- also I want to use progaurd in my application.

```<code>apply plugin: 'com.android.application'

android {
    compileSdkVersion 26
    buildToolsVersion '26.0.2'

    dexOptions{
        javaMaxHeapSize="2g"
    }

    defaultConfig {
        applicationId "com.example.projetinnovation.newadvocatediary"
        minSdkVersion 15
        targetSdkVersion 26
        versionCode 1
        versionName "1.0"
        multiDexEnabled=true

    }
    buildTypes {
        debug {
            minifyEnabled true
            useProguard false
            proguardFiles getDefaultProguardFile('proguard-andr    oid.txt'),
                    'proguard-rules.pro'
        }
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.    txt'), 'proguard-rules.pro'
        }
    }
}

repositories {
    maven {
        url "https://jitpack.io"
    }
    google()
}
dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile project(path: ':agendacalendarview')
    compile 'pl.droidsonroids.gif:android-gif-drawable:1.2.2'
    compile 'com.android.support:appcompat-v7:26.+'
    compile 'com.android.support:design:26.+'
    compile 'com.loopj.android:android-async-http:1.4.9'
    compile 'com.squareup.picasso:picasso:2.5.2'
    compile 'com.mcxiaoke.volley:library:1.0.19'
    compile 'com.google.code.gson:gson:2.8.+'
    compile 'com.github.clans:fab:1.6.4'
    compile 'com.github.dmytrodanylyk.android-process-button:library:1.0.4'
    compile 'com.google.firebase:firebase-messaging:10.0.1'
    testCompile 'junit:junit:4.12'
    compile 'com.github.ybq:Android-SpinKit:1.1.0'
    compile 'com.android.support:cardview-v7:26.+'
    compile 'com.github.d-max:spots-dialog:0.7@aar'
    compile 'com.github.ganfra:material-spinner:2.0.0'

    compile 'com.android.support:multidex:1.+'
}

apply plugin: 'com.google.gms.google-services'
</code>```

答: You need to add -dontwarn or -ignorewarnings to all third-party libraryes in proguard-rules.pro You can find description on docs/wiki pages of them</p>

Body:
Error:Execution failed for task
':app:transformClassesWithAndroidGradleClassShrinkerForDebug'.
Warnings found during shrinking, please use -dontwarn or -ignorewarnings to suppress them.

How do i fix this?

PS- also I want to use progaurd in my application.

apply plugin: 'com.android.application'

android {
    compileSdkVersion 26
    buildToolsVersion '26.0.2'

    dexOptions{
        javaMaxHeapSize="2g"
    }

    defaultConfig {
        applicationId "com.example.projetinnovation.newadvocatediary"
        minSdkVersion 15
        targetSdkVersion 26
        versionCode 1
        versionName "1.0"
        multiDexEnabled=true

    }
    buildTypes {
        debug {
            minifyEnabled true
            useProguard false
            proguardFiles getDefaultProguardFile('proguard-andr    oid.txt'),
                    'proguard-rules.pro'
        }
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.    txt'), 'proguard-rules.pro'
        }
    }
}

repositories {
    maven {
        url "https://jitpack.io"
    }
    google()
}
dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile project(path: ':agendacalendarview')
    compile 'pl.droidsonroids.gif:android-gif-drawable:1.2.2'
    compile 'com.android.support:appcompat-v7:26.+'
    compile 'com.android.support:design:26.+'
    compile 'com.loopj.android:android-async-http:1.4.9'
    compile 'com.squareup.picasso:picasso:2.5.2'
    compile 'com.mcxiaoke.volley:library:1.0.19'
    compile 'com.google.code.gson:gson:2.8.+'
    compile 'com.github.clans:fab:1.6.4'
    compile 'com.github.dmytrodanylyk.android-process-button:library:1.0.4'
    compile 'com.google.firebase:firebase-messaging:10.0.1'
    testCompile 'junit:junit:4.12'
    compile 'com.github.ybq:Android-SpinKit:1.1.0'
    compile 'com.android.support:cardview-v7:26.+'
    compile 'com.github.d-max:spots-dialog:0.7@aar'
    compile 'com.github.ganfra:material-spinner:2.0.0'

    compile 'com.android.support:multidex:1.+'
}

apply plugin: 'com.google.gms.google-services'


问:
Oracle SQL EXPLAIN PLAN - full table access
I have a query that joined up with 5 tables, it executed with elapse time about 0.2 seconds to retrieve 36 records from my DB. Attached below is the analysis of explain plan, as you can see full table access still occur even those tables already came with indexes.

Anyway if necessary to fine tune the query as below?

```<code>SELECT

  CASE WHEN DS.NAME = 'InteractiveCustomer' THEN 'NA' ELSE CUS.SOURCE_SYSTEM END AS SOURCE_SYSTEM,
  OU.ORGUNIT_CODE AS ORGANIZATION_UNITS,
  SUM(
    CASE WHEN WS.NAME = 'Pending Autoclosure' THEN 1 ELSE 0 END
  ) AS PENDING_AUTOCLOSURE,
  SUM(
    CASE WHEN WS.NAME = 'New' THEN 1 ELSE 0 END
  ) AS NEW,
  SUM(
    CASE WHEN WS.NAME = 'Under Investigation' THEN 1 ELSE 0 END
  ) AS UNDER_INVESTIGATION,
  SUM(
    CASE WHEN WS.NAME = 'Escalated' THEN 1 ELSE 0 END
  ) AS ESCALATED,
  SUM(
    CASE WHEN WS.NAME = 'Recommend True Positive' THEN 1 ELSE 0 END
  ) AS RECOMMEND_TRUE_POSITIVE,
  SUM(
    CASE WHEN WS.NAME = 'Reopen Under Investigation' THEN 1 ELSE 0 END
  ) AS REOPEN_UNDER_INVESTIGATION
FROM
  WORKFLOW_STATUSES WS
  JOIN WORKFLOW_WORKITEM WW ON WS.ID = WW.STATUS_ID
  JOIN WLM_ALERT_HEADER WAH ON WW.ENTITY_KEY = WAH.ALERT_KEY
  INNER JOIN ORGANIZATION_UNITS OU ON OU.ID = WAH.CUSTOMER_ORGUNIT_ID
  LEFT JOIN CUSTOMERS CUS ON CUS.CUSTOMER_ID = WAH.CUSTOMER_ID
  INNER JOIN DATA_SOURCE DS ON WAH.AT_DATASOURCE_ID = DS.ID
WHERE
  WW.ENTITY_NAME = 'WLM Alert'
GROUP BY
  OU.ORGUNIT_CODE,
  CUS.SOURCE_SYSTEM,
  DS.NAME;
</code>```

答:
Full table accesses may still occur on a table with an index, even if a query uses an indexed column simply because the query optimizer may deem if faster to blat the entire table data into memory than bother with the indirection of going to the index, looking for the relevant rows, then picking them off the disk

Full table scanning isn't necessarily a bad thing, though it can be a good place to start if a query is unacceptably long running and the suspicion is due to an FTS on a very large table. On small tables a full scan is pretty insignificant

You asked if it was necessary to fine tune the query - my personal opinion on this is "no, not at this stage" - as per my comment, boost the relevant data tables by a million rows, and run it again to get an idea of how it will scale. It's possible you'll get an entirely different plan. Even if it ends up running for 5 seconds, balance that up against how many times this data will be asked for in prod - if it's every 10 seconds then sure, do something about it. If it's once a month when accounts team sends out the invoices, don't bother with it even if it takes a minute

"Premature optimization is the root of all evil"

Body:
I have a query that joined up with 5 tables, it executed with elapse time about 0.2 seconds to retrieve 36 records from my DB. Attached below is the analysis of explain plan, as you can see full table access still occur even those tables already came with indexes.

Anyway if necessary to fine tune the query as below?

SELECT

  CASE WHEN DS.NAME = 'InteractiveCustomer' THEN 'NA' ELSE CUS.SOURCE_SYSTEM END AS SOURCE_SYSTEM,
  OU.ORGUNIT_CODE AS ORGANIZATION_UNITS,
  SUM(
    CASE WHEN WS.NAME = 'Pending Autoclosure' THEN 1 ELSE 0 END
  ) AS PENDING_AUTOCLOSURE,
  SUM(
    CASE WHEN WS.NAME = 'New' THEN 1 ELSE 0 END
  ) AS NEW,
  SUM(
    CASE WHEN WS.NAME = 'Under Investigation' THEN 1 ELSE 0 END
  ) AS UNDER_INVESTIGATION,
  SUM(
    CASE WHEN WS.NAME = 'Escalated' THEN 1 ELSE 0 END
  ) AS ESCALATED,
  SUM(
    CASE WHEN WS.NAME = 'Recommend True Positive' THEN 1 ELSE 0 END
  ) AS RECOMMEND_TRUE_POSITIVE,
  SUM(
    CASE WHEN WS.NAME = 'Reopen Under Investigation' THEN 1 ELSE 0 END
  ) AS REOPEN_UNDER_INVESTIGATION
FROM
  WORKFLOW_STATUSES WS
  JOIN WORKFLOW_WORKITEM WW ON WS.ID = WW.STATUS_ID
  JOIN WLM_ALERT_HEADER WAH ON WW.ENTITY_KEY = WAH.ALERT_KEY
  INNER JOIN ORGANIZATION_UNITS OU ON OU.ID = WAH.CUSTOMER_ORGUNIT_ID
  LEFT JOIN CUSTOMERS CUS ON CUS.CUSTOMER_ID = WAH.CUSTOMER_ID
  INNER JOIN DATA_SOURCE DS ON WAH.AT_DATASOURCE_ID = DS.ID
WHERE
  WW.ENTITY_NAME = 'WLM Alert'
GROUP BY
  OU.ORGUNIT_CODE,
  CUS.SOURCE_SYSTEM,
  DS.NAME;


问:
how i can show object in gridview or in any usful contro
```<code>public class EventDetail
{
    private Int64 logID;

    public Int64 LogID
    {
        get { return logID; }
        set { logID = value; }
    }
    private Object logedObject;

    public Object LogedObject
    {
        get { return logedObject; }
        set { logedObject = value; }
    }

}
</code>```

答: To bind with GridView (or similar controls such as Repeater, ListView), you typically need to know property names of object because that's what you will use to bind column to. So is this example, you may bind to LogID and LogedObject properties. For later, ToString will be invoked on object to show the string representation.</p>


问:
Search bar + select tag rails
I have a search bar + a dropdown list to search for restaurants or meals and be able to filter by category (French food, Indian, foot, etc.)

index.html.erb

```<code><%= form_tag meals_path, method: 'get', id: 'products_search' do %>
  <p>
    <%= text_field_tag :search, params[:search] %>
    <%= select_tag :search_category, options_for_select(@categories, @categories[0]) %>
    <%= submit_tag "Rechercher", name: nil %>
  </p>
<% end %>
</code>```

meals_controller.rb

```<code>@meals_search = @meals.search(params[:search], params[:search_category])
</code>```

model/meal.rb

```<code>def self.search(search, search_category)
  if search
    if search && search_category == "All"
    where('name LIKE ?', "%#{search}%")
    elsif search == "" && search_category != "All"
      where('category = ?',  "%#{search_category}%")
    else
      where('name LIKE ? AND category = ?', "%#{search}%", "%#{search_category}%")
    end
  else
    all
  end
end
</code>```

the search bar works perfectly but the category filter (search_category) does not. I actually get an empty list although you can only filter with category that has at least one restaurant or meal (so the list can't be empty).

Any idea ?

答: just use ransack, for advanced searching and sorting</p>

Title: Search bar + select tag rails

Body:
I have a search bar + a dropdown list to search for restaurants or meals and be able to filter by category (French food, Indian, foot, etc.)

index.html.erb

<%= form_tag meals_path, method: 'get', id: 'products_search' do %>

    <%= text_field_tag :search, params[:search] %>
    <%= select_tag :search_category, options_for_select(@categories, @categories[0]) %>
    <%= submit_tag "Rechercher", name: nil %>

<% end %>

meals_controller.rb

@meals_search = @meals.search(params[:search], params[:search_category])

model/meal.rb

def self.search(search, search_category)
  if search
    if search && search_category == "All"
    where('name LIKE ?', "%#{search}%")
    elsif search == "" && search_category != "All"
      where('category = ?',  "%#{search_category}%")
    else
      where('name LIKE ? AND category = ?', "%#{search}%", "%#{search_category}%")
    end
  else
    all
  end
end

the search bar works perfectly but the category filter (search_category) does not. I actually get an empty list although you can only filter with category that has at least one restaurant or meal (so the list can't be empty).

Any idea ?


问:
Getting error "Error: Could not find or load main class" when there are multiple jar files in java -cp command
I have 3 jar files A.jar, B.jar, C.jar.  C.jar contains a class com.rb.test.PResolver.java having main method.  C.jar has dependency on A.jar and B.jar.  When I try to run PResolver class using following command, the main method gets invoked, but it fails, since the dependent jar files are not in classpath:

```<code>java -cp C.jar com.rb.test.PResolver
</code>```

When I try to add the dependent jar filed in -CP option, then the class is not found:

```<code>java -cp A.jar:B.jar:C.jar com.rb.test.PResolver
</code>```

Above command gives following error:

```<code>Error: Could not find or load main class com.rb.test.PResolver
</code>```

So the moment I put the dependent jars in the -cp option of java command, the class is not found.

答:
Place all your jar files in a folder lib and then try:

for unix: java -cp  C.jar:lib/*:. com.rb.test.PResolver

for Windows: java -cp  C.jar;lib\*;. com.rb.test.PResolver

Refer to this question for details to see how you can execute jar with multiple classpath libraries from command line

Body:
I have 3 jar files A.jar, B.jar, C.jar.  C.jar contains a class com.rb.test.PResolver.java having main method.  C.jar has dependency on A.jar and B.jar.  When I try to run PResolver class using following command, the main method gets invoked, but it fails, since the dependent jar files are not in classpath:

java -cp C.jar com.rb.test.PResolver

When I try to add the dependent jar filed in -CP option, then the class is not found:

java -cp A.jar:B.jar:C.jar com.rb.test.PResolver

Above command gives following error:

Error: Could not find or load main class com.rb.test.PResolver

So the moment I put the dependent jars in the -cp option of java command, the class is not found.


答:
Remove everything from constructor.

public check: number = 0;

```<code>ngOnInit() {
this.check = JSON.parse(localStorage.getItem('incre')) || 0;

if (this.check === 0) {
 // do the rest
}

}
</code>```

Body:
Remove everything from constructor.

public check: number = 0;

ngOnInit() {
this.check = JSON.parse(localStorage.getItem('incre')) || 0;

if (this.check === 0) {
 // do the rest
}

}


问:
FATAL EXCEPTION: main KotlinNullPointerException
This is my first time building an android application. However when i run the app on my Virtual Device, it stopped working and keeps crashing. The error says something about null pointer exception. This is my first time using Kotlin and I coded in Java and changed to Kotlin.

```<code> override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_add_sales)

    val date: EditText? = null
    val changeDate: CheckBox? = null
    val yes: RadioButton? = null
    val no: RadioButton? = null

    date!!.setText("15-11-2017")
    date.isEnabled = false

    val button2 = findViewById<View>(R.id.btnSubmit) as Button
    button2.setOnClickListener {
        var name = findViewById<View>(R.id.name) as EditText
        var cost = findViewById<View>(R.id.cost) as EditText
        val itemcost = Integer.parseInt(cost!!.text.toString())
        var price = findViewById<View>(R.id.price) as EditText
        val itemprice = Integer.parseInt(price!!.text.toString())
        var qty = findViewById<View>(R.id.quantity) as EditText
        var chgDate = false
        var discount = false
        val toast = Toast(applicationContext)
        if (itemprice < itemcost) {
            price!!.error = "Selling price cannot be lower than item price!"
        } else {
            if (changeDate!!.isChecked) {
                chgDate = true
                date.isEnabled = true
            }
            if (yes!!.isChecked) {
                discount = true
            }
        }
        Toast.makeText(this@AddSales, "Item Name: " + name!!.text + "\n" + "Cost: " + cost!!.text + "\n" + "Item Price: " + price!!.text + "\n" + "Quantity: " + qty!!.text + "Date: " + date + "Staff Discount: " + discount, Toast.LENGTH_SHORT).show()
    }

}
</code>```

and the error is:

11-17 06:23:34.603 3540-3540/com.example.ruiru.salestracker
  E/AndroidRuntime: FATAL EXCEPTION: main
                                                                                Process: com.example.ruiru.salestracker, PID: 3540
                                                                                java.lang.RuntimeException: Unable to start activity
  ComponentInfo{com.example.ruiru.salestracker/com.example.ruiru.salestracker.AddSales}:
  kotlin.KotlinNullPointerException
                                                                                at
  android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2817)
                                                                                at
  android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2892)
                                                                                at android.app.ActivityThread.-wrap11(Unknown Source:0)
                                                                                at
  android.app.ActivityThread$H.handleMessage(ActivityThread.java:1593)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:105)
                                                                                at android.os.Looper.loop(Looper.java:164)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:6541)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at
  com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
                                                                                Caused by: kotlin.KotlinNullPointerException
                                                                                at com.example.ruiru.salestracker.AddSales.onCreate(AddSales.kt:25)
                                                                                at android.app.Activity.performCreate(Activity.java:6975)
                                                                                at
  android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1213)
                                                                                at
  android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2770)
                                                                                at
  android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2892)
                                                                                at android.app.ActivityThread.-wrap11(Unknown Source:0)
                                                                                at
  android.app.ActivityThread$H.handleMessage(ActivityThread.java:1593)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:105)
                                                                                at android.os.Looper.loop(Looper.java:164)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:6541)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at
  com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)

答:
It seems like you forgot to initialize date editText. Why not to try Kotlin Android Extension plugin. By using this plugin you don't need to initialize the views instead you can directly use them using their id. For your case:
Just add import

```<code>import kotlinx.android.synthetic.main.activity_add_sales.*
</code>```

Then you can now remove your:

```<code>val date: EditText? = null
val changeDate: CheckBox? = null
val yes: RadioButton? = null
val no: RadioButton? = null
</code>```

and you can access them by their ids. like

```<code>date.setText("15-11-2017")
</code>```

Body:
This is my first time building an android application. However when i run the app on my Virtual Device, it stopped working and keeps crashing. The error says something about null pointer exception. This is my first time using Kotlin and I coded in Java and changed to Kotlin.

 override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_add_sales)

    val date: EditText? = null
    val changeDate: CheckBox? = null
    val yes: RadioButton? = null
    val no: RadioButton? = null

    date!!.setText("15-11-2017")
    date.isEnabled = false

    val button2 = findViewById<View>(R.id.btnSubmit) as Button
    button2.setOnClickListener {
        var name = findViewById<View>(R.id.name) as EditText
        var cost = findViewById<View>(R.id.cost) as EditText
        val itemcost = Integer.parseInt(cost!!.text.toString())
        var price = findViewById<View>(R.id.price) as EditText
        val itemprice = Integer.parseInt(price!!.text.toString())
        var qty = findViewById<View>(R.id.quantity) as EditText
        var chgDate = false
        var discount = false
        val toast = Toast(applicationContext)
        if (itemprice < itemcost) {
            price!!.error = "Selling price cannot be lower than item price!"
        } else {
            if (changeDate!!.isChecked) {
                chgDate = true
                date.isEnabled = true
            }
            if (yes!!.isChecked) {
                discount = true
            }
        }
        Toast.makeText(this@AddSales, "Item Name: " + name!!.text + "\n" + "Cost: " + cost!!.text + "\n" + "Item Price: " + price!!.text + "\n" + "Quantity: " + qty!!.text + "Date: " + date + "Staff Discount: " + discount, Toast.LENGTH_SHORT).show()
    }

}

and the error is:

11-17 06:23:34.603 3540-3540/com.example.ruiru.salestracker
  E/AndroidRuntime: FATAL EXCEPTION: main
                                                                                Process: com.example.ruiru.salestracker, PID: 3540
                                                                                java.lang.RuntimeException: Unable to start activity
  ComponentInfo{com.example.ruiru.salestracker/com.example.ruiru.salestracker.AddSales}:
  kotlin.KotlinNullPointerException
                                                                                at
  android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2817)
                                                                                at
  android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2892)
                                                                                at android.app.ActivityThread.-wrap11(Unknown Source:0)
                                                                                at
  android.app.ActivityThread$H.handleMessage(ActivityThread.java:1593)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:105)
                                                                                at android.os.Looper.loop(Looper.java:164)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:6541)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at
  com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
                                                                                Caused by: kotlin.KotlinNullPointerException
                                                                                at com.example.ruiru.salestracker.AddSales.onCreate(AddSales.kt:25)
                                                                                at android.app.Activity.performCreate(Activity.java:6975)
                                                                                at
  android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1213)
                                                                                at
  android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2770)
                                                                                at
  android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2892)
                                                                                at android.app.ActivityThread.-wrap11(Unknown Source:0)
                                                                                at
  android.app.ActivityThread$H.handleMessage(ActivityThread.java:1593)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:105)
                                                                                at android.os.Looper.loop(Looper.java:164)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:6541)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at
  com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)

Body:
It seems like you forgot to initialize date editText. Why not to try Kotlin Android Extension plugin. By using this plugin you don't need to initialize the views instead you can directly use them using their id. For your case:
Just add import

import kotlinx.android.synthetic.main.activity_add_sales.*

Then you can now remove your:

val date: EditText? = null
val changeDate: CheckBox? = null
val yes: RadioButton? = null
val no: RadioButton? = null

and you can access them by their ids. like

date.setText("15-11-2017")


问:
Inline assembler question
Using inline assembler I could specify an add operation with
two inputs and one result as follows:

```<code>int a = 5;
int b = 5;
int res;

asm volatile (
" add %1, %2, %0          \n\t"
: "=r" (res)
: "r" (a), "r" (b)
: "%g0"
);
</code>```

On a 32-bit architecture, this produces me an instruction word that could look like
this: 0x91050101

Now I am wondering, rather then explicitly specifying the assembler code for the addition,
I would like to specify the instruction word right away and put it into the executable. That should look something like this here

```<code>asm volatile (%x91, %x05, %x01, %x01);
</code>```

Anyone an idea where I can find more information how this could be done and how the syntax has to look like to do that (the above is only a wild guess).

Many thanks!

答:
Microsoft supports the _emit pseudo instruction

http://msdn.microsoft.com/en-us/library/1b80826t.aspx

I'm not sure what g++ supports

Title: Inline assembler question

Body:
Using inline assembler I could specify an add operation with
two inputs and one result as follows:

int a = 5;
int b = 5;
int res;

asm volatile (
" add %1, %2, %0          \n\t"
: "=r" (res)
: "r" (a), "r" (b)
: "%g0"
);

On a 32-bit architecture, this produces me an instruction word that could look like
this: 0x91050101

Now I am wondering, rather then explicitly specifying the assembler code for the addition,
I would like to specify the instruction word right away and put it into the executable. That should look something like this here

asm volatile (%x91, %x05, %x01, %x01);

Anyone an idea where I can find more information how this could be done and how the syntax has to look like to do that (the above is only a wild guess).

Many thanks!