问:
Nested objects in javascript how to freeze it?
I am trying to freeze javascript nested object. As I am new to JS I am facing difficulty to freeze the nested objects.

```<code>const obj = { prop: { innerProp: 1 } };
obj.prop.innerProp = 5;
console.log(obj.prop.innerProp); // 5
</code>```

Is it possible do freeze nested objects?

答:
You can use the following example to freeze nested objects</p>

```<code>function deepFreeze (o) {
Object.freeze(o);
if (o === undefined) {
return o;
}

Object.getOwnPropertyNames(o).forEach(function (prop) {
if (o[prop] !== null
&& (typeof o[prop] === "object" || typeof o[prop] === "function")
&& !Object.isFrozen(o[prop])) {
  deepFreeze(o[prop]);
}
});

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

Body:
I am trying to freeze javascript nested object. As I am new to JS I am facing difficulty to freeze the nested objects.

const obj = { prop: { innerProp: 1 } };
obj.prop.innerProp = 5;
console.log(obj.prop.innerProp); // 5

Is it possible do freeze nested objects?

Body:
You can use the following example to freeze nested objects

function deepFreeze (o) {
Object.freeze(o);
if (o === undefined) {
return o;
}

Object.getOwnPropertyNames(o).forEach(function (prop) {
if (o[prop] !== null
&& (typeof o[prop] === "object" || typeof o[prop] === "function")
&& !Object.isFrozen(o[prop])) {
  deepFreeze(o[prop]);
}
});

return o;
};


来源: stackexchange

问:
Better SQL Replace
I wanted to know if there is a better way of writing this Update.

```<code>update Alumni_Export_New
set phone = replace(replace(replace(replace(phone,'-',''),' ',''),')',''),'(','')
from tbl
</code>```

I have a stored procedure in MSSQL 2005 to clean the phone field in a table and thought there should be a better way of doing this then what I have.

答:
You can consider putting the replace logic in a user defined function if you really don't like the look the REPLACE and if you don't mind a performance hit.  Otherwise, what you have is probably your best solution.

Sample:

```<code>UPDATE Alumni_Export_New
SET phone = dbo.StripPhoneNumber(phone)
FROM tbl
</code>```

ContentLicense: CC BY-SA 2.5

Title: Better SQL Replace

Body:
I wanted to know if there is a better way of writing this Update.

update Alumni_Export_New
set phone = replace(replace(replace(replace(phone,'-',''),' ',''),')',''),'(','')
from tbl

I have a stored procedure in MSSQL 2005 to clean the phone field in a table and thought there should be a better way of doing this then what I have.

Body:
You can consider putting the replace logic in a user defined function if you really don't like the look the REPLACE and if you don't mind a performance hit.  Otherwise, what you have is probably your best solution.

Sample:

UPDATE Alumni_Export_New
SET phone = dbo.StripPhoneNumber(phone)
FROM tbl


问:
How to remove id in url
now i face a problem with user will see the popout with "update sucessfully" if he reload the page or backward to the page.Anyone having idea of how to remove ?id=2 after click ok on pop out?

Here is my code:

update_action.php

```<code>$updresult = mysqli_query($conn, $sqlu);

    if (!$updresult)
        echo "Unable to update record". mysqli_error($conn);
    else
    {
        header('Location: index.php?id=2' );
        mysqli_close($conn);
    }
    ?>
</code>```

index.php

```<code>if ($id == 1)
    {
    ?>
        <script>
            alert("Invalid user name or password, Try again");
        </script>
    <?php
    }
        else if($error_id == 2)
    {
    ?>
        <script>
            alert("Update Sucessfully!");
        </script>
    <?php
    }
</code>```

the url show index.php?id=2

答:
What you need is to change the url with javascript without reloading the page.

Check out: https://wiki.selfhtml.org/wiki/JavaScript/History/pushState

You can put this after your alert/confirm

```<code>// Remove the "?.." from the url
var url = [location.protocol, '//', location.host, location.pathname].join('');
// maybe check if the browser supports history.pushState
history.pushState({}, '', url);
</code>```

ContentLicense: CC BY-SA 3.0

Title: How to remove id in url

Body:
now i face a problem with user will see the popout with "update sucessfully" if he reload the page or backward to the page.Anyone having idea of how to remove ?id=2 after click ok on pop out?

Here is my code:

update_action.php

$updresult = mysqli_query($conn, $sqlu);

    if (!$updresult)
        echo "Unable to update record". mysqli_error($conn);
    else
    {
        header('Location: index.php?id=2' );
        mysqli_close($conn);
    }
    ?>

index.php

if ($id == 1)
    {
    ?>

    <?php
    }
        else if($error_id == 2)
    {
    ?>

    <?php
    }

the url show index.php?id=2

Body:
What you need is to change the url with javascript without reloading the page.

Check out: https://wiki.selfhtml.org/wiki/JavaScript/History/pushState

You can put this after your alert/confirm

// Remove the "?.." from the url
var url = [location.protocol, '//', location.host, location.pathname].join('');
// maybe check if the browser supports history.pushState
history.pushState({}, '', url);


问:
Javascript extract object names to an array
How do I get object names to an array in JavaScript? </p>

```<code>{
    "Ford F-150": [
        {
            "year": 2007,
            "model": "Ford F-150"
        },
        {
            "year": 2007,
            "model": "Ford F-150"
        },
        {
            "year": 2007,
            "model": "Ford F-150"
        }
    ],
    "Toyota Camry": [
        {
            "year": 2011,
            "model": "Toyota Camry"
        }
    ],
    "Dodge RAM": [
        {
            "year": 2005,
            "model": "Dodge RAM"
        }
    ]
}
</code>```

<p>I expect the result like </p>

```<code>var result = ["Ford F-150", "Toyota Camry", "Dodge RAM"]
</code>```

答:
Use this property to access the keys of your object</p>

```<code>Object.keys(your_obj);
</code>```

Body:
How do I get object names to an array in JavaScript?

{
    "Ford F-150": [
        {
            "year": 2007,
            "model": "Ford F-150"
        },
        {
            "year": 2007,
            "model": "Ford F-150"
        },
        {
            "year": 2007,
            "model": "Ford F-150"
        }
    ],
    "Toyota Camry": [
        {
            "year": 2011,
            "model": "Toyota Camry"
        }
    ],
    "Dodge RAM": [
        {
            "year": 2005,
            "model": "Dodge RAM"
        }
    ]
}

I expect the result like

var result = ["Ford F-150", "Toyota Camry", "Dodge RAM"]

Body:
Use this property to access the keys of your object

Object.keys(your_obj);


问:
Solr Setup - Error: Could not find or load main class org.apache.solr.util.SolrCLI
Trying to setup solr 6.4.1 on Windows Server 2008 with JDK 64bit 1.8.0

Having set system environment-variables:

```<code>CLASSPATH = "C:\solr-6.4.1\dist\solr-core-6.4.1.jar"
JAVA_HOME = C:\Program Files\Java\jdk1.8.0_121
PATH = "...;C:\Program Files\Java\jdk1.8.0_121\bin"
</code>```

When trying to start via cmd (as admin) "solr start -p 8984" following error message appears:

```<code>Error: Could not find or load main class org.apache.solr.util.SolrCLI
Failed removing old solr logs (...)
</code>```

I have unzipped solr-core.6.4.1.jar and SolrCLI is actually in it.

答:
Make sure you've downloaded and unzipped the correct package:

Correct package "solr-6.5.0.tgz" usually weighs 140Mb

Incorrect package to run the server "solr-6.5.0-src.tgz" (resources to compile)

Body:
Trying to setup solr 6.4.1 on Windows Server 2008 with JDK 64bit 1.8.0

Having set system environment-variables:

CLASSPATH = "C:\solr-6.4.1\dist\solr-core-6.4.1.jar"
JAVA_HOME = C:\Program Files\Java\jdk1.8.0_121
PATH = "...;C:\Program Files\Java\jdk1.8.0_121\bin"

When trying to start via cmd (as admin) "solr start -p 8984" following error message appears:

Error: Could not find or load main class org.apache.solr.util.SolrCLI
Failed removing old solr logs (...)

I have unzipped solr-core.6.4.1.jar and SolrCLI is actually in it.


问:
vlookup but the name of the cell that will return not the value in the cell
just like to ask if you know a formula like in the vlookup style but the cell name that it will return not the value of the cell? thanks!

I want to put the value of sal in the Application.WorksheetFunction.VLookup(name, Sheet2.Range("Table6"), 5, False) but in this function the value inside the cell will return not the name of the cell

```<code>Sub purchase()

Dim name As String
name = ActiveSheet.Range("C3")
sal = Application.WorksheetFunction.VLookup(name, Sheet2.Range("Table6"), 5, False) - ActiveSheet.Range("d3").Value

MsgBox " remaining: " & sal

End Sub
</code>```

答:
VLookup only returns a value. You will need the match function. This will return the row number which you can use to access the desired cells.

```<code>Sub purchase()
    Dim Name As String
    Name = ActiveSheet.Range("C3")

    Dim MatchedRow As Long
    MatchedRow = Application.WorksheetFunction.Match(Name, Sheet2.Range("Table6").Columns(1), 0)
      'Find the row number (relative to the range table6) of the found name

    Dim Sal As Double
    Sal = Sheet2.Range("Table6").Cells(MatchedRow, 5).Value - ActiveSheet.Range("D3").Value

    Sheet2.Range("Table6").Cells(MatchedRow, 5).Value = Sal
      'Write the calculated Sal back

    MsgBox " remaining: " & Sal
End Sub
</code>```

Body:
just like to ask if you know a formula like in the vlookup style but the cell name that it will return not the value of the cell? thanks!

I want to put the value of sal in the Application.WorksheetFunction.VLookup(name, Sheet2.Range("Table6"), 5, False) but in this function the value inside the cell will return not the name of the cell

Sub purchase()

Dim name As String
name = ActiveSheet.Range("C3")
sal = Application.WorksheetFunction.VLookup(name, Sheet2.Range("Table6"), 5, False) - ActiveSheet.Range("d3").Value

MsgBox " remaining: " & sal

End Sub

Body:
VLookup only returns a value. You will need the match function. This will return the row number which you can use to access the desired cells.

Sub purchase()
    Dim Name As String
    Name = ActiveSheet.Range("C3")

    Dim MatchedRow As Long
    MatchedRow = Application.WorksheetFunction.Match(Name, Sheet2.Range("Table6").Columns(1), 0)
      'Find the row number (relative to the range table6) of the found name

    Dim Sal As Double
    Sal = Sheet2.Range("Table6").Cells(MatchedRow, 5).Value - ActiveSheet.Range("D3").Value

    Sheet2.Range("Table6").Cells(MatchedRow, 5).Value = Sal
      'Write the calculated Sal back

    MsgBox " remaining: " & Sal
End Sub


问:
Error to build a android app with cordova
I've had this problem when build a android app with cordova command:

```<code>cordova build android

D:\Desenvolvimento\ionicapps\AppBelle>cordova build android Running command: "C:\Program Files\nodejs\node.exe"
D:\Desenvolvimento\ionicapps \AppBelle\hooks\after_prepare\010_add_platform_class.js D:\Desenvolvimento\ionic apps\AppBelle add to body class: platform-android
Running command: "C:\Program Files\nodejs\node.exe" D:\Desenvolvimento\ionicapps \AppBelle\hooks\after_prepare\020_remove_sass_from_platforms.js D:\Desenvolvimen to\ionicapps\AppBelle
Running command: D:\Desenvolvimento\ionicapps\AppBelle\platforms\android\cordova \build.bat [Error: Android SDK not found. Make sure that it is installed. If it is not at t he default location, set the ANDROID_HOME environment variable.]
ERROR building one of the platforms:
Error: D:\Desenvolvimento\ionicapps\AppBell e\platforms\android\cordova\build.bat: Command failed with exit code 2 You may not have the required environment or OS to build this project
Error: D:\Desenvolvimento\ionicapps\AppBelle\platforms\android\cordova\build.bat : Command failed with exit code 2 at ChildProcess.whenDone (C:\Users\Victor\AppData\Roaming\npm\node_modules\c ordova\node_modules\cordova-lib\src\cordova\superspawn.js:131:23) at ChildProcess.emit (events.js:98:17) at maybeClose (child_process.js:756:16) at Process.ChildProcess._handle.onexit (child_process.js:823:5)

D:\Desenvolvimento\ionicapps\AppBelle>echo %ANDROID_HOME% C:\Users\Victor\AppData\Local\Android\sdk\
</code>```

Above I show location of env var  ANDROID_HOME . I don't know what to do.

Help me, please.

Thanks

答:
Unfortunately this can be a bug caused by upgrading android SDK versions. In general look for for different reasons:

First if you have to set the ANDROID_HOME environment variable.  (according to your OS - In windows , right click your PC icon "MY PC", --> properties -> Advanced system settings -> Environment Variables" and set ANDROID_HOME variable and edit PATH variable to your path to your android SDK, tools & platform tools.

Secound try the "android" command in command tool, if android sdk couldn't open it cause a problem to build your app. I got this error:

The "android" command is no longer available.
For manual SDK and AVD management, please use Android Studio.
For command-line tools, use
tools\bin\sdkmanager.bat and tools\bin\avdmanager.bat

to solve it, you should downgrade your sdk using this links:
(Mac) https://dl.google.com/android/repository/tools_r25.2.3-macosx.zip
(Windows) https://dl.google.com/android/repository/tools_r25.2.3-windows.zip

and replace the zip file with your "tools" folder in your android SDK, It will work fine after trying "android" command and building app command in cordova and ionic frameworks.

Digging the reason: (In my case)

Why failing android command is causing this problem?

part of the cordova or ionic configuration in js files are using android command to "VERIFY" your "ANDROID_HOME" and "PATH" environment variables to operate building your app, and in case of any failure accessing to Android sdk via command access, system tells you "Android SDK" is not found. Recently, in new version android command is no longer accessible and is causing issues for any operation whom used this command. :/

Hope it works for you, It took a time for me to figure out solving this issue and don't forget to (+1) if it helped you!

Body:
I've had this problem when build a android app with cordova command:

cordova build android

D:\Desenvolvimento\ionicapps\AppBelle>cordova build android Running command: "C:\Program Files\nodejs\node.exe"
D:\Desenvolvimento\ionicapps \AppBelle\hooks\after_prepare\010_add_platform_class.js D:\Desenvolvimento\ionic apps\AppBelle add to body class: platform-android
Running command: "C:\Program Files\nodejs\node.exe" D:\Desenvolvimento\ionicapps \AppBelle\hooks\after_prepare\020_remove_sass_from_platforms.js D:\Desenvolvimen to\ionicapps\AppBelle
Running command: D:\Desenvolvimento\ionicapps\AppBelle\platforms\android\cordova \build.bat [Error: Android SDK not found. Make sure that it is installed. If it is not at t he default location, set the ANDROID_HOME environment variable.]
ERROR building one of the platforms:
Error: D:\Desenvolvimento\ionicapps\AppBell e\platforms\android\cordova\build.bat: Command failed with exit code 2 You may not have the required environment or OS to build this project
Error: D:\Desenvolvimento\ionicapps\AppBelle\platforms\android\cordova\build.bat : Command failed with exit code 2 at ChildProcess.whenDone (C:\Users\Victor\AppData\Roaming\npm\node_modules\c ordova\node_modules\cordova-lib\src\cordova\superspawn.js:131:23) at ChildProcess.emit (events.js:98:17) at maybeClose (child_process.js:756:16) at Process.ChildProcess._handle.onexit (child_process.js:823:5)

D:\Desenvolvimento\ionicapps\AppBelle>echo %ANDROID_HOME% C:\Users\Victor\AppData\Local\Android\sdk\

Above I show location of env var  ANDROID_HOME . I don't know what to do.

Help me, please.

Thanks


问:
How to 'free' memory allocated to a variable in shell
```<code>function mem(){
local token
return $token
}

obj=$(ls)                      #list of object name
objstr=($obj)                  #array[i] whose ith element is object name
objno=$(echo "$obj" | wc -w)   #the number of object name

for i in $(seq 0 $(($objno-1)))
do
    objID=${objstr[$i]}    #object name
    IDlen=${#objID}        #length of object name
    for j in $(seq 0 $(($IDlen-1)))
    do
        subID=${objID:$j:1}        #charater in the name
        token=$(mem)               #allocate local variable returned
        token[0]+=$subID           #concatenate characters
    done
</code>```

I want to define a variable in which I can store an objects name.
(in a way that I can access each characters in the name)
But the most important thing is that it has to be disposable.
I want to 'free' the memory allocated to the variable before going on with another object name to minimize overhead.
So I defined a function, mem() which would return local variable.
If I initialize token[0] to the returned variable each time before I use it,
what happens to the memory previously allocated to the variable? Is it 'free'ed as intended?

答:
You don't free memory in the shell; there are no explicit ways to free such things as the storage for variables. That said, you could try

using local variables if your shell supports them; they may get freed when they go out of scope

unset NAME once you're done with NAME

Note that just like in C, this doesn't guarantee the memory is returned to the OS.

But then, why do you worry about memory for shell variables in the first place? What is your actual problem? If memory use and management is a constraint, maybe the shell is the wrong tool?

Body:
function mem(){
local token
return $token
}

obj=$(ls)                      #list of object name
objstr=($obj)                  #array[i] whose ith element is object name
objno=$(echo "$obj" | wc -w)   #the number of object name

for i in $(seq 0 $(($objno-1)))
do
    objID=${objstr[$i]}    #object name
    IDlen=${#objID}        #length of object name
    for j in $(seq 0 $(($IDlen-1)))
    do
        subID=${objID:$j:1}        #charater in the name
        token=$(mem)               #allocate local variable returned
        token[0]+=$subID           #concatenate characters
    done

I want to define a variable in which I can store an objects name.
(in a way that I can access each characters in the name)
But the most important thing is that it has to be disposable.
I want to 'free' the memory allocated to the variable before going on with another object name to minimize overhead.
So I defined a function, mem() which would return local variable.
If I initialize token[0] to the returned variable each time before I use it,
what happens to the memory previously allocated to the variable? Is it 'free'ed as intended?


问:
Change the size of a JTextField inside a JBorderLayout
When I use the code below it doesn't alter the size at all, it still fills the area in the grid.</p>

```<code>JPanel displayPanel = new JPanel(new GridLayout(4, 2));

JTextField titleText = new JTextField("title");

displayPanel.add(titleText);

titleText.setSize(200, 24);
</code>```

答:
From the api on GridLayout:

The container is divided into
  equal-sized rectangles, and one
  component is placed in each rectangle.

Try using FlowLayout or GridBagLayout for your set size to be meaningful. Also, @Serplat is correct. You need to use setPreferredSize( Dimension ) instead of setSize( int, int ).

```<code>    JPanel displayPanel = new JPanel();
    // JPanel displayPanel = new JPanel( new GridLayout( 4, 2 ) );
    // JPanel displayPanel = new JPanel( new BorderLayout() );
    // JPanel displayPanel = new JPanel( new GridBagLayout() );

    JTextField titleText = new JTextField( "title" );

    titleText.setPreferredSize( new Dimension( 200, 24 ) );

    // For FlowLayout and GridLayout, uncomment:
    displayPanel.add( titleText );

    // For BorderLayout, uncomment:
    // displayPanel.add( titleText, BorderLayout.NORTH );

    // For GridBagLayout, uncomment:
    // displayPanel.add( titleText, new GridBagConstraints( 0, 0, 1, 1, 1.0,
    // 1.0, GridBagConstraints.CENTER, GridBagConstraints.NONE,
    // new Insets( 0, 0, 0, 0 ), 0, 0 ) );
</code>```

Body:
When I use the code below it doesn't alter the size at all, it still fills the area in the grid.

JPanel displayPanel = new JPanel(new GridLayout(4, 2));

JTextField titleText = new JTextField("title");

displayPanel.add(titleText);

titleText.setSize(200, 24);

Body:
From the api on GridLayout:

The container is divided into
  equal-sized rectangles, and one
  component is placed in each rectangle.

Try using FlowLayout or GridBagLayout for your set size to be meaningful. Also, @Serplat is correct. You need to use setPreferredSize( Dimension ) instead of setSize( int, int ).

    JPanel displayPanel = new JPanel();
    // JPanel displayPanel = new JPanel( new GridLayout( 4, 2 ) );
    // JPanel displayPanel = new JPanel( new BorderLayout() );
    // JPanel displayPanel = new JPanel( new GridBagLayout() );

    JTextField titleText = new JTextField( "title" );

    titleText.setPreferredSize( new Dimension( 200, 24 ) );

    // For FlowLayout and GridLayout, uncomment:
    displayPanel.add( titleText );

    // For BorderLayout, uncomment:
    // displayPanel.add( titleText, BorderLayout.NORTH );

    // For GridBagLayout, uncomment:
    // displayPanel.add( titleText, new GridBagConstraints( 0, 0, 1, 1, 1.0,
    // 1.0, GridBagConstraints.CENTER, GridBagConstraints.NONE,
    // new Insets( 0, 0, 0, 0 ), 0, 0 ) );


问:
Editing data in multiple columns from front-end
I have a table in the database, I can edit a column of particular row at a time. but, i want to edit multiple columns of a single row at a time with an option of edit and then save it to the database ,we can do it from back-end by editing in the database itself. But, i want to do it from front-end .Now i am able to display the data in the table. I am new to coding , so can anyone help me where to start for this particular task of editing multiple columns at the same time.
Here is the code for displaying the data..</p>

```<code><?php
include('db.php');
include 'header.php';
include 'gobacktomenu.php';
$TND_ID =  $_GET['TND_ID'];
$sql = "SELECT * FROM new_tnds WHERE TND_ID = ('".$TND_ID."')";
$result = $link->query($sql);
echo "<div style='overflow-x:auto;'><table border = '1'><font size = '2' face='verdana'>
<th>TND ID</th><th>Site name S1</th><th>Site name S2</th><th>Call sign S1</th><th>Idea ID S1</th><th>Call sign S2</th><th>Idea ID S2</th><th>Site to integrate</th><th>True azimuth (°) S1</th><th>True azimuth (°) S2</th><th>Pathlength (km)</th><th>TR Antenna diameter (m)</th><th>TR Antenna height (m) S1</th><th>TR Antenna height (m) S2</th><th>Channel ID S1</th><th>Channel ID S2</th><th>Design frequency S1</th><th>Design frequency S2</th><th>Polarization</th><th>Radio model</th><th>TX power (dBm)</th><th>Receive signal (dBm)</th><th>Planning Remarks</th><th>Projects Remarks Uploaded by</th><th>O & M Remarks Uploaded by</th><th>Planning Remarks Uploaded by</th><th>TXN NOC Remarks Uploaded by</th></tr>";

if ($result->num_rows > 0) {
    // output data of each row
    $row = $result->fetch_assoc();

        echo "<tr><td>".$row["TND_ID"]."</td><td>".$row["Site_name_S1"]."</td><td>".$row["Site_name_S2"]."</td><td>".$row["Call_sign_S1"]."</td><td>".$row["Idea_ID_S1"]."</td><td>".$row["Call_sign_S2"]."</td><td>".$row["Idea_ID_S2"]."</td><td>".$row["Site_to_integrate"]."</td><td>".$row["True_azimuth_S1"]."</td><td>".$row["True_azimuth_S2"]."</td><td>".$row["Path_length_(km)"]."</td><td>".$row["TR_Antenna_diameter_(m)_S1"]."</td><td>".$row["TR_Antenna_height_(m)_S1"]."</td><td>".$row["TR_Antenna_height_(m)_S2"]."</td><td>".$row["#1_Channel_ID_S1"]."</td><td>".$row["#1_Channel_ID_S2"]."</td><td>".$row["#1_Design_frequency_S1"]."</td><td>".$row["#1_Design_frequency_S2"]."</td><td>".$row["Polarization"]."</td><td>".$row["Radio_model_S1"]."</td><td>".$row["TX_power_(dBm)_S1"]."</td><td>".$row["Receive_signal_(dBm)_S1"]."</td><td>".$row["Planning_Remarks"]."</td><td>".$row["Projects_remarksupdated_user_name"]."</td><td>".$row["O_M_remarksupdated_user_name"]."</td><td>".$row["Planning_remarksupdated_user_name"]."</td><td>".$row["txn_noc_remarksupdated_user_name"]."</td></tr>";

}
echo "</table></div>";
$link->close();
?>
</code>```

答:
you can use this structure ,this can be used for editing 2 tables and multiple columns table a has columns (aid,a1,a2) table b has columns (bid,b1,b2) i know code looks little rough but just wrote it in 5 min to give you an idea</p>

```<code><?php
//this only executes when button is clicked
if (isset($_POST["submit"] && $_POST["submit"]!=""){
    $counta=$_POST["aid"];
    //loops through the posts inside here do your query with the set command
    //like "update a set a1='$a1',a2='$a2" where aid ='$_POST["aid'][$i]"

    for($i=0;$i<$count;$i++){
        $a1[$i]=$_POST["a1"][$i];
        $a2[$i]=$_POST["a2"][$i];
        //your query here
        }
    $countb=$_POST["bid"];
    //loops through the posts inside here do your query with the set command
    //like "update b set b1='$b1',b2='$b2" where aid ='$_POST["bid'][$i]"
    for($i=0;$i<$count;$i++){
        $a1[$i]=$_POST["a1"][$i];
        $a2[$i]=$_POST["a2"][$i];
        }
//now the part before the button gets clicked
//do your query to select data from database
?>

<html>
<body>
//creating loop inside html

<?php
$a=0;
while($rowa = mysql_fetch_assoc($resulta){
?>

//getting the input data
<input type="checkbox" name="aid[]" value="<?php echo $row["aid"]; ?>>
<label>a1</label>
<input type="text" name="a1[]" value="<?php echo $row["a1"]; ?>>
<label>a2</label>
<input type="text" name="a2[]" value="<?php echo $row["a2"]; ?>>
//ending the loop

<?php
$a++;
}
//b works the same as a
$b=0;
while($rowb = mysql_fetch_assoc($resultb){
?>

<input type="checkbox" name="bid[]" value="<?php echo $row["bid"]; ?>>
<label>b1</label>
<input type="text" name="b1[]" value="<?php echo $row["b1"]; ?>>
<label>b2</label>
<input type="text" name="b2[]" value="<?php echo $row["b2"]; ?>>

<?php
$b++;
}
?>

<input type="submit" name="submit" value="submit">
</body>
</html>
</code>```

Body:
I have a table in the database, I can edit a column of particular row at a time. but, i want to edit multiple columns of a single row at a time with an option of edit and then save it to the database ,we can do it from back-end by editing in the database itself. But, i want to do it from front-end .Now i am able to display the data in the table. I am new to coding , so can anyone help me where to start for this particular task of editing multiple columns at the same time.
Here is the code for displaying the data..

<?php
include('db.php');
include 'header.php';
include 'gobacktomenu.php';
$TND_ID =  $_GET['TND_ID'];
$sql = "SELECT * FROM new_tnds WHERE TND_ID = ('".$TND_ID."')";
$result = $link->query($sql);
echo "

TND ID	Site name S1	Site name S2	Call sign S1	Idea ID S1	Call sign S2	Idea ID S2	Site to integrate	True azimuth (°) S1	True azimuth (°) S2	Pathlength (km)	TR Antenna diameter (m)	TR Antenna height (m) S1	TR Antenna height (m) S2	Channel ID S1	Channel ID S2	Design frequency S1	Design frequency S2	Polarization	Radio model	TX power (dBm)	Receive signal (dBm)	Planning Remarks	Projects Remarks Uploaded by	O & M Remarks Uploaded by	Planning Remarks Uploaded by	TXN NOC Remarks Uploaded by
";

if ($result->num_rows > 0) {
    // output data of each row
    $row = $result->fetch_assoc();

        echo "
".$row["TND_ID"]."	".$row["Site_name_S1"]."	".$row["Site_name_S2"]."	".$row["Call_sign_S1"]."	".$row["Idea_ID_S1"]."	".$row["Call_sign_S2"]."	".$row["Idea_ID_S2"]."	".$row["Site_to_integrate"]."	".$row["True_azimuth_S1"]."	".$row["True_azimuth_S2"]."	".$row["Path_length_(km)"]."	".$row["TR_Antenna_diameter_(m)_S1"]."	".$row["TR_Antenna_height_(m)_S1"]."	".$row["TR_Antenna_height_(m)_S2"]."	".$row["#1_Channel_ID_S1"]."	".$row["#1_Channel_ID_S2"]."	".$row["#1_Design_frequency_S1"]."	".$row["#1_Design_frequency_S2"]."	".$row["Polarization"]."	".$row["Radio_model_S1"]."	".$row["TX_power_(dBm)_S1"]."	".$row["Receive_signal_(dBm)_S1"]."	".$row["Planning_Remarks"]."	".$row["Projects_remarksupdated_user_name"]."	".$row["O_M_remarksupdated_user_name"]."	".$row["Planning_remarksupdated_user_name"]."	".$row["txn_noc_remarksupdated_user_name"]."
";

}
echo "

";
$link->close();
?>

Body:
you can use this structure ,this can be used for editing 2 tables and multiple columns table a has columns (aid,a1,a2) table b has columns (bid,b1,b2) i know code looks little rough but just wrote it in 5 min to give you an idea

<?php
//this only executes when button is clicked
if (isset($_POST["submit"] && $_POST["submit"]!=""){
    $counta=$_POST["aid"];
    //loops through the posts inside here do your query with the set command
    //like "update a set a1='$a1',a2='$a2" where aid ='$_POST["aid'][$i]"

    for($i=0;$i<$count;$i++){
        $a1[$i]=$_POST["a1"][$i];
        $a2[$i]=$_POST["a2"][$i];
        //your query here
        }
    $countb=$_POST["bid"];
    //loops through the posts inside here do your query with the set command
    //like "update b set b1='$b1',b2='$b2" where aid ='$_POST["bid'][$i]"
    for($i=0;$i<$count;$i++){
        $a1[$i]=$_POST["a1"][$i];
        $a2[$i]=$_POST["a2"][$i];
        }
//now the part before the button gets clicked
//do your query to select data from database
?>

<html>
<body>
//creating loop inside html

<?php
$a=0;
while($rowa = mysql_fetch_assoc($resulta){
?>

//getting the input data
<input type="checkbox" name="aid[]" value="<?php echo $row["aid"]; ?>>
<label>a1</label>
<input type="text" name="a1[]" value="<?php echo $row["a1"]; ?>>
<label>a2</label>
<input type="text" name="a2[]" value="<?php echo $row["a2"]; ?>>
//ending the loop

<?php
$a++;
}
//b works the same as a
$b=0;
while($rowb = mysql_fetch_assoc($resultb){
?>

<input type="checkbox" name="bid[]" value="<?php echo $row["bid"]; ?>>
<label>b1</label>
<input type="text" name="b1[]" value="<?php echo $row["b1"]; ?>>
<label>b2</label>
<input type="text" name="b2[]" value="<?php echo $row["b2"]; ?>>

<?php
$b++;
}
?>

<input type="submit" name="submit" value="submit">
</body>
</html>


问:
Adding External Scripts to one Magento page
I have read up on this a bit, but still must be missing something.

I have a photo gallery page, and am using fancy box to show larger versions of the images on click. There are two scripts I need to add for fancybox, a jquery and fancybox script.

I have gone into the gallery xml page, and added this code into it so that it looks like this:

```<code>    <reference name="head">
        <action method="addJs">
            <type>jquery_js</type>
            <script>http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js</script>
        </action>
        <action method="addJs">
            <type>fancybox_js</type>
            <script>/fancybox/jquery.fancybox-1.3.4.pack.js</script>
        </action>

    </reference>

    <reference name="root">
        <action method="setTemplate">
            <template>page/1column.phtml</template>
</code>```

...

but then I don't know how to use them in my view. When I go to the page, I am still getting 404 errors for these scripts. I am probably missing some simple things as I've never tackled a magento issue before.

Thanks in advance,
Alyssa

答:
To call an external file in Magento layout XML you can add a block

```<code><reference name="head">
    <block type="core/text" name="jquery.cdn.whatever.you.want.to.call.it">
        <action method="setText">
            <text><![CDATA[<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script>]]></text>
        </action>
    </block>
</reference>
</code>```

For your local fancybox file, (I presume it's locally hosted?), it depends where you saved it, there's a root js folder, so if it's in there you can use:

```<code><action method="addJs">
    <script>fancybox/jquery.fancybox-1.3.4.pack.js</script>
</action>
</code>```

You don't need to a add <type> as addJs already defines it as a JS type and fancybox_js isn't an option as far as I'm aware for the  attribute, also note there's no / at the start, the script tag will add the path itself with a trailing slash.

If it's inside your theme folder you can use:

```<code><action method="addJs">
    <type>skin_js</type>
    <script>fancybox/jquery.fancybox-1.3.4.pack.js</script>
</action>
</code>```

This will look in your theme js folder for a referred file.

Body:
I have read up on this a bit, but still must be missing something.

I have a photo gallery page, and am using fancy box to show larger versions of the images on click. There are two scripts I need to add for fancybox, a jquery and fancybox script.

I have gone into the gallery xml page, and added this code into it so that it looks like this:

    <reference name="head">
        <action method="addJs">
            <type>jquery_js</type>

        </action>
        <action method="addJs">
            <type>fancybox_js</type>

        </action>

    </reference>

    <reference name="root">
        <action method="setTemplate">
            <template>page/1column.phtml</template>

...

but then I don't know how to use them in my view. When I go to the page, I am still getting 404 errors for these scripts. I am probably missing some simple things as I've never tackled a magento issue before.

Thanks in advance,
Alyssa

Body:
To call an external file in Magento layout XML you can add a block

<reference name="head">
    <block type="core/text" name="jquery.cdn.whatever.you.want.to.call.it">
        <action method="setText">
            <text><![CDATA[<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script>]]></text>
        </action>
    </block>
</reference>

For your local fancybox file, (I presume it's locally hosted?), it depends where you saved it, there's a root js folder, so if it's in there you can use:

<action method="addJs">
    <script>fancybox/jquery.fancybox-1.3.4.pack.js</script>
</action>

You don't need to a add <type> as addJs already defines it as a JS type and fancybox_js isn't an option as far as I'm aware for the  attribute, also note there's no / at the start, the script tag will add the path itself with a trailing slash.

If it's inside your theme folder you can use:

<action method="addJs">
    <type>skin_js</type>
    <script>fancybox/jquery.fancybox-1.3.4.pack.js</script>
</action>

This will look in your theme js folder for a referred file.


问:
Bug in Deleting Row on UITableView at Multiple time delete row
Two bug in this code.

First one when i delete Row in tableview delete last row not selected row.

Second Bug is when try to delete more than one row that time will delete successfully but when reload tableview Only one row deleted. Rest row will appear again.

```<code>- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
      return result.count;
    }
    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath : indexPath];
        if (!(cell == nil)) {
              name = (UILabel *)[cell viewWithTag:10];
              name.text = [result objectAtIndex : indexPath.row];
        }
        name.tag=indexPath.row;
            return cell;
    }
    - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
        return YES;
    }
    - (IBAction)action:(id)sender {
        [_myTableView setEditing:YES animated:YES];
    }
    - (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
    {
        return UITableViewCellEditingStyleDelete;
    }

    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath : indexPath];
        if (!(cell == nil)) {
              name = (UILabel *)[cell viewWithTag:10];
              name.text = [result objectAtIndex : indexPath.row];
        }
        name.tag=indexPath.row;
            return cell;
    }
    - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
        return YES;
    }

    - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle
forRowAtIndexPath:(NSIndexPath *)indexPath { if (editingStyle == UITableViewCellEditingStyleDelete) {

            [result removeObjectAtIndex:indexPath.row];
            [tableView reloadData];
            [spinner startAnimating];
            NSString *id = [profile objectForKey:@"user_id"];
            NSString *tb =tid;

            NSString *string = [NSString stringWithFormat:@"userid=%@&topiid=%@",id,tb];
            NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"myDeleteUrl"]];

            NSData *data = [string dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
            [request setHTTPMethod:@"POST"];
            [request setHTTPBody : data];
            NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration
defaultSessionConfiguration]]; [[session dataTaskWithRequest : request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {

                NSDictionary *JSON= [NSJSONSerialization JSONObjectWithData :data options :NSJSONReadingMutableContainers error: nil];

               NSArray *alertArray = [JSON objectForKey:@"deletebookmark"];

                for (NSDictionary *alert in alertArray ){

                    if ([[alert objectForKey:@"status"] isEqualToString:@"done"]) {
                        NSLog(@"done");
                         [spinner stopAnimating];
                   }
                    else{
                       NSLog(@"notDone");
                        [spinner stopAnimating];
                    }
                 }

            }]resume];

        }
    }
</code>```

答:
```<code>- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath : indexPath];

        if (!(cell == nil)) {
                        name = (UILabel *)[cell viewWithTag:10]; name.text = [result objectAtIndex : indexPath.row];
                    }
                    name.tag=indexPath.row;
                    return cell;
            }
</code>```

In this datasource method, you have used a "if" condition, and due to your cell is reusable cell, so you have to use the else part too in this data source method.

Like

```<code>- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
                UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath : indexPath];

if (!(cell == nil)) {
                    name = (UILabel *)[cell viewWithTag:10]; name.text = [result objectAtIndex : indexPath.row];
                }
               else{

                 name.tag=indexPath.row;
               }

                return cell;
        }
</code>```

Thanks

Body:
Two bug in this code.

First one when i delete Row in tableview delete last row not selected row.

Second Bug is when try to delete more than one row that time will delete successfully but when reload tableview Only one row deleted. Rest row will appear again.

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
      return result.count;
    }
    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath : indexPath];
        if (!(cell == nil)) {
              name = (UILabel *)[cell viewWithTag:10];
              name.text = [result objectAtIndex : indexPath.row];
        }
        name.tag=indexPath.row;
            return cell;
    }
    - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
        return YES;
    }
    - (IBAction)action:(id)sender {
        [_myTableView setEditing:YES animated:YES];
    }
    - (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
    {
        return UITableViewCellEditingStyleDelete;
    }

    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath : indexPath];
        if (!(cell == nil)) {
              name = (UILabel *)[cell viewWithTag:10];
              name.text = [result objectAtIndex : indexPath.row];
        }
        name.tag=indexPath.row;
            return cell;
    }
    - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
        return YES;
    }

    - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle
forRowAtIndexPath:(NSIndexPath *)indexPath { if (editingStyle == UITableViewCellEditingStyleDelete) {

            [result removeObjectAtIndex:indexPath.row];
            [tableView reloadData];
            [spinner startAnimating];
            NSString *id = [profile objectForKey:@"user_id"];
            NSString *tb =tid;

            NSString *string = [NSString stringWithFormat:@"userid=%@&topiid=%@",id,tb];
            NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"myDeleteUrl"]];

            NSData *data = [string dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
            [request setHTTPMethod:@"POST"];
            [request setHTTPBody : data];
            NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration
defaultSessionConfiguration]]; [[session dataTaskWithRequest : request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {

                NSDictionary *JSON= [NSJSONSerialization JSONObjectWithData :data options :NSJSONReadingMutableContainers error: nil];

               NSArray *alertArray = [JSON objectForKey:@"deletebookmark"];

                for (NSDictionary *alert in alertArray ){

                    if ([[alert objectForKey:@"status"] isEqualToString:@"done"]) {
                        NSLog(@"done");
                         [spinner stopAnimating];
                   }
                    else{
                       NSLog(@"notDone");
                        [spinner stopAnimating];
                    }
                 }

            }]resume];

        }
    }

Body:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath : indexPath];

        if (!(cell == nil)) {
                        name = (UILabel *)[cell viewWithTag:10]; name.text = [result objectAtIndex : indexPath.row];
                    }
                    name.tag=indexPath.row;
                    return cell;
            }

In this datasource method, you have used a "if" condition, and due to your cell is reusable cell, so you have to use the else part too in this data source method.

Like

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
                UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath : indexPath];

if (!(cell == nil)) {
                    name = (UILabel *)[cell viewWithTag:10]; name.text = [result objectAtIndex : indexPath.row];
                }
               else{

                 name.tag=indexPath.row;
               }

                return cell;
        }

Thanks


问:
Is it possible to change the CSS style attributes of a web page when loading it in a JEditorPane
I'm loading a web page into a JEditorPane and need to change the background color of the page . Is it possible to do? </p>

答:
public void setBackground(Color bg)

Sets the background color of this component. You can use a method inherit from class javax.swing.JComponent.

https://www3.ntu.edu.sg/home/ehchua/programming/java/J4a_GUI_2.html#zz-1.5


问:
How to point url from Global file using URL routing 3.5 asp.net without parameters?
How to point url from Global file using URL routing 3.5 asp.net without parameters?

For example:

```<code>var url = "subdomain";

if(url == "subdomain")
{
//Route to the specific url
}

if(url == "subdomain2")
{
//Route to the specific url
}
</code>```

答:
If I understand you correctly, you can try something like

```<code>Server.Transfer("yourpage.aspx");
</code>```

or

```<code>Response.Redirect("http://www.google.com");
</code>```

To give a more detailed answer, we all need more details in you question.

Body:
How to point url from Global file using URL routing 3.5 asp.net without parameters?

For example:

var url = "subdomain";

if(url == "subdomain")
{
//Route to the specific url
}

if(url == "subdomain2")
{
//Route to the specific url
}

Body:
If I understand you correctly, you can try something like

Server.Transfer("yourpage.aspx");

or

Response.Redirect("http://www.google.com");

To give a more detailed answer, we all need more details in you question.


问:
Chat message with Google Firebase Realtime Database architecture with Unread Message counter and Last Message
I'm creating a chat section for android apps. By using Google Firebase.
Following task already completed

Create chat node
2. Separate particular chat thread using two users information.
3. Read all message for single chat thread.

Now my question is below.
1. How to retrieve last message by single chat thread.
2. How to create a database where i can get counter of unread message counter.

Attachment of my chat database and objective below.

Current objective.

Already done.

Firebase database architecture.

Now how it will be easier for me to create database for make solution this problem.

答:
this is my workaround.

as you can see i am making two reference one for message and second recent is for user list.

whenever i tap on user list and open my chat page, In my chat page i m checking condition for receiver id and send status and count to recent refrence in onCreate() of chat page, like this.

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

        uid = pref.getString("uid", null);
        sender_name = pref.getString("first_name", null);

        Bundle bundle = getIntent().getExtras();
        if(bundle != null && !bundle.isEmpty()){
            recevier_name = bundle.getString("uname");
            receiver_id = bundle.getString("UserId");
        }else {
            recevier_name = "Admin";
            receiver_id = "1";
        }

        chat_date = listAdapter.SIMPLE_DATE_FORMAT.format(new Date().getTime());
        if (Integer.parseInt(uid) < Integer.parseInt(receiver_id)) {
            value = String.valueOf(uid + "--*--" + receiver_id);
        } else {
            value = String.valueOf(receiver_id+"--*--"+uid);
        }

myRef1 = database.getReferenceFromUrl("https://firebaseio.com/messages/"+value);

myRef2 = database.getReferenceFromUrl("https://firebaseio.com/recents/"+value);

    myRef2.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            if(dataSnapshot != null){
                Map map1 = (Map) dataSnapshot.getValue();
                if(map1 != null){
                    String rec_id = (String) map1.get("recever_id");
                    if(rec_id.equals(uid)){
                        myRef2.getRef().child("count").setValue("0");
                        myRef2.getRef().child("status").setValue("online");
                    }
                }

            }
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });

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

so everytime when i open my chat my status is online if receiver_id is my_id.

now in chat button click i m checking for count if status is not online, like this.

```<code>private ImageView.OnClickListener clickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            if(v==enterChatView1)
            {
                message_text = chatEditText1.getText().toString();
                final Map<String, String> map = new HashMap<String, String>();
                map.put("sender_id", uid );
                map.put("recever_id", receiver_id);
                map.put("sender_name", sender_name);
                map.put("recevier_name", recevier_name);
                map.put("text", message_text);
                map.put("text_id", uid);
                map.put("date", chat_date);
                myRef1.push().setValue(map);
              //  myRef2.setValue(map);
               // sendMessage(chatEditText1.getText().toString(), chat_date, UserType.OTHER);

                myRef2.addListenerForSingleValueEvent(new ValueEventListener() {
                    @Override
                    public void onDataChange(DataSnapshot dataSnapshot) {
                        if(dataSnapshot != null){
                            Map map1 = (Map) dataSnapshot.getValue();
                            if(map1 != null){
                                String status = (String)map1.get("status");
                                if(map1.containsKey("count")){
                                    if(!status.equals("online")) {
                                        String count = (String) map1.get("count");
                                        int val = Integer.parseInt(count);
                                        map.put("count", String.valueOf(++val));
                                        map.put("status", "offline");
                                        myRef2.setValue(map);
                                        Log.d("VALUE", "YES" + val);
                                    }else {
                                        map.put("count", String.valueOf(0));
                                        map.put("status", "online");
                                        myRef2.setValue(map);
                                        Log.d("VALUE", "No");
                                    }
                                }else {
                                    map.put("count", String.valueOf(1));
                                    map.put("status", "offline");
                                    myRef2.setValue(map);
                                    Log.d("VALUE", "No");
                                }
                            }else {
                                map.put("count", String.valueOf(1));
                                map.put("status", "offline");
                                myRef2.setValue(map);
                                Log.d("VALUE", "first time");
                            }
                        }else {
                            map.put("count", String.valueOf(1));
                            map.put("status", "offline");
                            myRef2.setValue(map);
                            Log.d("VALUE", "first time");
                        }
                    }

                    @Override
                    public void onCancelled(DatabaseError databaseError) {

                    }
                });

            }

            chatEditText1.setText("");

        }
    };
</code>```

and at last when you close your chat page. add status offline to recent in onBackPress() event, like this.

```<code>@Override
    public void onBackPressed() {

            myRef2.addListenerForSingleValueEvent(new ValueEventListener() {
                @Override
                public void onDataChange(DataSnapshot dataSnapshot) {
                    if(dataSnapshot != null){
                        Map map1 = (Map) dataSnapshot.getValue();
                        if(map1!= null){
                            String rec_id = (String) map1.get("recever_id");
                            if(rec_id.equals(uid)){
                                myRef2.getRef().child("count").setValue("0");
                                myRef2.getRef().child("status").setValue("offline");

                            }
                        }
                    }
                }

                @Override
                public void onCancelled(DatabaseError databaseError) {

                }
            });
            finish();
            this.overridePendingTransition(R.anim.left_in,
                    R.anim.left_out);
    }
</code>```

Body:
this is my workaround.

as you can see i am making two reference one for message and second recent is for user list.

whenever i tap on user list and open my chat page, In my chat page i m checking condition for receiver id and send status and count to recent refrence in onCreate() of chat page, like this.

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

        uid = pref.getString("uid", null);
        sender_name = pref.getString("first_name", null);

        Bundle bundle = getIntent().getExtras();
        if(bundle != null && !bundle.isEmpty()){
            recevier_name = bundle.getString("uname");
            receiver_id = bundle.getString("UserId");
        }else {
            recevier_name = "Admin";
            receiver_id = "1";
        }

        chat_date = listAdapter.SIMPLE_DATE_FORMAT.format(new Date().getTime());
        if (Integer.parseInt(uid) < Integer.parseInt(receiver_id)) {
            value = String.valueOf(uid + "--*--" + receiver_id);
        } else {
            value = String.valueOf(receiver_id+"--*--"+uid);
        }

myRef1 = database.getReferenceFromUrl("https://firebaseio.com/messages/"+value);

myRef2 = database.getReferenceFromUrl("https://firebaseio.com/recents/"+value);

    myRef2.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            if(dataSnapshot != null){
                Map map1 = (Map) dataSnapshot.getValue();
                if(map1 != null){
                    String rec_id = (String) map1.get("recever_id");
                    if(rec_id.equals(uid)){
                        myRef2.getRef().child("count").setValue("0");
                        myRef2.getRef().child("status").setValue("online");
                    }
                }

            }
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });

    getChat();
}

so everytime when i open my chat my status is online if receiver_id is my_id.

now in chat button click i m checking for count if status is not online, like this.

private ImageView.OnClickListener clickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            if(v==enterChatView1)
            {
                message_text = chatEditText1.getText().toString();
                final Map<String, String> map = new HashMap<String, String>();
                map.put("sender_id", uid );
                map.put("recever_id", receiver_id);
                map.put("sender_name", sender_name);
                map.put("recevier_name", recevier_name);
                map.put("text", message_text);
                map.put("text_id", uid);
                map.put("date", chat_date);
                myRef1.push().setValue(map);
              //  myRef2.setValue(map);
               // sendMessage(chatEditText1.getText().toString(), chat_date, UserType.OTHER);

                myRef2.addListenerForSingleValueEvent(new ValueEventListener() {
                    @Override
                    public void onDataChange(DataSnapshot dataSnapshot) {
                        if(dataSnapshot != null){
                            Map map1 = (Map) dataSnapshot.getValue();
                            if(map1 != null){
                                String status = (String)map1.get("status");
                                if(map1.containsKey("count")){
                                    if(!status.equals("online")) {
                                        String count = (String) map1.get("count");
                                        int val = Integer.parseInt(count);
                                        map.put("count", String.valueOf(++val));
                                        map.put("status", "offline");
                                        myRef2.setValue(map);
                                        Log.d("VALUE", "YES" + val);
                                    }else {
                                        map.put("count", String.valueOf(0));
                                        map.put("status", "online");
                                        myRef2.setValue(map);
                                        Log.d("VALUE", "No");
                                    }
                                }else {
                                    map.put("count", String.valueOf(1));
                                    map.put("status", "offline");
                                    myRef2.setValue(map);
                                    Log.d("VALUE", "No");
                                }
                            }else {
                                map.put("count", String.valueOf(1));
                                map.put("status", "offline");
                                myRef2.setValue(map);
                                Log.d("VALUE", "first time");
                            }
                        }else {
                            map.put("count", String.valueOf(1));
                            map.put("status", "offline");
                            myRef2.setValue(map);
                            Log.d("VALUE", "first time");
                        }
                    }

                    @Override
                    public void onCancelled(DatabaseError databaseError) {

                    }
                });

            }

            chatEditText1.setText("");

        }
    };

and at last when you close your chat page. add status offline to recent in onBackPress() event, like this.

@Override
    public void onBackPressed() {

            myRef2.addListenerForSingleValueEvent(new ValueEventListener() {
                @Override
                public void onDataChange(DataSnapshot dataSnapshot) {
                    if(dataSnapshot != null){
                        Map map1 = (Map) dataSnapshot.getValue();
                        if(map1!= null){
                            String rec_id = (String) map1.get("recever_id");
                            if(rec_id.equals(uid)){
                                myRef2.getRef().child("count").setValue("0");
                                myRef2.getRef().child("status").setValue("offline");

                            }
                        }
                    }
                }

                @Override
                public void onCancelled(DatabaseError databaseError) {

                }
            });
            finish();
            this.overridePendingTransition(R.anim.left_in,
                    R.anim.left_out);
    }


问:
TYPO3 href not working
I am quite new to TYPO3, I am inspecting a code for errors and I saw a non working href.
the inspection in the browser shows empty href :

```<code><a class="download" target="_blank" title="Initiates file download" href=""> here..</a>
</code>```

The code is :

```<code><a class="download" target="_blank" title="Initiates file download" href="{location.pdf.originalResource.publicUrl}"><f:translate key="tx_locations_domain_model_location.here" />..</a>
</code>```

I don't understand this location.pdf.originalResource.publicUrl !!
When I display {location} I get : Locations\Locations\Domain\Model\Location:102
I can't find such path in my folders !!
What am I missing !!

When I make

```<code><f:debug>{location}</f:debug>
</code>```

I see : pdf => NULL , how can I fix it, in my backend I select a PDF and saved. no error message
UPDATE:
My Pdf field is int(11) unsigned,
Here is my TCA (typo3conf/ext/locations/Configuration/TCA/Location.php)

```<code>$GLOBALS['TCA']['tx_locations_domain_model_location'] = array(
....
    'columns' => array(
....
    'pdf' => array(
        'exclude' => 1,
        'label' => 'LLL:EXT:locations/Resources/Private/Language/locallang_db.xlf:tx_locations_domain_model_location.pdf',
        'config' => array (
            'type' => 'group',
            'internal_type' => 'file',
            'allowed' => $GLOBALS['TYPO3_CONF_VARS']['GFX']['imagefile_ext'],
            'max_size' => $GLOBALS['TYPO3_CONF_VARS']['BE']['maxFileSize'],
            'uploadfolder' => 'uploads/pics',
            'show_thumbs' => 1,
            'size' => 1,
            'minitems' => 0,
            'maxitems' => 1
        )
    ),
</code>```

here is my Location class :

```<code><?php
namespace Locations\Locations\Domain\Model;

/**
 * Location
 */
class Location extends \TYPO3\CMS\Extbase\DomainObject\AbstractEntity {

    /**
     * title
     *
     * @var string
     */
    protected $title = '';

    /**
     * fullTitle
     *
     * @var string
     */
    protected $fullTitle = '';

    /**
     * description
     *
     * @var string
     */
    protected $description = '';

    /**
     * image
     *
     * @var \TYPO3\CMS\Extbase\Domain\Model\FileReference
     */
    protected $image = NULL;

    /**
     * secondTitle
     *
     * @var string
     */
    protected $secondTitle = '';

    /**
     * secondDescription
     *
     * @var string
     */
    protected $secondDescription = '';

    /**
     * address
     *
     * @var string
     */
    protected $address = '';

    /**
     * howToGetIt
     *
     * @var string
     */
    protected $howToGetIt = '';

    /**
     * thirdTitle
     *
     * @var string
     */
    protected $thirdTitle = '';

    /**
     * thirdDescription
     *
     * @var string
     */
    protected $thirdDescription = '';

    /**
     * googleMap
     *
     * @var string
     */
    protected $googleMap = '';

    /**
     * pdf
     *
     * @var \TYPO3\CMS\Extbase\Domain\Model\FileReference
     */
    protected $pdf = NULL;

    /**
     * pricingtpl
     *
     * @var int
     */
    protected $pricingtpl;

    /**
     * category
     *
     * @var \TYPO3\CMS\Extbase\Persistence\ObjectStorage<\Locations\Locations\Domain\Model\Category>
     */
    protected $category = NULL;

    /**
     * __construct
     */
    public function __construct() {
        //Do not remove the next line: It would break the functionality
        $this->initStorageObjects();
    }

    /**
     * Initializes all ObjectStorage properties
     * Do not modify this method!
     * It will be rewritten on each save in the extension builder
     * You may modify the constructor of this class instead
     *
     * @return void
     */
    protected function initStorageObjects() {
        $this->category = new \TYPO3\CMS\Extbase\Persistence\ObjectStorage();
    }

    /**
     * Returns the title
     *
     * @return string $title
     */
    public function getTitle() {
        return $this->title;
    }

    /**
     * Sets the image
     *
     * @param \TYPO3\CMS\Extbase\Domain\Model\FileReference $image
     * @return void
     */
    public function setImage(\TYPO3\CMS\Extbase\Domain\Model\FileReference $image) {
        $this->image = $image;
    }

    /**
     * Sets the pdf
     *
     * @param \TYPO3\CMS\Extbase\Domain\Model\FileReference $pdf
     * @return void
     */
    public function setPdf(\TYPO3\CMS\Extbase\Domain\Model\FileReference $pdf) {
        $this->pdf = $pdf;
    }

    /**
     * Removes a Category
     *
     * @param \Locations\Locations\Domain\Model\Category $categoryToRemove The Category to be removed
     * @return void
     */
    public function removeCategory(\Locations\Locations\Domain\Model\Category $categoryToRemove) {
        $this->category->detach($categoryToRemove);
    }

    /**
     * Returns the category
     *
     * @return \TYPO3\CMS\Extbase\Persistence\ObjectStorage<\Locations\Locations\Domain\Model\Category> $category
     */
    public function getCategory() {
        return $this->category;
    }

    /**
     * Sets the category
     *
     * @param \TYPO3\CMS\Extbase\Persistence\ObjectStorage<\Locations\Locations\Domain\Model\Category> $category
     * @return void
     */
    public function setCategory(\TYPO3\CMS\Extbase\Persistence\ObjectStorage $category) {
        $this->category = $category;
    }

}
</code>```

答:
You don't have to use in Fluid things like href=""/>, you can find the <f:link..>, <f:uri..>,etc, in fluid documentation for generating links.

But there for file downloading you have to use this viewhelper. You have to know only the uid of the file. In your case {location.pdf.uid} Be sure that you have indexed files before use it.

```<code><v:resource.file additionalAttributes="{foo: 'bar'}" data="{foo: 'bar'}" identifier="[mixed]" categories="[mixed]" treatIdAsUid="1" treatIdAsReference="1" as="NULL">
    <!-- tag content - may be ignored! -->
</v:resource.file>
</code>```

Title: TYPO3 href not working

Body:
I am quite new to TYPO3, I am inspecting a code for errors and I saw a non working href.
the inspection in the browser shows empty href :

 here..

The code is :

<f:translate key="tx_locations_domain_model_location.here" />..

I don't understand this location.pdf.originalResource.publicUrl !!
When I display {location} I get : Locations\Locations\Domain\Model\Location:102
I can't find such path in my folders !!
What am I missing !!

When I make

<f:debug>{location}</f:debug>

I see : pdf => NULL , how can I fix it, in my backend I select a PDF and saved. no error message
UPDATE:
My Pdf field is int(11) unsigned,
Here is my TCA (typo3conf/ext/locations/Configuration/TCA/Location.php)

$GLOBALS['TCA']['tx_locations_domain_model_location'] = array(
....
    'columns' => array(
....
    'pdf' => array(
        'exclude' => 1,
        'label' => 'LLL:EXT:locations/Resources/Private/Language/locallang_db.xlf:tx_locations_domain_model_location.pdf',
        'config' => array (
            'type' => 'group',
            'internal_type' => 'file',
            'allowed' => $GLOBALS['TYPO3_CONF_VARS']['GFX']['imagefile_ext'],
            'max_size' => $GLOBALS['TYPO3_CONF_VARS']['BE']['maxFileSize'],
            'uploadfolder' => 'uploads/pics',
            'show_thumbs' => 1,
            'size' => 1,
            'minitems' => 0,
            'maxitems' => 1
        )
    ),

here is my Location class :

<?php
namespace Locations\Locations\Domain\Model;

/**
 * Location
 */
class Location extends \TYPO3\CMS\Extbase\DomainObject\AbstractEntity {

    /**
     * title
     *
     * @var string
     */
    protected $title = '';

    /**
     * fullTitle
     *
     * @var string
     */
    protected $fullTitle = '';

    /**
     * description
     *
     * @var string
     */
    protected $description = '';

    /**
     * image
     *
     * @var \TYPO3\CMS\Extbase\Domain\Model\FileReference
     */
    protected $image = NULL;

    /**
     * secondTitle
     *
     * @var string
     */
    protected $secondTitle = '';

    /**
     * secondDescription
     *
     * @var string
     */
    protected $secondDescription = '';

    /**
     * address
     *
     * @var string
     */
    protected $address = '';

    /**
     * howToGetIt
     *
     * @var string
     */
    protected $howToGetIt = '';

    /**
     * thirdTitle
     *
     * @var string
     */
    protected $thirdTitle = '';

    /**
     * thirdDescription
     *
     * @var string
     */
    protected $thirdDescription = '';

    /**
     * googleMap
     *
     * @var string
     */
    protected $googleMap = '';

    /**
     * pdf
     *
     * @var \TYPO3\CMS\Extbase\Domain\Model\FileReference
     */
    protected $pdf = NULL;

    /**
     * pricingtpl
     *
     * @var int
     */
    protected $pricingtpl;

    /**
     * category
     *
     * @var \TYPO3\CMS\Extbase\Persistence\ObjectStorage<\Locations\Locations\Domain\Model\Category>
     */
    protected $category = NULL;

    /**
     * __construct
     */
    public function __construct() {
        //Do not remove the next line: It would break the functionality
        $this->initStorageObjects();
    }

    /**
     * Initializes all ObjectStorage properties
     * Do not modify this method!
     * It will be rewritten on each save in the extension builder
     * You may modify the constructor of this class instead
     *
     * @return void
     */
    protected function initStorageObjects() {
        $this->category = new \TYPO3\CMS\Extbase\Persistence\ObjectStorage();
    }

    /**
     * Returns the title
     *
     * @return string $title
     */
    public function getTitle() {
        return $this->title;
    }

    /**
     * Sets the image
     *
     * @param \TYPO3\CMS\Extbase\Domain\Model\FileReference $image
     * @return void
     */
    public function setImage(\TYPO3\CMS\Extbase\Domain\Model\FileReference $image) {
        $this->image = $image;
    }

    /**
     * Sets the pdf
     *
     * @param \TYPO3\CMS\Extbase\Domain\Model\FileReference $pdf
     * @return void
     */
    public function setPdf(\TYPO3\CMS\Extbase\Domain\Model\FileReference $pdf) {
        $this->pdf = $pdf;
    }

    /**
     * Removes a Category
     *
     * @param \Locations\Locations\Domain\Model\Category $categoryToRemove The Category to be removed
     * @return void
     */
    public function removeCategory(\Locations\Locations\Domain\Model\Category $categoryToRemove) {
        $this->category->detach($categoryToRemove);
    }

    /**
     * Returns the category
     *
     * @return \TYPO3\CMS\Extbase\Persistence\ObjectStorage<\Locations\Locations\Domain\Model\Category> $category
     */
    public function getCategory() {
        return $this->category;
    }

    /**
     * Sets the category
     *
     * @param \TYPO3\CMS\Extbase\Persistence\ObjectStorage<\Locations\Locations\Domain\Model\Category> $category
     * @return void
     */
    public function setCategory(\TYPO3\CMS\Extbase\Persistence\ObjectStorage $category) {
        $this->category = $category;
    }

}

Body:
You don't have to use in Fluid things like <a href=""/>, you can find the <f:link..>, <f:uri..>,etc, in fluid documentation for generating links.

But there for file downloading you have to use this viewhelper. You have to know only the uid of the file. In your case {location.pdf.uid} Be sure that you have indexed files before use it.

<v:resource.file additionalAttributes="{foo: 'bar'}" data="{foo: 'bar'}" identifier="[mixed]" categories="[mixed]" treatIdAsUid="1" treatIdAsReference="1" as="NULL">
    <!-- tag content - may be ignored! -->
</v:resource.file>


问:
Intermittent bugs - sometimes this code works and sometimes it doesn't!
This code intermittently works. It's running on a small microcontroller. It will work fine even after restarting the processor, but if I change some part of the code, it breaks. This makes me think that it's some kind of pointer bug or memory corruption. What's happening is the coordinate, p_res.pos.x is sometimes read as 0 (the incorrect value) and 96 (the correct value) when it is passed to write_circle_outlined. y seems to be correct most of the time. If anyone can spot anything obviously wrong please point it out!

```<code>int demo_game()
{
    long int d;
    int x, y;
    struct WorldCamera p_viewer;
    struct Point3D_LLA p_subj;
    struct Point2D_CalcRes p_res;
    p_viewer.hfov = 27;
    p_viewer.vfov = 32;
    p_viewer.width = 192;
    p_viewer.height = 128;
    p_viewer.p.lat = 51.26f;
    p_viewer.p.lon = -1.0862f;
    p_viewer.p.alt = 100.0f;
    p_subj.lat = 51.20f;
    p_subj.lon = -1.0862f;
    p_subj.alt = 100.0f;
    while(1)
    {
        fill_buffer(draw_buffer_mask, 0x0000);
        fill_buffer(draw_buffer_level, 0xffff);
        compute_3d_transform(&p_viewer, &p_subj, &p_res, 10000.0f);
        x = p_res.pos.x;
        y = p_res.pos.y;
        write_circle_outlined(x, y, 1.0f / p_res.est_dist, 0, 0, 0, 1);
        p_viewer.p.lat -= 0.0001f;
        //p_viewer.p.alt -= 0.00001f;
        d = 20000;
        while(d--);
    }
    return 1;
}
</code>```

The code for compute_3d_transform is:

```<code>void compute_3d_transform(struct WorldCamera *p_viewer, struct Point3D_LLA *p_subj, struct Point2D_CalcRes *res, float cliph)
{
    // Estimate the distance to the waypoint. This isn't intended to replace
    // proper lat/lon distance algorithms, but provides a general indication
    // of how far away our subject is from the camera. It works accurately for
    // short distances of less than 1km, but doesn't give distances in any
    // meaningful unit (lat/lon distance?)
    res->est_dist = hypot2(p_viewer->p.lat - p_subj->lat, p_viewer->p.lon - p_subj->lon);
    // Save precious cycles if outside of visible world.
    if(res->est_dist > cliph)
        goto quick_exit;
    // Compute the horizontal angle to the point.
    // atan2(y,x) so atan2(lon,lat) and not atan2(lat,lon)!
    res->h_angle = RAD2DEG(angle_dist(atan2(p_viewer->p.lon - p_subj->lon, p_viewer->p.lat - p_subj->lat), p_viewer->yaw));
    res->small_dist = res->est_dist * 0.0025f; // by trial and error this works well.
    // Using the estimated distance and altitude delta we can calculate
    // the vertical angle.
    res->v_angle = RAD2DEG(atan2(p_viewer->p.alt - p_subj->alt, res->est_dist));
    // Normalize the results to fit in the field of view of the camera if
    // the point is visible. If they are outside of (0,hfov] or (0,vfov]
    // then the point is not visible.
    res->h_angle += p_viewer->hfov / 2;
    res->v_angle += p_viewer->vfov / 2;
    // Set flags.
    if(res->h_angle < 0 || res->h_angle > p_viewer->hfov)
        res->flags |= X_OVER;
    if(res->v_angle < 0 || res->v_angle > p_viewer->vfov)
        res->flags |= Y_OVER;
    res->pos.x = (res->h_angle / p_viewer->hfov) * p_viewer->width;
    res->pos.y = (res->v_angle / p_viewer->vfov) * p_viewer->height;
    return;
quick_exit:
    res->flags |= X_OVER | Y_OVER;
    return;
}
</code>```

Structure for the results:

```<code>typedef struct Point2D_Pixel { unsigned int x, y; };

// Structure for storing calculated results (from camera transforms.)
typedef struct Point2D_CalcRes
{
    struct Point2D_Pixel pos;
    float h_angle, v_angle, est_dist, small_dist;
    int flags;
};
</code>```

The code is part of an open source project of mine so it's okay to post a lot of code here.

答: I see some of your calculation depends on p_viewer->yaw, but I do not see any intialization for p_viewer->yaw.  Is this your problem?

Body:
This code intermittently works. It's running on a small microcontroller. It will work fine even after restarting the processor, but if I change some part of the code, it breaks. This makes me think that it's some kind of pointer bug or memory corruption. What's happening is the coordinate, p_res.pos.x is sometimes read as 0 (the incorrect value) and 96 (the correct value) when it is passed to write_circle_outlined. y seems to be correct most of the time. If anyone can spot anything obviously wrong please point it out!

int demo_game()
{
    long int d;
    int x, y;
    struct WorldCamera p_viewer;
    struct Point3D_LLA p_subj;
    struct Point2D_CalcRes p_res;
    p_viewer.hfov = 27;
    p_viewer.vfov = 32;
    p_viewer.width = 192;
    p_viewer.height = 128;
    p_viewer.p.lat = 51.26f;
    p_viewer.p.lon = -1.0862f;
    p_viewer.p.alt = 100.0f;
    p_subj.lat = 51.20f;
    p_subj.lon = -1.0862f;
    p_subj.alt = 100.0f;
    while(1)
    {
        fill_buffer(draw_buffer_mask, 0x0000);
        fill_buffer(draw_buffer_level, 0xffff);
        compute_3d_transform(&p_viewer, &p_subj, &p_res, 10000.0f);
        x = p_res.pos.x;
        y = p_res.pos.y;
        write_circle_outlined(x, y, 1.0f / p_res.est_dist, 0, 0, 0, 1);
        p_viewer.p.lat -= 0.0001f;
        //p_viewer.p.alt -= 0.00001f;
        d = 20000;
        while(d--);
    }
    return 1;
}

The code for compute_3d_transform is:

void compute_3d_transform(struct WorldCamera *p_viewer, struct Point3D_LLA *p_subj, struct Point2D_CalcRes *res, float cliph)
{
    // Estimate the distance to the waypoint. This isn't intended to replace
    // proper lat/lon distance algorithms, but provides a general indication
    // of how far away our subject is from the camera. It works accurately for
    // short distances of less than 1km, but doesn't give distances in any
    // meaningful unit (lat/lon distance?)
    res->est_dist = hypot2(p_viewer->p.lat - p_subj->lat, p_viewer->p.lon - p_subj->lon);
    // Save precious cycles if outside of visible world.
    if(res->est_dist > cliph)
        goto quick_exit;
    // Compute the horizontal angle to the point.
    // atan2(y,x) so atan2(lon,lat) and not atan2(lat,lon)!
    res->h_angle = RAD2DEG(angle_dist(atan2(p_viewer->p.lon - p_subj->lon, p_viewer->p.lat - p_subj->lat), p_viewer->yaw));
    res->small_dist = res->est_dist * 0.0025f; // by trial and error this works well.
    // Using the estimated distance and altitude delta we can calculate
    // the vertical angle.
    res->v_angle = RAD2DEG(atan2(p_viewer->p.alt - p_subj->alt, res->est_dist));
    // Normalize the results to fit in the field of view of the camera if
    // the point is visible. If they are outside of (0,hfov] or (0,vfov]
    // then the point is not visible.
    res->h_angle += p_viewer->hfov / 2;
    res->v_angle += p_viewer->vfov / 2;
    // Set flags.
    if(res->h_angle < 0 || res->h_angle > p_viewer->hfov)
        res->flags |= X_OVER;
    if(res->v_angle < 0 || res->v_angle > p_viewer->vfov)
        res->flags |= Y_OVER;
    res->pos.x = (res->h_angle / p_viewer->hfov) * p_viewer->width;
    res->pos.y = (res->v_angle / p_viewer->vfov) * p_viewer->height;
    return;
quick_exit:
    res->flags |= X_OVER | Y_OVER;
    return;
}

Structure for the results:

typedef struct Point2D_Pixel { unsigned int x, y; };

// Structure for storing calculated results (from camera transforms.)
typedef struct Point2D_CalcRes
{
    struct Point2D_Pixel pos;
    float h_angle, v_angle, est_dist, small_dist;
    int flags;
};

The code is part of an open source project of mine so it's okay to post a lot of code here.


问:
Creating a Spring bean from a Groovy class leads to "cannot find symbol error"
I have a groovy class that returns an instance of a data base client:

```<code>class DBClient {

private static DBClient INSTANCE

private String url
private String userName
private String password
private String driver

@Synchronized
static DBClient getInstance() {
    if (!INSTANCE) {
        INSTANCE = new DBClient()
    }
    return INSTANCE
}

 Sql sql = Sql.newInstance(url, userName, password, driver)

void setUrl(String url) {
    this.url = url
}

void setUserName(String userName) {
    this.userName = userName
}

void setPassword(String password) {
    this.password = password
}

void setDriver(String driver) {
    this.driver = driver
}

def getAllSaa() {
    sql.rows("select * from Saa")
}
}
</code>```

I try to create a bean of this class in a @Configuration class:

```<code>@Configuration
@Profile("prod")
public class OracleServerConfiguration {

@Bean
public DBClient dbClient () {

    DBClient dbClient = DBClient.getInstance();

    dbClient.setUrl("jdbc:oracle:thin:@localhost:1521:xe");
    dbClient.setUserName("SYSTEM");
    dbClient.setPassword("1111");
    dbClient.setDriver("oracle.jdbc.OracleDriver");

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

It looks ok in IntelliJ, but when I try to build the project with gradle, I get an error

"OracleServerConfiguration.java:14: error: cannot find symbol
DBClient dbClient = DBClient.getInstance();   symbol:  class DBClient location: class OracleServerConfiguration".

I tried creating getters and setters for all the fields in DBClient class, but to no avail.

Does someone have experience with creating beans from groovy classes?

答:
A similar question was answered here: Referencing Groovy from Java with Gradle and Spring Boot results in"cannot find symbol"
In my case, I just decided to keep the module fully in Groovy, which fixed the problem.</p>

Body:
I have a groovy class that returns an instance of a data base client:

class DBClient {

private static DBClient INSTANCE

private String url
private String userName
private String password
private String driver

@Synchronized
static DBClient getInstance() {
    if (!INSTANCE) {
        INSTANCE = new DBClient()
    }
    return INSTANCE
}

 Sql sql = Sql.newInstance(url, userName, password, driver)

void setUrl(String url) {
    this.url = url
}

void setUserName(String userName) {
    this.userName = userName
}

void setPassword(String password) {
    this.password = password
}

void setDriver(String driver) {
    this.driver = driver
}

def getAllSaa() {
    sql.rows("select * from Saa")
}
}

I try to create a bean of this class in a @Configuration class:

@Configuration
@Profile("prod")
public class OracleServerConfiguration {

@Bean
public DBClient dbClient () {

    DBClient dbClient = DBClient.getInstance();

    dbClient.setUrl("jdbc:oracle:thin:@localhost:1521:xe");
    dbClient.setUserName("SYSTEM");
    dbClient.setPassword("1111");
    dbClient.setDriver("oracle.jdbc.OracleDriver");

    return dbClient;
}
}

It looks ok in IntelliJ, but when I try to build the project with gradle, I get an error

"OracleServerConfiguration.java:14: error: cannot find symbol
DBClient dbClient = DBClient.getInstance();   symbol:  class DBClient location: class OracleServerConfiguration".

I tried creating getters and setters for all the fields in DBClient class, but to no avail.

Does someone have experience with creating beans from groovy classes?


答:
```<code>if ($id == 1)
{
?>
    <script>
        alert("Invalid user name or password, Try again");
    </script>
<?php
}
    else if($error_id == 2)
{
?>
    <script>
        alert("Update Sucessfully!");
 //---------- added ---------------
        window.location.href= 'index.php';
 //-------------------------

    </script>
<?php
}
</code>```

Title: How to remove id in url

Body:
now i face a problem with user will see the popout with "update sucessfully" if he reload the page or backward to the page.Anyone having idea of how to remove ?id=2 after click ok on pop out?

Here is my code:

update_action.php

$updresult = mysqli_query($conn, $sqlu);

    if (!$updresult)
        echo "Unable to update record". mysqli_error($conn);
    else
    {
        header('Location: index.php?id=2' );
        mysqli_close($conn);
    }
    ?>

index.php

if ($id == 1)
    {
    ?>

    <?php
    }
        else if($error_id == 2)
    {
    ?>

    <?php
    }

the url show index.php?id=2


问:
No module named 'xxx'; 'yyy' is not a package
I have the following structure:

```<code>Oracle
| before_OOP
| | dump_ora_shelve.py
cOr.py
</code>```

get_users.py retrieves the data from shelve "database" and works just fine:

```<code>def get_shelve_users(field):
    import shelve
    db = shelve.open('oracle-shelve')
    for key in db:
        if key == field:
             return db[key]
    db.close()
</code>```

cOr.py has to have get_shelve_users to be imported:

```<code> from Oracle.before_OOP.dump_ora_shelve import get_shelve_users
</code>```

But when I call for an import (even if PyCharm can successfully find this folder and suggest me what I want to import) import doesn't work:

```<code>    from Oracle.before_OOP.dump_ora_shelve import get_shelve_users
ModuleNotFoundError: No module named 'Oracle.before_OOP'; 'Oracle' is not a package
</code>```

答:
It appears the import should look like this:</p>

```<code>from before_OOP.dump_ora_shelve import get_shelve_users
</code>```

Body:
I have the following structure:

Oracle
| before_OOP
| | dump_ora_shelve.py
cOr.py

get_users.py retrieves the data from shelve "database" and works just fine:

def get_shelve_users(field):
    import shelve
    db = shelve.open('oracle-shelve')
    for key in db:
        if key == field:
             return db[key]
    db.close()

cOr.py has to have get_shelve_users to be imported:

 from Oracle.before_OOP.dump_ora_shelve import get_shelve_users

But when I call for an import (even if PyCharm can successfully find this folder and suggest me what I want to import) import doesn't work:

    from Oracle.before_OOP.dump_ora_shelve import get_shelve_users
ModuleNotFoundError: No module named 'Oracle.before_OOP'; 'Oracle' is not a package

Body:
It appears the import should look like this:

from before_OOP.dump_ora_shelve import get_shelve_users


问:
Android Fragment appends when calling other fragment
Im currently working on a sample app that will be using fragments, but im having a little problem regarding changing the fragment.

My default layout for my fragment is fragmentOne (see code below).

```<code><fragment
    android:id="@+id/fplace"
    android:layout_width="match_parent"
    android:layout_height="498dp"
    android:name="layout.FragmentOne"
    tools:layout="@layout/fragment_fragment_one" />
</code>```

and that's working correctly.

but when im changing the fragment it appends. the behavior must replace the fragment not append.

here is my code for the activity (see code below).

```<code>public void onClick(View view) {
    Button button = (Button) view;
    Fragment fragment = null;
    switch (button.getId()) {
        case R.id.f1:
            fragment = new FragmentOne();
            FragmentManager fm = getFragmentManager();
            FragmentTransaction ft = fm.beginTransaction();
            ft.replace(R.id.fplace, fragment);
            ft.commit();
            break;
        case R.id.f2:
            fragment = new FragmentTwo();
            fm = getFragmentManager();
            ft = fm.beginTransaction();
            ft.replace(R.id.fplace, fragment);
            ft.commit();
            break;
    }
}
</code>```

and from the fragment one i am loading the data from the onCreateView() which is working correctly. the main problem is the fragment appends not replace.

(see photo below)

the red and yellow must be replaced by the blue colored fragment

答: declare a new fragmenttransaction in the second case dont use the fragment transaction  that is used in the first case</p>

Body:
Im currently working on a sample app that will be using fragments, but im having a little problem regarding changing the fragment.

My default layout for my fragment is fragmentOne (see code below).

<fragment
    android:id="@+id/fplace"
    android:layout_width="match_parent"
    android:layout_height="498dp"
    android:name="layout.FragmentOne"
    tools:layout="@layout/fragment_fragment_one" />

and that's working correctly.

but when im changing the fragment it appends. the behavior must replace the fragment not append.

here is my code for the activity (see code below).

public void onClick(View view) {
    Button button = (Button) view;
    Fragment fragment = null;
    switch (button.getId()) {
        case R.id.f1:
            fragment = new FragmentOne();
            FragmentManager fm = getFragmentManager();
            FragmentTransaction ft = fm.beginTransaction();
            ft.replace(R.id.fplace, fragment);
            ft.commit();
            break;
        case R.id.f2:
            fragment = new FragmentTwo();
            fm = getFragmentManager();
            ft = fm.beginTransaction();
            ft.replace(R.id.fplace, fragment);
            ft.commit();
            break;
    }
}

and from the fragment one i am loading the data from the onCreateView() which is working correctly. the main problem is the fragment appends not replace.

(see photo below)

the red and yellow must be replaced by the blue colored fragment


问:
Redirect user to login if not logged in ASP.NET web form using C#
I'm trying to develop  web app in ASP.NET web forms using C# and I've looked everywhere I could on the internet, but I found no solution to the problem. I've tried editing the default Web app template, to restrict a user from accessing any page if the user is not logged in. The default page should be the log in page and if the user clicks on anything else, he/she must be redirected to login page. Using MVC is easier, with just one bit of code on web.config but I've no idea what to do here in the web form

This is currently what my web.config contains.

```<code><?xml version="1.0"?>
<configuration>

  <location path="Manage.aspx">
    <system.web>
      <authorization>
        <deny users="?"/>
      </authorization>
    </system.web>
  </location>

</configuration>
</code>```

Where exactly I need to change?

答:
Mmm....okay lets do it by another way,
First on the login page, in code behind (The C# code not the HTML)
you must create a session like this

```<code>Session["user"] = username;
</code>```

you must create the Session before redirect the user to any page on your website
, Now you created the session with the username or the email whatever you like to store in the session, You must check for the session in every page on your website in the Page_Load method in code behind
to check for the session you do it like this

```<code>protected void Page_Load(object sender, EventArgs e)
        {
            if (Session["user"] == null)
                Response.Redirect("login.aspx", true);
        }
</code>```

where the "login.aspx" is the page in your website that the user will redirected to so, Now if Session["user"] is null the server will go to login.aspx with "just one bit of code"
and to clear the session on the logout button you do it like

```<code>                Session.Clear();
                Session.Abandon();
                Session.RemoveAll();
</code>```

Body:
I'm trying to develop  web app in ASP.NET web forms using C# and I've looked everywhere I could on the internet, but I found no solution to the problem. I've tried editing the default Web app template, to restrict a user from accessing any page if the user is not logged in. The default page should be the log in page and if the user clicks on anything else, he/she must be redirected to login page. Using MVC is easier, with just one bit of code on web.config but I've no idea what to do here in the web form

This is currently what my web.config contains.

<?xml version="1.0"?>
<configuration>

  <location path="Manage.aspx">
    <system.web>
      <authorization>
        <deny users="?"/>
      </authorization>
    </system.web>
  </location>

</configuration>

Where exactly I need to change?

Body:
Mmm....okay lets do it by another way,
First on the login page, in code behind (The C# code not the HTML)
you must create a session like this

Session["user"] = username;

you must create the Session before redirect the user to any page on your website
, Now you created the session with the username or the email whatever you like to store in the session, You must check for the session in every page on your website in the Page_Load method in code behind
to check for the session you do it like this

protected void Page_Load(object sender, EventArgs e)
        {
            if (Session["user"] == null)
                Response.Redirect("login.aspx", true);
        }

where the "login.aspx" is the page in your website that the user will redirected to so, Now if Session["user"] is null the server will go to login.aspx with "just one bit of code"
and to clear the session on the logout button you do it like

                Session.Clear();
                Session.Abandon();
                Session.RemoveAll();


问:
combobox in django?
What's the simplest way to create an editable dropdown in django, i.e a dropdown list that I can also edit as though it's a textarea?

Is there something that's close to plug-and-play, or do I need to write a lot of gritty code?

答: Are you looking for something like a Combobox? I don't know if such a thing exists in the browser. Perhaps it can be done with some Javascript. Google around is my best suggestion. </p>

Title: combobox in django?


问:
Why is the output of this program 312213444 and not 3122134?
In the code given, the output that I can think of is 3122134 because the the last printf statement gets executed only once when n=1. so condition become 1>1 which is definitely not true and the loop exits and the last printf statement is executed. but the original output is 312213444. Why is it so ? Where am I going wrong ? kindly explain every concept and instance of it ? </p>

```<code> #include <stdio.h>
 void count (int n)
 {
 static int d=1;

 printf("%d", n);
 printf("%d", d);
 d++ ;
 if(n>1)
 count(n-1);
 printf("%d", d);
 }

 void main ()
 {
 count(3);
 }
</code>```

答:
Rewrite your printf() statements (and fix your main declaration), for example into

```<code>#include <stdlib.h>
#include <stdio.h>

void count(int n)
{
    static int d=1;

    printf("A) n = %d\n", n);
    printf("B) d = %d\n", d);
    d++;
    if (n>1)
        count(n-1);
    printf("C) d = %d\n", d);
}

int main(void)
{
    count(3);

    return EXIT_SUCCESS;
}
</code>```

Compile and run the code, and look at the output, and you shall understand.

One technique that can help unravel recursive functions, is to unwrap a couple of the recursive calls into separate functions. Here, main() calls count(3), which does a recursive call count(2), which does a recursive call count(1). We can change these recursive calls to calls to separate functions by repeating the function three times. We do need to change the d variable into a global, though, so that each of the function copies uses the same one, instead of separate copies that just happen to have the same name.

```<code>#include <stdlib.h>
#include <stdio.h>

int d = 1;

void count1(void)
{
    int n = 1;
    printf("count1(): A) n = %d\n", n);
    printf("count1(): B) d = %d\n", d);
    d++;
    /* The following is never true, so
       we comment it out:
      if (n>1)
          count0();
    */
    printf("count1(): C) d = %d\n", d);
}

void count2(void)
{
    int n = 2;
    printf("count2(): A) n = %d\n", n);
    printf("count2(): B) d = %d\n", d);
    d++;
    if (n>1)
        count1();
    printf("count2(): C) d = %d\n", d);
}

void count3(void)
{
    int n = 3;
    printf("count3(): A) n = %d\n", n);
    printf("count3(): B) d = %d\n", d);
    d++;
    if (n>1)
        count2();
    printf("count3(): C) d = %d\n", d);
}

int main(void)
{
    count3();

    return EXIT_SUCCESS;
}
</code>```

In this particular case, unraveling the recursive function should help understand control flow. (Specifically, that when you call another function, and the function returns, the execution continues in the caller in the statement following the function call.)

Body:
In the code given, the output that I can think of is 3122134 because the the last printf statement gets executed only once when n=1. so condition become 1>1 which is definitely not true and the loop exits and the last printf statement is executed. but the original output is 312213444. Why is it so ? Where am I going wrong ? kindly explain every concept and instance of it ?

 #include <stdio.h>
 void count (int n)
 {
 static int d=1;

 printf("%d", n);
 printf("%d", d);
 d++ ;
 if(n>1)
 count(n-1);
 printf("%d", d);
 }

 void main ()
 {
 count(3);
 }

Body:
Rewrite your printf() statements (and fix your main declaration), for example into

#include <stdlib.h>
#include <stdio.h>

void count(int n)
{
    static int d=1;

    printf("A) n = %d\n", n);
    printf("B) d = %d\n", d);
    d++;
    if (n>1)
        count(n-1);
    printf("C) d = %d\n", d);
}

int main(void)
{
    count(3);

    return EXIT_SUCCESS;
}

Compile and run the code, and look at the output, and you shall understand.

One technique that can help unravel recursive functions, is to unwrap a couple of the recursive calls into separate functions. Here, main() calls count(3), which does a recursive call count(2), which does a recursive call count(1). We can change these recursive calls to calls to separate functions by repeating the function three times. We do need to change the d variable into a global, though, so that each of the function copies uses the same one, instead of separate copies that just happen to have the same name.

#include <stdlib.h>
#include <stdio.h>

int d = 1;

void count1(void)
{
    int n = 1;
    printf("count1(): A) n = %d\n", n);
    printf("count1(): B) d = %d\n", d);
    d++;
    /* The following is never true, so
       we comment it out:
      if (n>1)
          count0();
    */
    printf("count1(): C) d = %d\n", d);
}

void count2(void)
{
    int n = 2;
    printf("count2(): A) n = %d\n", n);
    printf("count2(): B) d = %d\n", d);
    d++;
    if (n>1)
        count1();
    printf("count2(): C) d = %d\n", d);
}

void count3(void)
{
    int n = 3;
    printf("count3(): A) n = %d\n", n);
    printf("count3(): B) d = %d\n", d);
    d++;
    if (n>1)
        count2();
    printf("count3(): C) d = %d\n", d);
}

int main(void)
{
    count3();

    return EXIT_SUCCESS;
}

In this particular case, unraveling the recursive function should help understand control flow. (Specifically, that when you call another function, and the function returns, the execution continues in the caller in the statement following the function call.)


问:
What is the !! (not not) operator in JavaScript?
I saw some code that seems to use an operator I don't recognize, in the form of two exclamation points, like so: !!. Can someone please tell me what this operator does?

The context in which I saw this was,

```<code>this.vertical = vertical !== undefined ? !!vertical : this.vertical;
</code>```

答:
After seeing all these great answers, I would like to add another reason for using !!. Currently I'm working in Angular 2-4 (TypeScript) and I want to return a Boolean as false when my user is not authenticated. If he isn't authenticated, the token-string would be null or "". I can do this by using the next block of code:

```<code>public isAuthenticated(): boolean {
   return !!this.getToken();
}
</code>```

Body:
I saw some code that seems to use an operator I don't recognize, in the form of two exclamation points, like so: !!. Can someone please tell me what this operator does?

The context in which I saw this was,

this.vertical = vertical !== undefined ? !!vertical : this.vertical;

Body:
After seeing all these great answers, I would like to add another reason for using !!. Currently I'm working in Angular 2-4 (TypeScript) and I want to return a Boolean as false when my user is not authenticated. If he isn't authenticated, the token-string would be null or "". I can do this by using the next block of code:

public isAuthenticated(): boolean {
   return !!this.getToken();
}

ContentLicense: CC BY-SA 4.0