问:
How to loop through a file based on conditions
I have a file with following contents. File name is "myXLog.txt":

```<code>IAAS Session factory creation started

X

Y

z

Communications link failure
</code>```

What I want is to read the file and if a string "IAAS Session factory creation started" is found then continue reading and if another string "Communications link failure" is found then return a message. My code only gets the first line and does not go further. Please help I checked a lot of help on internet but could not manage as I am new to shell scripting (very new).`

```<code>#!/bin/bash
filename="myXLog.txt"
while read line
do

if [[ $line == "IAAS Session factory creation started" ]] ; then
       a="YES"
       echo $a
       if a="YES"; then #HERE I WANT TO CONTINUE READING BUT NOT SURE HOW
       if [[ $line == "Communications link failure" ]] ; then
            echo "ERROR"

       else echo "ALL IS WELL"      $line
       fi
       fi
else echo "BYE"
    #fi
fi
done < $filename
</code>```

This only prints

YES

ALL IS WELL IAAS Session factory creation started

BYE

BYE

BYE

BYE

答:
I think if you stop nesting your conditions, this will work. You basically want to test "if I've seen the 'start' line and the current line is the 'end' line, print something and break out of the loop". At present, the code is only checking for the error message while it's on the same line as when it finds the "start" message, which will never be true, since the line can either be the start or the end message, but not both at the same time. Instead, you want to track "have I seen the start message" in a variable outside of the loop (well, it could be inside, since Bash defaults to global variables, but putting it outside makes things much easier to understand), set that variable when you see the "start" line, and then on every subsequent line, check for the error and the "found start" variable.

I think the following code would likely do the trick. There are many shorter ways to do this, but this one is the easiest (for me) to understand:

```<code>#!/bin/bash
filename="myXLog.txt"
found=""
while read line; do
    if [[ $line == "IAAS Session factory creation started" ]]; then
        echo "START: $line"
        found="start"
    # This tests: "Have we found the start line, and is the line the error message?"
    elif [[ $found == "start" && $line == "Communications link failure" ]]; then
        found="error"
        echo "ERROR: $line"
        break
    elif [[ $found == "start" ]]; then
        echo "ALL IS WELL: $line"
    fi
    # Implicit else: if we have not yet seen the 'started' line, do nothing.
done < $filename
</code>```

After that loop ran, you could check the value of the $found variable to see if it got to the end of the file without seeing an error, e.g.:

```<code># Check if $found is empty.
if [[ -z $found ]]; then
    echo "Never found a 'started' line!"
elif [[ $found == "start" ]]; then
    echo "Found a 'started' line and no errors; finished reading the file!"
else # $found is "error"
    echo "Stopped reading after an error!"
fi
</code>```

Body:
I have a file with following contents. File name is "myXLog.txt":

IAAS Session factory creation started

X

Y

z

Communications link failure

What I want is to read the file and if a string "IAAS Session factory creation started" is found then continue reading and if another string "Communications link failure" is found then return a message. My code only gets the first line and does not go further. Please help I checked a lot of help on internet but could not manage as I am new to shell scripting (very new).`

#!/bin/bash
filename="myXLog.txt"
while read line
do

if [[ $line == "IAAS Session factory creation started" ]] ; then
       a="YES"
       echo $a
       if a="YES"; then #HERE I WANT TO CONTINUE READING BUT NOT SURE HOW
       if [[ $line == "Communications link failure" ]] ; then
            echo "ERROR"

       else echo "ALL IS WELL"      $line
       fi
       fi
else echo "BYE"
    #fi
fi
done < $filename

This only prints

YES

ALL IS WELL IAAS Session factory creation started

BYE

BYE

BYE

BYE

Body:
I think if you stop nesting your conditions, this will work. You basically want to test "if I've seen the 'start' line and the current line is the 'end' line, print something and break out of the loop". At present, the code is only checking for the error message while it's on the same line as when it finds the "start" message, which will never be true, since the line can either be the start or the end message, but not both at the same time. Instead, you want to track "have I seen the start message" in a variable outside of the loop (well, it could be inside, since Bash defaults to global variables, but putting it outside makes things much easier to understand), set that variable when you see the "start" line, and then on every subsequent line, check for the error and the "found start" variable.

I think the following code would likely do the trick. There are many shorter ways to do this, but this one is the easiest (for me) to understand:

#!/bin/bash
filename="myXLog.txt"
found=""
while read line; do
    if [[ $line == "IAAS Session factory creation started" ]]; then
        echo "START: $line"
        found="start"
    # This tests: "Have we found the start line, and is the line the error message?"
    elif [[ $found == "start" && $line == "Communications link failure" ]]; then
        found="error"
        echo "ERROR: $line"
        break
    elif [[ $found == "start" ]]; then
        echo "ALL IS WELL: $line"
    fi
    # Implicit else: if we have not yet seen the 'started' line, do nothing.
done < $filename

After that loop ran, you could check the value of the $found variable to see if it got to the end of the file without seeing an error, e.g.:

# Check if $found is empty.
if [[ -z $found ]]; then
    echo "Never found a 'started' line!"
elif [[ $found == "start" ]]; then
    echo "Found a 'started' line and no errors; finished reading the file!"
else # $found is "error"
    echo "Stopped reading after an error!"
fi


来源: stackexchange

问:
Counting items in Jitterbit JSON transformation
I am trying to create a Jitterbit condition which depending on the json passed into it will call one of two operations if true or false.

The previous transformation filters the JSON using a transformation condition so if a certain piece of data exists or not in the JSON it will return either one or no items in the JSON.

How do I create a condition after this which will branch depending on whether one or no items are passed to this? I was expecting something like :

json$item.Count 'GREATER THAN' 0

to work?

Thanks
Martin

答: Solved using scripting in Jitterbit (Javascript rather than the Jitterbit scripting)</p>

ContentLicense: CC BY-SA 3.0


问:
How To Write Series Of Number In Excel
I want to write numbers in excel starting from 000001 till 999999

I have done like this =TEXT(A2,"000001") but i am not been able to generate series even though not able to separate this in different attributes

Further I want to distribute each number in each different cell for example like this

```<code>A           B         C        D         E         F       G

000001      0         0        0         0         0       1

000002      0         0        0         0         0       2

till

999999      9          9       9         9          9       9
</code>```

答:
Here is a better way:

In cell A1, type 1.

Select A1 and from Home tab, choose Fill > Series (top-right).

Choose Columns; Linear; set Step Value to 1 and Stop Value to 999999 or whatever you want. Click OK.

Use AutoFill feature to fill up to the number you want.

Right-click column A header and choose Format Cells.

Choose Custom formatting and type 000000 in the custom format type textbox.

Click OK. Your cells will now show 000001, 000002, ... and so on.

In cell B1, type the following formula:

```<code>=INT(MOD($A1/(POWER(10, 7- COLUMN())), 10))
</code>```

Copy B1 to columns C1 through G1.

Copy range B1:G1 to all subsequent rows B2:G999999 or whatever.

Notes

One advantage of this approach is that column A is numeric, not text, so you can enter any 6-digit (or less) integer in it directly from keyboard and the cells will update themselves correctly.

Column A will adjust number of leading zeros automatically for 6-digits or smaller numbers.

The formula simply divides the number in column A by 10, 100, 1000 and so on and then takes remainder by 10, to get the corresponding digit at that decimal place.

You can easily modify this formula to work with larger or smaller numbers. You simply need to replace 7 by (maximum number of digits in your number + 1).

Title: How To Write Series Of Number In Excel

Body:
I want to write numbers in excel starting from 000001 till 999999

I have done like this =TEXT(A2,"000001") but i am not been able to generate series even though not able to separate this in different attributes

Further I want to distribute each number in each different cell for example like this

A           B         C        D         E         F       G

000001      0         0        0         0         0       1

000002      0         0        0         0         0       2

till

999999      9          9       9         9          9       9

Body:
Here is a better way:

In cell A1, type 1.

Select A1 and from Home tab, choose Fill > Series (top-right).

Choose Columns; Linear; set Step Value to 1 and Stop Value to 999999 or whatever you want. Click OK.

Use AutoFill feature to fill up to the number you want.

Right-click column A header and choose Format Cells.

Choose Custom formatting and type 000000 in the custom format type textbox.

Click OK. Your cells will now show 000001, 000002, ... and so on.

In cell B1, type the following formula:

=INT(MOD($A1/(POWER(10, 7- COLUMN())), 10))

Copy B1 to columns C1 through G1.

Copy range B1:G1 to all subsequent rows B2:G999999 or whatever.

Notes

One advantage of this approach is that column A is numeric, not text, so you can enter any 6-digit (or less) integer in it directly from keyboard and the cells will update themselves correctly.

Column A will adjust number of leading zeros automatically for 6-digits or smaller numbers.

The formula simply divides the number in column A by 10, 100, 1000 and so on and then takes remainder by 10, to get the corresponding digit at that decimal place.

You can easily modify this formula to work with larger or smaller numbers. You simply need to replace 7 by (maximum number of digits in your number + 1).


问:
Background zooms in incorrectly when following mouse movement
I've created a button, when you hover over it a div with a background image enlarges. The background should follow the cursor's movements. Meaning that the background image follows your cursor as you hover over the button.

When I hover over the bottom right part of the button, the image will zoom in to the top left before moving to the cursor's location. Check out the example below to see what I mean. I'd like to make it zoom directly to the cursor's location, any ideas?

var imgZoomIn = 1.2; //% of how much the image will enlarge

function buttonImgResize(x, e){
    //Location of the cursor (as percentage of the container's size)
    var imgContPosition = x.getBoundingClientRect();
    var mousePosX = (e.clientX - imgContPosition.left) / x.offsetWidth;
    var mousePosY = (e.clientY - imgContPosition.top) / x.offsetHeight;

    //Finding how far to move the image from top and left
    var leftImgOverlap = x.offsetWidth * (imgZoomIn - 1) * mousePosX;
    var topImgOverlap = x.offsetHeight * (imgZoomIn - 1) * mousePosY;

    //implementing changes
    x.firstElementChild.style.left = 0 - leftImgOverlap + "px";
    x.firstElementChild.style.top = 0 - topImgOverlap + "px";
}

//Reseting values
function buttonImgDownsize(x){
    x.firstElementChild.style.left = "0";
    x.firstElementChild.style.top = "0";
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>/*Container*/
.showCaseBtn{
    overflow: hidden;
    position: relative;
    width: 500px; height: 300px;
}
/*div with background image*/
.showcaseBtn_Back{
    position: absolute; top: 0; left: 0;
    width: 100%; height: 100%;
    background: black no-repeat center center / cover;
    transition: 0.4s;
}
.showCaseBtn:hover .showcaseBtn_Back{
    height: 120%; width: 120%;
}</code>```

```

答:
The problem is caused by the css transition. If you remove it, the zooming works but no fancy scaling will happen.

var imgZoomIn = 1.2;

function buttonImgResize(x, e){
    var imgContPosition = x.getBoundingClientRect();
    var mousePosX = (e.clientX - imgContPosition.left) / imgContPosition.width;
    var mousePosY = (e.clientY - imgContPosition.top) / imgContPosition.height;

    var leftImgOverlap = imgContPosition.width * (imgZoomIn - 1) * mousePosX;
    var topImgOverlap = imgContPosition.height * (imgZoomIn - 1) * mousePosY;

    x.firstElementChild.style.left = - leftImgOverlap + "px";
    x.firstElementChild.style.top =  - topImgOverlap + "px";
}

function buttonImgDownsize(x){
    x.firstElementChild.style.left = "0";
    x.firstElementChild.style.top = "0";
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.showCaseBtn{
    overflow: hidden;
    position: relative;
    width: 500px; height: 300px;
}
.showcaseBtn_Back{
    position: absolute; top: 0; left: 0;
    width: 100%; height: 100%;
    background: black no-repeat center center / cover;
}
.showCaseBtn:hover .showcaseBtn_Back{
    height: 120%; width: 120%;
}</code>```

```

Body:
I've created a button, when you hover over it a div with a background image enlarges. The background should follow the cursor's movements. Meaning that the background image follows your cursor as you hover over the button.

When I hover over the bottom right part of the button, the image will zoom in to the top left before moving to the cursor's location. Check out the example below to see what I mean. I'd like to make it zoom directly to the cursor's location, any ideas?

var imgZoomIn = 1.2; //% of how much the image will enlarge

function buttonImgResize(x, e){
    //Location of the cursor (as percentage of the container's size)
    var imgContPosition = x.getBoundingClientRect();
    var mousePosX = (e.clientX - imgContPosition.left) / x.offsetWidth;
    var mousePosY = (e.clientY - imgContPosition.top) / x.offsetHeight;

    //Finding how far to move the image from top and left
    var leftImgOverlap = x.offsetWidth * (imgZoomIn - 1) * mousePosX;
    var topImgOverlap = x.offsetHeight * (imgZoomIn - 1) * mousePosY;

    //implementing changes
    x.firstElementChild.style.left = 0 - leftImgOverlap + "px";
    x.firstElementChild.style.top = 0 - topImgOverlap + "px";
}

//Reseting values
function buttonImgDownsize(x){
    x.firstElementChild.style.left = "0";
    x.firstElementChild.style.top = "0";
}

/*Container*/
.showCaseBtn{
    overflow: hidden;
    position: relative;
    width: 500px; height: 300px;
}
/*div with background image*/
.showcaseBtn_Back{
    position: absolute; top: 0; left: 0;
    width: 100%; height: 100%;
    background: black no-repeat center center / cover;
    transition: 0.4s;
}
.showCaseBtn:hover .showcaseBtn_Back{
    height: 120%; width: 120%;
}

Body:
The problem is caused by the css transition. If you remove it, the zooming works but no fancy scaling will happen.

var imgZoomIn = 1.2;

function buttonImgResize(x, e){
    var imgContPosition = x.getBoundingClientRect();
    var mousePosX = (e.clientX - imgContPosition.left) / imgContPosition.width;
    var mousePosY = (e.clientY - imgContPosition.top) / imgContPosition.height;

    var leftImgOverlap = imgContPosition.width * (imgZoomIn - 1) * mousePosX;
    var topImgOverlap = imgContPosition.height * (imgZoomIn - 1) * mousePosY;

    x.firstElementChild.style.left = - leftImgOverlap + "px";
    x.firstElementChild.style.top =  - topImgOverlap + "px";
}

function buttonImgDownsize(x){
    x.firstElementChild.style.left = "0";
    x.firstElementChild.style.top = "0";
}

.showCaseBtn{
    overflow: hidden;
    position: relative;
    width: 500px; height: 300px;
}
.showcaseBtn_Back{
    position: absolute; top: 0; left: 0;
    width: 100%; height: 100%;
    background: black no-repeat center center / cover;
}
.showCaseBtn:hover .showcaseBtn_Back{
    height: 120%; width: 120%;
}

<div class="showCaseBtn" onmousemove="buttonImgResize(this, event)" onmouseout="buttonImgDownsize(this)">
  <div class="showcaseBtn_Back" style="background-image: url(https://media.contentapi.ea.com/content/dam/need-for-speed/common/2017/10/nfs-payback-jaguar-f-type-2x.jpg.adapt.1920w.jpg);"></div>
</div>


问:
Updating Oracle 12.1 to 12.2 Oracle Dependency Error occurs
We have recently been struggling to update our C# applications with the new Oracle DLLs. We create our software for multiple platforms. So our software solution is both a winform desktop application and a ASP.NET MVC webapplication.

Both applications run Oracle 12.1 stand-alone perfectly. We add all necessary Oracle DLLs with the redistribution of our software. So the desktop application has all the DLLs within the MSI and the publish of the website has all the DLLs in the ~\Bin. Making sure that when the website is hosted on IIS the web application runs. This way our customers do not need to install Oracle Client.

Now comes the problem, since updating to Oracle 12.2 it's not possible for us to run the web application any more. The desktop application still runs fine although since Oracle 12.2 we get a Firewall Exception message, if we want to allow our desktop application to connect to the internet.

We didn’t get that message in Oracle 12.1 or below:

We have published our webapplication with all the new Oracle dll’s (the same dll’s as desktop and the same way as for when the webapplication has Oracle 12.1) and since then we are not able anymore to connect to our Oracle databases. We get the error below:

```<code>Unable to load DLL 'OraOps12.dll': The specified module could not be found. (Exception from HRESULT: 0x8007007E)

System.TypeInitializationException: The type initializer for 'Oracle.DataAccess.Client.OracleConnection' threw an exception. ---> System.DllNotFoundException: Unable to load DLL 'OraOps12.dll': The specified module could not be found. (Exception from HRESULT: 0x8007007E)
   at Oracle.DataAccess.Client.OpsInit.CheckVersionCompatibility(String version)
   at Oracle.DataAccess.Client.OracleInit.Initialize()
   at Oracle.DataAccess.Client.OracleConnection..cctor()
   --- End of inner exception stack trace ---
</code>```

We have checked, but YES the DLL is there. We also put it in different locations to see if this would work but no.

These are the DLLs we are using:

The strange thing is that when we copy our desktop application to the server, the desktop application runs fine! The desktop application has the exact same DLLs as the web application!

The DLLs we are using for both desktop and web application are from the XCopy folders of Oracle:
http://download.oracle.com/otn/other/ole-oo4o/ODAC122010Xcopy_32bit.zip   x86
http://download.oracle.com/otn/other/ole-oo4o/ODAC122010Xcopy_x64.zip   x64

There are more people struggling with this issue, here is what we have found so far:

Oracle 12.2 needs minimum .NET Framework 4.5.2 our server has 4.6 and up

The rights of the DLLs are set correctly and may be used by IIS

We have for our x86 web application enabled 32-bit application in the Advanced Settings window

We have set the environment making sure the right DLLs are added to the environment

In Visual Studio we made sure that the references are: Copied if newer and Local copy is set to true

Our application are full x86 or x64 NOT anyCPU build.

We have checked our Regedit, Machine.config and GAC for any possible left-over of other Oracle versions.

Redownloaded the xcopy zip and copied the files again

Server has DISABLED firewall (development)

Oracle.DataAccess.Client Dependencies this is more or less our method to!

Our server-specs:

Windows Server 2012R2 DataCenter (clean)

X64-based pc

using IIS 8.5

答:
This way our customers do not need to install Oracle Client.

I think this is a bad idea, I do not recommend doing it like this.

Either

Ask your customer to install Oracle Client (include ODP.NET provider) by themselves using standard Oracle downloads

or

Use the ODP.NET Managed Driver, then you don't need any further installation. You just have to provide the Oracle.ManagedDataAccess.dll with your application.

It it hard to determine your problem without further information, there could be several reasons:

Missing DLL -> For this I cannot help you, make a normal Oracle installation

Wrong PATH settings. -> Ensure %ORACLE_HOME% and %ORACLE_HOME%\bin are in

How did you check your GAC? Did you usegacutil.exe version 4.0? Older version 3.5 does not show 4.0 (and above) assemblies.

You may have a conflict with 32-bit vs. 64-bit Oracle installation. In case you need both of them, follow this installation instruction: BadImageFormatException. This will occur when running in 64 bit mode with the 32 bit Oracle client components installed

Version of ODP.NET does not match with version of installed Oracle Client. The major release (e.g. 11.1, 11.2, 12.1, 12.2) has to be the same for both.

You can also use Process Monitor tool, in order to see which DLL and/or registry entry is missing.

ContentLicense: CC BY-SA 4.0

Body:
We have recently been struggling to update our C# applications with the new Oracle DLLs. We create our software for multiple platforms. So our software solution is both a winform desktop application and a ASP.NET MVC webapplication.

Both applications run Oracle 12.1 stand-alone perfectly. We add all necessary Oracle DLLs with the redistribution of our software. So the desktop application has all the DLLs within the MSI and the publish of the website has all the DLLs in the ~\Bin. Making sure that when the website is hosted on IIS the web application runs. This way our customers do not need to install Oracle Client.

Now comes the problem, since updating to Oracle 12.2 it's not possible for us to run the web application any more. The desktop application still runs fine although since Oracle 12.2 we get a Firewall Exception message, if we want to allow our desktop application to connect to the internet.

We didn’t get that message in Oracle 12.1 or below:

We have published our webapplication with all the new Oracle dll’s (the same dll’s as desktop and the same way as for when the webapplication has Oracle 12.1) and since then we are not able anymore to connect to our Oracle databases. We get the error below:

Unable to load DLL 'OraOps12.dll': The specified module could not be found. (Exception from HRESULT: 0x8007007E)

System.TypeInitializationException: The type initializer for 'Oracle.DataAccess.Client.OracleConnection' threw an exception. ---> System.DllNotFoundException: Unable to load DLL 'OraOps12.dll': The specified module could not be found. (Exception from HRESULT: 0x8007007E)
   at Oracle.DataAccess.Client.OpsInit.CheckVersionCompatibility(String version)
   at Oracle.DataAccess.Client.OracleInit.Initialize()
   at Oracle.DataAccess.Client.OracleConnection..cctor()
   --- End of inner exception stack trace ---

We have checked, but YES the DLL is there. We also put it in different locations to see if this would work but no.

These are the DLLs we are using:

The strange thing is that when we copy our desktop application to the server, the desktop application runs fine! The desktop application has the exact same DLLs as the web application!

The DLLs we are using for both desktop and web application are from the XCopy folders of Oracle:
http://download.oracle.com/otn/other/ole-oo4o/ODAC122010Xcopy_32bit.zip   x86
http://download.oracle.com/otn/other/ole-oo4o/ODAC122010Xcopy_x64.zip   x64

There are more people struggling with this issue, here is what we have found so far:

Oracle 12.2 needs minimum .NET Framework 4.5.2 our server has 4.6 and up

The rights of the DLLs are set correctly and may be used by IIS

We have for our x86 web application enabled 32-bit application in the Advanced Settings window

We have set the environment making sure the right DLLs are added to the environment

In Visual Studio we made sure that the references are: Copied if newer and Local copy is set to true

Our application are full x86 or x64 NOT anyCPU build.

We have checked our Regedit, Machine.config and GAC for any possible left-over of other Oracle versions.

Redownloaded the xcopy zip and copied the files again

Server has DISABLED firewall (development)

Oracle.DataAccess.Client Dependencies this is more or less our method to!

Our server-specs:

Windows Server 2012R2 DataCenter (clean)

X64-based pc

using IIS 8.5


问:
Detect click outside control
I display TestControl in grid when user clicks on the button:

```<code><Grid>
    <myControls:TestControl Panel.ZIndex="2" Visibility="Collapsed" Width="100" Height="100" />
    <Button "Open Test Control" Click="btnOpen_Click" />
</Grid>
</code>```

How can I hide TestControl when user clicks outside this control?

答:
You could handle the PreviewMouseLeftButtonDown event for the Grid:

```<code><Grid Background="Transparent" PreviewMouseLeftButtonDown="Grid_PreviewMouseLeftButtonDown">
    <Grid.RowDefinitions>
        <RowDefinition />
        <RowDefinition />
    </Grid.RowDefinitions>
    <myControls:TestControl x:Name="tc" Visibility="Collapsed" Width="100" Height="100" />
    <Button Content="Open Test Control" Click="btnOpen_Click" Grid.Row="1" />
</Grid>
</code>```

```<code>private void Grid_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
    if (!tc.IsMouseOver)
        tc.Visibility = Visibility.Collapsed;
}
</code>```

Title: Detect click outside control

Body:
I display TestControl in grid when user clicks on the button:

<Grid>
    <myControls:TestControl Panel.ZIndex="2" Visibility="Collapsed" Width="100" Height="100" />
    <Button "Open Test Control" Click="btnOpen_Click" />
</Grid>

How can I hide TestControl when user clicks outside this control?

Body:
You could handle the PreviewMouseLeftButtonDown event for the Grid:

<Grid Background="Transparent" PreviewMouseLeftButtonDown="Grid_PreviewMouseLeftButtonDown">
    <Grid.RowDefinitions>
        <RowDefinition />
        <RowDefinition />
    </Grid.RowDefinitions>
    <myControls:TestControl x:Name="tc" Visibility="Collapsed" Width="100" Height="100" />
    <Button Content="Open Test Control" Click="btnOpen_Click" Grid.Row="1" />
</Grid>

private void Grid_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
    if (!tc.IsMouseOver)
        tc.Visibility = Visibility.Collapsed;
}


问:
How to attach "slide" & "slid" events to the Bootstrap toolkit's carousel?
Here's a fiddle with a working Bootstrap carousel.
http://jsfiddle.net/jeykeu/5TDff/

And here's the official documentation which tells nothing about event usage.
http://twitter.github.com/bootstrap/javascript.html#carousel

I thought this would work but no:

```<code>     $('#carousel').bind('slide',function(){
            alert("Slide Event");
    });
</code>```

答:
Old post I know, but I wanted to show both slide and slid using the .on function.

So, my 2 cents...
JSFiddle

```<code>$('#myCarousel').on('slide.bs.carousel', function (e) {
    $( '.carousel' ).removeClass('color-start');
    $( '.carousel' ).addClass('color-finish');
    $('#bind').html('Sliding!');
});

$('#myCarousel').on('slid.bs.carousel', function (e) {
    $( '.carousel' ).removeClass('color-finish');
    $( '.carousel' ).addClass('color-start');
    $('#bind').html('slid again!');
});
</code>```

The 'addClass & removeClass' are for the fun of showing something is happening and when. Also, you could use this along with animate.css to add/remove the 'animated' class to elements .on(slide,).

```<code>$('#bind').html('Sliding!')
</code>```

The above is I don't like 'alerts' and showing console.log can be a pain on smaller screens.

Body:
Here's a fiddle with a working Bootstrap carousel.
http://jsfiddle.net/jeykeu/5TDff/

And here's the official documentation which tells nothing about event usage.
http://twitter.github.com/bootstrap/javascript.html#carousel

I thought this would work but no:

     $('#carousel').bind('slide',function(){
            alert("Slide Event");
    });

Body:
Old post I know, but I wanted to show both slide and slid using the .on function.

So, my 2 cents...
JSFiddle

$('#myCarousel').on('slide.bs.carousel', function (e) {
    $( '.carousel' ).removeClass('color-start');
    $( '.carousel' ).addClass('color-finish');
    $('#bind').html('Sliding!');
});

$('#myCarousel').on('slid.bs.carousel', function (e) {
    $( '.carousel' ).removeClass('color-finish');
    $( '.carousel' ).addClass('color-start');
    $('#bind').html('slid again!');
});

The 'addClass & removeClass' are for the fun of showing something is happening and when. Also, you could use this along with animate.css to add/remove the 'animated' class to elements .on(slide,).

$('#bind').html('Sliding!')

The above is I don't like 'alerts' and showing console.log can be a pain on smaller screens.


问:
Keep text aligned vertically on a Checkbox Input
I want to keep my text aligned vertically on a checkbox input, but when larger labels are added the text will drop a line, ending up below the checkbox.

See screenshot:
http://prntscr.com/hb7ow2

Is there any way to keep the text aligned as shown in the second screenshot?

答: I fixed it, for future reference for anyone reading this: target the checkbox (I used :before), position as absolute, position accordingly, wrap label in a span tag, add a margin-left, finally add spacing to your suiting. </p>


问:
ASP.NET MVC 4 - razor empty post in for loop
I have the following code in razor:

```<code>  @for (int i = 0; i < Model.Count; i++)
  {
      using (Html.BeginForm("Bonnen", "Bon"))
      {
          <tr>
              <td> @Html.TextBoxFor(model => Model[i].Id)</td>
              <td>@Html.DisplayFor(model => Model[i].Date)</td>
              <td>@Html.DisplayFor(model => Model[i].Description)</td>
              <td><button type="submit" value="Details" class="btn btn-info">Details</button></td>
          </tr>
      }
  }
</code>```

When i post the data to the controller it becomes empty.
I've already seen a question where it said you can't use a foreach loop here.
On the website itself it does show all the data, but it won't give it to the controller.

Controller:

```<code>  [HttpPost]
  public ActionResult Bonnen(Bon bon)
  {
   return RedirectToAction("Details", "Bon", bon);
  }
</code>```

Model:

```<code>  public int Id { get; set; }
  public string Description { get; set; }
  public DateTime Date { get; set; }
</code>```

答:
Your code needs to be inside the form and button type "submit" wont work. You need to use input type "submit". See code below:</p>

```<code>  @using (Html.BeginForm("Bonnen", "Bon"))
  {
    @for (int i = 0; i < Model.Count; i++)
    {
       <tr>
           <td> @Html.TextBoxFor(model => Model[i].Id)</td>
           <td>@Html.DisplayFor(model => Model[i].Date)</td>
           <td>@Html.DisplayFor(model => Model[i].Description)</td>
           <td><input type="submit" value="Details" class="btn btn-info"/></td>
       </tr>
    }
  }
</code>```

Body:
I have the following code in razor:

  @for (int i = 0; i < Model.Count; i++)
  {
      using (Html.BeginForm("Bonnen", "Bon"))
      {

               @Html.TextBoxFor(model => Model[i].Id)
              @Html.DisplayFor(model => Model[i].Date)
              @Html.DisplayFor(model => Model[i].Description)
              <button type="submit" value="Details" class="btn btn-info">Details</button>

      }
  }

When i post the data to the controller it becomes empty.
I've already seen a question where it said you can't use a foreach loop here.
On the website itself it does show all the data, but it won't give it to the controller.

Controller:

  [HttpPost]
  public ActionResult Bonnen(Bon bon)
  {
   return RedirectToAction("Details", "Bon", bon);
  }

Model:

  public int Id { get; set; }
  public string Description { get; set; }
  public DateTime Date { get; set; }

Body:
Your code needs to be inside the form and button type "submit" wont work. You need to use input type "submit". See code below:

  @using (Html.BeginForm("Bonnen", "Bon"))
  {
    @for (int i = 0; i < Model.Count; i++)
    {
       <tr>
           <td> @Html.TextBoxFor(model => Model[i].Id)</td>
           <td>@Html.DisplayFor(model => Model[i].Date)</td>
           <td>@Html.DisplayFor(model => Model[i].Description)</td>
           <td><input type="submit" value="Details" class="btn btn-info"/></td>
       </tr>
    }
  }


问:
How to make method calls async
I have about 30 method calls (filling dataset). I want to make these calls parallel (asynchronous).
Please give me some code idea.Following are some of the calls.</p>

```<code> ds = (DS)dbManager.ExecuteDataSet(CommandType.StoredProcedure, Proc1, ds, tableNames);
 ds = (DS)dbManager.ExecuteDataSet(CommandType.StoredProcedure, Proc2, ds, tableNames);
 ds = (DS)dbManager.ExecuteDataSet(CommandType.StoredProcedure, Proc3, ds, tableNames);
 ds = (DS)dbManager.ExecuteDataSet(CommandType.StoredProcedure, Proc4, ds, tableNames);
 ds = (DS)dbManager.ExecuteDataSet(CommandType.StoredProcedure, Proc5, ds, tableNames);
 ds = (DS)dbManager.ExecuteDataSet(CommandType.StoredProcedure, Proc6, ds, tableNames);
 ds = (DS)dbManager.ExecuteDataSet(CommandType.StoredProcedure, Proc7, ds, tableNames);
 ds = (DS)dbManager.ExecuteDataSet(CommandType.StoredProcedure, Proc8, ds, tableNames);
</code>```

答:
From my understanding your Proc1, proc2.. are procedure names. Just load them to the list and try this:

```<code>string[] procNames = {"Proc1","Proc2","Proc3","Proc4","Proc5"};
List<string> list =new List<string>();
foreach (var procName in procNames)
{
    list.Add(procName);
}
Parallel.ForEach(list, current =>
{
    ds = (DS)dbManager.ExecuteDataSet(CommandType.StoredProcedure, current, ds, tableNames);
});
</code>```

Just be aware that this will NOT execute your procedures in any particular order.

Title: How to make method calls async

Body:
I have about 30 method calls (filling dataset). I want to make these calls parallel (asynchronous).
Please give me some code idea.Following are some of the calls.

 ds = (DS)dbManager.ExecuteDataSet(CommandType.StoredProcedure, Proc1, ds, tableNames);
 ds = (DS)dbManager.ExecuteDataSet(CommandType.StoredProcedure, Proc2, ds, tableNames);
 ds = (DS)dbManager.ExecuteDataSet(CommandType.StoredProcedure, Proc3, ds, tableNames);
 ds = (DS)dbManager.ExecuteDataSet(CommandType.StoredProcedure, Proc4, ds, tableNames);
 ds = (DS)dbManager.ExecuteDataSet(CommandType.StoredProcedure, Proc5, ds, tableNames);
 ds = (DS)dbManager.ExecuteDataSet(CommandType.StoredProcedure, Proc6, ds, tableNames);
 ds = (DS)dbManager.ExecuteDataSet(CommandType.StoredProcedure, Proc7, ds, tableNames);
 ds = (DS)dbManager.ExecuteDataSet(CommandType.StoredProcedure, Proc8, ds, tableNames);

Body:
From my understanding your Proc1, proc2.. are procedure names. Just load them to the list and try this:

string[] procNames = {"Proc1","Proc2","Proc3","Proc4","Proc5"};
List<string> list =new List<string>();
foreach (var procName in procNames)
{
    list.Add(procName);
}
Parallel.ForEach(list, current =>
{
    ds = (DS)dbManager.ExecuteDataSet(CommandType.StoredProcedure, current, ds, tableNames);
});

Just be aware that this will NOT execute your procedures in any particular order.


问:
Drupal RESTful web services to access image URL using Ionic
Firstly, I'm a long time user of stackoverflow for existing answers, first time asker, so go easy if this is too basic or has been answered elsewhere.

I'm trying to use Drupal 7's RESTful web services module to serve content to an Ionic app. I have the content flowing through fine (e.g. title and body text) but am struggling to access the images. The relevant part of the JSON response is:

```<code>  "field_cover_image": {
    "file": {
      "uri": "http://example.com/drupal/file/9",
      "id": "9",
      "resource": "file"
    }
  },
</code>```

How can I translate that information for use inside an image tag, from what I can see I am only being given the ID of the image at this point where what I need is the url/filename.

Thanks

答:
You can create path to original image file (the one user uploaded) from uri with function file_create_url() :

https://api.drupal.org/api/drupal/includes%21file.inc/function/file_create_url/7.x

And you can create path to image file in specific image style with function image_style_url(). Second parameter of this function is actually uri, not path.

https://api.drupal.org/api/drupal/modules%21image%21image.module/function/image_style_url/7.x

I didn't use Restful Web Service, so I can't tell you how to do that exactly, but you must somehow pass of this uri to one of those 2 functions to get url to image file.

Body:
Firstly, I'm a long time user of stackoverflow for existing answers, first time asker, so go easy if this is too basic or has been answered elsewhere.

I'm trying to use Drupal 7's RESTful web services module to serve content to an Ionic app. I have the content flowing through fine (e.g. title and body text) but am struggling to access the images. The relevant part of the JSON response is:

  "field_cover_image": {
    "file": {
      "uri": "http://example.com/drupal/file/9",
      "id": "9",
      "resource": "file"
    }
  },

How can I translate that information for use inside an image tag, from what I can see I am only being given the ID of the image at this point where what I need is the url/filename.

Thanks


问:
Vertx js and Redis Sentinel Connectivity
Am Working on the versions of Vertx 3.5.0 Version and Redis with master and Slave Architecture .In their Official Site they have didn't mention of their redis sentinel Support.

So can i create a jar file which gets the Master Details of Redis and use that jar file in Vertx-js Program to get the Master Details and make the Connectivity.

答:
3.5.0 does contain basic support for Redis Sentinel but was not properly documented. It is now updated to be polyglot and there is a small reference to it on the new docs:

https://github.com/vert-x3/vertx-redis-client/blob/master/src/main/asciidoc/java/index.adoc#redis-sentinel

This should be available on 3.5.1 but you can already use it on 3.5.0 as the only missing parts were polyglot generation and the docs themselves.


问:
Storing list of custom objects in Entity Framework
Started to learn asp.net and DB manipulations. Trying to implement some simple functionality - two models, one has list of references to another.

Here is an error that I currently get:

An exception occurred while initializing the database. See the InnerException for details.

Inner exception:

  Unable to determine a valid ordering for dependent operations. Dependencies may exist due to foreign key constraints, model requirements, or store-generated values.

My models:

```<code>public class Killer
{
        public Killer(string name, string biography)
        {
            Name = name;
            Biography = biography;
            KillerId = Guid.NewGuid();
        }

        public Guid KillerId { get; set; }
        public string Name { get; set; }
        public string Biography { get; set; }

        public virtual Contract Contract { get; set; }
}

public class Contract
{
        public Contract(Status status, Killer target, string description, params Killer[] targets)
        {
            ContractId = Guid.NewGuid();
            this.status = status;
            Target = target;
            Description = description;

            Killers = new HashSet<Killer>();
            foreach (var t in targets) Killers.Add(t);

        }

        public Guid ContractId { get; set; }

        public enum Status { active, done, failed, rejected, abandoned }
        public Status status { get; set; }

        public Killer Target { get; set; }
        public string Description { get; set; }

        //[ForeignKey("ContractID")]
        public virtual ICollection<Killer> Killers { get; set; }
}
</code>```

In context I initialize db with lists of objects

```<code>public class KillerContext : DbContext
{
    public DbSet<Killer> Killers { get; set; }
    public DbSet<Contract> Contracts { get; set; }
}
</code>```

In controller I do:

```<code>KillerContext k = new KillerContext();

public ActionResult Index()
{
    var contracts = k.Contracts.ToList();
    ViewBag.contracts = contracts;
    return View();
}
</code>```

In Global.asax:

```<code>Database.SetInitializer(new KillerContextInitialization());
</code>```

Here is how I enter first data in db:

```<code>public sealed class KillerContextInitialization : DropCreateDatabaseAlways<KillerContext>
{
    protected override void Seed(KillerContext db)
    {
        List<Killer> killers = new List<Killer>();
        //List<Contract> contracts = new List<Contract>();

        killers.Add(new Killer(name: "Ivan Firstein", biography: "He was born in the shadows."));
        killers.Add(new Killer(name: "Oleg Gazmanov", biography: "test man"));
        db.Contracts.Add(new Contract(
                Contract.Status.active,
                killers.SingleOrDefault(x => x.Name == "Ivan Firstein"),
                "KILL OR BE KILLED. As always with love.",
                killers.SingleOrDefault(x => x.Name == "Oleg Gazmanov")
                ));

        db.Killers.AddRange(killers);
        base.Seed(db);
    }
}
</code>```

答:
Looks like you need add ForeignKey attribute for killer Model, and store this key in property ContractId:

```<code>public class Killer
{
    [ForeignKey(nameof(ContractId)]  //Name of added property in line below
    public Contract Contract { get; set; } //no need "virtual"
    public Guid? ContractId { get; set; }

    // other properties...
}

public class Contract
{
        [ForeignKey("ContractId")] //Name of added property in Killer Model
        public virtual ICollection<Killer> Killers { get; set; }

        // other code...
}
</code>```

EDIT

You should do something similar to the Contract.Target property:

```<code>[ForeignKey(nameof(TargetId)]
public Killer Target { get; set; }
public Guid TargetId { get; set; }
</code>```

For enum types you should add attributes like this:

```<code>[Column(nameof(status), TypeName = "int")]
public Status status { get; set; }
</code>```

Body:
Started to learn asp.net and DB manipulations. Trying to implement some simple functionality - two models, one has list of references to another.

Here is an error that I currently get:

An exception occurred while initializing the database. See the InnerException for details.

Inner exception:

  Unable to determine a valid ordering for dependent operations. Dependencies may exist due to foreign key constraints, model requirements, or store-generated values.

My models:

public class Killer
{
        public Killer(string name, string biography)
        {
            Name = name;
            Biography = biography;
            KillerId = Guid.NewGuid();
        }

        public Guid KillerId { get; set; }
        public string Name { get; set; }
        public string Biography { get; set; }

        public virtual Contract Contract { get; set; }
}

public class Contract
{
        public Contract(Status status, Killer target, string description, params Killer[] targets)
        {
            ContractId = Guid.NewGuid();
            this.status = status;
            Target = target;
            Description = description;

            Killers = new HashSet<Killer>();
            foreach (var t in targets) Killers.Add(t);

        }

        public Guid ContractId { get; set; }

        public enum Status { active, done, failed, rejected, abandoned }
        public Status status { get; set; }

        public Killer Target { get; set; }
        public string Description { get; set; }

        //[ForeignKey("ContractID")]
        public virtual ICollection<Killer> Killers { get; set; }
}

In context I initialize db with lists of objects

public class KillerContext : DbContext
{
    public DbSet<Killer> Killers { get; set; }
    public DbSet<Contract> Contracts { get; set; }
}

In controller I do:

KillerContext k = new KillerContext();

public ActionResult Index()
{
    var contracts = k.Contracts.ToList();
    ViewBag.contracts = contracts;
    return View();
}

In Global.asax:

Database.SetInitializer(new KillerContextInitialization());

Here is how I enter first data in db:

public sealed class KillerContextInitialization : DropCreateDatabaseAlways<KillerContext>
{
    protected override void Seed(KillerContext db)
    {
        List<Killer> killers = new List<Killer>();
        //List<Contract> contracts = new List<Contract>();

        killers.Add(new Killer(name: "Ivan Firstein", biography: "He was born in the shadows."));
        killers.Add(new Killer(name: "Oleg Gazmanov", biography: "test man"));
        db.Contracts.Add(new Contract(
                Contract.Status.active,
                killers.SingleOrDefault(x => x.Name == "Ivan Firstein"),
                "KILL OR BE KILLED. As always with love.",
                killers.SingleOrDefault(x => x.Name == "Oleg Gazmanov")
                ));

        db.Killers.AddRange(killers);
        base.Seed(db);
    }
}

Body:
Looks like you need add ForeignKey attribute for killer Model, and store this key in property ContractId:

public class Killer
{
    [ForeignKey(nameof(ContractId)]  //Name of added property in line below
    public Contract Contract { get; set; } //no need "virtual"
    public Guid? ContractId { get; set; }

    // other properties...
}

public class Contract
{
        [ForeignKey("ContractId")] //Name of added property in Killer Model
        public virtual ICollection<Killer> Killers { get; set; }

        // other code...
}

EDIT

You should do something similar to the Contract.Target property:

[ForeignKey(nameof(TargetId)]
public Killer Target { get; set; }
public Guid TargetId { get; set; }

For enum types you should add attributes like this:

[Column(nameof(status), TypeName = "int")]
public Status status { get; set; }


问:
Convert List<object> to List<Type>, Type is known at runtime
I am implementing some kind of deserialization and struggled with a next problem:

I have List<object> and System.Reflection.Field, it's FieldType can be List<string>, List<int> or List<bool>, so I need to convert from List<object> to that types.

```<code>public static object ConvertList(List<object> value, Type type)
{
   //type may be List<int>, List<bool>, List<string>
}
</code>```

I can write each case separately, but there should be a better way using reflection.

答:
```<code>    /// <summary>
    /// Converts list of items into typed list of item of new type
    /// </summary>
    /// <example><code>
    /// Consider source to be List<object>, newItemType is typeof(string), so resulting list wil have type List<string>
    /// </code></example>
    /// <param name="newItemType">New item type</param>
    /// <param name="source">List of objects</param>
    /// <returns>Typed List object</returns>
    public static IList ConvertList(Type newItemType, IList source)
    {
        var listType = typeof(List<>);
        Type[] typeArgs = { newItemType };
        var genericListType = listType.MakeGenericType(typeArgs);
        var typedList = (IList)Activator.CreateInstance(genericListType);
        foreach (var item in source)
        {
            typedList.Add(item);
        }
        return typedList;
    }
</code>```

Body:
I am implementing some kind of deserialization and struggled with a next problem:

I have List<object> and System.Reflection.Field, it's FieldType can be List<string>, List<int> or List<bool>, so I need to convert from List<object> to that types.

public static object ConvertList(List<object> value, Type type)
{
   //type may be List<int>, List<bool>, List<string>
}

I can write each case separately, but there should be a better way using reflection.


问:
what is the most pythonic way to split a 2d array to arrays of each row?
I have a function foo that returns an array with the shape (1000, 2)
how can I split it to two arrays a(1000) and b(1000)
I'm looking for something like this:

```<code>a;b = foo()
</code>```

I'm looking for an answer that can easily generalize to the case in which the shape is (1000, 5) or so.

答:
You can use numpy.hsplit.

```<code>x = np.arange(12).reshape((3, 4))
np.hsplit(x, x.shape[1])
</code>```

This returns a list of subarrays.  Note that in the case of a 2d input, the subarrays will be shape (n, 1).  Unless you wrap a function around it to squeeze them to 1d:

```<code>def split_1d(arr_2d):
    """Split 2d NumPy array on its columns."""
    split = np.hsplit(arr_2d, arr_2d.shape[1])
    split = [np.squeeze(arr) for arr in split]
    return split

a, b, c, d = split_1d(x)

a
# array([0, 4, 8])

d
# array([ 3,  7, 11])
</code>```

Body:
I have a function foo that returns an array with the shape (1000, 2)
how can I split it to two arrays a(1000) and b(1000)
I'm looking for something like this:

a;b = foo()

I'm looking for an answer that can easily generalize to the case in which the shape is (1000, 5) or so.

Body:
You can use numpy.hsplit.

x = np.arange(12).reshape((3, 4))
np.hsplit(x, x.shape[1])

This returns a list of subarrays.  Note that in the case of a 2d input, the subarrays will be shape (n, 1).  Unless you wrap a function around it to squeeze them to 1d:

def split_1d(arr_2d):
    """Split 2d NumPy array on its columns."""
    split = np.hsplit(arr_2d, arr_2d.shape[1])
    split = [np.squeeze(arr) for arr in split]
    return split

a, b, c, d = split_1d(x)

a
# array([0, 4, 8])

d
# array([ 3,  7, 11])


问:
Android Studio List View
I would like to set up my code where when I click a line in my list view it returns text from a text file (from notepad or Access). Is this possible or will it need to be a different format.

This is what code I have so far, I believe it should be just one or two lines of code that will pull from a file. Here is my Main Activity Code:
`

```<code>Toolbar toolbar;
ListView listView;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    toolbar=(Toolbar) findViewById(R.id.toolbar);
    toolbar.setTitle(getResources().getString(R.string.app_name));
    listView=(ListView) findViewById(R.id.listView);

    ArrayAdapter<String> mAdapter = new ArrayAdapter<String>(MainActivity.this,
            android.R.layout.simple_list_item_1,
            getResources().getStringArray(R.array.Materials));

    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
            Intent intent= new Intent(MainActivity.this, SecondActivity.class);
            intent.putExtra("MaterialName", listView.getItemAtPosition(i).toString());
            startActivity(intent);
        }
    });
    listView.setAdapter(mAdapter);
}
</code>```

Here is my Second Activity Code:

```<code>`
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_second);

    mToolbar = (Toolbar) findViewById(R.id.toolbar1);
    material = (TextView) findViewById(R.id.textView);

    Bundle bundle = getIntent().getExtras();
    if(bundle != null) {
        mToolbar.setTitle(bundle.getString("MaterialName"));
        if(mToolbar.getTitle().toString().equalsIgnoreCase("4140")){
            //how do I get it to return the information from a text file
        }
    }

}`
</code>```

After looking through the links in the Answers my Second Activity now looks like this:

```<code>@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_second);
    BufferedReader reader = null;

   try {
       reader = new BufferedReader(
               new InputStreamReader(getAssets().open("4140.txt")));

       String mLine;
       while ((mLine = reader.readLine()) != null) {
           text.append(mLine);
           text.append('\n');
       }
   } catch (IOException e) {
       Toast.makeText(getApplicationContext(), "Error reading file!", Toast.LENGTH_LONG).show();
       e.printStackTrace();
   } finally {
       if (reader != null) {
       try {
           reader.close();
       } catch (IOException e) {

       }
    }

    TextView output= (TextView) findViewById(R.id.toolbar1);
    output.setText((CharSequence)text);
   }

}
</code>```

}

When I run the emulator, my Main Activity comes up correctly.
Main Activity of my project

When I click on list value of 4140 Instead of bringing up the Second Activity with a tool bar and the textview with the text from my file it stops working.

Also I seem to have left out is that I want to link the text file to a specific list value. When I did this with images, when I clicked a list value my toolbar on the second activity repeated that list value and then depending on what my toolbar said it pulled in the correct image from my drawable file. It seems I am missing that part that will link each list value to its specific and correct text file.

答:
In the second Activity you should use a Reader to get the txt file string.

Check this q&a about reading a txt and outputing as a textview.

About opening an Access database, that's a big topic that will involve a reader and maybe a way to run queries on it. This other question addressed the thing.

P.S.: Sorry for adding just links, but I think they did best explaining each point.

Title: Android Studio List View

Body:
I would like to set up my code where when I click a line in my list view it returns text from a text file (from notepad or Access). Is this possible or will it need to be a different format.

This is what code I have so far, I believe it should be just one or two lines of code that will pull from a file. Here is my Main Activity Code:
`

Toolbar toolbar;
ListView listView;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    toolbar=(Toolbar) findViewById(R.id.toolbar);
    toolbar.setTitle(getResources().getString(R.string.app_name));
    listView=(ListView) findViewById(R.id.listView);

    ArrayAdapter<String> mAdapter = new ArrayAdapter<String>(MainActivity.this,
            android.R.layout.simple_list_item_1,
            getResources().getStringArray(R.array.Materials));

    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
            Intent intent= new Intent(MainActivity.this, SecondActivity.class);
            intent.putExtra("MaterialName", listView.getItemAtPosition(i).toString());
            startActivity(intent);
        }
    });
    listView.setAdapter(mAdapter);
}

Here is my Second Activity Code:

`
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_second);

    mToolbar = (Toolbar) findViewById(R.id.toolbar1);
    material = (TextView) findViewById(R.id.textView);

    Bundle bundle = getIntent().getExtras();
    if(bundle != null) {
        mToolbar.setTitle(bundle.getString("MaterialName"));
        if(mToolbar.getTitle().toString().equalsIgnoreCase("4140")){
            //how do I get it to return the information from a text file
        }
    }

}`

After looking through the links in the Answers my Second Activity now looks like this:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_second);
    BufferedReader reader = null;

   try {
       reader = new BufferedReader(
               new InputStreamReader(getAssets().open("4140.txt")));

       String mLine;
       while ((mLine = reader.readLine()) != null) {
           text.append(mLine);
           text.append('\n');
       }
   } catch (IOException e) {
       Toast.makeText(getApplicationContext(), "Error reading file!", Toast.LENGTH_LONG).show();
       e.printStackTrace();
   } finally {
       if (reader != null) {
       try {
           reader.close();
       } catch (IOException e) {

       }
    }

    TextView output= (TextView) findViewById(R.id.toolbar1);
    output.setText((CharSequence)text);
   }

}

}

When I run the emulator, my Main Activity comes up correctly.
Main Activity of my project

When I click on list value of 4140 Instead of bringing up the Second Activity with a tool bar and the textview with the text from my file it stops working.

Also I seem to have left out is that I want to link the text file to a specific list value. When I did this with images, when I clicked a list value my toolbar on the second activity repeated that list value and then depending on what my toolbar said it pulled in the correct image from my drawable file. It seems I am missing that part that will link each list value to its specific and correct text file.


问:
Multiple modules and routing in angular 5
can somebody tell me how correct to set up routing when using multiple modules in my project? I have app.module and courses.module with some components declared in. I want to know how to connect modules and edit properly routing in courses.module, thats share routes: "/courses/list" and "/courses/detail"

app.routing.module.ts

```<code>import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';

//import { CoursesRoutingModule } from './components/courses/courses-routing.module';

const routes: Routes = [
  {
    path: 'courses',
    loadChildren: './components/courses/courses-routing.module#CoursesRoutingModule'
  }
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }
</code>```

app.component.html

```<code><h1>App.component</h1>
<p>
    <button routerLink="/">HOME</button>
    <button routerLink="/courses">KURSY</button>
</p>
<router-outlet></router-outlet>
</code>```

And here's courses component:

courses.routing.module.ts

```<code>import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';

import { CoursesComponent } from './courses.component';
import { CoursesDetailComponent } from './components/courses-detail/courses-detail.component';
import { CoursesListComponent } from './components/courses-list/courses-list.component';

const routes: Routes = [
//  {
//    path: 'courses',
//    loadChildren: '/src/app/components/courses/courses.module'
//  }
//  ,
//  {
//    path: 'courses/list',
//    component: CoursesListComponent,
//    outlet: 'courseslist'
//  }
];

@NgModule({
  imports: [RouterModule.forChild(routes)],
  exports: [RouterModule]
})
export class CoursesRoutingModule { }
</code>```

courses.component.html:

```<code><p>
    <button routerLink="/">HOME</button>
    <button routerLink="/courses/list">list</button>
    <button routerLink="/courses/detail">detail</button>
</p>
</code>```

答:
Edit 08/2019

Adapted the lazy load module syntax to the newly, strong-typed syntax introduced in angular 8.

Edit 10/2021:

This construct is still valid for Angular 12.

Solution

Here is how I do it:

app.module.ts

import {ModuleRouting} from './app.routing';

@NgModule({
    declarations: [
        AppComponent,
    ],
    imports: [
        ModuleRouting,
        SubmoduleModule
    ]
    bootstrap: [AppComponent]
})
export class AppModule {
}
```
<p><strong>app.routing.ts</strong></p>
<pre class="lang-ts prettyprint-override"><code>import {Routes, RouterModule} from '@angular/router';
import {ModuleWithProviders} from '@angular/core';

const routes: Routes = [
    {path: 'submodule', loadChildren: () => import('app/submodule/submodule.module').then(m => m.SubmoduleModule)}
];

export const ModuleRouting: ModuleWithProviders = RouterModule.forRoot(routes);
</code>```

submodule.module.ts

import {NgModule} from '@angular/core';
import {CommonModule} from '@angular/common';
import {SubmoduleRouting} from './submodule.routing';

@NgModule({
    imports: [
        CommonModule,
        SubmoduleRouting
    ],
    declarations: [
        //...
    ]
})
export class SubmoduleModule {
}
```
<p><strong>submodule.routing.ts</strong></p>
<pre class="lang-ts prettyprint-override"><code>import {RouterModule, Routes} from '@angular/router';
import {ModuleWithProviders} from '@angular/core';

const routes: Routes = [
    {
        path: '',
        component: SomeComponent,
    },
    {
        path: 'other',
        component: SomeOtherComponent,
    }
];

export const SubmoduleRouting: ModuleWithProviders = RouterModule.forChild(routes);
</code>```

You can also generate the module and routing files using the angular cli and then adapt them:
(cd to the directory where the files should be created before every command)

```<code>ng g m module --routing
ng g m submodule --routing
</code>```

Body:
can somebody tell me how correct to set up routing when using multiple modules in my project? I have app.module and courses.module with some components declared in. I want to know how to connect modules and edit properly routing in courses.module, thats share routes: "/courses/list" and "/courses/detail"

app.routing.module.ts

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';

//import { CoursesRoutingModule } from './components/courses/courses-routing.module';

const routes: Routes = [
  {
    path: 'courses',
    loadChildren: './components/courses/courses-routing.module#CoursesRoutingModule'
  }
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }

app.component.html

App.component

    <button routerLink="/">HOME</button>
    <button routerLink="/courses">KURSY</button>

<router-outlet></router-outlet>

And here's courses component:

courses.routing.module.ts

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';

import { CoursesComponent } from './courses.component';
import { CoursesDetailComponent } from './components/courses-detail/courses-detail.component';
import { CoursesListComponent } from './components/courses-list/courses-list.component';

const routes: Routes = [
//  {
//    path: 'courses',
//    loadChildren: '/src/app/components/courses/courses.module'
//  }
//  ,
//  {
//    path: 'courses/list',
//    component: CoursesListComponent,
//    outlet: 'courseslist'
//  }
];

@NgModule({
  imports: [RouterModule.forChild(routes)],
  exports: [RouterModule]
})
export class CoursesRoutingModule { }

courses.component.html:

    <button routerLink="/">HOME</button>
    <button routerLink="/courses/list">list</button>
    <button routerLink="/courses/detail">detail</button>

Body:
Edit 08/2019

Adapted the lazy load module syntax to the newly, strong-typed syntax introduced in angular 8.

Edit 10/2021:

This construct is still valid for Angular 12.

Solution

Here is how I do it:

app.module.ts

import {ModuleRouting} from './app.routing';

@NgModule({
    declarations: [
        AppComponent,
    ],
    imports: [
        ModuleRouting,
        SubmoduleModule
    ]
    bootstrap: [AppComponent]
})
export class AppModule {
}

app.routing.ts

import {Routes, RouterModule} from '@angular/router';
import {ModuleWithProviders} from '@angular/core';

const routes: Routes = [
    {path: 'submodule', loadChildren: () => import('app/submodule/submodule.module').then(m => m.SubmoduleModule)}
];

export const ModuleRouting: ModuleWithProviders = RouterModule.forRoot(routes);

submodule.module.ts

import {NgModule} from '@angular/core';
import {CommonModule} from '@angular/common';
import {SubmoduleRouting} from './submodule.routing';

@NgModule({
    imports: [
        CommonModule,
        SubmoduleRouting
    ],
    declarations: [
        //...
    ]
})
export class SubmoduleModule {
}

submodule.routing.ts

import {RouterModule, Routes} from '@angular/router';
import {ModuleWithProviders} from '@angular/core';

const routes: Routes = [
    {
        path: '',
        component: SomeComponent,
    },
    {
        path: 'other',
        component: SomeOtherComponent,
    }
];

export const SubmoduleRouting: ModuleWithProviders = RouterModule.forChild(routes);

You can also generate the module and routing files using the angular cli and then adapt them:
(cd to the directory where the files should be created before every command)

ng g m module --routing
ng g m submodule --routing


问:
c++ assign to pointer a pointer to constant
I have the following code:

```<code>class B{
    /*
    ...
    */
};
class A{
    B** elements;
    public:
        A operator+=(const B& b){
            // this->elements[0] = &b;

        }
        A(int number){
            this->elements = new B*[number];
        }
    /*
    ...
    */
};

int main(){
    A a(10);
    return 0;
}
</code>```

What I want is that the += operator should add the B object(operator's right side) to the A object's elements member.
So let's say I modify main to :

```<code>int main{
    A a(10);
    B b();
    a += b;
}
</code>```

After this a.elements[0] should be the b object.
I commented a line which is not working,but shows what I want.Uncommenting it gives the following error: invalid conversion from const B* to B*

The real code is much longer of course, it's enough if you show me how to make the += operator always assign the B object to A.elements[0], then I can edit my code as neccessary.

Thanks

答:
Focusing your issue, a B* is not a B const*: on the first you are allowed to call methods which are not const, while this is not true for the latter.

And the compiler is complaining about this: you declare an array of pointers to modifiable Bs but then you try to store a pointer to an unmodifiable B inside it. So if you merely want to fix this problem you can decide for example to store unmodifiable Bs:

```<code>  B const** elements;
public:
 A& operator+=(const B& b) {
    this->elements[0] = &b;
    return *this;
  }

  A(int number) {
    this->elements = new B const*[number];
  }
</code>```

But there are serious issues in your code:

you are taking the address of a const B& but where is this B coming from? It could have automatic storage and become an invalid pointer somewhere in the future

there is no way to know who is owning the pointer to B objects so who is responsible of releasing it.

It's C++, you have std::unique_ptr, std::shared_ptr, std::vector, just trying to do things as you would do them in C without even attempting to make them safe and secure doesn't make any sense.

Body:
I have the following code:

class B{
    /*
    ...
    */
};
class A{
    B** elements;
    public:
        A operator+=(const B& b){
            // this->elements[0] = &b;

        }
        A(int number){
            this->elements = new B*[number];
        }
    /*
    ...
    */
};

int main(){
    A a(10);
    return 0;
}

What I want is that the += operator should add the B object(operator's right side) to the A object's elements member.
So let's say I modify main to :

int main{
    A a(10);
    B b();
    a += b;
}

After this a.elements[0] should be the b object.
I commented a line which is not working,but shows what I want.Uncommenting it gives the following error: invalid conversion from const B* to B*

The real code is much longer of course, it's enough if you show me how to make the += operator always assign the B object to A.elements[0], then I can edit my code as neccessary.

Thanks

Body:
Focusing your issue, a B* is not a B const*: on the first you are allowed to call methods which are not const, while this is not true for the latter.

And the compiler is complaining about this: you declare an array of pointers to modifiable Bs but then you try to store a pointer to an unmodifiable B inside it. So if you merely want to fix this problem you can decide for example to store unmodifiable Bs:

  B const** elements;
public:
 A& operator+=(const B& b) {
    this->elements[0] = &b;
    return *this;
  }

  A(int number) {
    this->elements = new B const*[number];
  }

But there are serious issues in your code:

you are taking the address of a const B& but where is this B coming from? It could have automatic storage and become an invalid pointer somewhere in the future

there is no way to know who is owning the pointer to B objects so who is responsible of releasing it.

It's C++, you have std::unique_ptr, std::shared_ptr, std::vector, just trying to do things as you would do them in C without even attempting to make them safe and secure doesn't make any sense.


问:
git ssh fails to access host but succeed when direct IP is used (Windows 10)
I am using git/bash in Windows 10 and try to clone a repository.
When I use the command: git clone username@hostname, I get:
ssh: Could not resolve hostname stbcmgit: Name or service not known

However, when I use a direct IP address instead of the hostname (git clone username@x.x.x.x), the access is successful and the clone starts.

Notes:

"known_hosts" file is located at c:\Users\myname\.ssh
The file is taken from my Linux account where everything works fine there.

The .ssh folder contains also the id_rsa and id_rsa.pub keys (copied also from Linux).

When I use 'ls $HOME/.ssh', I see these files listed.

Using Windows 10.

Thanks.

答:
In Windows 10 and after the latest updates concerning the "Windows Subsystem for linux" aka "Bash" now you MUST assign any desired hostname with its relative IP Address by editing this file:

```<code>C:\Windows\System32\drivers\etc\hosts
</code>```

P.S: on your linux please check /etc/hosts and not the 'known_hosts' file

Body:
In Windows 10 and after the latest updates concerning the "Windows Subsystem for linux" aka "Bash" now you MUST assign any desired hostname with its relative IP Address by editing this file:

C:\Windows\System32\drivers\etc\hosts

P.S: on your linux please check /etc/hosts and not the 'known_hosts' file


Title: what is the most pythonic way to split a 2d array to arrays of each row?

Body:
Transpose and unpack?

a, b = foo().T

>>> a, b = np.arange(20).reshape(-1, 2).T
>>> a
array([ 0,  2,  4,  6,  8, 10, 12, 14, 16, 18])
>>> b
array([ 1,  3,  5,  7,  9, 11, 13, 15, 17, 19])


问:
Generating and accessing stored procedures using Entity framework core
I am implementing Asp.Net core Web API , entity framework core, database first approach using Visual Studio 2017. I have managed to generate the context and class files based on an existing database. I need to access stored procedures using my context. In earlier version of entity framework it was simple by selecting the stored procedure objects in the wizard and generating an edmx that contains those objects. I could then access stored procedures via the complex type objects exposed by entity framework. How do I do a similar thing in entity framework core. An example would help ?</p>

答:
The above examples work fine when executing a Stored Procedure if you are expecting the result set to be the same as any object already defined. But what if you want a resultset that is not supported? According to the developers of EF Core 2, this is a feature that will come, but there is already today an easy solution.

Create the model you want to use for your output. This model will represent the output, not a table in the database.

```<code>namespace Example.EF.Model
{
    public class Sample
    {
        public int SampleID { get; set; }
        public string SampleName { get; set; }
    }
}
</code>```

Then add to your context a new DBSet with your model:

```<code>public virtual DbSet<Sample> Sample { get; set; }
</code>```

And then do as above, and use your model for the output:

```<code>var products = _samplecontext.Sample
      .FromSql($"EXEC ReturnAllSamples {id}, {startdate}, {enddate}").ToList();
</code>```

I hope this helps anyone out.

Body:
The above examples work fine when executing a Stored Procedure if you are expecting the result set to be the same as any object already defined. But what if you want a resultset that is not supported? According to the developers of EF Core 2, this is a feature that will come, but there is already today an easy solution.

Create the model you want to use for your output. This model will represent the output, not a table in the database.

namespace Example.EF.Model
{
    public class Sample
    {
        public int SampleID { get; set; }
        public string SampleName { get; set; }
    }
}

Then add to your context a new DBSet with your model:

public virtual DbSet<Sample> Sample { get; set; }

And then do as above, and use your model for the output:

var products = _samplecontext.Sample
      .FromSql($"EXEC ReturnAllSamples {id}, {startdate}, {enddate}").ToList();

I hope this helps anyone out.


问:
Executing simple terminal commands through Wifi on raspberry pi using QT creator
I'm attempting to write a program for a school project, where I need to make an interface on a linux-based platform, in which I can click a button, that'll then run a set of commands on a raspberry pi connected via wifi.

The RPI is connected via SSH and the wifi network is one created from my own router on which both the PC and the raspberry are the only ones connected. I've given the RPI a static IP adress, so connecting to it outside of QT isn't an issue.

My issue is, that I'm having trouble finding a way to execute even a single command on the RPI using a button in QT.

答:
Use system() to execute a command inside the button's callback function.

Example:

```<code>system("ssh raspi \"/bin/echo hello world > file.txt\"");
</code>```

Body:
Use system() to execute a command inside the button's callback function.

Example:

system("ssh raspi \"/bin/echo hello world > file.txt\"");


问:
Best practice designing REST API to get and send multiple files with spring boot
I have a requirement to have a service for many files on my request (uploading) and many files on my response (downloading).

Something like that:

```<code>@PostMapping("upload")
public MultipartFile uploadFiles(MultipartFile[] files) {}

@PostMapping("download")
public MultipartFile[] uploadFiles(MultipartFile file) {}
</code>```

I need the filename, content-type and ByteStream for every "attachment".
Zipping is no solution.

I want to do that with the Spring framework. But it is possible to use other frameworks.

Does anybody know how to do that?

答:
```<code>@PostMapping("/upload")
public String handleFileUpload(@RequestParam("file") MultipartFile file,
        RedirectAttributes redirectAttributes) {

    storageService.store(file);
    redirectAttributes.addFlashAttribute("message",
            "You successfully uploaded " + file.getOriginalFilename() + "!");

    return "redirect:/";
}
</code>```

Body:
I have a requirement to have a service for many files on my request (uploading) and many files on my response (downloading).

Something like that:

@PostMapping("upload")
public MultipartFile uploadFiles(MultipartFile[] files) {}

@PostMapping("download")
public MultipartFile[] uploadFiles(MultipartFile file) {}

I need the filename, content-type and ByteStream for every "attachment".
Zipping is no solution.

I want to do that with the Spring framework. But it is possible to use other frameworks.

Does anybody know how to do that?


问:
Icon is loaded, but not shown (html, css)
I have an icon which is actually on my webpage but I still cant see it.

HTML

```<code><i class="iconMan"></i>
</code>```

CSS

```<code>.iconMan{
    background-image: url(../../assets/imgs/iconMan.png);
    display: block;
  }
</code>```

this is what I get:

The Icon should be next to "Test User" but it's not showing. I already tried adjusting height and width but it didn't work.
Any suggestions what I could do?

答:
for displaying an icon you can move your styling to the ::after or ::before pseudo selectors.

```<code>.iconMan {
    display: inline-block;
}

.iconMan::before {
    content: url(../../assets/imgs/iconMan.png);
}
</code>```

Body:
I have an icon which is actually on my webpage but I still cant see it.

HTML

CSS

.iconMan{
    background-image: url(../../assets/imgs/iconMan.png);
    display: block;
  }

this is what I get:

The Icon should be next to "Test User" but it's not showing. I already tried adjusting height and width but it didn't work.
Any suggestions what I could do?

Body:
for displaying an icon you can move your styling to the ::after or ::before pseudo selectors.

.iconMan {
    display: inline-block;
}

.iconMan::before {
    content: url(../../assets/imgs/iconMan.png);
}


问:
oracle update trigger using case/if
I want to update a table with sort of a status. the status should be displayed using three traffic-light-pictures. I successfully made a view which fills the corresponding traffic-light-picture (filepath) depending on the other attributes. (ampel_rot.jpg is a red traffic-light, ampel_gelb.jpg is a yellow traffic-light, *ampel_gruen.jpg is a green traffic-light)

```<code>case when (L.STATUS = 'Aktiv' AND (((select count(*) from INFOVERSAND_FILES I where I.FID_BAUGESUCH=L.FID) = 0) AND ((select count(*) from ENTWAESSERUNGSPLAN_FILES E where E.FID_BAUGESUCH=L.FID)= 0)  AND ((select count(*) from DOKKTV_FILES K where K.FID_BAUGESUCH=L.FID) = 0) AND L.ABWASSER_EINMASS is NULL AND  L.ABWASSER_ABNAHME is NULL AND  L.PAW is NULL AND  L.DOK_K_TV is NULL AND  L.DICHTHEITSPRUEFUNG is NULL AND  L.SANIERUNGSVERFUEGUNG is NULL AND  L.NACHPRUEFUNG is NULL AND  L.ABSCHLUSS is NULL AND  L.KOMMENTAR is NULL)) then 'C:\Temp\Ampel_rot.jpg'
when (L.STATUS = 'Aktiv' AND (((select count(*) from INFOVERSAND_FILES I where I.FID_BAUGESUCH=L.FID) > 0) OR ((select count(*) from ENTWAESSERUNGSPLAN_FILES E where E.FID_BAUGESUCH=L.FID)> 0)  OR ((select count(*) from DOKKTV_FILES K where K.FID_BAUGESUCH=L.FID) > 0) OR L.ABWASSER_EINMASS is not NULL OR L.ABWASSER_ABNAHME is not NULL OR L.PAW is not NULL OR L.DOK_K_TV is not NULL OR L.DICHTHEITSPRUEFUNG is not NULL OR L.SANIERUNGSVERFUEGUNG is not NULL OR L.NACHPRUEFUNG is not NULL OR L.ABSCHLUSS is not NULL OR L.KOMMENTAR is not NULL) AND L.ABSCHLUSS is NULL AND L.ABSCHLUSS_ZUSATZ is NULL) then 'C:\Temp\Ampel_gelb.jpg'
when (L.ABSCHLUSS is not NULL OR L.ABSCHLUSS_ZUSATZ is not NULL) then 'C:\Temp\Ampel_gruen.jpg' end as Ampel
from LIEGENSCHAFT L
</code>```

Unfortunately I need these traffic-light-filepaths in the table directly, as
views are read-only.
So I tried to write another update-trigger, with no success so far:

I tried with IF:

```<code>create or replace
  TRIGGER LS_STATUS
  before UPDATE ON LIEGENSCHAFT
  for each row
  DECLARE
  AMP VARCHAR2(50) := 'C:\Temp\Ampel_rot'
  BEGIN
  if :new.STATUS = 'Aktiv' AND (:new.ABWASSER_EINMASS is NULL AND :new.ABWASSER_ABNAHME is NULL AND :new.PAW is NULL AND :new.DOK_K_TV is NULL AND :new.DICHTHEITSPRUEFUNG is NULL AND :new.SANIERUNGSVERFUEGUNG is NULL AND :new.NACHPRUEFUNG is NULL AND :new.ABSCHLUSS is NULL AND :new.KOMMENTAR is NULL)) then AMP:='C:\Temp\Ampel_rot.jpg' else 'leer' END IF;
  :NEW.AMPEL := AMP;
  END;
</code>```

and also using case:

```<code>create or replace
  TRIGGER LS_STATUS
  before UPDATE ON LIEGENSCHAFT
  for each row
  DECLARE
  AMP VARCHAR2(50) := 'C:\Temp\Ampel_rot'
  BEGIN
  AMP := select case when :new.STATUS = 'Aktiv' AND (:new.ABWASSER_EINMASS is NULL AND  :new.ABWASSER_ABNAHME is NULL AND :new.PAW is NULL AND  :new.DOK_K_TV is NULL AND  :new.DICHTHEITSPRUEFUNG is NULL AND  :new.SANIERUNGSVERFUEGUNG is NULL AND  :new.NACHPRUEFUNG is NULL AND  :new.ABSCHLUSS is NULL AND  :new.KOMMENTAR is NULL)) then 'C:\Temp\Ampel_rot.jpg' else 'leer' END;
:NEW.AMPEL := AMP;
END;
</code>```

I only tried to do the red traffic-light to begin. When this works, I can add the other definitions...

答:
Oh, you have several syntax errors. If you format your code, they'd be more obvious. You also might try using an IDE with syntax highlighting, like SQL Developer or TOAD, which will point out these kind of problems.

See my comments below. In the first one:

```<code>create or replace
  TRIGGER LS_STATUS
  before UPDATE ON LIEGENSCHAFT
  for each row
  DECLARE
    AMP VARCHAR2(50) := 'C:\Temp\Ampel_rot' -- missing ; at end
  BEGIN
  if :new.STATUS = 'Aktiv' AND
    (:new.ABWASSER_EINMASS is NULL
     AND :new.ABWASSER_ABNAHME is NULL
     AND :new.PAW is NULL
     AND :new.DOK_K_TV is NULL
     AND :new.DICHTHEITSPRUEFUNG is NULL
     AND :new.SANIERUNGSVERFUEGUNG is NULL
     AND :new.NACHPRUEFUNG is NULL
     AND :new.ABSCHLUSS is NULL
     AND :new.KOMMENTAR is NULL)
     ) -- what's this? no matching left parenthesis.
  then
     AMP:='C:\Temp\Ampel_rot.jpg' -- missing ;
  else
     'leer' -- also what's this? It should be "AMP:='leer';"
  END IF;
  :NEW.AMPEL := AMP;
END;
</code>```

And in the second one:

```<code>create or replace
  TRIGGER LS_STATUS
  before UPDATE ON LIEGENSCHAFT
  for each row
  DECLARE
    AMP VARCHAR2(50) := 'C:\Temp\Ampel_rot' -- missing ; at end
  BEGIN
  AMP := select -- if you want a select, put 'from dual' at the end. but a select isn't needed here.
    case
    when :new.STATUS = 'Aktiv'
        AND (:new.ABWASSER_EINMASS is NULL
            AND  :new.ABWASSER_ABNAHME is NULL
            AND :new.PAW is NULL
            AND  :new.DOK_K_TV is NULL
            AND  :new.DICHTHEITSPRUEFUNG is NULL
            AND  :new.SANIERUNGSVERFUEGUNG is NULL
            AND  :new.NACHPRUEFUNG is NULL
            AND  :new.ABSCHLUSS is NULL
            AND  :new.KOMMENTAR is NULL)
        ) -- also no matching left paren
    then 'C:\Temp\Ampel_rot.jpg'
    else 'leer'
    END;
:NEW.AMPEL := AMP;
END;
</code>```

Title: oracle update trigger using case/if

Body:
I want to update a table with sort of a status. the status should be displayed using three traffic-light-pictures. I successfully made a view which fills the corresponding traffic-light-picture (filepath) depending on the other attributes. (ampel_rot.jpg is a red traffic-light, ampel_gelb.jpg is a yellow traffic-light, *ampel_gruen.jpg is a green traffic-light)

case when (L.STATUS = 'Aktiv' AND (((select count(*) from INFOVERSAND_FILES I where I.FID_BAUGESUCH=L.FID) = 0) AND ((select count(*) from ENTWAESSERUNGSPLAN_FILES E where E.FID_BAUGESUCH=L.FID)= 0)  AND ((select count(*) from DOKKTV_FILES K where K.FID_BAUGESUCH=L.FID) = 0) AND L.ABWASSER_EINMASS is NULL AND  L.ABWASSER_ABNAHME is NULL AND  L.PAW is NULL AND  L.DOK_K_TV is NULL AND  L.DICHTHEITSPRUEFUNG is NULL AND  L.SANIERUNGSVERFUEGUNG is NULL AND  L.NACHPRUEFUNG is NULL AND  L.ABSCHLUSS is NULL AND  L.KOMMENTAR is NULL)) then 'C:\Temp\Ampel_rot.jpg'
when (L.STATUS = 'Aktiv' AND (((select count(*) from INFOVERSAND_FILES I where I.FID_BAUGESUCH=L.FID) > 0) OR ((select count(*) from ENTWAESSERUNGSPLAN_FILES E where E.FID_BAUGESUCH=L.FID)> 0)  OR ((select count(*) from DOKKTV_FILES K where K.FID_BAUGESUCH=L.FID) > 0) OR L.ABWASSER_EINMASS is not NULL OR L.ABWASSER_ABNAHME is not NULL OR L.PAW is not NULL OR L.DOK_K_TV is not NULL OR L.DICHTHEITSPRUEFUNG is not NULL OR L.SANIERUNGSVERFUEGUNG is not NULL OR L.NACHPRUEFUNG is not NULL OR L.ABSCHLUSS is not NULL OR L.KOMMENTAR is not NULL) AND L.ABSCHLUSS is NULL AND L.ABSCHLUSS_ZUSATZ is NULL) then 'C:\Temp\Ampel_gelb.jpg'
when (L.ABSCHLUSS is not NULL OR L.ABSCHLUSS_ZUSATZ is not NULL) then 'C:\Temp\Ampel_gruen.jpg' end as Ampel
from LIEGENSCHAFT L

Unfortunately I need these traffic-light-filepaths in the table directly, as
views are read-only.
So I tried to write another update-trigger, with no success so far:

I tried with IF:

create or replace
  TRIGGER LS_STATUS
  before UPDATE ON LIEGENSCHAFT
  for each row
  DECLARE
  AMP VARCHAR2(50) := 'C:\Temp\Ampel_rot'
  BEGIN
  if :new.STATUS = 'Aktiv' AND (:new.ABWASSER_EINMASS is NULL AND :new.ABWASSER_ABNAHME is NULL AND :new.PAW is NULL AND :new.DOK_K_TV is NULL AND :new.DICHTHEITSPRUEFUNG is NULL AND :new.SANIERUNGSVERFUEGUNG is NULL AND :new.NACHPRUEFUNG is NULL AND :new.ABSCHLUSS is NULL AND :new.KOMMENTAR is NULL)) then AMP:='C:\Temp\Ampel_rot.jpg' else 'leer' END IF;
  :NEW.AMPEL := AMP;
  END;

and also using case:

create or replace
  TRIGGER LS_STATUS
  before UPDATE ON LIEGENSCHAFT
  for each row
  DECLARE
  AMP VARCHAR2(50) := 'C:\Temp\Ampel_rot'
  BEGIN
  AMP := select case when :new.STATUS = 'Aktiv' AND (:new.ABWASSER_EINMASS is NULL AND  :new.ABWASSER_ABNAHME is NULL AND :new.PAW is NULL AND  :new.DOK_K_TV is NULL AND  :new.DICHTHEITSPRUEFUNG is NULL AND  :new.SANIERUNGSVERFUEGUNG is NULL AND  :new.NACHPRUEFUNG is NULL AND  :new.ABSCHLUSS is NULL AND  :new.KOMMENTAR is NULL)) then 'C:\Temp\Ampel_rot.jpg' else 'leer' END;
:NEW.AMPEL := AMP;
END;

I only tried to do the red traffic-light to begin. When this works, I can add the other definitions...

Body:
Oh, you have several syntax errors. If you format your code, they'd be more obvious. You also might try using an IDE with syntax highlighting, like SQL Developer or TOAD, which will point out these kind of problems.

See my comments below. In the first one:

create or replace
  TRIGGER LS_STATUS
  before UPDATE ON LIEGENSCHAFT
  for each row
  DECLARE
    AMP VARCHAR2(50) := 'C:\Temp\Ampel_rot' -- missing ; at end
  BEGIN
  if :new.STATUS = 'Aktiv' AND
    (:new.ABWASSER_EINMASS is NULL
     AND :new.ABWASSER_ABNAHME is NULL
     AND :new.PAW is NULL
     AND :new.DOK_K_TV is NULL
     AND :new.DICHTHEITSPRUEFUNG is NULL
     AND :new.SANIERUNGSVERFUEGUNG is NULL
     AND :new.NACHPRUEFUNG is NULL
     AND :new.ABSCHLUSS is NULL
     AND :new.KOMMENTAR is NULL)
     ) -- what's this? no matching left parenthesis.
  then
     AMP:='C:\Temp\Ampel_rot.jpg' -- missing ;
  else
     'leer' -- also what's this? It should be "AMP:='leer';"
  END IF;
  :NEW.AMPEL := AMP;
END;

And in the second one:

create or replace
  TRIGGER LS_STATUS
  before UPDATE ON LIEGENSCHAFT
  for each row
  DECLARE
    AMP VARCHAR2(50) := 'C:\Temp\Ampel_rot' -- missing ; at end
  BEGIN
  AMP := select -- if you want a select, put 'from dual' at the end. but a select isn't needed here.
    case
    when :new.STATUS = 'Aktiv'
        AND (:new.ABWASSER_EINMASS is NULL
            AND  :new.ABWASSER_ABNAHME is NULL
            AND :new.PAW is NULL
            AND  :new.DOK_K_TV is NULL
            AND  :new.DICHTHEITSPRUEFUNG is NULL
            AND  :new.SANIERUNGSVERFUEGUNG is NULL
            AND  :new.NACHPRUEFUNG is NULL
            AND  :new.ABSCHLUSS is NULL
            AND  :new.KOMMENTAR is NULL)
        ) -- also no matching left paren
    then 'C:\Temp\Ampel_rot.jpg'
    else 'leer'
    END;
:NEW.AMPEL := AMP;
END;