答:
Just as I proposed in the comment, create a new file and write the extracted text into it:</p>

```<code>with open('file.txt', 'w') as outfile:
    outfile.write(image_to_string(Image.open('sample.jpg')))
</code>```

Title: Write image text to a new text file?

Body:
Just as I proposed in the comment, create a new file and write the extracted text into it:

with open('file.txt', 'w') as outfile:
    outfile.write(image_to_string(Image.open('sample.jpg')))


来源: stackexchange

问:
How to give line break in string inside wijmo grid cell?
This is my typescript file. I am binding this data to wijmo grid. I need to give line break in between 'shankar' and the date '12/10/2018'.

```<code>this.dataSource.push({
Name: 'John',
Select: 'Selected',
lastmodified: 'Shankar' +'/n'+
'12/10/2018'
  });
</code>```

"/n" and "/br"are not working.

My Html code for wijmo

```<code><wj-flex-grid-column *ngFor="let col of columnDefinitions"
[minWidth]="200" width="*"
[header]="col.header" [binding]="col.binding" [visible]="col.visible"
[allowDragging]="false" [wordWrap]="true" >
 </wj-flex-grid-column>
</code>```

thanks in Advance!

答:
You also need to set the multiLine property of the column to true.

```<code><wj-flex-grid-column *ngFor="let col of columnDefinitions" [minWidth]="200" width="[header]=" col.header " [binding]="col.binding " [visible]="col.visible "
    [allowDragging]="false " [wordWrap]="true " [multiLine]="true">
</wj-flex-grid-column>
</code>```

Also, the size of the rows will be smaller, so you will not be able to see the data of the next line. So, you will need to set the default size of rows using:

```<code>flexGrid.rows.defaultSize = 50;
</code>```

ContentLicense: CC BY-SA 4.0

Body:
This is my typescript file. I am binding this data to wijmo grid. I need to give line break in between 'shankar' and the date '12/10/2018'.

this.dataSource.push({
Name: 'John',
Select: 'Selected',
lastmodified: 'Shankar' +'/n'+
'12/10/2018'
  });

"/n" and "/br"are not working.

My Html code for wijmo

<wj-flex-grid-column *ngFor="let col of columnDefinitions"
[minWidth]="200" width="*"
[header]="col.header" [binding]="col.binding" [visible]="col.visible"
[allowDragging]="false" [wordWrap]="true" >
 </wj-flex-grid-column>

thanks in Advance!

Body:
You also need to set the multiLine property of the column to true.

<wj-flex-grid-column *ngFor="let col of columnDefinitions" [minWidth]="200" width="[header]=" col.header " [binding]="col.binding " [visible]="col.visible "
    [allowDragging]="false " [wordWrap]="true " [multiLine]="true">
</wj-flex-grid-column>

Also, the size of the rows will be smaller, so you will not be able to see the data of the next line. So, you will need to set the default size of rows using:

flexGrid.rows.defaultSize = 50;


问:
mail delivery issue in woocommerce website
I am using a GoDaddy server for a Woocommerce website. in this case, if I purchase something the mail notification to customer works perfectly. but the admin didn't get any mail. I checked it with log mail plugin all emails are successfully sent from the website but it didn't reach in the recipient side.

How can I solve the issue or how can I troubleshoot?

答: You might want to check that your SMTP settings match GoDaddy's instructions. However, even if that fixes the immediate problem, it might be worth checking that GoDaddy's mail looks ok to mail services using something like MX Toolbox or Mail Tester.</p>


问:
Basic C# question if - else
I was wondering if someone could tell me if this sample is correct please.
Please ignore the if statement i wrote it for demonstration purposes only.

basically what I want to know is, if I need to throw an exception in my else, is it right to have it return false then thrown an exception, like follows:

```<code>public bool test(Int j)
{
    if(!TestOnJThatcanThrowOutOfMemoryException E)
    {
        return true;
    }
    else
    {
        return false;
        throw new OutOfMemoryException();
    }
}
</code>```

OR - should I throw exception then return false outside else statement like this:

```<code>public bool test(Int j)
{
    if(!TestOnJThatcanThrowOutOfMemoryException E)
    {
        return true;
    }
    else
    {
        throw new OutOfMemoryException();
    }
    return false;
}
</code>```

答:
When an exception occurs it does not execute the rest of the code in the method.
When a return statement is used it breaks the execution of the current method.

So you only need to call one of the two

i.e.

```<code>public bool test(Int j)
{
     if(!TestOnJThatcanThrowOutOfMemoryException E)
     {
          return true;
     }
     else
     {
         throw new OutOfMemoryException();
     }
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: Basic C# question if - else

Body:
I was wondering if someone could tell me if this sample is correct please.
Please ignore the if statement i wrote it for demonstration purposes only.

basically what I want to know is, if I need to throw an exception in my else, is it right to have it return false then thrown an exception, like follows:

public bool test(Int j)
{
    if(!TestOnJThatcanThrowOutOfMemoryException E)
    {
        return true;
    }
    else
    {
        return false;
        throw new OutOfMemoryException();
    }
}

OR - should I throw exception then return false outside else statement like this:

public bool test(Int j)
{
    if(!TestOnJThatcanThrowOutOfMemoryException E)
    {
        return true;
    }
    else
    {
        throw new OutOfMemoryException();
    }
    return false;
}

Body:
When an exception occurs it does not execute the rest of the code in the method.
When a return statement is used it breaks the execution of the current method.

So you only need to call one of the two

i.e.

public bool test(Int j)
{
     if(!TestOnJThatcanThrowOutOfMemoryException E)
     {
          return true;
     }
     else
     {
         throw new OutOfMemoryException();
     }
}


问:
React prop disappears
I'm obviously not understanding something here when it comes to react/react router 4. I'm trying to check if a user is logged in or out to control the navbar user status routes. I can't seem to access the prop, it just disappears. Can someone point out what I'm not understanding? isUserLoggedInServerCheck returns a value at Server, it then returns a value at AppServer, however, at CandidateLanding it returns undefined.

Path: Server

```<code>onPageLoad(sink => {
  let isUserLoggedInServerCheck = false;
  if (sink.request.cookies.sssr) {
    isUserLoggedInServerCheck = true;
  }

  sink.renderIntoElementById(
    'react-target',
    renderToString(
      <AppServer
        location={sink.request.url}
        isUserLoggedInServerCheck={isUserLoggedInServerCheck}
      />
    )
  );
});
</code>```

Path: AppServer

```<code>const AppServer = props => {
  const context = {};
  const { location, isUserLoggedInServerCheck } = props;

  return (
    <StaticRouter context={context} location={location} isUserLoggedInServerCheck={isUserLoggedInServerCheck}>
      <div className="application">
        <Switch>
          <Route path="/" exact component={CandidateLanding} />
        </Switch>
      </div>
    </StaticRouter>
  );
};
</code>```

Path: CandidateLanding

```<code>function CandidateLanding(props) {
  const { location, isUserLoggedInServerCheck } = props;

  return (
    <div>
      <Navbar location={location.path} isUserLoggedInServerCheck={isUserLoggedInServerCheck} />
    </div>
  );
}

const CandidateLandingContainer = withTracker(props => {
  const { isUserLoggedInServerCheck } = props;
  if (Meteor.isServer) {
    return {
      isUserLoggedInServerCheck
    };
  }

  if (Meteor.isClient) {
    return {
      isUserLoggedInServerCheck
    };
  }
})(CandidateLanding);
</code>```

答:
The StaticRouter will not provide the property isUserLoggedInServerCheck to its children. One way to achieve this is to use the react context. This prevents the requirement to pass the parameter from one competent to the next. To use the context you will need an context instance, const UserLoggedInContext = React.createContext(); the provider <UserLoggedInContext.Provider value={isUserLoggedInServerCheck}> and finally the consumer (useContext) const isUserLoggedInServerCheck = React.useContext(UserLoggedInContext); to get the provided value where you need it.

Example

const UserLoggedInContext = React.createContext();
const AppServer = props => {
  const context = {};
  const { location, isUserLoggedInServerCheck } = props;

  return (
    <UserLoggedInContext.Provider value={isUserLoggedInServerCheck}>
      <StaticRouter context={context} location={location} >

          <Switch>
            <Route path="/" exact component={CandidateLanding} />
          </Switch>

        </StaticRouter>
      </UserLoggedInContext.Provider>
    );
};

 // ...

function CandidateLanding(props) {
  const { location } = props;

  return (

      <Navbar location={location.path} />

  );
}

const CandidateLandingContainer = withTracker(props => {
  const isUserLoggedInServerCheck = React.useContext(UserLoggedInContext);
  if (Meteor.isServer) {
    return {
      isUserLoggedInServerCheck
    };
  }

  if (Meteor.isClient) {
    return {
      isUserLoggedInServerCheck
    };
  }
})(CandidateLanding);
```

For more details please refer to: react context

Title: React prop disappears

Body:
I'm obviously not understanding something here when it comes to react/react router 4. I'm trying to check if a user is logged in or out to control the navbar user status routes. I can't seem to access the prop, it just disappears. Can someone point out what I'm not understanding? isUserLoggedInServerCheck returns a value at Server, it then returns a value at AppServer, however, at CandidateLanding it returns undefined.

Path: Server

onPageLoad(sink => {
  let isUserLoggedInServerCheck = false;
  if (sink.request.cookies.sssr) {
    isUserLoggedInServerCheck = true;
  }

  sink.renderIntoElementById(
    'react-target',
    renderToString(
      <AppServer
        location={sink.request.url}
        isUserLoggedInServerCheck={isUserLoggedInServerCheck}
      />
    )
  );
});

Path: AppServer

const AppServer = props => {
  const context = {};
  const { location, isUserLoggedInServerCheck } = props;

  return (
    <StaticRouter context={context} location={location} isUserLoggedInServerCheck={isUserLoggedInServerCheck}>

        <Switch>
          <Route path="/" exact component={CandidateLanding} />
        </Switch>

    </StaticRouter>
  );
};

Path: CandidateLanding

function CandidateLanding(props) {
  const { location, isUserLoggedInServerCheck } = props;

  return (

      <Navbar location={location.path} isUserLoggedInServerCheck={isUserLoggedInServerCheck} />

  );
}

const CandidateLandingContainer = withTracker(props => {
  const { isUserLoggedInServerCheck } = props;
  if (Meteor.isServer) {
    return {
      isUserLoggedInServerCheck
    };
  }

  if (Meteor.isClient) {
    return {
      isUserLoggedInServerCheck
    };
  }
})(CandidateLanding);

Body:
The StaticRouter will not provide the property isUserLoggedInServerCheck to its children. One way to achieve this is to use the react context. This prevents the requirement to pass the parameter from one competent to the next. To use the context you will need an context instance, const UserLoggedInContext = React.createContext(); the provider <UserLoggedInContext.Provider value={isUserLoggedInServerCheck}> and finally the consumer (useContext) const isUserLoggedInServerCheck = React.useContext(UserLoggedInContext); to get the provided value where you need it.

Example

const UserLoggedInContext = React.createContext();
const AppServer = props => {
  const context = {};
  const { location, isUserLoggedInServerCheck } = props;

  return (
    <UserLoggedInContext.Provider value={isUserLoggedInServerCheck}>
      <StaticRouter context={context} location={location} >
        <div className="application">
          <Switch>
            <Route path="/" exact component={CandidateLanding} />
          </Switch>
        </div>
        </StaticRouter>
      </UserLoggedInContext.Provider>
    );
};

 // ...

function CandidateLanding(props) {
  const { location } = props;

  return (
    <div>
      <Navbar location={location.path} />
    </div>
  );
}

const CandidateLandingContainer = withTracker(props => {
  const isUserLoggedInServerCheck = React.useContext(UserLoggedInContext);
  if (Meteor.isServer) {
    return {
      isUserLoggedInServerCheck
    };
  }

  if (Meteor.isClient) {
    return {
      isUserLoggedInServerCheck
    };
  }
})(CandidateLanding);

For more details please refer to: react context


问:
MarkLogic "Could not find trigger module" error when update triggered in Amps
Getting an XDMP-TRIGGERMODULE: Could not find trigger module: error when updating a document from an Amps module.

Do triggers have issues running from amps?

Setup is for PayPal payment verification, using webhooks. The PayPal API sends an HTTP callback to an endpoint on the MarkLogic server, notifying the server of payment completion. The endpoint code then processes the message, and sends relevant data to an amps module for execution. The idea is the webhook needs to hit a public endpoint, so it will be using the default public user in terms of execution permissions. The amp is used so the code can have the appropriate permissions to update the document, noting that the payment has been received.

A separate (unrelated) trigger is set up to run on any modification of the same aforementioned document, for the purposes of a separate unrelated process. This trigger runs perfectly fine when the document is modified in all other ways, as intended for its intended purpose, but for some reason when the amp module modifies the document, the XDMP-TRIGGERMODULE error is triggered instead, causing the whole transaction to fail, and preventing the amp code from ever executing (and therefore preventing the payment completion from being recorded).

I'm wondering if there is some sort of issue with the trigger being triggered by an update done in an amp module? If so, how can I avoid this problem occurring? The trigger code isn't even needed in this particular case, but it is set up to run on all modifications to this specific type of document, and I'm not sure if there's a way to prevent that in unique cases.

Thanks for any and all help!

答:
If your organization has support from MarkLogic, I would recommend you go via them.

Otherwise, more data is required to help you. Perhaps the trigger code and the amped module code that invokes it and how the amp is setup and information about the user/role calling the module would be useful.


问:
Function to insert text line by line from a file into string array passed by pointer
I'm trying to create a function read_lines that takes a file *fp, a pointer to char** lines, and pointer to int num_lines. The function should insert each line of text into lines, and increase num_lines to however many lines the file has.

Its probably really simple but I've been trying to insert the text for several hours now.

This is what main.c would look like. Everything but read_lines is already defined and working.

```<code>int main(int argc, char* argv[]){

    char** lines = NULL;
    int num_lines = 0;
    FILE* fp = validate_input(argc, argv);
    read_lines(fp, &lines, &num_lines);
    print_lines(lines, num_lines);
    free_lines(lines, num_lines);
    fclose(fp);

    return 0;
}
</code>```

This is one of my attempts at trying to append lines, but I couldn't figure it out.

read_lines.c

```<code>void read_lines(FILE *fp, char ***lines, int *num_lines) {
    int i;
    int N = 0;
    char s[200];
    for (i=0; i<3; i++)
    {
        while(fgets(s, 200, fp)!=NULL){N++;}
        char strings[50][200];

        rewind(fp);
        fgets(s, 200, fp);
        strcpy(lines[i],s);
    }

}
</code>```

I'd appreciate any help at solving this, thanks.

答:
I find fgets hard to use and more trouble than it's worth. Here is a fgetc and malloc-based approach:

```<code>void read_lines(FILE *fp, char ***lines, int *num_lines) {
    int c;

    size_t line = 0;
    size_t pos  = 0;
    size_t len  = 64;
    *lines = malloc(1 * sizeof(char*));
    (*lines)[0] = malloc(len);
    while ((c = fgetc(fp)) != EOF) {
        if (c == '\n') {
             (*lines)[line][pos] = '\0';
             line++;
             pos = 0;
             len = 64;
             *lines = realloc(*lines, (line+1) * sizeof(char*));
        } else {
            (*lines)[line][pos] = c;
        }
        pos++;
        if (pos >= len) {
            len *= 2;
            (*lines)[line] = realloc((*lines)[line], len);
        }
    }
    *num_lines = line+1;
}
</code>```

I haven't checked this, so correct me if I made any mistakes. Also, in real code you would do lots of error checking here that I have omitted.

Body:
I'm trying to create a function read_lines that takes a file *fp, a pointer to char** lines, and pointer to int num_lines. The function should insert each line of text into lines, and increase num_lines to however many lines the file has.

Its probably really simple but I've been trying to insert the text for several hours now.

This is what main.c would look like. Everything but read_lines is already defined and working.

int main(int argc, char* argv[]){

    char** lines = NULL;
    int num_lines = 0;
    FILE* fp = validate_input(argc, argv);
    read_lines(fp, &lines, &num_lines);
    print_lines(lines, num_lines);
    free_lines(lines, num_lines);
    fclose(fp);

    return 0;
}

This is one of my attempts at trying to append lines, but I couldn't figure it out.

read_lines.c

void read_lines(FILE *fp, char ***lines, int *num_lines) {
    int i;
    int N = 0;
    char s[200];
    for (i=0; i<3; i++)
    {
        while(fgets(s, 200, fp)!=NULL){N++;}
        char strings[50][200];

        rewind(fp);
        fgets(s, 200, fp);
        strcpy(lines[i],s);
    }

}

I'd appreciate any help at solving this, thanks.

Body:
I find fgets hard to use and more trouble than it's worth. Here is a fgetc and malloc-based approach:

void read_lines(FILE *fp, char ***lines, int *num_lines) {
    int c;

    size_t line = 0;
    size_t pos  = 0;
    size_t len  = 64;
    *lines = malloc(1 * sizeof(char*));
    (*lines)[0] = malloc(len);
    while ((c = fgetc(fp)) != EOF) {
        if (c == '\n') {
             (*lines)[line][pos] = '\0';
             line++;
             pos = 0;
             len = 64;
             *lines = realloc(*lines, (line+1) * sizeof(char*));
        } else {
            (*lines)[line][pos] = c;
        }
        pos++;
        if (pos >= len) {
            len *= 2;
            (*lines)[line] = realloc((*lines)[line], len);
        }
    }
    *num_lines = line+1;
}

I haven't checked this, so correct me if I made any mistakes. Also, in real code you would do lots of error checking here that I have omitted.


问:
How to provide custom comparator for `std::multiset` without overloading `operator()`, `std::less`, `std::greater`?
I want a custom comparator for the following code. However, I am not allowed to overload  operator(), std::less, std::greater.

I tried to achieve this using lambda but gcc won't allow me to use auto as a non-static member. Any other way to make this work?

```<code>#include <iostream>
#include <map>
#include <set>

class Test
{
public:
    // bool operator () (const int lhs, const int rhs) { // not allowed
    //     return lhs > rhs;
    // };
    using list = std::multiset<int  /*, Test*/>;
    std::map<const char*, list> scripts;
};

int main()
{
    Test t;
    t.scripts["Linux"].insert(5);
    t.scripts["Linux"].insert(8);
    t.scripts["Linux"].insert(0);

    for (auto a : t.scripts["Linux"]) {
        std::cout << a << std::endl;
    }

    std::cout << "end";
}
</code>```

Edit: With lambdas

```<code>class Test
{
  public:
    auto compare = [] (const int a, const int b) { return a < b;}
    using list = std::multiset<int, compare>;    //here
    std::map<const char*, list> scripts;
};
</code>```

Error:

```<code>'auto' not allowed in non-static class member
 auto compare = [] (const int a, const int b) { return a < b;}
</code>```

答:
I want a custom comparator for the following code. However, I cannot
  overload operator(), std::less, std::greater.

I assume that you are not allowed to overload operator() of the Test class, but could be that of other class. If so, create a internal private functor which overloads operator() and that could be part of the alias using list = std::multiset<int, Compare>;

```<code>class Test
{
private:
    struct Compare
    {
        bool operator()(const int lhs, const int rhs) const /* noexcept */ { return lhs > rhs; }
    };

public:
    using list = std::multiset<int, Compare>;
    std::map<std::string, list> scripts;
};
</code>```

I tried to achieve these using lambdas but gcc won't allow me to use
  auto as a non-static member. Any other way to make this work?

Update: After researching a while, I found a way to go which does work† with a lambda function.

The idea is to use the decltype of std::multiset with custom lambda compare as the key of the std::map scripts. In addition to that, provide a wrapper method for inserting the entries to the CustomMultiList.

Complete example code: (See live)

```<code>#include <iostream>
#include <string>
#include <map>
#include <set>

// provide a lambda compare
const auto compare = [](int lhs, int rhs) noexcept { return lhs > rhs; };

class Test
{
private:
    // make a std::multi set with custom compare function
    std::multiset<int, decltype(compare)> dummy{ compare };
    using CustomMultiList = decltype(dummy); // use the type for values of the map
public:
    std::map<std::string, CustomMultiList> scripts{};
    // warper method to insert the `std::multilist` entries to the corresponding keys
    void emplace(const std::string& key, const int listEntry)
    {
        scripts.try_emplace(key, compare).first->second.emplace(listEntry);
    }
    // getter function for custom `std::multilist`
    const CustomMultiList& getValueOf(const std::string& key) const noexcept
    {
        static CustomMultiList defaultEmptyList{ compare };
        const auto iter = scripts.find(key);
        return iter != scripts.cend() ? iter->second : defaultEmptyList;
    }
};

int main()
{
    Test t{};
    // 1: insert using using wrapper emplace method
    t.emplace(std::string{ "Linux" }, 5);
    t.emplace(std::string{ "Linux" }, 8);
    t.emplace(std::string{ "Linux" }, 0);

    for (const auto a : t.getValueOf(std::string{ "Linux" }))
    {
        std::cout << a << '\n';
    }
    // 2: insert the `CustomMultiList` directly using `std::map::emplace`
    std::multiset<int, decltype(compare)> valueSet{ compare };
    valueSet.insert(1);
    valueSet.insert(8);
    valueSet.insert(5);
    t.scripts.emplace(std::string{ "key2" }, valueSet);

    // 3: since C++20 : use with std::map::operator[]
    t.scripts["Linux"].insert(5);
    t.scripts["Linux"].insert(8);
    t.scripts["Linux"].insert(0);

    return 0;
}
</code>```

† Until c++20 lambda are not default constructable and copyable. But, the std::map::operator[] does requered the mapped_type to be  copy constructible and default constructible. Hence the insertion to the value of the scripts map(i.e. to std::multiset<int, decltype(/*lambda compare*/)>) using subscription operator of std::map is only possible from from C++20.

Body:
I want a custom comparator for the following code. However, I am not allowed to overload  operator(), std::less, std::greater.

I tried to achieve this using lambda but gcc won't allow me to use auto as a non-static member. Any other way to make this work?

#include <iostream>
#include <map>
#include <set>

class Test
{
public:
    // bool operator () (const int lhs, const int rhs) { // not allowed
    //     return lhs > rhs;
    // };
    using list = std::multiset<int  /*, Test*/>;
    std::map<const char*, list> scripts;
};

int main()
{
    Test t;
    t.scripts["Linux"].insert(5);
    t.scripts["Linux"].insert(8);
    t.scripts["Linux"].insert(0);

    for (auto a : t.scripts["Linux"]) {
        std::cout << a << std::endl;
    }

    std::cout << "end";
}

Edit: With lambdas

class Test
{
  public:
    auto compare = [] (const int a, const int b) { return a < b;}
    using list = std::multiset<int, compare>;    //here
    std::map<const char*, list> scripts;
};

Error:

'auto' not allowed in non-static class member
 auto compare = [] (const int a, const int b) { return a < b;}

Body:
I want a custom comparator for the following code. However, I cannot
  overload operator(), std::less, std::greater.

I assume that you are not allowed to overload operator() of the Test class, but could be that of other class. If so, create a internal private functor which overloads operator() and that could be part of the alias using list = std::multiset<int, Compare>;

class Test
{
private:
    struct Compare
    {
        bool operator()(const int lhs, const int rhs) const /* noexcept */ { return lhs > rhs; }
    };

public:
    using list = std::multiset<int, Compare>;
    std::map<std::string, list> scripts;
};

I tried to achieve these using lambdas but gcc won't allow me to use
  auto as a non-static member. Any other way to make this work?

Update: After researching a while, I found a way to go which does work† with a lambda function.

The idea is to use the decltype of std::multiset with custom lambda compare as the key of the std::map scripts. In addition to that, provide a wrapper method for inserting the entries to the CustomMultiList.

Complete example code: (See live)

#include <iostream>
#include <string>
#include <map>
#include <set>

// provide a lambda compare
const auto compare = [](int lhs, int rhs) noexcept { return lhs > rhs; };

class Test
{
private:
    // make a std::multi set with custom compare function
    std::multiset<int, decltype(compare)> dummy{ compare };
    using CustomMultiList = decltype(dummy); // use the type for values of the map
public:
    std::map<std::string, CustomMultiList> scripts{};
    // warper method to insert the `std::multilist` entries to the corresponding keys
    void emplace(const std::string& key, const int listEntry)
    {
        scripts.try_emplace(key, compare).first->second.emplace(listEntry);
    }
    // getter function for custom `std::multilist`
    const CustomMultiList& getValueOf(const std::string& key) const noexcept
    {
        static CustomMultiList defaultEmptyList{ compare };
        const auto iter = scripts.find(key);
        return iter != scripts.cend() ? iter->second : defaultEmptyList;
    }
};

int main()
{
    Test t{};
    // 1: insert using using wrapper emplace method
    t.emplace(std::string{ "Linux" }, 5);
    t.emplace(std::string{ "Linux" }, 8);
    t.emplace(std::string{ "Linux" }, 0);

    for (const auto a : t.getValueOf(std::string{ "Linux" }))
    {
        std::cout << a << '\n';
    }
    // 2: insert the `CustomMultiList` directly using `std::map::emplace`
    std::multiset<int, decltype(compare)> valueSet{ compare };
    valueSet.insert(1);
    valueSet.insert(8);
    valueSet.insert(5);
    t.scripts.emplace(std::string{ "key2" }, valueSet);

    // 3: since C++20 : use with std::map::operator[]
    t.scripts["Linux"].insert(5);
    t.scripts["Linux"].insert(8);
    t.scripts["Linux"].insert(0);

    return 0;
}

† Until c++20 lambda are not default constructable and copyable. But, the std::map::operator[] does requered the mapped_type to be  copy constructible and default constructible. Hence the insertion to the value of the scripts map(i.e. to std::multiset<int, decltype(/*lambda compare*/)>) using subscription operator of std::map is only possible from from C++20.


问:
Powershell - How to select and click hyperlink in firefox
I am trying to find, select and click on a specific Hyperlink in Firefox using Powershell.

I have been able to find all the Hyperlinks available through .Links I am unsure of how to select the one that I want and how to click on it.

```<code>$azr = Invoke-WebRequest -uri "https://Website/" -SessionVariable sbv
$sbv
$azr.Links
</code>```

This is for a typing test website. There is a link that says start typing test, and that's what I'm trying to click on. I'm just not sure of how to select that within all of the HTML that is produced with .Links and how to click on it.

答:
What you are calling though is not using a browser at all.

In a browser, this is a very common thing and well documented and asked about. So, your query could be viewed as a duplicate of this and it's accepted answer.

Click a hyperlink using powershell

```<code>$ie = new-object -com internetexplorer.application
$ie.visible=$true
$ie.navigate('http://www.somewhere.com')
while($ie.busy) {sleep 1}
$link = $ie.Document.getElementsByTagName('A') | where-object {$_.innerText -eq 'Click here'}
$link.click()
</code>```

Now, the above is for IE, so, you'd do the same thing for another browser.

With Invoke-WebRequest, then the discussion and sample here:

Teaching PowerShell to Click

Body:
I am trying to find, select and click on a specific Hyperlink in Firefox using Powershell.

I have been able to find all the Hyperlinks available through .Links I am unsure of how to select the one that I want and how to click on it.

$azr = Invoke-WebRequest -uri "https://Website/" -SessionVariable sbv
$sbv
$azr.Links

This is for a typing test website. There is a link that says start typing test, and that's what I'm trying to click on. I'm just not sure of how to select that within all of the HTML that is produced with .Links and how to click on it.

Body:
What you are calling though is not using a browser at all.

In a browser, this is a very common thing and well documented and asked about. So, your query could be viewed as a duplicate of this and it's accepted answer.

Click a hyperlink using powershell

$ie = new-object -com internetexplorer.application
$ie.visible=$true
$ie.navigate('http://www.somewhere.com')
while($ie.busy) {sleep 1}
$link = $ie.Document.getElementsByTagName('A') | where-object {$_.innerText -eq 'Click here'}
$link.click()

Now, the above is for IE, so, you'd do the same thing for another browser.

With Invoke-WebRequest, then the discussion and sample here:

Teaching PowerShell to Click


问:
Change cursor style depending on sort or not
I'm using the jqGrid and have 3 columns that can NOT be sorted.  At this point the cursor changes to a hand when the user hovers over the headers regardless of sorting set to true or false.  I'd like that cursor to be something other than a hand (text or pointer) on those column heads.  It's confusing to the users this way. Is this something that can be set?

Thanks,
Mark

答:
I find the question very good. So +1 from me.

You are not the first person (and not the last one) who wish to have another cursor on non-sortable columns. It's pity, but jqGrid gives you not classes or some other simple attributes which can be used to find the elements at which one can set CSS "cursor:default".

So I suggest to do this with the following code:

```<code>var myGrid = $("#list");

// create the grid
myGrid.jqGrid({
  // all jqGrid parameters
});

// fix cursor on non-sortable columns
var cm = myGrid[0].p.colModel;
$.each(myGrid[0].grid.headers, function(index, value) {
    var cmi = cm[index], colName = cmi.name;
    if(!cmi.sortable && colName!=='rn' && colName!=='cb' && colName!=='subgrid') {
        $('div.ui-jqgrid-sortable',value.el).css({cursor:"default"});
    }
});
</code>```

You can see on the demo live that the method work. In the demo the last column 'Notes' is non-sortable.

It would be nice if such behavior would be standard in the next version of jqGrid. I will try to find time and to write suggestion what from the code of jqGrid should be changed to make the behavior out-of-the-box.

UPDATED: The problem with the cursor on non-sortable columns is not exist more in free jqGrid 4.8.

Body:
I find the question very good. So +1 from me.

You are not the first person (and not the last one) who wish to have another cursor on non-sortable columns. It's pity, but jqGrid gives you not classes or some other simple attributes which can be used to find the elements at which one can set CSS "cursor:default".

So I suggest to do this with the following code:

var myGrid = $("#list");

// create the grid
myGrid.jqGrid({
  // all jqGrid parameters
});

// fix cursor on non-sortable columns
var cm = myGrid[0].p.colModel;
$.each(myGrid[0].grid.headers, function(index, value) {
    var cmi = cm[index], colName = cmi.name;
    if(!cmi.sortable && colName!=='rn' && colName!=='cb' && colName!=='subgrid') {
        $('div.ui-jqgrid-sortable',value.el).css({cursor:"default"});
    }
});

You can see on the demo live that the method work. In the demo the last column 'Notes' is non-sortable.

It would be nice if such behavior would be standard in the next version of jqGrid. I will try to find time and to write suggestion what from the code of jqGrid should be changed to make the behavior out-of-the-box.

UPDATED: The problem with the cursor on non-sortable columns is not exist more in free jqGrid 4.8.


问:
How to store the contents of a __m128d simd vector as doubles without accessing it as a union?
The code i want to optimize is basically a simple but large arithmetic formula, it should be fairly simple to analyze the code automatically to compute the independent multiplications/additions in parallel, but i read that autovectorization only works for loops.

I've read multiple times now that access of single elements in a vector via union or some other way should be avoided at all costs, instead should be replaced by a _mm_shuffle_pd (i'm working on doubles only)...

I don't seem to figure out how I can store the content of a __m128d vector as doubles without accessing it as a union. Also, does an operation like this give any performance gain when compared to scalar code?

```<code>union {
  __m128d v;
  double d[2];
} vec;
union {
  __m128d v;
double d[2];
} vec2;

vec.v = index1;
vec2.v = index2;
temp1 = _mm_mul_pd(temp1, _mm_set_pd(bvec[vec.d[1]], bvec[vec2[1]]));
</code>```

also, the two unions look ridiculously ugly, but when using

```<code>union dvec {
  __m128d v;
  double d[2];
} vec;
</code>```

Trying to declare the indexX as dvec, the compiler complained dvec is undeclared.

答:
_mm_cvtsd_f64 + _mm_unpackhi_pd

For doubles:

```<code>#include <assert.h>

#include <x86intrin.h>

int main(void) {
    __m128d x = _mm_set_pd(1.5, 2.5);
    /* _mm_cvtsd_f64 + _mm_unpackhi_pd */
    assert(_mm_cvtsd_f64(x) == 2.5);
    assert(_mm_cvtsd_f64(_mm_unpackhi_pd(x, x)) == 1.5);
}
</code>```

For floats, I have posted the following examples at How to convert a hex float to a float in C/C++ using _mm_extract_ps SSE GCC instrinc function

_mm_cvtss_f32 + _mm_shuffle_ps

_MM_EXTRACT_FLOAT

For ints you can use _mm_extract_epi32:

```<code>#include <assert.h>

#include <x86intrin.h>

int main(void) {
    __m128i x = _mm_set_epi32(1, 2, 3, 4);
    assert(_mm_extract_epi32(x, 3) == 4);
    assert(_mm_extract_epi32(x, 2) == 3);
    assert(_mm_extract_epi32(x, 1) == 1);
    assert(_mm_extract_epi32(x, 0) == 1);
}
</code>```

GitHub upstream.

Compile and run examples with:

```<code>gcc -ggdb3 -O0 -std=c99 -Wall -Wextra -pedantic -o main.out main.c
./main.out
</code>```

Tested on Ubuntu 19.04 amd64.

Body:
The code i want to optimize is basically a simple but large arithmetic formula, it should be fairly simple to analyze the code automatically to compute the independent multiplications/additions in parallel, but i read that autovectorization only works for loops.

I've read multiple times now that access of single elements in a vector via union or some other way should be avoided at all costs, instead should be replaced by a _mm_shuffle_pd (i'm working on doubles only)...

I don't seem to figure out how I can store the content of a __m128d vector as doubles without accessing it as a union. Also, does an operation like this give any performance gain when compared to scalar code?

union {
  __m128d v;
  double d[2];
} vec;
union {
  __m128d v;
double d[2];
} vec2;

vec.v = index1;
vec2.v = index2;
temp1 = _mm_mul_pd(temp1, _mm_set_pd(bvec[vec.d[1]], bvec[vec2[1]]));

also, the two unions look ridiculously ugly, but when using

union dvec {
  __m128d v;
  double d[2];
} vec;

Trying to declare the indexX as dvec, the compiler complained dvec is undeclared.

Body:
_mm_cvtsd_f64 + _mm_unpackhi_pd

For doubles:

#include <assert.h>

#include <x86intrin.h>

int main(void) {
    __m128d x = _mm_set_pd(1.5, 2.5);
    /* _mm_cvtsd_f64 + _mm_unpackhi_pd */
    assert(_mm_cvtsd_f64(x) == 2.5);
    assert(_mm_cvtsd_f64(_mm_unpackhi_pd(x, x)) == 1.5);
}

For floats, I have posted the following examples at How to convert a hex float to a float in C/C++ using _mm_extract_ps SSE GCC instrinc function

_mm_cvtss_f32 + _mm_shuffle_ps

_MM_EXTRACT_FLOAT

For ints you can use _mm_extract_epi32:

#include <assert.h>

#include <x86intrin.h>

int main(void) {
    __m128i x = _mm_set_epi32(1, 2, 3, 4);
    assert(_mm_extract_epi32(x, 3) == 4);
    assert(_mm_extract_epi32(x, 2) == 3);
    assert(_mm_extract_epi32(x, 1) == 1);
    assert(_mm_extract_epi32(x, 0) == 1);
}

GitHub upstream.

Compile and run examples with:

gcc -ggdb3 -O0 -std=c99 -Wall -Wextra -pedantic -o main.out main.c
./main.out

Tested on Ubuntu 19.04 amd64.


问:
Not able to load dataset as per the instructions in article
I am new to data science field.
I came through this article
https://towardsdatascience.com/train-test-split-and-cross-validation-in-python-80b61beca4b6
Here I am not able to load diabetes dataset as per the code they have written.

```<code># Load the Diabetes dataset

columns = “age sex bmi map tc ldl hdl tch ltg glu”.split() # Declare the columns names
diabetes = datasets.load_diabetes() # Call the diabetes dataset from sklearn
df = pd.DataFrame(diabetes.data, columns=columns) # load the dataset as a pandas data frame
y = diabetes.target # define the target variable (dependent variable) as y
</code>```

I have tried to load data set through csv but in vain.

答:
As @DYZ mentioned it is the quotation marks issue, copy paste the below and run</p>

```<code>import pandas as pd
from sklearn import datasets, linear_model
from sklearn.model_selection import train_test_split
from matplotlib import pyplot as plt

columns = "age sex bmi map tc ldl hdl tch ltg glu".split() # Declare the columns names
diabetes = datasets.load_diabetes() # Call the diabetes dataset from sklearn
df = pd.DataFrame(diabetes.data, columns=columns) # load the dataset as a pandas data frame
y = diabetes.target # define the target variable (dependent variable) as y
</code>```

Body:
I am new to data science field.
I came through this article
https://towardsdatascience.com/train-test-split-and-cross-validation-in-python-80b61beca4b6
Here I am not able to load diabetes dataset as per the code they have written.

# Load the Diabetes dataset

columns = “age sex bmi map tc ldl hdl tch ltg glu”.split() # Declare the columns names
diabetes = datasets.load_diabetes() # Call the diabetes dataset from sklearn
df = pd.DataFrame(diabetes.data, columns=columns) # load the dataset as a pandas data frame
y = diabetes.target # define the target variable (dependent variable) as y

I have tried to load data set through csv but in vain.

Body:
As @DYZ mentioned it is the quotation marks issue, copy paste the below and run

import pandas as pd
from sklearn import datasets, linear_model
from sklearn.model_selection import train_test_split
from matplotlib import pyplot as plt

columns = "age sex bmi map tc ldl hdl tch ltg glu".split() # Declare the columns names
diabetes = datasets.load_diabetes() # Call the diabetes dataset from sklearn
df = pd.DataFrame(diabetes.data, columns=columns) # load the dataset as a pandas data frame
y = diabetes.target # define the target variable (dependent variable) as y


问:
cudaGetDevice() failed. Status: CUDA driver version is insufficient for CUDA runtime version
I get the following error when l run tensorflow in GPU.

```<code>2018-09-15 18:56:51.011724: E tensorflow/core/common_runtime/direct_session.cc:158] Internal: cudaGetDevice() failed. Status: CUDA driver version is insufficient for CUDA runtime version
Traceback (most recent call last):
  File "evaluate_sample.py", line 160, in <module>
    tf.app.run(main)
  File "/anaconda3/envs/tf/lib/python2.7/site-packages/tensorflow/python/platform/app.py", line 125, in run
    _sys.exit(main(argv))
  File "evaluate_sample.py", line 123, in main
    with tf.Session() as sess:
  File "/anaconda3/envs/tf/lib/python2.7/site-packages/tensorflow/python/client/session.py", line 1494, in __init__
    super(Session, self).__init__(target, graph, config=config)
  File "/anaconda3/envs/tf/lib/python2.7/site-packages/tensorflow/python/client/session.py", line 626, in __init__
    self._session = tf_session.TF_NewSession(self._graph._c_graph, opts)
tensorflow.python.framework.errors_impl.InternalError: Failed to create session.
</code>```

Where do  the following errors come from  ?

```<code>E tensorflow/core/common_runtime/direct_session.cc:158] Internal: cudaGetDevice() failed. Status: CUDA driver version is insufficient for CUDA runtime version
</code>```

and
tensorflow.python.framework.errors_impl.InternalError: Failed to create session.

Such tha my version of :

tensorflow is : 1.10

```<code>cat /proc/driver/nvidia/version
</code>```

NVRM version: NVIDIA UNIX x86_64 Kernel Module  390.77  Tue Jul 10 18:28:52 PDT 2018

GCC version:  gcc version 7.3.0 (Debian 7.3.0-28)

```<code>nvcc --version
</code>```

nvcc: NVIDIA (R) Cuda compiler driver

Copyright (c) 2005-2016 NVIDIA Corporation

Built on Sun_Sep__4_22:14:01_CDT_2016

Cuda compilation tools, release 8.0, V8.0.44

答:
For Ubuntu 18.04 and Tensorflow 1.13.1

First make sure system is up to data:

```<code>sudo apt update
sudo apt dist-upgrade
sudo reboot now
</code>```

Install later drivers:

```<code>sudo add-apt-repository ppa:graphics-drivers/ppa
</code>```

Open Software & Updates and select the Additional Drivers tab:

Select the nvidia-driver-396 and click Apply Changes

Now reboot:

```<code>sudo reboot now
</code>```

To verify which that NVIDIA driver 396 active:

```<code>nvidia-smi
</code>```

Body:
I get the following error when l run tensorflow in GPU.

2018-09-15 18:56:51.011724: E tensorflow/core/common_runtime/direct_session.cc:158] Internal: cudaGetDevice() failed. Status: CUDA driver version is insufficient for CUDA runtime version
Traceback (most recent call last):
  File "evaluate_sample.py", line 160, in <module>
    tf.app.run(main)
  File "/anaconda3/envs/tf/lib/python2.7/site-packages/tensorflow/python/platform/app.py", line 125, in run
    _sys.exit(main(argv))
  File "evaluate_sample.py", line 123, in main
    with tf.Session() as sess:
  File "/anaconda3/envs/tf/lib/python2.7/site-packages/tensorflow/python/client/session.py", line 1494, in __init__
    super(Session, self).__init__(target, graph, config=config)
  File "/anaconda3/envs/tf/lib/python2.7/site-packages/tensorflow/python/client/session.py", line 626, in __init__
    self._session = tf_session.TF_NewSession(self._graph._c_graph, opts)
tensorflow.python.framework.errors_impl.InternalError: Failed to create session.

Where do  the following errors come from  ?

E tensorflow/core/common_runtime/direct_session.cc:158] Internal: cudaGetDevice() failed. Status: CUDA driver version is insufficient for CUDA runtime version

and
tensorflow.python.framework.errors_impl.InternalError: Failed to create session.

Such tha my version of :

tensorflow is : 1.10

cat /proc/driver/nvidia/version

NVRM version: NVIDIA UNIX x86_64 Kernel Module  390.77  Tue Jul 10 18:28:52 PDT 2018

GCC version:  gcc version 7.3.0 (Debian 7.3.0-28)

nvcc --version

nvcc: NVIDIA (R) Cuda compiler driver

Copyright (c) 2005-2016 NVIDIA Corporation

Built on Sun_Sep__4_22:14:01_CDT_2016

Cuda compilation tools, release 8.0, V8.0.44

Body:
For Ubuntu 18.04 and Tensorflow 1.13.1

First make sure system is up to data:

sudo apt update
sudo apt dist-upgrade
sudo reboot now

Install later drivers:

sudo add-apt-repository ppa:graphics-drivers/ppa

Open Software & Updates and select the Additional Drivers tab:

Select the nvidia-driver-396 and click Apply Changes

Now reboot:

sudo reboot now

To verify which that NVIDIA driver 396 active:

nvidia-smi


问:
Python age calculator based on DOB
I am practicing by creating an age calculator which calculates age in years based on given date of birth.

However it doesn't work the way I intend it to function. I want to show age in year e.g 19 to the user when their age is 19 and month is less than 6 and if the month is more than 6 then I want to add 1 to the age in this case 19+1.

Can anyone create the same program with the same concept in a better way?  Please add some explanation so that it is easy for me to understand.

I am python beginner, so please excuse my bad code as well as my bad English. Thanks in advance for the help.

from datetime import date

Doby,Dobm,Dobd =input("enter your DOB : i.e year,month,days  1999,02,08   : ").split(",")
born = date(year = int(Doby) , month= int(Dobm) , day= int(Dobd))
today = date.today()
age = today.year - born.year
condition = today.month - born.month
if condition >= 6 :
    age += 1
elif condition <= -6 :
    age -= 1
print(age)
```

答:
here is your function

```<code>def years_of_age():
    from datetime import date, datetime
    dob = input("Please enter your DOB as mm-dd-yyyy: ")

    #time delta in days
    val = date.today().toordinal() - datetime.strptime(dob, "%m-%d-%Y").toordinal()

    # this is just so you can confirm, comment out the following 4 lines
    print("months {}, years {}".format(\
                                       int(datetime.fromordinal(val).strftime("%m")),\
                                       int(datetime.fromordinal(val).strftime("%Y"))\
                                      ))

    # conditional return based on the months figure
    if int(datetime.fromordinal(val).strftime("%m")) >=6:
        return int(datetime.fromordinal(val).strftime("%Y")) + 1
    else:
        return int(datetime.fromordinal(val).strftime("%Y"))
</code>```

Here are a few examples

```<code>years_of_age()
</code>```

Please enter your DOB as mm-dd-yyyy: 5-16-1976

months 1, years 44

44

```<code>years_of_age()
</code>```

Please enter your DOB as mm-dd-yyyy: 7-16-1976

months 11, years 43

44

```<code>years_of_age()
</code>```

Please enter your DOB as mm-dd-yyyy: 2-16-1977

months 4, years 43

43

instance method .toordinal() converts a datetime object into a number of days since Jan 1 0000.

the instance method .strftime() converts a string to a datetime object given that there are format directives datetime ("%m-%d-%Y").

since you are a beginner I made sure to use python standard library packages, not because numpy is too advanced, because standard library packages are efficient, great and overlooked.

Title: Python age calculator based on DOB

Body:
here is your function

def years_of_age():
    from datetime import date, datetime
    dob = input("Please enter your DOB as mm-dd-yyyy: ")

    #time delta in days
    val = date.today().toordinal() - datetime.strptime(dob, "%m-%d-%Y").toordinal()

    # this is just so you can confirm, comment out the following 4 lines
    print("months {}, years {}".format(\
                                       int(datetime.fromordinal(val).strftime("%m")),\
                                       int(datetime.fromordinal(val).strftime("%Y"))\
                                      ))

    # conditional return based on the months figure
    if int(datetime.fromordinal(val).strftime("%m")) >=6:
        return int(datetime.fromordinal(val).strftime("%Y")) + 1
    else:
        return int(datetime.fromordinal(val).strftime("%Y"))

Here are a few examples

years_of_age()

Please enter your DOB as mm-dd-yyyy: 5-16-1976

months 1, years 44

44

years_of_age()

Please enter your DOB as mm-dd-yyyy: 7-16-1976

months 11, years 43

44

years_of_age()

Please enter your DOB as mm-dd-yyyy: 2-16-1977

months 4, years 43

43

instance method .toordinal() converts a datetime object into a number of days since Jan 1 0000.

the instance method .strftime() converts a string to a datetime object given that there are format directives datetime ("%m-%d-%Y").

since you are a beginner I made sure to use python standard library packages, not because numpy is too advanced, because standard library packages are efficient, great and overlooked.


问:
How can I conditionally insert a character into a string?
Brand new to programming, what I've learned so far I've just copied from similar examples online.

This is a random sentence generator for a foreign language. But, I want to insert a character in between two specific characters in a string if they happen to occur next to each other. In this case, I want the characters in the evowel and avowel variables to be separated by 'y'.

I thought I could try a conditional split + rejoin, but I'm not sure how to search for (in this case) evowel_avowel, split it at that boundary, insert y, then join it back. So a randomly generated string 'eametetuk' would change to 'eyametetuk', 'eseapah' > 'eseyapah' etc.

Edit: I need to be able to handle anything in the evowel with anything in the avowel. For simplicity's sake I've only included two varations of each, but the language has more vowels and more variations (so roughly 60 permutations where this change needs to happen).

Would I need to create my own function for this? I'm guessing I would need regex somewhere.

import random

c1 = ("e","é")
c2 = ("a","se")
root = ("apa","mete")
tense = ("h","tuk")

avowel = ("a","á")
evowel = ("e","é")

#syntax
x = [c1,c2,root,tense]

#randomly selects morphemes
s = "".join([random.choice(i) for i in x])

print(s)
```

答:
Using regular expression (re module):

```<code>import re
txt1 = "eametetuk"
txt2 = "eseapah"
evowel = ("e","é")
avowel = ("a","á")
evowels = "|".join(evowel)
avowels = "|".join(avowel)
out1 = re.sub(r'('+evowels+')('+avowels+')',r'\1y\2',txt1)
out2 = re.sub(r'('+evowels+')('+avowels+')',r'\1y\2',txt2)
print(out1) # eyametetuk
print(out2) # eseyapah
</code>```

That method will work for any evowel-avowel combination, for example:

```<code>txt3 = "xéay"
out3 = re.sub(r'('+evowels+')('+avowels+')',r'\1y\2',txt3)
print(out3) # xéyay
</code>```

and so on.

Explanation: I used | which inside regular expression pattern mean LOGICAL OR. Then I created pattern with two groups - denoted by brackets, then in second argument of re.sub I write that I want 1stgroup then letter y then 2nd group.

Note that re.sub's group indexing start at 1 rather than 0, also note that I used raw strings, meaning I do not have to escape \ in order to point 1st group and 2nd group.

Body:
Using regular expression (re module):

import re
txt1 = "eametetuk"
txt2 = "eseapah"
evowel = ("e","é")
avowel = ("a","á")
evowels = "|".join(evowel)
avowels = "|".join(avowel)
out1 = re.sub(r'('+evowels+')('+avowels+')',r'\1y\2',txt1)
out2 = re.sub(r'('+evowels+')('+avowels+')',r'\1y\2',txt2)
print(out1) # eyametetuk
print(out2) # eseyapah

That method will work for any evowel-avowel combination, for example:

txt3 = "xéay"
out3 = re.sub(r'('+evowels+')('+avowels+')',r'\1y\2',txt3)
print(out3) # xéyay

and so on.

Explanation: I used | which inside regular expression pattern mean LOGICAL OR. Then I created pattern with two groups - denoted by brackets, then in second argument of re.sub I write that I want 1stgroup then letter y then 2nd group.

Note that re.sub's group indexing start at 1 rather than 0, also note that I used raw strings, meaning I do not have to escape \ in order to point 1st group and 2nd group.


问:
ActiveStorage - Create or Update attachment
I’m actually working on a rails app and I have some troubles with ActiveStorage.

My rails app is online, everything work perfectly.
I have a model call Room in my app, and each owner of a Room can add a banner image.

Actually if a user create a new Room, he can add a banner image, everything work, that’s good.

My first problem is for the Room already created before I install Active Storage, I can not add banner image.

I thought I can re-use the form i used for New in Edit but not, my attachment is nill.

My second problem  : if I a user try to update the image, that’s doesn’t work. The user has to delete first and then add a new one, from my edit page.

My Room.rb :

```<code>class Room < ApplicationRecord
  validates :title, uniqueness: true, presence: true, length: {maximum: 50}
  validates :description, uniqueness: true, presence: true, length: {maximum: 200}
  validates :theme, presence: true

  belongs_to :user
  belongs_to :theme

  has_many :subjects, dependent: :destroy
  has_many :rubrics, dependent: :destroy
  has_many :favorites, dependent: :destroy

  has_one_attached :header_image

  attr_accessor :remove_header_image

  # delette header image
  after_save :purge_header_image, if: :remove_header_image
  private def purge_header_image
    header_image.purge_later
  end

  # Consider room as searchable
  searchkick searchable: [:title]
end
</code>```

my Room controller  :

```<code>class RoomsController < ApplicationController

  def index
    # @rooms = Room.all
    @rooms = policy_scope(Room)
  end

  def new
    @room = Room.new
    authorize @room
  end

  def show
    @room = Room.find(params[:id])
    @favorite_exists = Favorite.where(room: @room, user: current_user) == [] ? false : true
    if params[:rubric_id]
      @subject = Subject.where(room: @room, rubric_id: params[:rubric_id])
    else
      @subject = Subject.where(room: @room)
    end
    authorize @room
    @footer_variable = true
  end

  def create
    @room = Room.new(room_params)
    @room.user_id = current_user.id
    authorize @room
    if @room.save
      redirect_to new_room_rubric_path(@room)
      RoomMailer.creation_confirmation(@room).deliver_now
    else
      render :new
    end
  end

  def edit
    @room = Room.find(params[:id])
    authorize @room
  end

  def update
    @room = Room.find(params[:id])
    @room.update(room_params)
    redirect_to room_edit_room_rubric_path(@room)
    authorize @room
  end

private

  def room_params
    params.require(:room).permit(:title, :description, :theme_id, :header_image, :remove_header_image)
  end
end
</code>```

my Edit form :

```<code><div class="col-sm-7">
      <%= simple_form_for [@room], :html => { class: 'form-create'} do |f| %>
  <!-- form row 1 -->
      <span><p class="box"><i class="fas fa-clipboard-check"></i></p></span>
      <%= f.association :theme, input_html: {class: 'mt-15-n fa-select'}, prompt: 'Selectionnez un thème', collection: Theme.all, label_method: :title, value_method: :id, label: "Theme" %>
  <!-- form row 2 -->
      <span><p class="box"><i class="fas fa-rocket"></i></p></span>
      <%=f.input :title, input_html: {class: 'mt-15-n' ,:rows => 4}, :placeholder => 'Nom de votre communauté' %>
  <!-- edit header image -->
      <span><p class="box"><i class="far fa-images"></i></p></span>
  <!-- actual image -->
      <% if @room.header_image.attached?  %>
        <p class="description">Votre bannière actuelle</p>
        <%= image_tag @room.header_image.variant(resize: "300x300") %>
   <!--  delete image -->
        <p class="description">Supprimer la bannière.</p>
        <%=f.check_box :remove_header_image  %>
        <% else %>
        <p>Vous n'avez pas de banière, ajoutez une banière ci-dessous :</p>
        <%=f.file_field :header_image, :class => "asterisk" %>
      <% end %>
    <!-- form row 3 -->
      <div class="mt-20">
        <span><p class="box"><i class="fas fa-bars"></i></p></span>
        <%= f.input :description, :input_html => {class: 'mt-15-n', :rows => 5}, :maxlength =>"200", :placeholder => 'Description', hint: "Max 200 characters" %>
        <%= f.submit "Suivant", class: "btn-primary" %>
        <% end %>
      </div>
    </div>
</code>```

Rooms Routes :

```<code>rooms GET   /rooms(.:format)          rooms#index
          POST  /rooms(.:format)          rooms#create
 new_room GET   /rooms/new(.:format)      rooms#new
edit_room GET   /rooms/:id/edit(.:format) rooms#edit
     room GET   /rooms/:id(.:format)      rooms#show
          PATCH /rooms/:id(.:format)      rooms#update
          PUT   /rooms/:id(.:format)      rooms#update
</code>```

If you have an Idea ...
Thanks a lot for your help !

Regards

答:
I was not able to reproduce your problems, but I had an issue with this line:

```<code>after_save :purge_header_image, if: :remove_header_image
</code>```

The variable remove_header_image comes as parameter from the checkbox, so it can be "0" or "1", as String, not false or true. It means it evaluates always to true.

So I suggest to change as follows and see if it works:

```<code>after_save :purge_header_image

private
  def purge_header_image
    header_image.purge_later if remove_header_image == '1'
  end
</code>```

Body:
I’m actually working on a rails app and I have some troubles with ActiveStorage.

My rails app is online, everything work perfectly.
I have a model call Room in my app, and each owner of a Room can add a banner image.

Actually if a user create a new Room, he can add a banner image, everything work, that’s good.

My first problem is for the Room already created before I install Active Storage, I can not add banner image.

I thought I can re-use the form i used for New in Edit but not, my attachment is nill.

My second problem  : if I a user try to update the image, that’s doesn’t work. The user has to delete first and then add a new one, from my edit page.

My Room.rb :

class Room < ApplicationRecord
  validates :title, uniqueness: true, presence: true, length: {maximum: 50}
  validates :description, uniqueness: true, presence: true, length: {maximum: 200}
  validates :theme, presence: true

  belongs_to :user
  belongs_to :theme

  has_many :subjects, dependent: :destroy
  has_many :rubrics, dependent: :destroy
  has_many :favorites, dependent: :destroy

  has_one_attached :header_image

  attr_accessor :remove_header_image

  # delette header image
  after_save :purge_header_image, if: :remove_header_image
  private def purge_header_image
    header_image.purge_later
  end

  # Consider room as searchable
  searchkick searchable: [:title]
end

my Room controller  :

class RoomsController < ApplicationController

  def index
    # @rooms = Room.all
    @rooms = policy_scope(Room)
  end

  def new
    @room = Room.new
    authorize @room
  end

  def show
    @room = Room.find(params[:id])
    @favorite_exists = Favorite.where(room: @room, user: current_user) == [] ? false : true
    if params[:rubric_id]
      @subject = Subject.where(room: @room, rubric_id: params[:rubric_id])
    else
      @subject = Subject.where(room: @room)
    end
    authorize @room
    @footer_variable = true
  end

  def create
    @room = Room.new(room_params)
    @room.user_id = current_user.id
    authorize @room
    if @room.save
      redirect_to new_room_rubric_path(@room)
      RoomMailer.creation_confirmation(@room).deliver_now
    else
      render :new
    end
  end

  def edit
    @room = Room.find(params[:id])
    authorize @room
  end

  def update
    @room = Room.find(params[:id])
    @room.update(room_params)
    redirect_to room_edit_room_rubric_path(@room)
    authorize @room
  end

private

  def room_params
    params.require(:room).permit(:title, :description, :theme_id, :header_image, :remove_header_image)
  end
end

my Edit form :

      <%= simple_form_for [@room], :html => { class: 'form-create'} do |f| %>

      <%= f.association :theme, input_html: {class: 'mt-15-n fa-select'}, prompt: 'Selectionnez un thème', collection: Theme.all, label_method: :title, value_method: :id, label: "Theme" %>

      <%=f.input :title, input_html: {class: 'mt-15-n' ,:rows => 4}, :placeholder => 'Nom de votre communauté' %>

      <% if @room.header_image.attached?  %>

Votre bannière actuelle

        <%= image_tag @room.header_image.variant(resize: "300x300") %>

Supprimer la bannière.

        <%=f.check_box :remove_header_image  %>
        <% else %>

Vous n'avez pas de banière, ajoutez une banière ci-dessous :

        <%=f.file_field :header_image, :class => "asterisk" %>
      <% end %>

        <%= f.input :description, :input_html => {class: 'mt-15-n', :rows => 5}, :maxlength =>"200", :placeholder => 'Description', hint: "Max 200 characters" %>
        <%= f.submit "Suivant", class: "btn-primary" %>
        <% end %>

Rooms Routes :

rooms GET   /rooms(.:format)          rooms#index
          POST  /rooms(.:format)          rooms#create
 new_room GET   /rooms/new(.:format)      rooms#new
edit_room GET   /rooms/:id/edit(.:format) rooms#edit
     room GET   /rooms/:id(.:format)      rooms#show
          PATCH /rooms/:id(.:format)      rooms#update
          PUT   /rooms/:id(.:format)      rooms#update

If you have an Idea ...
Thanks a lot for your help !

Regards

Body:
I was not able to reproduce your problems, but I had an issue with this line:

after_save :purge_header_image, if: :remove_header_image

The variable remove_header_image comes as parameter from the checkbox, so it can be "0" or "1", as String, not false or true. It means it evaluates always to true.

So I suggest to change as follows and see if it works:

after_save :purge_header_image

private
  def purge_header_image
    header_image.purge_later if remove_header_image == '1'
  end


问:
How to retrieve only the updated rows data from the tabulator as a JSON object?
I am working with Tabulator which has an Input Field in it through which the user can enter a numeric value, and I need to upload the data from it as it is to MySQL Database. However, I want a way to get only the updated rows i.e. only the rows in which the user has entered value so that I can just update those rows in MySQL Database.
I wish to get only the updated row data as a JSON Object so that I can just pass it to my PHP code through the AJAX Request.

答:
Ok let me answer your question. While you are updating a row then definitely you have used a unique id to update the row.
After update you should use that same unique id and fetch the data from database from that same row which you have updated.
And at last put it in echo with json encode that will be the response of you ajax request see my code it will work for sure:-</p>

```<code> // update the row where unique id is quote_id

      $sqlbt = "UPDATE `quote_data_master_kotak` SET `reg_date` = '$reg_date',
                `make_year` = '$makeyear' WHERE `quote_id` = '$quoteid'";
      $result = $conn->query($sqlbt); //row updated

    //now its time to get the updated row data using quote_id as unique id

    $sql = "SELECT * FROM `quote_data_master_kotak` WHERE `quote_id` = '$quote_id'";
    $result = $conn->query($sql);
    if ($result->num_rows > 0) {
            $updated_row_data = $result->fetch_assoc();
            $data['row_data'] = $updated_row_data ;
    }

    //now you can echo it in Json formate
         echo json_encode($data);

   // output json like this:-

       {
        "row_data":{

           "quote_id":"5",
           "reg_date":"20/11/2018",
           "make_year":"2018"
                }
       }
</code>```

Body:
Ok let me answer your question. While you are updating a row then definitely you have used a unique id to update the row.
After update you should use that same unique id and fetch the data from database from that same row which you have updated.
And at last put it in echo with json encode that will be the response of you ajax request see my code it will work for sure:-

 // update the row where unique id is quote_id

      $sqlbt = "UPDATE `quote_data_master_kotak` SET `reg_date` = '$reg_date',
                `make_year` = '$makeyear' WHERE `quote_id` = '$quoteid'";
      $result = $conn->query($sqlbt); //row updated

    //now its time to get the updated row data using quote_id as unique id

    $sql = "SELECT * FROM `quote_data_master_kotak` WHERE `quote_id` = '$quote_id'";
    $result = $conn->query($sql);
    if ($result->num_rows > 0) {
            $updated_row_data = $result->fetch_assoc();
            $data['row_data'] = $updated_row_data ;
    }

    //now you can echo it in Json formate
         echo json_encode($data);

   // output json like this:-

       {
        "row_data":{

           "quote_id":"5",
           "reg_date":"20/11/2018",
           "make_year":"2018"
                }
       }


问:
How to display for loop PHP variable in newline in html table
I want to display forloop value in newline in html table

echo "
";
echo "".$i++."	";
echo "".$row['instructorname']."	";
echo "".$row['batchname']."	";
echo "".$row['fromdate']."	";
echo "".$row['todate']."	";

for ($i = $startdate; $i < $todate; $i++) echo ''.$i.'	';
echo "
";
```

I want to display each  $i value in newline but it appears in same line.

答:
Just echo
 to make a new line

```<code>echo '<td>', $startdate;

for($i = $startdate + 1; $i < $todate; $i++)
    echo '<br/>', $i;

echo '</td>';
</code>```

FYI use comma in echo statement is better than dot

Body:
I want to display forloop value in newline in html table

echo "
";
echo "".$i++."	";
echo "".$row['instructorname']."	";
echo "".$row['batchname']."	";
echo "".$row['fromdate']."	";
echo "".$row['todate']."	";

for ($i = $startdate; $i < $todate; $i++) echo ''.$i.'	';
echo "
";

I want to display each  $i value in newline but it appears in same line.

Body:
Just echo <br/> to make a new line

echo '<td>', $startdate;

for($i = $startdate + 1; $i < $todate; $i++)
    echo '<br/>', $i;

echo '</td>';

FYI use comma in echo statement is better than dot


问:
Emgu crop image, crop wrong area
I'm practice with emgu libraries, trying to crop and image to later apply another filtesre or search, the problem is I select a rectangle with the mouse, in the ImageBox(Emgu component) I selected zoom in the SizeMode property, and load the crop picture in another imagebox but the result is always a bit up of the area I selected.

I check the calculation with GIMP and I can see that the rectangle is ok, so I dont know what can be the problem

```<code>Point f1=scaleCalculation(firstPoint, pIma.Size, imOri.Size);
Point f2= scaleCalculation(secondPoint, pIma.Size, imOri.Size);
imGray.ROI = new Rectangle(Math.Min(f1.X, f2.X), Math.Min(f1.Y, f2.Y)
                        , Math.Abs(f1.X - f2.X), Math.Abs(f1.Y-f2.Y));
imOri.ROI = imGray.ROI;
pRec.Image = imOri.Copy();
imOri.ROI = new Rectangle();
</code>```

And here is the function

```<code>        private Point scaleCalculation(Point real, Size pBox, Size imCalc) {

        double scale, spare;

        try {
            if (imCalc.Height > imCalc.Width){
                scale = (double) imCalc.Height/ pBox.Height  ;
                spare =  pBox.Width-((imCalc.Width / scale));
                var x = ((real.X * scale) -(spare/4));
                x = (x < 0) ? 0 : x;
                return new Point((int) x, (int)(real.Y * scale));
            }
            else {
                scale = (double) imCalc.Width/ pBox.Width ;
                spare = pBox.Height - ((imCalc.Height / scale));
                var y = ((real.Y * scale) - (spare /4));
                y = (y < 0) ? 0 : y;
                return new Point((int)(real.X * scale), (int) y);
            }
        }
        catch (Exception ex) {
            return new Point();
        }
    }
</code>```

答:
After look for a while I see that the problem it was in the scalecalculation function.

```<code>        private Point scaleCalculation(Point real, Size pBox, Size imCalc) {

        double scale, spare;

        try {
            if (imCalc.Height > imCalc.Width){
                scale = (double)imCalc.Height / pBox.Height;
                spare = (pBox.Width - (imCalc.Width / scale)) / 2;
                var x = (real.X - spare);
                x = (x < 0) ? 0 : x;
                return new Point((int)(x * scale), (int)(real.Y * scale));
            }
            else {
                scale = (double)imCalc.Width / pBox.Width;
                spare = (pBox.Height - (imCalc.Height/scale))/2;
                var y = (real.Y - spare);
                y = (y < 0) ? 0 : y;
                return new Point((int)(real.X * scale),(int) (y *scale));
            }
        }
        catch (Exception ex) {
            return new Point();
        }
    }
</code>```

I going to try to explain it here with the help of the picture.

(Xr,Yr): Coordinate that we want to know.
(Xm,Ym): Coordinate of the mouse.
(Wi,Hi): Size of the picture.
(Wp,Hp): Size of the ImageBox.
S: Space form the edge of the Imagebox to the picture.

```<code>Xr = (Xm * scale)
S = [Hp -(Hi/scale)]/2
Yr = (Ym-S)
</code>```

(This explanation is when width is bigger than height)

The first I do is calculate the scale using width or height depend which is the bigger.

To calculate S (spare) the height of the Image have to scale to the height of the Imagebox, substract it from the Imagebox height and divide for 2 the result to have the value of only one size.

From Ym (Real.Y) is substract the spare to calculate the y. and check if the result is negative.

Finally the result is Xm and y multiply for scale respectively

Title: Emgu crop image, crop wrong area

Body:
I'm practice with emgu libraries, trying to crop and image to later apply another filtesre or search, the problem is I select a rectangle with the mouse, in the ImageBox(Emgu component) I selected zoom in the SizeMode property, and load the crop picture in another imagebox but the result is always a bit up of the area I selected.

I check the calculation with GIMP and I can see that the rectangle is ok, so I dont know what can be the problem

Point f1=scaleCalculation(firstPoint, pIma.Size, imOri.Size);
Point f2= scaleCalculation(secondPoint, pIma.Size, imOri.Size);
imGray.ROI = new Rectangle(Math.Min(f1.X, f2.X), Math.Min(f1.Y, f2.Y)
                        , Math.Abs(f1.X - f2.X), Math.Abs(f1.Y-f2.Y));
imOri.ROI = imGray.ROI;
pRec.Image = imOri.Copy();
imOri.ROI = new Rectangle();

And here is the function

        private Point scaleCalculation(Point real, Size pBox, Size imCalc) {

        double scale, spare;

        try {
            if (imCalc.Height > imCalc.Width){
                scale = (double) imCalc.Height/ pBox.Height  ;
                spare =  pBox.Width-((imCalc.Width / scale));
                var x = ((real.X * scale) -(spare/4));
                x = (x < 0) ? 0 : x;
                return new Point((int) x, (int)(real.Y * scale));
            }
            else {
                scale = (double) imCalc.Width/ pBox.Width ;
                spare = pBox.Height - ((imCalc.Height / scale));
                var y = ((real.Y * scale) - (spare /4));
                y = (y < 0) ? 0 : y;
                return new Point((int)(real.X * scale), (int) y);
            }
        }
        catch (Exception ex) {
            return new Point();
        }
    }

Body:
After look for a while I see that the problem it was in the scalecalculation function.

        private Point scaleCalculation(Point real, Size pBox, Size imCalc) {

        double scale, spare;

        try {
            if (imCalc.Height > imCalc.Width){
                scale = (double)imCalc.Height / pBox.Height;
                spare = (pBox.Width - (imCalc.Width / scale)) / 2;
                var x = (real.X - spare);
                x = (x < 0) ? 0 : x;
                return new Point((int)(x * scale), (int)(real.Y * scale));
            }
            else {
                scale = (double)imCalc.Width / pBox.Width;
                spare = (pBox.Height - (imCalc.Height/scale))/2;
                var y = (real.Y - spare);
                y = (y < 0) ? 0 : y;
                return new Point((int)(real.X * scale),(int) (y *scale));
            }
        }
        catch (Exception ex) {
            return new Point();
        }
    }

I going to try to explain it here with the help of the picture.

(Xr,Yr): Coordinate that we want to know.
(Xm,Ym): Coordinate of the mouse.
(Wi,Hi): Size of the picture.
(Wp,Hp): Size of the ImageBox.
S: Space form the edge of the Imagebox to the picture.

Xr = (Xm * scale)
S = [Hp -(Hi/scale)]/2
Yr = (Ym-S)

(This explanation is when width is bigger than height)

The first I do is calculate the scale using width or height depend which is the bigger.

To calculate S (spare) the height of the Image have to scale to the height of the Imagebox, substract it from the Imagebox height and divide for 2 the result to have the value of only one size.

From Ym (Real.Y) is substract the spare to calculate the y. and check if the result is negative.

Finally the result is Xm and y multiply for scale respectively


问:
Does bitcoin-js have a method to check unspent transaction status?
How does BlockCypher explorer get data about spent or unspent transaction status?

Does bitcoin-js library have some methods for it?

答:
I'm not sure about bitcoin-js lib, but Blockcypher has API method:

const fetch = require('cross-fetch')

const getAddress = async address => {
  const url = `https://api.blockcypher.com/v1/btc/test3/addrs/${address}`
  const res = await fetch(url)

  return await res.json()
}

getAddress('mitTmNgXyoEANondxZns8dS6GcXTzVhJW6')
  .then(({txrefs}) => txrefs.filter(tx => tx.spent === false))
  .then(data => console.log(data))
```

<p>and you'll get sth like this</p>

```[ { tx_hash: 'bdbd9253b052cb17afdf42c006c69f6d9f7513d2176db1c088fdbd2381edf2de',
    block_height: 1519165,
    tx_input_n: -1,
    tx_output_n: 1,
    value: 15800000,
    ref_balance: 32343852,
    spent: false, // @docs tx status
    confirmations: 60,
    confirmed: '2019-05-31T20:43:22Z',
    double_spend: false },
  { tx_hash: '4014e09c48ec4de6c4f1e82b38107f4ca77037e96e4989abe5ba5cf459d57700',
    block_height: 1519149,
    tx_input_n: -1,
    tx_output_n: 1,
    value: 10000,
    ref_balance: 17044852,
    spent: false, // @docs tx status
    confirmations: 76,
    confirmed: '2019-05-31T18:43:02Z',
    double_spend: false } ]
```

Body:
I'm not sure about bitcoin-js lib, but Blockcypher has API method:

const fetch = require('cross-fetch')

const getAddress = async address => {
  const url = `https://api.blockcypher.com/v1/btc/test3/addrs/${address}`
  const res = await fetch(url)

  return await res.json()
}

getAddress('mitTmNgXyoEANondxZns8dS6GcXTzVhJW6')
  .then(({txrefs}) => txrefs.filter(tx => tx.spent === false))
  .then(data => console.log(data))

and you'll get sth like this

[ { tx_hash: 'bdbd9253b052cb17afdf42c006c69f6d9f7513d2176db1c088fdbd2381edf2de',
    block_height: 1519165,
    tx_input_n: -1,
    tx_output_n: 1,
    value: 15800000,
    ref_balance: 32343852,
    spent: false, // @docs tx status
    confirmations: 60,
    confirmed: '2019-05-31T20:43:22Z',
    double_spend: false },
  { tx_hash: '4014e09c48ec4de6c4f1e82b38107f4ca77037e96e4989abe5ba5cf459d57700',
    block_height: 1519149,
    tx_input_n: -1,
    tx_output_n: 1,
    value: 10000,
    ref_balance: 17044852,
    spent: false, // @docs tx status
    confirmations: 76,
    confirmed: '2019-05-31T18:43:02Z',
    double_spend: false } ]


问:
How to print symbol's table, symbol name
I want to print symbol's name in symbol table.
i'm mapping the the elf to the virtual memory (using mmap), I successfully an accessed  to the symbol table, but when trying to print symbol names it fails (an odd string is show, comparing it to the elf file results).

my code :

```<code>void printSymboles() {
Elf32_Sym* symtab;
Elf32_Shdr * sh_strtab_p ;
char *sh_strtab;
int symbol_num=-1;
  if(currentFd==-1){
    printf("not legal file set\n");
} else {

    sectionHeader=(Elf32_Shdr*)(map_start+header->e_shoff);
    int section_num=header->e_shnum;

    int numSectionsFound=0;
    for(int i=0;i<section_num &&numSectionsFound<2;i++){
        if(sectionHeader[i].sh_type==SHT_SYMTAB) {
            symtab=(Elf32_Sym *) (map_start+sectionHeader[i].sh_offset);
            symbol_num= sectionHeader[i].sh_size/sectionHeader[i].sh_entsize; // symobl tbl size/ entrysize
            numSectionsFound++;
        }
        if(sectionHeader[i].sh_type==SHT_STRTAB) {
            sh_strtab_p=&sectionHeader[i];
            sh_strtab=(char*) map_start+sh_strtab_p->sh_offset;
            numSectionsFound++;

        }
    }

    if(symbol_num==-1) {
        printf("symbol table doesn't exist");
    } else {
        printf("symbol table : \n");
        for(int i=0;i<symbol_num;i++) {
        printf("name : %s\n",sh_strtab+symtab[i].st_name);
        }
    }
</code>```

答:
as @chris Dodd mentioned, the problem indeed was the wrong SHT_STRTAB.
I've changed this section of code :

```<code>   if(sectionHeader[i].sh_type==SHT_STRTAB) {
        sh_strtab_p=&sectionHeader[i];
        sh_strtab=(char*) map_start+sh_strtab_p->sh_offset;
        numSectionsFound++;

    }
</code>```

to this :

```<code>    Elf32_Shde * sh_sectionStrTbl_p;
    char * sh_sectionStrTbl;
    sh_sectionStrTbl_p=&sectionHeader[header->e_shoff);
    sh_sectionStrTbl=map_start+sh_sectionStrTbl_p->sh_offset;

    if(sectionHeader[i].sh_type==SHT_STRTAB) {
        if(strcmp(sectionHeader[i].sh_name+sh_sectionStrTbl,".strtab")==0) {
        sh_strtab_p=&sectionHeader[i];
        sh_strtab=(char*) map_start+sh_strtab_p->sh_offset;
        numSectionsFound++;
        }
    }
</code>```

and it works.

Body:
I want to print symbol's name in symbol table.
i'm mapping the the elf to the virtual memory (using mmap), I successfully an accessed  to the symbol table, but when trying to print symbol names it fails (an odd string is show, comparing it to the elf file results).

my code :

void printSymboles() {
Elf32_Sym* symtab;
Elf32_Shdr * sh_strtab_p ;
char *sh_strtab;
int symbol_num=-1;
  if(currentFd==-1){
    printf("not legal file set\n");
} else {

    sectionHeader=(Elf32_Shdr*)(map_start+header->e_shoff);
    int section_num=header->e_shnum;

    int numSectionsFound=0;
    for(int i=0;i<section_num &&numSectionsFound<2;i++){
        if(sectionHeader[i].sh_type==SHT_SYMTAB) {
            symtab=(Elf32_Sym *) (map_start+sectionHeader[i].sh_offset);
            symbol_num= sectionHeader[i].sh_size/sectionHeader[i].sh_entsize; // symobl tbl size/ entrysize
            numSectionsFound++;
        }
        if(sectionHeader[i].sh_type==SHT_STRTAB) {
            sh_strtab_p=&sectionHeader[i];
            sh_strtab=(char*) map_start+sh_strtab_p->sh_offset;
            numSectionsFound++;

        }
    }

    if(symbol_num==-1) {
        printf("symbol table doesn't exist");
    } else {
        printf("symbol table : \n");
        for(int i=0;i<symbol_num;i++) {
        printf("name : %s\n",sh_strtab+symtab[i].st_name);
        }
    }

Body:
as @chris Dodd mentioned, the problem indeed was the wrong SHT_STRTAB.
I've changed this section of code :

   if(sectionHeader[i].sh_type==SHT_STRTAB) {
        sh_strtab_p=&sectionHeader[i];
        sh_strtab=(char*) map_start+sh_strtab_p->sh_offset;
        numSectionsFound++;

    }

to this :

    Elf32_Shde * sh_sectionStrTbl_p;
    char * sh_sectionStrTbl;
    sh_sectionStrTbl_p=&sectionHeader[header->e_shoff);
    sh_sectionStrTbl=map_start+sh_sectionStrTbl_p->sh_offset;

    if(sectionHeader[i].sh_type==SHT_STRTAB) {
        if(strcmp(sectionHeader[i].sh_name+sh_sectionStrTbl,".strtab")==0) {
        sh_strtab_p=&sectionHeader[i];
        sh_strtab=(char*) map_start+sh_strtab_p->sh_offset;
        numSectionsFound++;
        }
    }

and it works.


问:
Update data using Linq in SQL Server database without assinging values to each property
I would like to update a record on bases of simple update Linq query but the problem is I don't want to assign values to each property.

Here is what I have to do every time that I want to update some recorders

```<code>var frm = db.MYTable.Where(s => s.Code == code).FirstOrDefault();
frm.Name = TxtName.Text;
frm.Code = TxtCode.Text;
frm.Mno = Convert.ToInt32(TxtMno.Text);
db.SaveChanges();
</code>```

What I want is instead of using this way because some of my tables will have more than 50 columns, I would like to give a context/model context having values to set values in the database.

答:
The only thing I can really recommend you look at is something like data binding, to connect your text boxes to your data objects so that typing in the textbox sets the data value, and the code for linking them up is written by the winforms designer instead of you:

https://learn.microsoft.com/en-us/ef/ef6/fundamentals/databinding/winforms

I don't normally post such answers that are merely a link to the docs but you've asked a short question that has a huge answer, and it doesn't make sense to replicate all of MSDN into stack overflow "in case MSDN goes down" - it's pretty reliably always going to be available until the technology is well phased out and dead

Body:
I would like to update a record on bases of simple update Linq query but the problem is I don't want to assign values to each property.

Here is what I have to do every time that I want to update some recorders

var frm = db.MYTable.Where(s => s.Code == code).FirstOrDefault();
frm.Name = TxtName.Text;
frm.Code = TxtCode.Text;
frm.Mno = Convert.ToInt32(TxtMno.Text);
db.SaveChanges();

What I want is instead of using this way because some of my tables will have more than 50 columns, I would like to give a context/model context having values to set values in the database.


问:
why does tinyMce escape my PHP code that i want to display on my blog?
I'm trying to display PHP code in my blog, and I'm inserting it into tinymce textrea, but it escapes the php code? I tried doing it without tinymce and it worked, but with tinymce it doesn't? :)) thanks</p>

答:
If you type the PHP directly into designer mode (the mode that shows the rendered HTML rather than the source code) TinyMCE will escape it assuming that you want to talk about the PHP rather than execute it.  This is pretty much standard behaviour for rich text editors since it matches the user expectation that they can type < and have it appear correctly on the webpage rather than acting as the start of a tag.

You want to enter the PHP code directly into the source view and ensure that the HTML filter is configured to allow PHP properly (this depends on the version of TinyMCE you use).

That said, TinyMCE really isn't designed for editing HTML that has PHP inside it - it can do it, but generally it's better to use a rich text editor for plain HTML that non-technical users would edit and a plain text area for HTML that technical authors write which may contain PHP.