text:
Q: Select multiple table rows with php Hi I have a table populated from MYSQL, what i am trying to do is have a check box on each row where i can just select and then press one button and update all of the selected rows with one press.
Here is the code for my checkboxes.
 <input type='checkbox' name='checked[]' value='<?php echo $row['id']; ?>'>

And here is my PHP Code
 if ($_POST['submit']){ //check if they submitted

  //see which check boxes were selected
  foreach ($_POST['checked'] as $key => $val){

  //update records
  $result = mysql_query("UPDATE masterip_details SET type='3' WHERE id='$key'")
             or die(mysql_error());
    }
  }

At the moment nothing happens, and if i try and echo key then i get no id's

A: You need to use $val instead of $key. $key will only contain the index of the order of checked[]
I have also removed the if($_POST['submit']) code and replaced it with if(count($_POST['checked']>0))
if (count($_POST['checked']>0)){
    foreach ($_POST['checked'] as $key => $val){

        $val = mysql_real_escape_string($val);

        $result = mysql_query("UPDATE masterip_details SET type='3' WHERE id='{$val}'");
    }
}

A: A checkbox that isn't checked won't be send to the server, and I remember something about it only sending 1 if it is checked.
So, you can change your script to:
<input type='checkbox' name='checked[<?php echo $row['id']; ?>]' />

And check it with the $key


text:
Q: Installing strapi application I'm trying to install Strapi application but I kept getting these error messages after installation. I have attached the error messages below. Does anyone know how to fix it?
PS C:\Users\Abon\Documents\vscode\shop\api> npx create-strapi-app@latest . --quickstart
Need to install the following packages:
  create-strapi-app@4.6.0
Ok to proceed? (y) y
Creating a quickstart project.
Creating a new Strapi application at C:\Users\Abon\Documents\vscode\shop\api.
Creating files.
Error while installing dependencies:
warning ..\package.json: No license field
warning @strapi/strapi > koa-session > uuid@3.4.0: Please upgrade  to version 7 or higher.  Older versions may use Math.random() in certain circumstances, which is known to be problematic.  See https://v8.dev/blog/math-random for details.
warning @strapi/strapi > koa-body > formidable@1.2.6: Please upgrade to latest, formidable@v2 or formidable@v3!
warning @strapi/strapi > @strapi/admin > react-router > mini-create-react-context@0.4.1: Package no longer supported. Contact Support at https://www.npmjs.com/support for more info.
warning @strapi/strapi > @strapi/admin > node-polyfill-webpack-plugin > url > querystring@0.2.0: The querystring API is considered Legacy. new code should use the URLSearchParams API instead.
warning @strapi/strapi > @strapi/plugin-email > @strapi/provider-email-sendmail > sendmail > mailcomposer@3.12.0: This project is unmaintained
warning @strapi/strapi > @strapi/plugin-email > @strapi/provider-email-sendmail > sendmail > mailcomposer > buildmail@3.10.0: This project is unmaintained
warning @strapi/strapi > @strapi/generators > plop > liftoff > findup-sync > micromatch > snapdragon > source-map-resolve@0.5.3: See https://github.com/lydell/source-map-resolve#deprecated
warning @strapi/strapi > @strapi/generators > plop > liftoff > findup-sync > micromatch > snapdragon > source-map-resolve > resolve-url@0.2.1: https://github.com/lydell/resolve-url#deprecated
warning @strapi/strapi > @strapi/generators > plop > liftoff > findup-sync > micromatch > snapdragon > source-map-resolve > urix@0.1.0: Please see https://github.com/lydell/urix#deprecated
warning @strapi/strapi > @strapi/generators > plop > liftoff > findup-sync > micromatch > snapdragon > source-map-resolve > source-map-url@0.4.1: See https://github.com/lydell/source-map-url#deprecated
warning @strapi/plugin-users-permissions > request@2.88.2: request has been deprecated, see https://github.com/request/request/issues/3142
warning @strapi/plugin-users-permissions > request > uuid@3.4.0: Please upgrade  to version 7 or higher.  Older versions may use Math.random() in certain circumstances, which is known to be problematic.  See https://v8.dev/blog/math-random for details.
warning @strapi/plugin-users-permissions > request > har-validator@5.1.5: this library is no longer supported
warning "@strapi/plugin-users-permissions > @strapi/helper-plugin@4.6.0" has unmet peer dependency "webpack@^5.74.0".
warning "@strapi/strapi > @strapi/admin > @strapi/design-system > @uiw/react-codemirror > codemirror > @codemirror/autocomplete@6.4.0" has unmet peer dependency "@lezer/common@^1.0.0".
warning "@strapi/strapi > @strapi/plugin-content-type-builder > @strapi/helper-plugin > react-select > @emotion/react > @emotion/babel-plugin@11.10.5" has unmet peer dependency
"@babel/core@^7.0.0".
error C:\Users\Abon\Documents\vscode\shop\api\node_modules\better-sqlite3: Command failed.
Exit code: 1
Command: prebuild-install || npm run build-release
Arguments:
Directory: C:\Users\Abon\Documents\vscode\shop\api\node_modules\better-sqlite3
Output:
prebuild-install warn install No prebuilt binaries found (target=18.12.1 runtime=node arch=x64 libc= platform=win32)

> better-sqlite3@7.4.6 build-release
> node-gyp rebuild --release

gyp info it worked if it ends with ok
gyp info using node-gyp@9.1.0
gyp info using node@18.12.1 | win32 | x64
gyp info find Python using Python version 3.11.1 found at "C:\Users\Abon\AppData\Local\Programs\Python\Python311\python.exe"
gyp ERR! find VS
gyp ERR! find VS msvs_version not set from command line or npm config
gyp ERR! find VS VCINSTALLDIR not set, not running in VS Command Prompt
gyp ERR! find VS could not use PowerShell to find Visual Studio 2017 or newer, try re-running with '--loglevel silly' for more details
gyp ERR! find VS looking for Visual Studio 2015
gyp ERR! find VS - not found
gyp ERR! find VS not looking for VS2013 as it is only supported up to Node.js 8
gyp ERR! find VS
gyp ERR! find VS **************************************************************
gyp ERR! find VS You need to install the latest version of Visual Studio
gyp ERR! find VS including the "Desktop development with C++" workload.
gyp ERR! find VS For more information consult the documentation at:
gyp ERR! find VS https://github.com/nodejs/node-gyp#on-windows
gyp ERR! find VS **************************************************************
gyp ERR! find VS
gyp ERR! configure error
gyp ERR! stack Error: Could not find any Visual Studio installation to use
gyp ERR! stack     at VisualStudioFinder.fail (C:\Program Files\nodejs\node_modules\npm\node_modules\node-gyp\lib\find-visualstudio.js:122:47)
gyp ERR! stack     at C:\Program Files\nodejs\node_modules\npm\node_modules\node-gyp\lib\find-visualstudio.js:75:16
gyp ERR! stack     at VisualStudioFinder.findVisualStudio2013 (C:\Program Files\nodejs\node_modules\npm\node_modules\node-gyp\lib\find-visualstudio.js:364:14)
gyp ERR! stack     at C:\Program Files\nodejs\node_modules\npm\node_modules\node-gyp\lib\find-visualstudio.js:71:14
gyp ERR! stack     at C:\Program Files\nodejs\node_modules\npm\node_modules\node-gyp\lib\find-visualstudio.js:385:16
gyp ERR! stack     at C:\Program Files\nodejs\node_modules\npm\node_modules\node-gyp\lib\util.js:54:7
gyp ERR! stack     at C:\Program Files\nodejs\node_modules\npm\node_modules\node-gyp\lib\util.js:33:16
gyp ERR! stack     at ChildProcess.exithandler (node:child_process:420:5)
gyp ERR! stack     at ChildProcess.emit (node:events:513:28)
gyp ERR! stack     at maybeClose (node:internal/child_process:1091:16)
gyp ERR! System Windows_NT 10.0.19045
gyp ERR! command "C:\\Program Files\\nodejs\\node.exe" "C:\\Program Files\\nodejs\\node_modules\\npm\\node_modules\\node-gyp\\bin\\node-gyp.js" "rebuild" "--release"
gyp ERR! cwd C:\Users\Abon\Documents\vscode\shop\api\node_modules\better-sqlite3
gyp ERR! node -v v18.12.1
gyp ERR! node-gyp -v v9.1.0
gyp ERR! not ok

Oh, it seems that you encountered errors while installing dependencies in your project.
Don't give up, your project was created correctly.
Fix the issues mentioned in the installation errors and try to run the following command:
cd C:\Users\Abon\Documents\vscode\shop\api && yarn install

redpajama_set_name: RedPajamaStackExchange


text:
Q: c++ tic tac toe Non int characters causing infinite loop Trying to complete an assignment for a simple tic tac toe game without using functions or anything that has not been covered in our class.  Currently everything in the code is acceptable but I keep getting an infinite loop issue when picking a square and using a character that is not a number.  Any help would be appreciated!
#include <iostream>
using namespace std;

int i;
char board[10];
bool gameover;
bool check_choice;
char player;
int choice = 0;
char restart;

int main()
{

do
{

    for (int i = 0; i < 10; i++) board[i] = ' ';

    bool gameover = false;
    bool check_choice = true;
    char player = 'X';

    do
    {
        // Draw game board

        cout << "+---+---+---+ \n";
        cout << "| " << board[1] << " | " << board[2] << " | " << board[3] << " |  \n";
        cout << "+---+---+---+ \n";
        cout << "| " << board[4] << " | " << board[5] << " | " << board[6] << " |  \n";
        cout << "+---+---+---+ \n";
        cout << "| " << board[7] << " | " << board[8] << " | " << board[9] << " |  \n";
        cout << "+---+---+---+ \n";

        // Win Check

        if ((board[1] == 'X' && board[2] == 'X' && board[3] == 'X') ||
            (board[4] == 'X' && board[5] == 'X' && board[6] == 'X') ||
            (board[7] == 'X' && board[8] == 'X' && board[9] == 'X') ||
            (board[1] == 'X' && board[4] == 'X' && board[7] == 'X') ||
            (board[2] == 'X' && board[5] == 'X' && board[8] == 'X') ||
            (board[3] == 'X' && board[6] == 'X' && board[9] == 'X') ||
            (board[1] == 'X' && board[5] == 'X' && board[9] == 'X') ||
            (board[3] == 'X' && board[5] == 'X' && board[7] == 'X'))
        {
            cout << "Game Over - X wins! \n";
            gameover = true;
        }

        else if ((board[1] == 'O' && board[2] == 'O' && board[3] == 'O') ||
            (board[4] == 'O' && board[5] == 'O' && board[6] == 'O') ||
            (board[7] == 'O' && board[8] == 'O' && board[9] == 'O') ||
            (board[1] == 'O' && board[4] == 'O' && board[7] == 'O') ||
            (board[2] == 'O' && board[5] == 'O' && board[8] == 'O') ||
            (board[3] == 'O' && board[6] == 'O' && board[9] == 'O') ||
            (board[1] == 'O' && board[5] == 'O' && board[9] == 'O') ||
            (board[3] == 'O' && board[5] == 'O' && board[7] == 'O'))
        {
            cout << "Game Over - O wins! \n \n";
            gameover = true;
        }
        // Draw Check

        else if ((board[1] != ' ' && board[2] != ' ' && board[3] != ' ') &&
                 (board[4] != ' ' && board[5] != ' ' && board[6] != ' ') &&
                 (board[7] != ' ' && board[8] != ' ' && board[9] != ' '))
        {
            cout << "Game Over - Draw \n \n";
            gameover = true;
        }
        else

            check_choice = true;

        while (check_choice == true)
        {
            cout << "Place " << player << " at: ";
            cin >> choice;

            if (choice > sizeof(board) || choice == 0 || choice == 10)
            {
                cout << "Invalid input! 1-9 only. \n";
                check_choice = true;
            }

            else if (board[choice] == ' ')
            {
                board[choice] = (player == 'X') ? 'X' : 'O';
                player = (player == 'X') ? 'O' : 'X';
                check_choice = false;
            }
            else
            {
                cout << "Invalid input! Position already filled. \n";
                check_choice = true;
            }
        }

    } while (gameover == false);

    cout << "Would you like to play again? (Y / N): ";
    cin >> restart;
    cin.ignore();

} while (restart == 'y' || restart == 'Y');

cout << "Thanks for playing!! \n \n";

system("pause");
return 0;
}

A: When an error occurs when reading from a stream, an error flag gets set and no more reading is possible until you clear the error flags. That's why you get an infinite loop.
Copied the answer from here, so no credit to me :P
And as @PaulMcKenzie said, you're better of reading it into a string first, and then doing the necessary checks.

A: As melk correctly pointed out, the issue is with the error flag which gets set when you get wrong input preventing you from using the stream before you clear the flag.
Others have suggested using strings and then validating the input which would work quite well. But, if you don't want to make a lot of changes in your code, you can just declare your choice variable to be of type char.
Now, after you take the input, because of the way the char data type works, your choice variable will store the ASCII value of the character entered by the user. To make it store the numeric value itself instead, you can do this neat trick:
choice -= '0';

This exploits the fact that in ASCII, the numeric characters come one after the other starting from '0'. So '1' - '0' would give 1 and '5' - '0' would give 5.
Now the rest of your code now works well, since you won't face any problem checking whether the entered character was a number between 1-9.
Though one more thing you'll need to do is to flush the input buffer when the user enters a wrong choice. This is to prevent the error message from appearing multiple times ( once for each character entered ) if the user enters multiple characters.
So your code should overall look like this ( I have just added two more lines):
#include <iostream>
using namespace std;

int i;
char board[10];
bool gameover;
bool check_choice;
char player;
char choice = 0; // the choice variable is now a character
char restart;

int main()
{

do
{

    for (int i = 0; i < 10; i++) board[i] = ' ';

    bool gameover = false;
    bool check_choice = true;
    char player = 'X';

    do
    {
        // Draw game board

        cout << "+---+---+---+ \n";
        cout << "| " << board[1] << " | " << board[2] << " | " << board[3] << " |  \n";
        cout << "+---+---+---+ \n";
        cout << "| " << board[4] << " | " << board[5] << " | " << board[6] << " |  \n";
        cout << "+---+---+---+ \n";
        cout << "| " << board[7] << " | " << board[8] << " | " << board[9] << " |  \n";
        cout << "+---+---+---+ \n";

        // Win Check

        if ((board[1] == 'X' && board[2] == 'X' && board[3] == 'X') ||
            (board[4] == 'X' && board[5] == 'X' && board[6] == 'X') ||
            (board[7] == 'X' && board[8] == 'X' && board[9] == 'X') ||
            (board[1] == 'X' && board[4] == 'X' && board[7] == 'X') ||
            (board[2] == 'X' && board[5] == 'X' && board[8] == 'X') ||
            (board[3] == 'X' && board[6] == 'X' && board[9] == 'X') ||
            (board[1] == 'X' && board[5] == 'X' && board[9] == 'X') ||
            (board[3] == 'X' && board[5] == 'X' && board[7] == 'X'))
        {
            cout << "Game Over - X wins! \n";
            gameover = true;
        }

        else if ((board[1] == 'O' && board[2] == 'O' && board[3] == 'O') ||
            (board[4] == 'O' && board[5] == 'O' && board[6] == 'O') ||
            (board[7] == 'O' && board[8] == 'O' && board[9] == 'O') ||
            (board[1] == 'O' && board[4] == 'O' && board[7] == 'O') ||
            (board[2] == 'O' && board[5] == 'O' && board[8] == 'O') ||
            (board[3] == 'O' && board[6] == 'O' && board[9] == 'O') ||
            (board[1] == 'O' && board[5] == 'O' && board[9] == 'O') ||
            (board[3] == 'O' && board[5] == 'O' && board[7] == 'O'))
        {
            cout << "Game Over - O wins! \n \n";
            gameover = true;
        }
        // Draw Check

        else if ((board[1] != ' ' && board[2] != ' ' && board[3] != ' ') &&
                 (board[4] != ' ' && board[5] != ' ' && board[6] != ' ') &&
                 (board[7] != ' ' && board[8] != ' ' && board[9] != ' '))
        {
            cout << "Game Over - Draw \n \n";
            gameover = true;
        }
        else

            check_choice = true;

        while (check_choice == true)
        {
            cout << "Place " << player << " at: ";
            cin >> choice;
            choice -= '0'; // added this line to convert character to number

            if (choice > sizeof(board) || choice == 0 || choice == 10)
            {
                cout << "Invalid input! 1-9 only." << std::endl;
                check_choice = true;
                fflush(stdin); // added this line to clear input buffer
            }

            else if (board[choice] == ' ')
            {
                board[choice] = (player == 'X') ? 'X' : 'O';
                player = (player == 'X') ? 'O' : 'X';
                check_choice = false;
            }
            else
            {
                cout << "Invalid input! Position already filled. \n";
                check_choice = true;
            }
        }

    } while (gameover == false);

    cout << "Would you like to play again? (Y / N): ";
    cin >> restart;
    cin.ignore();

} while (restart == 'y' || restart == 'Y');

cout << "Thanks for playing!! \n \n";

system("pause");
return 0;
}

Nice work on the game, otherwise, by the way. Looking great for a console project.

A: You can use something like
string mystr;
getline (cin,mystr);

to read a line from cin into a string. After this, you can check if it is a number and then obtain it or, if it is not, show an error.
PS: you should not use global variables and you should split your code into functions. Also, your array is one larger than it needs to be (you are allocating space for 10 elements but you just need 9). Be careful tho, since you are mistakenly starting the indices at 1, when arrays start at 0, which means right now you are ignoring completely the first element. If you change it to allocate 9 elements make sure to substract 1 to all your indices have them correct (otherwise accesing 9 will cause errors as you are accesing an element out of the array bounds).


text:
Q: Make new column based on only the first value of another column while fill others with 0 I have a data frame and a key, key[1,2,3,4] :
Animal Arm
1      2
1      4
1      3
1      3
1      1
1      1

I want to create a new column called response based on the condition that if the arm values are in the key then response is equal to 1 else response is equal to 0. However the trick is that it should be only for the first values only and any repetition of the arm value should yield a response as 0. Just like this :
Animal  Arm  Response
1       2    1
1       4    1
1       3    1
1       3    0
1       1    1
1       1    0

There can be only a maximum of 4 value having response as 1
This is what i tried :
resp = []
for i in range(len(df3)):
            for j in key:
                if df['Arm'][i] == j:
                    resp.append(1)
                    break
            else: resp.append(0)

df['Response'] = resp

but i dont know how to make only the first values of the key as 1 and any repition of the values as zero.
Can someone help?

A: Use Series.isin with DataFrame.duplicated - per both columns for test duplicated values per Animal and Arm, in another words duplicated values of Arm are tested per groups by Animal
I understand this logic from tag group-by.
df['Response'] = (df['Arm'].isin(key) & ~df.duplicated(['Animal','Arm'])).astype(int)
print (df)
   Animal  Arm  Response
0       1    2         1
1       1    4         1
2       1    3         1
3       1    3         0
4       1    1         1
5       1    1         0

Add data for see difference:
key = [1,2,3,4]
df['Response'] = (df['Arm'].isin(key) & ~df.duplicated(['Animal','Arm'])).astype(int)
print (df)
    Animal  Arm  Response
0        1    2         1
1        1    4         1
2        1    3         1
3        1    3         0
4        1    1         1
5        1    1         0
6        2    2         1
7        2    4         1
8        2    3         1
9        2    3         0
10       2    1         1
11       2    1         0

A: You can use isin combined with duplicated:
df['Response'] = (df['Arm'].isin(key)&~df['Arm'].duplicated()).astype(int)

Or:
df['Response'] = np.where(df['Arm'].isin(key)&~df['Arm'].duplicated(), 1, 0)

Output:
   Animal  Arm  Response
0       1    2         1
1       1    4         1
2       1    3         1
3       1    3         0
4       1    1         1
5       1    1         0

A: resp = []
respDone= []
for i in range(len(df)):
    for j in key:
        if df['Arm'][i] == j and df["Arm"][i] not in respDone:
            resp.append(1)
            respDone.append(df["Arm"][i])
            break
    else: resp.append(0)

df['Response'] = resp


text:
Q: Use the rel text in the current text displayed by Colorbox Is it possible to use the rel text in the current text displayed by Colorbox?
I have a gallery of images grouped with rel="Project Name"

Intertek

I would like the current text to say "Project Name 1 of 10" instead of "image 1 of 10". Is it possible to use the value from rel= in the current= text
EDIT: I have multiple galleries so the rel would need to be dynamic. http://ggsc.info/new/index.html
Here is the colorbox jquery:
$("div.projectBlock").each(function(index){
            var className = "group" + (index+1);

            $(this).find("a")
            .addClass(className)
            .colorbox({maxWidth:'95%', maxHeight:'95%', current: '{current} of {total}'});
          });

In the current parameter, I was hoping for something like "current: '{rel} {current} of {total}'"

A: You can manually change the var in the plugin:
Line 62: current: "image {current} of {total}",
Change image to Project name.
EDIT:
$("div.projectBlock").each(function (index) {
    var className = "group" + (index + 1),
        $this = $(this),
        rel = $this.find("a").attr("rel");

    $(this).find("a")
        .addClass(className)
        .colorbox({
        maxWidth: '95%',
        maxHeight: '95%',
        current: rel + '{current} of {total}'
    });
});

A: $('.projectName').text($(this).parent().parent().attr('rel'));


text:
Q: Dynamically updating Telegraf config with agent hosts? I have a number of network switches in my infrastructure and I have been using telegraf to collect data traffic information from switches with snmp. So far switch IP addresses were added to the config statically. I was wondering if it is possible to call IP list from a database so I don't need to add it every time statically into the config? Or maybe telegraf is just not the tool for that.
Usual config looks like this:
[[inputs.snmp]]
  agents = [ "192.168.252.15:161" ]
  version = 2
  community = "public"
  name = "snmp"

 [[inputs.snmp.field]]
    name = "hostname"
    oid = "RFC1213-MIB::sysName.0"
    is_tag = true

  [[inputs.snmp.table]]
    name = "snmp"
    inherit_tags = [ "hostname" ]
    oid = "IF-MIB::ifXTable"

    [[inputs.snmp.table.field]]
      name = "ifName"
      oid = "IF-MIB::ifName"
      is_tag = true

A: I would just write a script that would modify the telegraf.conf file as you need. I do something similar for auto-scaled servers in AWS... So I have a bash script that cloud-init runs when instances are created from an image which has most of my telegraf config already in it, and then this script modifies it so the hostname is modified with the new IP address.
So ultimately, I think you just need a script that runs upon creation or whatever the scenario is for your needs. My two cents anyway...


text:
Q: Use *#9900# to take log where to use this I am getting this error Use *#9900# to take log where should I use this to take crash log.
I am not having eclipse or adt to see the logcat.
Thanks

A: It may be probably OEM key short cut to save sys dump in some specific folder.
You can check in your sdcard to view them

A: You must type this as if it were a phone number.

A: *

*Select the 'Phone' icon on your android as if you were about to dial a phone number.

*Dial *#9900#

*Select 'DELETE DUMPSTATE/LOGCAT' - second option from top.

*When option 'delete Dump!' appears click on 'OK'
This may or may not solve your problem but it will clear all the rubbish from your android.


text:
Q: When Will textFieldDidEndEditing:textField be called? I have 2 UITextField in a ViewController. One brings up a UIDatePicker another brings up a KeyBoard(number pad). I then assign user inputs to two class variables, a NSDate variable and a NSNumber variable, in the following method.
-(void)textFieldDidEndEditing:(UITextField *)textField{
    if (textField == self.datePickerTextField){
        //update xxtime
        self.xxTime = self.datePicker.date;
        NSLog(@"...%@",self.xxTime);
    }
     if (textField == self.numberTextField) {
        int val = [textField.text intValue];
        self.xxNumber = [NSNumber numberWithInt:val];
        NSLog(@"...%@",self.xxNumber);
    }

}

If I tap the datePickerTextField first then the numberTextField, this method won't get called after I finish typing in the numberTextField.
So my question is how do I make this method to get called?  Should I specify "resignFirstResponder" somewhere?
TIA

A: It will invoke didEndEditing once another control gains focus
According to the API,

This method is called after the text field resigns its first responder
  status.

So if you want didEndEditing to be invoked, you need to call
[textField resignFirstResponder];

A: Yo are right you need to specify resignFirstResponder
- (BOOL)textFieldShouldReturn:(UITextField *)textField {//Text Field Delegate
    if (textField == textField1) {
        [textField1 becomeFirstResponder];
    }else{
        [textField resignFirstResponder];
    }
    return TRUE; }

this can used with textFieldDidEndEditing also

A: Please check what iOS you are using. Remember that if you are using iOS 10, there is a method that is replacing the old textFieldDidEndEditing called func textFieldDidEndEditing(_ textField: UITextField, reason: UITextFieldDidEndEditingReason)


text:
Q: ant build change a file without rebuild entire project I have a config file that is very large and I do not wish to change its content.
Whenever I tried to change a file, I have to rebuild the entire war package. Which this could cause a large amount of time loss due to large codebase. I was wondering if I can just change a jar of the class that I have changed?
For example if I could just use native javac and generate the class file and copy/replace to the jar without rebuilding the entire project. Would that work? will it impact my other class files?
If the above generate a different result are there any alternative that I could use without changing the configuration for generating the war package?

A: You can deploy separate jar files in your project:
I assume you use Tomcat:

*

*Go to the webapps directory.

*Remove the .war

*copy over your changes to the webapps/yourapp directory using rsync (for example).


text:
Q: create inputfield with span on the right side First: I dont use bootstrap, I want to build this, without bootstrap.
I want to create this

,but I dont know how to handle the span on the right side of the input field. Here is my try.

.input_register{
 padding: 5px;
 border: 2px solid green;
}

.input_register:hover{
 border: 2px solid #151A22;
}

.input_register:focus{
 border: 2px solid #151A22;
}

.register_span{
 background-color: red;
 padding: 5px;
 border: 2px solid #151A22;
    border-left: none;
}

  <input class="input_register" type="text"/>D

Why is the span higher as the inputfield?

A: display: inline-block;
inline-block displays similar characteristics as an inline element while being able to alter the sizing like a block element.
Setting line-height: 1em sets the height of the containing block equal to the size of the font. In this case I've used line-height: 1.5em to give it some extra space.
Also, vertical padding on these elements yields unexpected results, using line-height instead gives a more consistent appearance.

.input_register,
.register_span {
    display: inline-block;
    font-size: 12pt;
    line-height: 1.5em;
    padding: 0px 5px;
}

.input_register{
    border: 2px solid green;
}

.input_register:hover{
    border: 2px solid #151A22;
}

.input_register:focus{
    border: 2px solid #151A22;
}

.register_span{
    background-color: red;
    border: 2px solid #151A22;
    border-left: none;
}

  <input class="input_register" type="text"/>D


text:
Q: Regular Expression to match zero or more spaces in Microsoft Word I hope I'm just missing the obvious here, but how in the world do I match zero or more spaces with Microsoft Word 2010's "Regex" engine?
As a silly example, I want to match all of the following in a capture group:
cowseat grass
cows eat grass
cows  eat grass
cows   eat grass
cows    eat grass

I would normally do (cows\s*eat grass) and be done with it. But I can't see how to match zero or more spaces. I want to capture the whole phrase in a capture group, but I have variable number of spaces.
I've been using this document as a reference.

A: The document you linked to shows that Microsoft's "regular expressions" aren't really regular expressions at all; they're a bizarre hybrid (bastard child, rather) of shell-style globbing (http://www.tldp.org/LDP/GNU-Linux-Tools-Summary/html/x11655.htm) and true regular expressions.
Since the glob syntax makes use of the * character as a synonym for the regex .*, and Microsoft decided (as mentioned in a comment) to make @ equivalent to the regex quantifier + instead of * (which is stupid since a+ is equivalent to aa* for any atom a, making + unnecessary), it looks like you're out of luck.
My personal opinion is that (1) this is stupid and (2) calling these patterns "regular expressions" is misleading at best, but unfortunately I don't see any way around this except for abandoning Word in favor of a tool that properly supports regex. (Though I suppose in theory you could try to parse the xml-ish format of the docx file itself, extract the text, and then apply your regex....)


text:
Q: There is a MS Access internal timestamp for updates/creations? I'm looking to fetch everything in a MS Access database but only rows from a given timestamp and there is no timestamps attributes by default.
Someone told me that there is an internal timestamp for updates/creation in MS Access but I can't find something about that.
ps: The database is read-only

A: Based off of the information here: Microsoft Access : How can I get creation date of row?, the answer to your question is no.
It seems Access doesn't keep track of when a timestamp was created.  You need to have your own system implemented.


text:
Q: How to access value inside String. Flutter/Dart This is my code :
    String text = snapshot.data[index];
     var splitText = text.split("\n") ;

final jdata = jsonEncode(splitText[5]);

                          print(jdata);

which prints the String :
"RunHyperlink : {classid: 25510, id: 2, mad_key: 32835}"

snapshot.data[index] contains :
I/flutter (14351): Code : LE-0000000002
I/flutter (14351): Description : test_01
I/flutter (14351): Organisation Unit : 01_01_04_01_SA - Shah Alam
I/flutter (14351): Date Reported : 18/09/2020
I/flutter (14351): Status : LE110 - Pending Approval
I/flutter (14351): RunHyperlink : {classid: 25510, id: 2, mad_key: 32835}

my question is how do I access the value of "id".
Thanks!

A: I'm assuming that string is not changing in any condition other wise logic may fail..
void main() {
  // actual string
  // String x="RunHyperlink : {classid: 25510, id: 2, mad_key: 32835}";
  String x = snapshot.data[index];

  // remove unwanted substring form string
  List keyValues= x.replaceAll('RunHyperlink : {','').replaceAll('}','').replaceAll(', ',',').split(",");

  //create map
  Map map = {};

  // run for loop to split key and value
  for (var element in keyValues){
    print(element.split(": ")[0]);
    map.addAll({element.split(": ")[0] : element.split(": ")[1]});
  }

  // get the id balue

  print(map['id']);

}

A:           String temp;
          const start = " id:";
          const end = ",";
          if (str.contains(start)) {
            final startIndex = str.indexOf(start);
            final endIndex = str.indexOf(end, startIndex + start.length);
            temp = str.substring(startIndex + start.length, endIndex);
            print("ID $temp");
          }

or
          Iterable<Match>? matches = RegExp(r' id\W*([a-z0-9\s]+,)').allMatches(str);
          for (var m in matches) {
            print(m.group(0));
          }


text:
Q: Test import react-native or react-native-web I've React monorepo project with React-Native and React-Native-Web.
In common module, i would like use View and Text component, but i need to change my import on mobile (react-native) or web (react).
I've try this :
const { View, Text } = window ? require('react-native-web') : require('react-native');
But that does not work, which makes sense.
Anyone have already this use case ?
Thank you !

A: After setting up your project to use react-native-web, you simply import everything from react-native and react-native-web takes care of the rest. If you have your project configured correctly import { View, Text } from 'react-native is all you need, and on web react-native-web will render divs instead of View and p or whatever instead of Text. Code like it's react native.


text:
Q: Java ADF stored value from data control doesn't display until next run Basically I've got a JSF page with a number of components, including an ADF table populated with a List of data returned from a getData() method in my data control class.
Above the table I'm trying to display some calculated values from the data displayed - but the field values are not being displayed correctly.
(I'm using JDev 11.1.1.5)
The data control class is called RecentDeals and the getData() method returns a List of Deal objects that includes a number of fields (dates, values, names, etc).
The RecentDeals class also contains private variables to store the calculated (average) values to be displayed above the table (eg. avgSize, avgTerm, avgRent, etc).
In the same getData() method, after iterating through the List of Deals to perform required calculations (and storing the respective values along the way), the variables are updated with the calculated averages before returning the List of Deal objects that populates the table.
Below is an excerpt of the code for reference:
public class RecentDealsDC {

    private Double avgSize;
    private Double avgTerm;
    private Double avgRent;
    ...

    public RecentDealsDC() {
        super();
        avgSize = 0.0;
        avgTerm = 0.0;
        avgRent = 0.0;
        ...
    }

    public List<DealDTO> getData(List<String> businessUnits){
        List<TransactionDTO> transactions = new ArrayList<TransactionDTO>();
        List<DealDTO> deals = new ArrayList<DealDTO>();
        TransactionSessionBean transBean = lookupTransactionSessionBean();

        Double size = 0.0;
        Double term = 0.0;
        Double totalBaseRent = 0.0;
        ...
        Integer recordCount = 0;

        if (businessUnits != null && !businessUnits.isEmpty()){
            transactions = transBean.getDealsData(SystemUtil.getCurrentUser(), businessUnits);

            recordCount = transactions.size();

            if( recordCount > 0 ){
                for (int i=0; i < recordCount; i++){
                    TransactionDTO transObj = new TransactionDTO();
                    DealDTO dealObj = new DealDTO();

                    transObj = transactions.get(i);

                    // process transaction, execute logic, store deal values

                    size = size + transObj.getRentableArea();
                    term = term + transObj.getLeaseTerm();
                    totalBaseRent = totalBaseRent + (transObj.getRentableArea() * transObj.getBaseRent());
                    ...

                    deals.add(dealObj);
                }
            }

            avgSize = size / recordCount;
            avgTerm = term / recordCount;
            avgRent = totalBaseRent / size;
            ...

        }

        return deals;
    }
}

When I run my JSF page it correctly displays the data from the List of Deal objects but the calculated fields just display zero.
When the user selects the next "criteria" to populate the table (from a dropdown list in the header), the calculated fields are then updated with the previous stored values.
So in other words the header fields are showing the averages pertaining to the previous set of data and the cycle seems to continue for each subsequent user selection - so the user is forced to select another value to get the averages needed, which is obviously not acceptable.
I have confirmed in debug mode that the calculations are being executed correctly and the correct values are stored in the private variables before the List is returned.
Not sure what I'm missing here but I'm thinking I need to somehow "refresh" the outputText components to display the expected values right away.
That is what I'm researching but at something of a loss right now.
Any suggestions/direction/ideas would be really appreciated.
EDIT:  It looks like the outputText fields also update when I collapse and re-expand the panelBox they are contained inside.  So I'm wondering if there's some way for me to manually perform that same update...
Thanks,
Karim

A: The solution I came to is as follows:
Revised the DC class getData method to return a new DTO that contained the original List resultset and the 4 variables I needed to display.
Then I bound the resultset and variables from below the returned DTO to the same respective components (resultset in ADF table, variables in 4 outputText fields in header above resultset table).
Then I added a Refresh="IfNeeded" property to the Iterator for the attribute bindings.
Now my outputText fields refresh as expected at the same time as the resultSet changes!
Karim


text:
Q: Conversion is not correct in C program? I have created this program, it converts miles into km but answer is wrong when i compare it with my Phone's result. But in program everything is fine.
int main(void) {

char i;
float km, miles;

do {
    printf("Enter Distance in Miles: "); scanf("%f", &miles);
    km = miles * 1.906;

    printf("Distance in KM is: %.2f \n", km);

    printf("Enter Y/y to continue or any other key to stop."); scanf(" %c", &i);
}
while( i == 'y' || i == 'Y' );
}

A: Your conversion factor is wrong: there are 1.609 km in 1 mile.
More precisely, 1 foot is 0.3048 m (by definition), so 5280 ft (1 mile) is (5280 * 0.3048 / 1000) = 1.609344 km.

A: Your formula is wrong, the correct one is:
km = miles * 1.609


text:
Q: Adding extension methods to ASP.net repeater's NamingContainer I'm trying to write an extension method for the asp.net repeater control that would allow me to call the following code in the repeaters template. This is to say that I would like to call my own Eval method on the repeater.
<%# UmbracoEval("propertyName") %>

I've tried targeting the Repeater control itself as well as the NamingContainer but I get accessibility errors seeing as the Container is protected.
Is this even possible? I've never called extension methods from markup so I'm not sure. Thanks.

A: You still need Eval or Bind -  UmbracoEval(Eval("propertyName")) or UmbracoEval(Bind("propertyName")).
Both Eval and Bind return an object, so extension method for an object is not a good idea.
However, you can create that UmbracoEval in code behind and call it from aspx.
protected string UmbracoEval(object eval)
{
    return eval.ToString() + " abc"; // do something
}


text:
Q: finding a topological group with specific conditions I have a question, it sounds difficult.
The question is the following:
Let $X$ be a topological group such that the binary operation defined on it is $*$. For any two points $a$ and $b$ in $X$ define a new operation by $a(*)b=b^{-1}*a*b$, [$(*)$ is a new operation on $X$ inherited from $*$]. By this $(*)$, we get that $a(*)a=a$, for all $a$ in $X$. Now let $X_3$ be a subset of $X$ contains 3 elements, say $a$, $b$ and $c$ such that $a(*)b=b(*)a=c$; $a(*)c=c(*)a=b$; $c(*)b=b(*)c=a$. The question is find a specific example of topological group described above. Explain what is $*$ and determine the three elements $a$, $b$ and $c$.
I thought about it and unfortunately I have not found any topological group with the conditions mentioned. We can define $(*)$ for any group, yes, but the problem how to find the 3 elements in the question. I tried circle, torus, $SO_3$. What do you think, can we find one as described in the question?
By topological group we mean a topological space and a group $G$ at the same time such that the operation $G \times G \to G$ and taking the inverse  $x \mapsto x^{-1}$ are continuous functions. So it has algebraic structure (group) and topological structure. Examples: Circle, torus, $SO_3$.
Please give me a hint.
Thank you in advance

A: The symmetric group on three letters works.
Let $a,b,c$ be the three transpositions. Conjugate any one by any other and you get the third. Now choose any topological group that contains a copy of $S_3$ . For instance  $SO(3)$. Where the three elements can be seen as rotations by 180 degrees around three axes lying in the plane, where each pair makes an angle of 120 degrees at the origin.

A: This is too long to be a comment.
Let $O(2)$ be $2\times 2$ matrices $A$ with real entries so that $$AA^t=\begin{pmatrix} 1 & 0 \\ 0 & 1 \end{pmatrix}.$$
Notice it's just the group of orthogonal $2\times 2$ matrices.  Topologically it is the disjoint union of two circles.  Any matrix in $A\in O(2)$ has $det(A)=\pm 1$ since $1=det(AA^t)=det(A)det(A^t)=det(A)^2$.  This corresponds to the fact that $O(2)$ has two connected components, each homeomorphic to a circle.  The first component is made up of rotations, and consists of the matrices with determinant $1$. The identification with the circle is via the angle of rotation.
The second component is made up of reflections in lines through the origin and is made up of matrices of determinant $-1$.
The identification of the second component with a circle is more tenuous, as a reflection in a line through the origin fixes two antipodal points on the circle.
However the quotient space from the circle coming from the equivalence relation that identifies antipodal points is still a circle.  So the identification is via the pair of fixed points of the reflection.
The component made up of reflections is closed under conjugation, so it is a quandle. It contains any quandle corresponding to any dihedral group, so it contains all the quandles corresponding to knot coloring, no matter how many colors you use.
So maybe $O(2)$ is the Lie group associated to knot coloring.
Notice also that this subsumes the other answer I gave because the maps of $\mathbb{R}^3$ that I gave above preserve the $xy$-plane and induce elements of this quandle.

A: I also think O2 is a topological group associated to a dihederal quandle Rn for prime number n. From your idea, I also get another topological space which is associated to the dihederal quandle: the real projective plane RP^2. Unless RP2 is not a topological group, but it is a quandle. Let u and v be two vectors in RP2, then u*v is a vector obtained by reflecting u about v through the origin. (RP^2,*) is a quandle. Now we can embed dihederal quandles of prime order into any great circle on S^2, and then identify the antipodal points.


text:
Q: "Could not create Makefile" when trying to install mysql gem I am running Ruby v2.3.3 on Debian 9.6. I executed this command in the terminal: sudo gem install mysql.
This gave me an error.
    Could not create Makefile due to some reason, probably lack of necessary
libraries and/or headers.  Check the mkmf.log file for more details.  You may
need configuration options.

Here's the full text of the error: https://pastebin.com/raw/HZcL2UtF
Here's the contents of mkmf.log: https://pastebin.com/raw/Bki5e9tT
Why can't I install the mysql gem? How do I fix this error?

A: Usually that means that you don't have required mysql libs on your system.
Try execute:
sudo apt-get update
sudo apt-get install libmysqlclient-dev libmysqlclient16

Then run mysql gem installation again:
sudo gem install mysql


text:
Q: Convert Array to Object for table Schema What is the best way to convert:
["Foo", "Bar", "John"]

To:
{
Foo: { name: 'Foo', index: 0, type: 'String' },
Bar: { name: 'Bar', index: 1, type: 'String' },
John: { name: 'John', index: 2, type: 'String' },
}

I believe I need to utilize
array.map()

but am not sure how to structure my mapping function. Any insight would be helpful.

A: You can the function Array.prototype.reduce as follow.

const source = ["Foo", "Bar", "John"],
  capitalize = string => string.charAt(0).toUpperCase() + string.slice(1),
  result = source.reduce((a, name, index) => ({...a, [name]: {name, index, type: capitalize(typeof name)}}), {});

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

A: your json is not valid , so if you need the valid json like this
[{"name":"Foo","index":0,"type":"string"},{"name":"Foo","index":1,"type":"string"},{"name":"Foo","index":2,"type":"string"}]

you can use this code
var result=[];
arr.forEach( (element,i )=> {
  result.push( {name:element, index:i, type: typeof element});
 });

UPDATE
for your another json
var jarr=["Foo", "Bar", "John"]

you can use this code
var result = {};
jarr.forEach((element, i) => {
  result[element] = { name: element, index: i, type: typeof element };
});

result
{
  "Foo": {
    "name": "Foo",
    "index": 0,
    "type": "string"
  },
  "Bar": {
    "name": "Bar",
    "index": 1,
    "type": "string"
  },
  "John": {
    "name": "John",
    "index": 2,
    "type": "string"
  }
}

A: I think you could do as follows
const array = ["Foo", "Bar", "John"];
Object.fromEntries(
   array
   .map((el, index) => {
     return [el, {name: el, index, type: el.constructor.name}]
   })
)

Here you can find an example snippet:

const array = ["Foo", "Bar", "John"];
const result = Object.fromEntries(
   array
   .map((el, index) => {
     return [el, {name: el, index, type: el.constructor.name}]
   })
);
console.log(result);


text:
Q: How to align legend elements dynamically? Question
How do I align the ticks and text labels with the colour gradient, and so that the legend container expands to contain those elements

Notes

*

*The colour gradient, ticks and labels have to be created dynamically in JS

*The width of labels will vary, so the legend container has to expand accordingly

*I can't use JQuery

*I'm not a javascript/html/css developer, so happy to hear alternative approaches

HTML

Javascript
var legend = document.getElementById("legend");

var divColours = document.createElement('div');
var jsColours = ["#440154", "#443A83", "#31688E", "#21908C", "#35B779", "#8FD744", "#FDE725"];
var colours = '(' + jsColours.join() + ')';

style = 'height: ' + jsColours.length * 20 + 'px; width: 10px; ';
style += 'background: ' + jsColours[1] + ';';
style += 'background: -webkit-linear-gradient' + colours + ';'
style += 'background: -o-linear-gradient' + colours + ';'
style += 'background: -moz-linear-gradient' + colours + ';'
style += 'background: linear-gradient' + colours + ';'

divColours.setAttribute('style', style);
legend.appendChild(divColours);

for (var i = 0; i < 7; i++) {

  var left = 10 + 10 + 1;
  var top = 10 + (i * 20);

  var tick = 'position: absolute; top: ' + top + 'px; left: ' + left + 'px; width: 3px; height: 1px; background: #b8b9ba;';
  var tickVal = 'position: absolute; top: ' + (top - 5) + 'px; left: ' + (left + 5) + 'px; background: red; color: #b8b9ba;';

  var divTicks = document.createElement('div');
  var divVal = document.createElement('div');

  divTicks.setAttribute('style', tick);
  divVal.setAttribute('style', tickVal);
  divVal.innerHTML = ' this is a variable ' + i;

  legend.appendChild(divTicks);
  legend.appendChild(divVal);
}

CSS
#legend {
    font-family: Arial, sans-serif;
    background: #fff;
    padding: 10px;
    margin: 10px;
    border: 1px solid #b8b8b8;
    border-radius: 4px;
    height: auto;
    display: inline-block;
}

Working Demo

*

*JSFiddle
Related
I'm trying to adapt this answer

A: I wrapped your ticks on a parent div tag and appended ticks inside it.
Replace your current JavaScript code with following one. I think you want something like this.
JavaScript
var legend = document.getElementById("legend");

var divColours = document.createElement('div');
var jsColours = ["#440154", "#443A83", "#31688E", "#21908C", "#35B779", "#8FD744", "#FDE725"];
var colours = '(' + jsColours.join() + ')';

style = 'height: ' + jsColours.length * 20 + 'px; width: 10px; ';
style += 'background: ' + jsColours[1] + ';';
style += 'background: -webkit-linear-gradient' + colours + ';'
style += 'background: -o-linear-gradient' + colours + ';'
style += 'background: -moz-linear-gradient' + colours + ';'
style += 'background: linear-gradient' + colours + ';'

divColours.setAttribute('style', style);
legend.appendChild(divColours);

var divTicksParent = document.createElement('div');
divTicksParent.style.position = "absolute";
divTicksParent.style.width = "200px";
divTicksParent.style.top = "28px";

legend.appendChild(divTicksParent);

for (var i = 0; i < 7; i++) {
  var left = 10;
  var top = (i * 23) + (1);
  var tick = 'position: absolute; top: ' + top + 'px; left: ' + left + 'px; width: 6px; height: 1px; background: #b8b9ba;';
  var tickVal = 'position: absolute; top: ' + (top - 6) + 'px; left: ' + (left + 12) + 'px; color: #b8b9ba; font-size: 12px;';

  var divTicks = document.createElement('div');
  var divVal = document.createElement('div');

  divTicks.setAttribute('style', tick);
  divVal.setAttribute('style', tickVal);
  divVal.innerHTML = ' this is a variable ' + i;

  divTicksParent.appendChild(divTicks);
  divTicksParent.appendChild(divVal);
}

CSS
#legend {
  font-family: Arial, sans-serif;
  background: #fff;
  padding: 10px;
  margin: 10px;
  border: 1px solid #b8b8b8;
  border-radius: 4px;
  height: auto;
  width: 130px;
  display: inline-block;
}

A:

check the demo, I've updated

A: The other solutions didn't quite answer my question about auto-sizing the width based on the content.
I think this resolves my problem

*

*Updated fiddle
Javascript
var legend = document.getElementById("legend");

var tickContainer = document.createElement("div");
tickContainer.setAttribute('class', 'labelContainer');

var labelContainer = document.createElement("div");
labelContainer.setAttribute('class', 'labelContainer');

var legendColours = document.createElement('div');
var jsColours = ["#440154", "#443A83", "#31688E", "#21908C", "#35B779", "#8FD744", "#FDE725"];
var colours = '(' + jsColours.join() + ')';

style = 'display: inline-block; height: ' + jsColours.length * 20 + 'px; width: 10px;';
style += 'background: ' + jsColours[1] + ';';
style += 'background: -webkit-linear-gradient' + colours + ';'
style += 'background: -o-linear-gradient' + colours + ';'
style += 'background: -moz-linear-gradient' + colours + ';'
style += 'background: linear-gradient' + colours + ';'

legendColours.setAttribute('style', style);
legend.appendChild(legendColours);

for (var i = 0; i < jsColours.length; i++) {
  var tickVal = 'text-align: center; color: #b8b9ba; font-size: 12px; height: 20px;';

  var divTicks = document.createElement('div');
  var divVal = document.createElement('div');

  divTicks.setAttribute('style', tickVal);
  divTicks.innerHTML = '-';
  tickContainer.appendChild(divTicks);

  divVal.setAttribute('style', tickVal);
  divVal.innerHTML = ' this is a variable ' + i;
  labelContainer.appendChild(divVal);
}

legend.appendChild(tickContainer);
legend.appendChild(labelContainer);

CSS
.legend {
  font-family: Arial, sans-serif;
  background: #fff;
  padding: 8px;
  margin: 8px;
  border: 1px solid #b8b8b8;
  border-radius: 4px;
  display:inline-flex;
}

.labelContainer{
  border: 1px solid #00FF00;
  padding-left: 4px;
  height: auto;
  display: inline-block;
}


text:
Q: The sides of an obtuse triangle have lengths $x$, $2x+2$ and $2x+3$. Between what values is $x$? I attempted to apply the triangle equality here and ended up with the following inequalities:
\begin{align*}
x < 4x + 5 & \implies -\frac{5}{3} < x, \\
2x + 2 < 3x +3 & \implies -1 < x, \\
2x + 3 < 3x +2 & \implies 1 < x.
\end{align*}
Where do I go from here? I feel like I'm missing something silly. This is a problem on a middle school math homework.

A: We need to solve the following system:
$$x>1$$ and $$(2x+2)^2+x^2<(2x+3)^2.$$
I got $$1<x<5.$$

A: A bit of  detail:
1) Sum of $2$ sides of a triangle is greater than $3$rd side:
$x >1$.
2) Cosine rule:
$(2x+3)^2=$
$(2x+2)^2+ x^2 -2(2x+2)x \cos \gamma.$
Obtuse : $\gamma >90°$, then $\cos \gamma <0$.
This implies
$(2x+3)^2  > (2x+2)^2+x^2;$
$0>x^2-4x-5$;
$0>(x+1)(x-5);$
$ -1< x<5$;
Combining 1) and 2): $1<x<5$.
https://en.m.wikipedia.org/wiki/Law_of_cosines

A: Alternatively, refer to the figure:
$\hspace{5cm}$
For the triangle $ABC$ to be obtuse, $y$ must be positive. Hence:
$$\begin{cases}(x+y)^2+z^2=(2x+3)^2\\ y^2+z^2=(2x+2)^2\end{cases} \stackrel{(1)-(2)}\Rightarrow y=\frac{4x+5-x^2}{2x}>0 \stackrel{x>0}\Rightarrow \\
x^2-4x-5<0 \Rightarrow -1<x<5.$$
And for the triangle $ABC$ to exist, the triangle inequalities dictate $x>1$ as you found.


text:
Q: double pointers w/o array notation I'm trying to iterate through a double pointer without using Array notation. I've been given these guidelines through my instructor.
In .h file:
int** A, B, C;

In .c file
void initNumbers() {

    int** a = A;
    int** b = B;
    int** c = C;

    int* p;// = *a;
    int* q;// = *b;
    int* r;// = *c;

    for (int i = 0; i < 10; i++) {
        p = *a;
        q = *b;
        r = *c;
        for (int j = 0; j < 10; j++) {
            *r = rand() % 50;
            *p = rand() % 50;
            *q = rand() % 50;
            p++;
            q++;
            r++;
        }
        a++;
        b++;
        c++;
    }
}

I've allocated memory via.
void initNumSpace() {
    A = malloc(sizeof(int*) * 10);
    B = malloc(sizeof(int*) * 10);
    C = malloc(sizeof(int*) * 10);

    int** a = A;
    int** b = B;
    int** c = C;

    for (int i = 0; i < 10; i++) {
        a = malloc(sizeof(int) * 10);
        b = malloc(sizeof(int) * 10);
        c = malloc(sizeof(int) * 10);

        a++;
        b++;
        c++;
    }
}

The code gets no syntax errors, but there is a segmentation fault at the very first iteration of the imbedded loop of initNumbers. Why is this happening? What is the best way to iterate through a pointer array without array notation e.g., indices or offset values.

A: Your code has a few problems.
First of all, you shouldn't DEFINE variables in header files; you should only DECLARE them. That is, you if you wanted to declare an integer N, then you shouldn't write int N; but instead extern int N; and then go to your source file and write int N; to define it. C (and C++) have the multiple declaration-one definition rule: you can declare something as many times as you like (you can write 'extern int A;five times in a row and the compiler won't mind), but you have to define each variable and function exactly once (you should writeint A;` exactly once in a source file.
Secondly, there's a slight problem with your header file. In C, writing int** A,B,C; is the same as int **A;int B;int C;. A is a double pointer, but B and C are integers. So, you should write int **A,**B,**C; (or even better, write each one on a separate line).
Your code should now look like this:
HEADER:
int** A;
int** B;
int** C;

SOURCE:
void initNumSpace() {
    A = malloc(sizeof(int*) * 10);
    B = malloc(sizeof(int*) * 10);
    C = malloc(sizeof(int*) * 10);

    int** a = A;
    int** b = B;
    int** c = C;

    for (int i = 0; i < 10; i++) {
        //you should dereference these btw
        *a = malloc(sizeof(int) * 10);
        *b = malloc(sizeof(int) * 10);
        *c = malloc(sizeof(int) * 10);

        a++;
        b++;
        c++;
    }
}

void initNumbers() {

    int** a = A;
    int** b = B;
    int** c = C;

    int* p;// = *a;
    int* q;// = *b;
    int* r;// = *c;

    for (int i = 0; i < 10; i++) {
        p = *a;
        q = *b;
        r = *c;
        for (int j = 0; j < 10; j++) {
            *r = rand() % 50;
            *p = rand() % 50;
            *q = rand() % 50;
            p++;
            q++;
            r++;
        }
        a++;
        b++;
        c++;
    }
}

PS: why are you doing this way? It's not wrong, but it's really comlicated and hard to read. Why would you not want to use array indexing ([]).

A: The error is in your init function. The double pointers get set to the newly allocated space, but the pointer array A does not get set to the value of a.
Try this instead:
for (int i = 0; i < 10; i++) {
    *a = malloc(sizeof(int) * 10);
    *b = malloc(sizeof(int) * 10);
    *c = malloc(sizeof(int) * 10);

    a++;
    b++;
    c++;
}

Update: You also have to change the type of B and C to int*, or int**. Otherwise this may not work on systems, which are not 32bit. (void* would have to be of size int and the indexing also has to be the same for this to work).
Using int in this context at all is kind of a liability, since the size of int is defined differently on different systems and it is not consistent with the size of void*. You can use int32_t and such from stdint.h for better compatability.


text:
Q: Parse service now ticket data in Perl INC and short description I am trying to parse raw Service now ticket data into just the INC number and the short description.
The script below does not throw an error; however, it is not giving me what I want.
#!/usr/bin/perl
use warnings;
use strict ;

#my $rawTicket = "$ARGV[0]" ;
my $line = "";
my $incnumb = "";

#open my $ticketPaste, '<', $rawTicket or die "Failed to open $rawTicket: $!\n";
#while( $line = <$ticketPaste> ) {

while( $line = <DATA> ) {
    next if $line =~ /^$/ ;
    next if $line =~ /\(empty\)/ ;
    if ($line =~ /Select record for action.* Preview (INC\d+)/) {
            $incnumb = $1;
    }
    next if $line =~ /Select record for action/ ;

    print "$incnumb $line\n" ;
    #sleep 1 ;
    }

    #    close $ticketPaste or die "Failed to close $rawTicket: $!\n";

##Can't use string (" ") as a symbol ref while "strict refs" in use at ./ticket_watch.pl line 18, <$ticketPaste> line 7. <!-- did not like the 'my line' in line 7

 __END__

(empty)
Ctas
?Select record for action ?Preview INC1008626119
(empty)

(empty)

(empty)
RE: RPM 117036-2 - New Service Request for CASPER
?Select record for action ?Preview INC1008625854
(empty)

(empty)

This is what it is giving me:
casper@CASPER ~$ ./rawTicketParse.pl
 Ctas

 RE: RPM 117036-2 - New Service Request for CASPER

However, this is What I am trying to get :
casper@CASPER ~$ ./rawTicketParse.pl
INC1008626119 Ctas

INC1008625854  RE: RPM 117036-2 - New Service Request for CASPER

A: You need to fix the regex and keep track of the previous line so that you can prepend the number:
use warnings;
use strict ;

my $prevline;
while (my $line = <DATA> ) {
    next if $line =~ /^$/ ;
    next if $line =~ /\(empty\)/ ;
    if ($line =~ /Select record for action.*Preview (INC\d+)/) {
        my $incnumb = $1;
        print "$incnumb $prevline\n" ;
    }
    $prevline = $line;
}


text:
Q: Programming logic best practice - redundant checks I'm creating a large PHP project and I've a trivial doubt about how to proceed.
Assume we got a class books, in this class I've the method ReturnInfo:
function ReturnInfo($id) {
    if( is_numeric($id) ) {
        $query = "SELECT * FROM books WHERE id='" . $id . "' LIMIT 1;";

        if( $row = $this->DBDrive->ExecuteQuery($query, $FetchResults=TRUE) )   {
                return $row;
        } else {
            return FALSE;
        }
    } else {
        throw new Exception('Books - ReturnInfo - id not valid.');
    }
}

Then i have another method PrintInfo
function PrintInfo($id) {
    print_r( $this->ReturnInfo($id) );
}

Obviously the code sample are just for example and not actual production code.
In the second method should I check (again) if id is numeric ? Or can I skip it because is already taken care in the first method and if it's not an exception will be thrown?
Till now I always wrote code with redundant checks (no matter if already checked elsewhere i'll check it also here)
Is there a best practice? Is just common sense?
Thank you in advance for your kind replies.

A: Well, ask yourself what you gain by checking in every layer. Is it more security? No, since the function which uses the value for something, which is the only one being vulnerable, does the checking itself.
The only advantage it has is that you can stop invalid values earlier, which executes less code. It doesn't have to go all the way down and back up before you know the value is invalid. This may or may not be a real advantage.
It does create problems though: you have more code. Your code is not DRY anymore. If you change the definition of what makes a "valid" value, you have to change the checks all over the place. Those are much bigger problems.
I'd approach the problem this way: your core business model does the in-detail checking, it is ultimately responsible for making sure the value is valid, and it is the only one doing something "dangerous" with this value. The outer layers (controllers, views) merely pass the value along. With one exception: they may do "rough" data validation. Say your model expects a phone number with specific formatting. You should check this specific rule inside the model. In the view/controller layer you may roughly validate the value as being at least somewhat numeric though. Say, you have a Javascript check. This blocks obviously wrong values from bothering your core app, while still giving you the flexibility to tweak the core validation rule in just one place.

A: Unless you are double-checking the return inside of a loop that is executing many thousands of times in succession you're not even going to notice the redundant check. Even so, a type check is a very small operation and will be orders of magnitude faster than the SQL query being used to retrieve the data in your example.
Unless you're really pinching CPU cycles for a realtime application you're likely going to enjoy the ass-coverage that the extra check affords you.
That said, your functions should generally be validating their inputs as much or more strictly than their outputs, so the only place where you would be writing an extra redundant check like this would be for some inline functionality that requires strict typing/validation.


text:
Q: Android : Binding to update UI In my android application, I have below classes. I want to bind these classes in UI to display the UI content based on object data.
<layout xmlns:android="http://schemas.android.com/apk/res/android">
<data>
    <import type="java.util.Map"/>
    <import type="java.util.List"/>
    <variable name="itemContainerInformation" type="com.myApp.Models.ItemsContainerInformation"/>
</data>
<RelativeLayout
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/cardview_light_background"
    tools:context="com.myApp.Fragments.DetailedViewFragment"
    android:id="@+id/layout_detailed_view">

<!-- TODO: Update blank fragment layout -->
<TextView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="@{itemInformation.t1Caption}"
    android:textAlignment="textStart"
    android:gravity="start"
    android:id="@+id/textView_day_t1_header"
    android:layout_below="@+id/textView_date_header"
    android:textStyle="normal|bold"
    android:textSize="20sp"
    android:layout_alignParentEnd="true"
    android:layout_alignParentRight="true"
    android:textColor="@color/cardview_light_background"
    android:background="@color/colorPrimary"/>

<TextView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="@{itemContainerInformation.currentDateHeaderCaption}"
    android:layout_alignParentTop="true"
    android:layout_alignParentStart="true"
    android:layout_alignParentLeft="true"
    android:textAlignment="center"
    android:textColor="@color/colorAccent"
    android:background="@color/colorPrimaryDark"
    android:id="@+id/textView_date_header"
    android:textStyle="normal|bold"
    android:layout_marginTop="10dp"
    android:textSize="24sp" />

<LinearLayout android:orientation="horizontal"
    android:id="@+id/linear_layout_information"
    android:layout_below="@+id/textView_day_t1_header"
    android:background="@color/fall"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    >

    <LinearLayout android:orientation="vertical"
        android:id="@+id/linear_layout_day_information_list"
        android:layout_weight="1" android:layout_height="fill_parent" android:layout_width="0dp" >
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@{itemContainerInformation.itemInformations[0].Caption}"
            android:textAlignment="textStart"
            android:gravity="start"
            android:id="@+id/textView_day_information1"
            android:textStyle="normal|bold"
            android:textSize="16sp"
            android:layout_marginTop="30dp"
            android:textColor="@color/colorPrimary" />
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@{itemContainerInformation.itemInformations[1].Caption}"
            android:textAlignment="textStart"
            android:gravity="start"
            android:id="@+id/textView_day_information2"
            android:textStyle="normal|bold"
            android:textSize="16sp"
            android:textColor="@color/colorPrimary" />
        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="@{itemContainerInformation.itemInformations[2].Caption}"
            android:textAlignment="textStart"
            android:gravity="start"
            android:id="@+id/textView_day_information3"
            android:textStyle="normal|bold"
            android:textSize="16sp"
            android:textColor="@color/colorPrimary" />
        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="@{itemContainerInformation.itemInformations[3].Caption}"
            android:textAlignment="textStart"
            android:gravity="start"
            android:id="@+id/textView_day_information4"
            android:textStyle="normal|bold"
            android:textSize="16sp"
            android:textColor="@color/colorPrimary" />
        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="@{itemContainerInformation.itemInformations[4].Caption}"
            android:textAlignment="textStart"
            android:gravity="start"
            android:id="@+id/textView_day_information5"
            android:textStyle="normal|bold"
            android:textSize="16sp"
            android:textColor="@color/colorPrimary" />
        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text=" "
            android:textAlignment="textStart"
            android:gravity="start"
            android:id="@+id/textView_day_information6"
            android:textStyle="normal|bold"
            android:layout_marginBottom="20dp"
            android:textSize="16sp"
            android:textColor="@color/colorPrimary" />
    </LinearLayout>
    <LinearLayout android:orientation="vertical"
        android:id="@+id/linear_layout_day"
        android:layout_weight="1" android:layout_height="match_parent" android:layout_width="0dp" >
        <TextView
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_toRightOf="@+id/linear_layout_day_information_list"
        android:text="@{itemContainerInformation.currentDate}"
        android:textAlignment="viewEnd"
        android:gravity="end"
        android:id="@+id/textView_day"
        android:textStyle="normal|bold"
        android:textSize="100dp"
        android:layout_alignParentEnd="true"
        android:layout_alignParentRight="true"
        android:textColor="@color/colorPrimary" />
    </LinearLayout>

</LinearLayout>
<LinearLayout android:orientation="vertical"
    android:id="@+id/linear_layout_information_bottom"
    android:layout_below="@+id/linear_layout_information"
    android:background="@color/fall"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">
    <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="@{itemContainerInformation.itemInformations[5].Caption}"
            android:textAlignment="viewEnd"
            android:gravity="end"
            android:id="@+id/textView_day_information_bottom1"
            android:textStyle="normal|bold"
            android:textSize="16sp"
            android:layout_marginTop="0dp"
            android:textColor="@color/colorPrimary" />

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@{itemContainerInformation.itemInformations[6].Caption}"
        android:textAlignment="viewEnd"
        android:gravity="end"
        android:id="@+id/textView_day_information_bottom2"
        android:layout_below="@+id/textView_day_information_bottom1"
        android:textStyle="normal|bold"
        android:textSize="16sp"
        android:layout_alignParentEnd="true"
        android:layout_alignParentRight="true"
        android:textColor="@color/colorPrimary" />
</LinearLayout>

ItemInformation.java
public class ItemInformation extends BaseObservable {
private String caption;
private int lineIndex;
private int lineFontSize;
private int lineFontColor;
private int lineIndentation;
private int imageIndex;

public ItemInformation()
{

}

@Bindable
public String getCaption() {    return caption;    }

public void setCaption(String caption) {
    this.caption = caption;
    notifyPropertyChanged(BR.caption);
}

@Bindable
public int getLineIndex() {     return lineIndex;    }

public void setLineIndex(int lineIndex) {
    this.lineIndex = lineIndex;
    notifyPropertyChanged(BR.lineIndex);
}

@Bindable
public int getLineFontSize() {     return lineFontSize;    }

public void setLineFontSize(int lineFontSize) {
    this.lineFontSize = lineFontSize;
    notifyPropertyChanged(BR.lineFontSize);
}

@Bindable
public int getLineFontColor() {     return lineFontColor;    }

public void setLineFontColor(int lineFontColor) {
    this.lineFontColor = lineFontColor;
    notifyPropertyChanged(BR.lineFontColor);
}

@Bindable
public int getLineIndentation() {     return lineIndentation;    }

public void setLineIndentation(int lineIndentation) {
    this.lineIndentation = lineIndentation;
    notifyPropertyChanged(BR.lineIndentation);
}

@Bindable
public int getImageIndex() {     return imageIndex;    }

public void setImageIndex(int imageIndex) {
    this.imageIndex = imageIndex;
    notifyPropertyChanged(BR.imageIndex);}

public static int GetColorInformation(String fontcolor)
{
    return  Color.parseColor(fontcolor);
    //int desiredColour = getResources().getColor(getResources().getIdentifier("my_color", "color"
}
}

ItemContainerInformation.java
public class ItemContainerInformation extends BaseObservable {
private List<ItemInformation> itemInformations = new ArrayList<ItemInformation>();

private String currentDate;
private String currentDateHeaderCaption;
private String t1Caption;
private int rowIndex;
private int columnIndex;

private int currentMonth;
private int currentYear;

public ItemContainerInformation()
{
    Calendar calendar = Calendar.getInstance();
    int mYear = calendar.get(Calendar.YEAR);
    int mMonth = calendar.get(Calendar.MONTH);
    int mDay = calendar.get(Calendar.DAY_OF_MONTH);
}

public ItemContainerInformation(String currentDate) {

    this.currentDate = currentDate;
}

@Bindable
public String getCurrentDate() {
    return currentDate;
}

public void setCurrentDate(String currentDate) {
    this.currentDate = currentDate;
    notifyPropertyChanged(BR.currentDate);
}

@Bindable
public String getCurrentDateHeaderCaption() {
    return currentDateHeaderCaption;
}

public void setCurrentDateHeaderCaption(String currentDateHeaderCaption) {
    this.currentDateHeaderCaption = currentDateHeaderCaption;
    notifyPropertyChanged(BR.currentDateHeaderCaption);
}

@Bindable
public String getT1Caption() {
    return t1Caption;
}

public void setT1Caption(String t1Caption) {
    this.t1Caption = t1Caption;
    notifyPropertyChanged(BR.t1Caption);
}

@Bindable
public int getRowIndex() {
    return rowIndex;
}

public void setRowIndex(int rowIndex) {
    this.rowIndex = rowIndex;
    notifyPropertyChanged(BR.rowIndex);
}

@Bindable
public int getColumnIndex() {
    return columnIndex;
}

public void setColumnIndex(int columnIndex) {
    this.columnIndex = columnIndex;
    notifyPropertyChanged(BR.columnIndex);
}

@Bindable
public int getCurrentMonth() {
    return currentMonth;
}

public void setCurrentMonth(int currentMonth) {
    this.currentMonth = currentMonth;
    notifyPropertyChanged(BR.currentMonth);
}

@Bindable
public int getCurrentYear() {
    return currentYear;
}

public void setCurrentYear(int currentYear) {
    this.currentYear = currentYear;
    notifyPropertyChanged(BR.currentYear);
}

@Bindable
public List<ItemInformation> getItemInformations() {
    return itemInformations;
}

public void setItemInformations(List<ItemInformation> itemInformations) {
    this.itemInformations = itemInformations;
    notifyPropertyChanged(BR.itemInformations);
}
}

DetailedViewFagment
public class DetailedViewFragment extends Fragment {

    ItemContainerInformation currentInormationItem;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                            Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View v =   inflater.inflate(R.layout.fragment_detailed_view, container, false);

        if(currentInormationItem == null)
        {
            currentInormationItem = new ItemContainerInformation("100");

            List<ItemInformation> dailyItems = new ArrayList<ItemInformation>();

            for(int i = 0; i < 10; i++)
            {
                ItemInformation item = new ItemInformation();
                item.setCaption("Caption_");

                dailyItems.add(item);
            }

            currentDayInormationItem.setItemInformations(dailyItems);
        }

        FragmentDetailedDayViewBinding binding = DataBindingUtil.inflate(
                inflater, R.layout.fragment_detailed_view, container, false);
        View view = binding.getRoot();

        //here data must be an instance of the class MarsDataProvider
        binding.setDateInformation(currentDayInormationItem);

        return v;
    }

    // This method is used to update the object from 'ParentItem'
    // So when a UI click happens in the ParentFragment this method is called from ParentFragment
    // which updates the objects. Now this updated object () will have new values which i want to update in the UI inside detailed view fragment.
    public void UpdateDetailedDayView(DateInformation dayInormationItem)
    {
        // Should update all textviews in the child view but not working???
        currentDayInormationItem = dayInormationItem;
    }

}

ParentViewFragment
public class ParentViewFragment extends Fragment {

// This is inside the parent fragment class which has multiple items populated using Adapter and ViewHolder
// On item click of the UI i want to update the 'DetailedViewFragment'.
MyRecyclerViewAdapter.OnItemClickListener onItemClickListener = new MyRecyclerViewAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(ItemInformation itemInformation) {
                Toast.makeText(getContext(), "Item Clicked --- " + itemInformation.getCurrentDate(), Toast.LENGTH_LONG).show();

                // On click i am creating new fragment and updating it
                DetailedViewFragment detailedView = new DetailedViewFragment();
                FragmentTransaction transaction = getChildFragmentManager().beginTransaction();
                transaction.replace(R.id.month_detailed_view_container, detailedView).commit();

                detailedView.UpdateDetailedDayView(itemInformation);
            }
        };

}

Basically i have different textviews in UI and respective UI properties are stored in object like indentation, foreground color, font size etc. How I can bind this information to a textview?
I am not able to view the text using this line, can someone help me to correct my mistake in the below line and display the text using the specific identation and forground color.
android:text="@{itemContainerInformation.itemInformations[0].Caption}"
How I can bind the object and update the UI based on  object data?
Thanks.


text:
Q: Batch File Techinque for Set /A and quoting I've always wondered about how and when to use quotes if my script is making a calculation. For example,
Set /A exp=%some%+(!calculation!-0).
I know, if the line uses parentheses, and I'm inside an IF block, I should use
Set /A exp="%some%+(!calculation!-0)".
The quotes just go around the part after the equals.
Aside from that, quoting from the variable name to the end of the line,
Set /A "exp=%some%+(!calculation!-0)"
seems to work as well.
I'm wondering, is there a "proper" way to use SET /A? What's the correct/best technique for batch scripts? When should I use quotes? Are they mostly optional unless one gets an error?
Thank you.

A: It makes more sense, if you try it without /a: if you use "after the =, it will become part of the variable; if you use it before =, it delimits the expression (usualy used to avoid unintended or insert intended trailing spaces in a variable)
C:\>set x="1+3"
C:\>set x
x="1+3"

C:\>set "x=2+5"
C:\>set x
x=2+5

C:\>set x=text
C:\>echo -%x%-
-text  -

C:\>set "x=text"
C:\>echo -%x%-
-text-

(note, there are two "unintended" spaces after set x=text and set "x=text")
with /a, the qoutes are just stripped (/a was added to the former setcommand from "good old DOS")


text:
Q: Reference WPF button to Winform .dll I have a Winform .dll referenced inside my WPF project. Main method of .dll has a parameter for passing a Control object. I need to pass reference of WPF Button control inside that method parameter, but I receieve error : "Value of type 'Button' cannot be converted to 'Control'".
As far as I've seen I can't do that because WPF and Winform controls are entirely different things, but Is there anything I can do ?
P.S.: Main .dll method opens WinForm window next to specified control (WPF control in this case), that is why I need reference of WPF control.

A: Honestly, the best, easiest, cleanest solution is to make another version of the Main method which accepts System.Windows.Controls.Control instead of System.Windows.Forms.Control. They can even be overloaded (share the same name). The changes to this new version would probably be very few and simple.
However, assuming Main is some huge, complicated method that would be a nightmare to even look at- or you don't have the source code anymore- and you really have to use the existing method, there is one other potential option:
Make a class that inherits from System.Windows.Forms.Control which will act as a wrapper around a System.Windows.Controls.Control. You can use new and/or override keywords to replace the existing properties in System.Windows.Forms.Control and instead expose the equivalent properties of System.Windows.Controls.Control.
To give a rushed example:
    class WinformsControlWrapper : System.Windows.Forms.Control
    {
        protected System.Windows.Controls.Control WrappedControl;

        public WinformsControlWrapper(System.Windows.Controls.Control wrappedControl)
        {
            WrappedControl = wrappedControl;
        }

        public new int Width
        {
            get { return (int)WrappedControl.Width; }
            set { WrappedControl.Width = value; }
        }
    }

Of course there are numerous problems even with the above example: the fact that WPF uses double and winforms uses int, and the fact that WPF has both Width and ActualWidth to name a couple. But you should probably be able to write your class to work the way you need it to.
Again, making another version of Main is a much simpler, cleaner and probably easier solution. But if you really can't the above tactic should work.

A: My solution was to change Main .dll method. Instead of passing Control object I changed parameter to accept Point object - which Is what I need in the end from a control, to get their X and Y coordinates... However WPF and Winform uses different Point library references (System.Drawing.Point and System.Point) which are different types so  when  calling .dll in WPF I had to convert WPF Point object into type that Winform System.Drawing.Point accepts. That was easiest I could come with.


text:
Q: ZendFramework 2 - how can i do the similar Bootstrap.php like in ZF1? I have ZF 1 where i got working Bootstrap.php with lots of routing and other preDispatch stuff.
But in ZF2 there is no Bootstrap.php concept anymore? Or i mean how can i do this same in Zf2?
<?php

class Bootstrap extends Zend_Application_Bootstrap_Bootstrap {

  protected function _initPdispatch() {
    $this->bootstrap('frontController');
    require_once APPLICATION_PATH . '/controllers/plugin/LanguageSelector.php';
    $plugin = new LanguageSelector();
    $front = Zend_Controller_Front::getInstance();
    $front->registerPlugin($plugin);
    return $plugin;
  }

  protected function _initRoutes() {
    $front = Zend_Controller_Front::getInstance();
    $router = $front->getRouter();
    $dynamic1 = new Zend_Controller_Router_Route(
                    '/:variable1',
                    array(
                        'controller' => 'router',
                    ),
//              array('variable1' => '^[a-zA-Z0-9_-]*$')
                    array('variable1' => '^[\w.-]*$')
    );
    $router->addRoute('dynamic1', $dynamic1);
  }

A: One of the best features of ZF2 is something that I actually hated at first, which are the routes.  It's both great and annoying because now you're required to set the routes for all of your modules.
Part of understanding ZF2 (more quickly) is understanding modules.  If you can get past this, you will begin to adapt much more quickly. (At least that's how it was for me).  So, what in ZF2 is a module?  Anything!
Anyway, all of the config files for every module and for the application eventually get merged within the Zend Framework, so that means you can define routes anywhere really.
That said, you don't need to "bootstrap" your routes anymore as that is part of your ModuleName/config/module.config.php file. now.
Now, I'm not an expert on regex routes within ZF2, but it would be something like:
// MyModule/config/module.config.php
return array(
    'router' => array(
        'routes' => array(
            'dynamic1' => array(
                'type' => 'regex',
                'options' => array(
                    'route' => '/[:variable1]'
                )
            )
        )
    )
);

Somewhere in there you define the regex.  Additionally, I saw in their docs that you can also define a regex route manually:
use Zend\Mvc\Router\Http\Regex;

// ...

$route = Regex::factory(array(
    'regex' => '/blog/(?<id>[a-zA-Z0-9_-]+)(\.(?<format>(json|html|xml|rss)))?',
    'defaults' => array(
        'controller' => 'Application\Controller\BlogController',
        'action'     => 'view',
        'format'     => 'html',
    ),
    'spec' => '/blog/%id%.%format%',
));

$router->addRoute($route);

You should be able to add this as a service or put it in onBootstrap() within the Application module if you're using the Skeleton Application.
Keep in mind, that was their example and again, I'm not an expert on this. Here is some more information.
Hope this helps!


text:
Q: Linking Data Fields from Different Worksheets I have reports that I run frequently from 2 different sources that both have one unique identifier that links the data across both reports (I'll call the field ID "LINK ID").  This field appears in both sets of exports (however the exports are from 2 different systems that populate different data points). I typically cut and paste each report to separate sheets within a newly created workbook and then go about matching them up.
At one point I had worked on a subroutine that would cycle through the column that contained the "LINK ID" in one sheet, and then cycle through the other column that contained the same "LINK ID" on the other worksheet, and if it found a match it would copy the entire row of data linked to that match and paste it over onto the first worksheet.
The code that I had worked on never got completely finished, but I am trying to see if I can figure out this once and for all because it would be AWESOME if I didn't have to sift through these with my eyes one at a time.
Here is what I have:
Private Sub Find_And_Link()

Dim rw As Long

Dim mr2 As Long

Dim ws3 As Worksheet

Set ws3 = Sheets("VM")

With Sheets("AY")

For rw = 2 To .Cells(Rows.Count, "F").End(xlUp).Row

If CBool(Application.CountIf(ws3.Columns(1), .Cells(rw, "F").Value)) Then

mrw = Application.Match(.Cells(rw, "F"), ws3.Columns(1), 0)

ws3.Cells(mrw, "A").Resize(1, 12).Copy _
Destination:=.Cells(rw, "G")
ws3.Rows(mrw).EntireRow.Delete
'getting rid of the row if match found

End If

Next rw

End With

Set ws3 = Nothing

End Sub

A: Here's what I was able to get.  I made an assumption that your sheet "AY" is the original sheet that you want the data copied to, and "VM" is the sheet you're searching for the data to copy from (change this if it's backwards).  I also changed the variable names to be a little more clear:
Sub Find_And_Link()

Dim i As Long, copyRow As Long

Dim origWS As Worksheet, copyWS As Worksheet

Set copyWS = Sheets("VM")
Set origWS = Sheets("AY")

With origWS
    For i = 2 To .Cells(.Rows.Count, "F").End(xlUp).Row
        If CBool(Application.CountIf(copyWS.Columns(1), .Cells(i, "F").Value)) Then
            copyRow = Application.Match(.Cells(i, "F"), copyWS.Columns(1), 0)
            Debug.Print "Match found in row " & copyRow & "."
            copyWS.Cells(copyRow, "A").Resize(1, 12).Copy Destination:=.Cells(i, "G")
            copyWS.Rows(copyRow).EntireRow.Delete 'getting rid of the row if match found
        Else
            Debug.Print "No match found for Link ID " & .Cells(i, 6) & " :("
        End If
    Next i
End With

Set copyWS = Nothing

End Sub

I tried this and it worked.  Note: In "AY", your "Link IDs" are all in column F.  In "VM", the "Link IDs" are all in Column A.
This will find a match in "VM", copy the data from column A to L, then paste that in "AY", column G through S.  Note that it's not quite what you asked (you asked to replace the entire row in the original sheet), but I did this because it's in your code.
To instead replace the entire line in your original "AY" sheet, change the Copy destination to Destination:=.Cells(i,"A").  (You might want to add .Rows(i).Clear before that line to clear any data in that row.)


text:
Q: Multi-threaded TcpClient send timeout after long open connection I'm having a problem with a TcpClient closing with a send timeout in a multi-threaded application after the connection has been open for a long period of time (several hours or overnight).  The NetworkStream is being used by two threads, a UI thread and a background thread.  There is a StreamReader used for reading incoming data, and a StreamWriter used for outgoing data.  The StreamReader is only ever accessed one thread (the background one), but the StreamWriter is accessed by both the UI thread and the background thread.
What happens is that if I open a connection and connect to a remote server, I can immediately send and receive data without any problems.  I do not get any send timeouts and data is correctly sent and received.  However, if I then walk away and do not send any data for several hours and then return and start sending data (this is a chat application if that helps make it make sense), the socket will timeout on the send.  During the time that I walk away there is no problem at all receiving data.  Additionally, the remote server polls for an active connection and my client must respond to that, and since the connection is open for several hours it must be correctly sending a response.  This polling response is only sent on the background thread, though.  Data I enter is sent from the UI thread, and that's where the timeout occurs.
I'm guessing it's something to do with concurrent access, but I can't figure out what's causing it and why I can initially send data from the UI without a problem and only have it timeout after being idle for several hours.
Below is the relevant code.  The variables at the top are declared in the class.  Address and Port are properties in the class.  WriteLine is the only method anywhere in the application that sends data with the StreamWriter.  I put a lock around the call to StreamWriter.WriteLine hoping that would correct any synchronization issues.  WriteLine is called from the background thread inside ParseMessage, and elsewhere from the UI.
If I increase TcpClient.SendTimeout to something larger, that doesn't fix anything.  It just takes longer for the socket to timeout.  I can't have the background thread both read and write because the background thread is blocking on ReadLine, so nothing would ever get written.
private TcpClient _connection;
private StreamWriter _output;
private Thread _parsingThread;
private object _outputLock = new object();

public void Connect(string address, int port)
{
    Address = address;
    Port = port;

    _parsingThread = new Thread(new ThreadStart(Run));
    _parsingThread.IsBackground = true;
    _parsingThread.Start();
}

private void Run()
{
    try
    {
        using (_connection = new TcpClient())
        {
            _connection.Connect(Address, Port);
            _connection.ReceiveTimeout = 180000;
            _connection.SendTimeout = 60000;

            StreamReader input = new StreamReader(_connection.GetStream());
            _output = new StreamWriter(_connection.GetStream());

            string line;
            do
            {
                line = input.ReadLine();

                if (!string.IsNullOrEmpty(line))
                {
                    ParseMessage(line);
                }
            }
            while (line != null);
        }
    }
    catch (Exception ex)
    {
        //not actually catching exception, just compressing example
    }
    finally
    {
       //stuff
    }
}

protected void WriteLine(string line)
{
    lock (_outputLock)
    {
        _output.WriteLine(line);
        _output.Flush();
    }
}

A: The blocking methods (Read and Write) of the NetworkStream class are not designed to be used concurrently from multiple threads. From MSDN:

Use the Write and Read methods for simple single thread synchronous blocking I/O. If you want to process your I/O using separate threads, consider using the BeginWrite and EndWrite methods, or the BeginRead and EndRead methods for communication.

My assumption is that, when you call WriteLine (and, internally, NetworkStream.Write) from your UI thread, it would block until the concurrent ReadLine (internally, NetworkStream.Read) operation completes in the background thread. If the latter does not do so within the SendTimeout, then the Write would time out.
To work around your issue, you should convert your implementation to use non-blocking methods. However, as a quick hack to first test whether this is really the issue, try introducing a DataAvailable poll before your ReadLine:
NetworkStream stream = _connection.GetStream();
StreamReader input = new StreamReader(stream);
_output = new StreamWriter(stream);

string line;
do
{
    // Poll for data availability.
    while (!stream.DataAvailable)
        Thread.Sleep(300);

    line = input.ReadLine();

    if (!string.IsNullOrEmpty(line))
    {
        ParseMessage(line);
    }
}
while (line != null);

line = input.ReadLine();


text:
Q: Formula to calculate the control point from three known points on a D3 "basis" curve I have a curve generated by a D3.js line generating function with interpolate set as "basis". The problem is that the line generated only touches the first and last point given into the line generating function and does not pass through the ones in between. I am aware that these are treated as control points to generate the b-spline curve, but what I am looking for is a way to "project"/calculate the control points so that the curve does go through every point in my path array.
These in between points in my application are "handle" points which the user can drag to manipulate the curve. If I set interpolate to "cardinal" then the curve does go through every point, but this is not the type of curve that I want, I want the smoother curve produced by the "basis" interpolation.
Here is my line generator code:
 this.lineGenerator =  d3.svg.line()
                             .tension(0.5)
                             .x(function(d) { return d.x; })
                             .y(function(d) { return d.y; })
                             .interpolate("basis");

And here is a picture that illustrates the problem.

In other words the three points that I have are the points at the start and end of the curve and the point at the "apex" (don't know what it is called... but the "highest" point of the curve). So in the diagram, the red dot will represent the apex and the curve must run though this point.
I found this question which deals with this same issue, but with HTML 5 Canvas rather than D3.js. I tried to apply the formula given here to calculate the control points for the curve, but ended up with this result:

The "drag point" (red dot) is now below the curve rather than on it and the distance between the dot and the curve grows as the curve is dragged further out. I speculate that the reason that the formula in the question linked to did not work is because the formula for the D3 curve is a b-spline and therefore different from curve generated by quadraticCurveTo mentioned in that question. (I may be wrong about this though... what I know about the maths involved is dangerous!)
So my questions are: does anyone know the formula for the curve generated by the D3 "basis" interpolation? And can anyone help in deriving the formula for calculating the control points for the curve similar to what is done in the question that I linked to.


text:
Q: Trying to convert from decimal to octal. Why is my array returning like this? I'm a new programmer trying to convert a decimal number to an octal number but when I try to print my array it keeps giving me a weird value. Any thoughts on why?
    int i = 0;
    int p = 1;
    int[] octalTotal = new int[16];
    int copyTotal = total;
    int value = 0;

    while (copyTotal >0) {
        value = copyTotal % 8;
        System.out.println(value);
        copyTotal = copyTotal / 8;
        octalTotal[p] = value;
        i++;
        System.out.println(octalTotal);
    }

Returns:
1
[I@7eda2dbb
2
[I@7eda2dbb
5
[I@7eda2dbb