text:
Q: why is "static" both storage class and linkage specifier? The static keyword defines how a variable is to be stored in memory, i.e., in the data segment if initialized or in the BSS if uninitialized. But the keyword also specifies how a variable is to be linked, i.e., local scope only.
How or why are these two things related? Can the two be separated, or was this a necessary design consideration?
IOW, why is it that if I want my variable to exist for the duration of the program, it must be linked internally?

A: Re

"why is it that if I want my variable to exist for the duration of the program, it must be linked internally?"

no that is not so.
Program-global variables are supported, and that's the default for a non-const namespace level variable. It's just wise to avoid them (to the extent possible).

Re apparent conflation of concepts in the single keyword static, since C++ doesn't support dynamic libraries, local to the translation unit linkage is not meaningful for lifetime shorter than the program execution.

A: The keyword static can probably be seen as somewhat "overloaded".
The following usage-options are all viable:

*

*Static local variables

*Static global variables

*Static member variables

*Static global functions

*Static member functions

Variables:
In terms of runtime, all types of static variables are essentially the same. They all reside in the data-section of the program, and their addresses remain constant throughout the execution of the program. So the only difference between them is during compilation, in the scope of declaration:

*

*Static local variable: recognized by the compiler only in the scope of the function

*Static global variable: recognized by the compiler only in the scope of the file

*Static member variable: recognized by the compiler only in the scope of the class

Functions:
In terms of runtime, all types of functions (static and non-static) are essentially the same. They all reside in the code-section of the program, and their addresses remain constant throughout the execution of the program. So the only difference between them is during compilation, in the scope of declaration:

*

*Static global function: recognized by the compiler only in the scope of the file

*Static member function: recognized by the compiler only in the scope of the class


text:
Q: I am unable to click on a link with class selectable using watir webdriver I been trying to click on a link with class "selectable" without success.
The html code is as display below:

    Email

        <input type="checkbox" id="chkNoEmail" data-bind="checked: noEmail, attr: { 'disabled': baseController.readonly() }">

    no email
    <input type="text" class="form-control" id="txtEmail" placeholder="Email" data-bind="value: email, attr: { 'disabled': noEmail() || baseController.readonly() }">

I have try using the parent div and also using
browser.selectable(:text, /no email/).click

and
browser.selectable(:text, /no email/).fire_event("onclick") but not success.

A: I would try something like this.
@browser.div(:class => "forum-group").label(:class => "selectable").check

However, I am not sure you can do a ".check" on a label element. You could also try
@browser.div(:class => "forum-group").checkbox(:id => "chkNoEmail").check

Or, since I dont think it is an actual check box, you could try ".click" instead of ".check" on either one of them, I still do not think you can do either action on a label element though.

redpajama_set_name: RedPajamaStackExchange


text: Q: Hide trash icon in Nautilus (not on desktop) By default, Nautilus show the icon of the trash, in the side panel. I wish to keep the function of the trash but hide the icon in Nautilus in the side panel. I'm not talk about to hide the trash icon on desktop (different topic).


text:
Q: Network Activity Monitoring on iPhone I've been working for 5 days trying to learn and implement Network monitor on the iPhone.
I looked into netstat code from apple, and i lost like 25% of my hair.
I found links for JB Devices but i need it to execute on a non JB device. (Irrespective of whether Apple accepts it on the App store or not).
I found some useful links :
how to get tcp udp opening port list on iPhone (I couldn't parse the data returned in this question :( )
Data Usage on iPhone
sysctlbyname buf return type (I'm not a networking guy..could not understand this one, may be you guys can help :) )
TCP/UPD port list
I can say i got some thing from the first link. Can you guys help me to Parse the data ?
Is there any other method to achieve this??

A: Ok, you have all that you need over the table.
You can check the question Is there any private api to monitor network traffic on iPhone?
And here you can find the source code of inet. That code have all you need to parse the data returned of how to get tcp udp opening port list on iPhone
size_t len = 0;
if (sysctlbyname("net.inet.tcp.pcblist_n", 0, &len, 0, 0) < 0) {
    perror("sysctlbyname");
} else {
    char *buf = malloc(len);
    sysctlbyname("net.inet.tcp.pcblist_n", buf, &len, 0, 0);
    NSData *data = [NSData dataWithBytesNoCopy:buf length:len];
    NSLog(@"data = %@", data);
}

Ok, yes the source code of inet is a little complicate. But, you know that netstat print the net status. So, you only need to see when inet execute printf, at this point you will have the data parsed.
If you try to compile the source of inet for iOS, you will find a lot of problems: some header files are not present in ios sdk. Ok, no problem copy the headers.
For the simulator you only need copy the header of netstat.h. And add some struct declaration that are private:
struct  xtcpcb_n {
    u_int32_t                      xt_len;
    u_int32_t                        xt_kind;                /* XSO_TCPCB */

    u_int64_t t_segq;
    int     t_dupacks;              /* consecutive dup acks recd */

    int t_timer[TCPT_NTIMERS_EXT];  /* tcp timers */

    int     t_state;                /* state of this connection */
    u_int   t_flags;

    int     t_force;                /* 1 if forcing out a byte */

    tcp_seq snd_una;                /* send unacknowledged */
    tcp_seq snd_max;                /* highest sequence number sent;
                                     * used to recognize retransmits
                                     */
    tcp_seq snd_nxt;                /* send next */
    tcp_seq snd_up;                 /* send urgent pointer */

    tcp_seq snd_wl1;                /* window update seg seq number */
    tcp_seq snd_wl2;                /* window update seg ack number */
    tcp_seq iss;                    /* initial send sequence number */
    tcp_seq irs;                    /* initial receive sequence number */

    tcp_seq rcv_nxt;                /* receive next */
    tcp_seq rcv_adv;                /* advertised window */
    u_int32_t rcv_wnd;              /* receive window */
    tcp_seq rcv_up;                 /* receive urgent pointer */

    u_int32_t snd_wnd;              /* send window */
    u_int32_t snd_cwnd;             /* congestion-controlled window */
    u_int32_t snd_ssthresh;         /* snd_cwnd size threshold for
                                     * for slow start exponential to
                                     * linear switch
                                     */
    u_int   t_maxopd;               /* mss plus options */

    u_int32_t t_rcvtime;            /* time at which a packet was received */
    u_int32_t t_starttime;          /* time connection was established */
    int     t_rtttime;              /* round trip time */
    tcp_seq t_rtseq;                /* sequence number being timed */

    int     t_rxtcur;               /* current retransmit value (ticks) */
    u_int   t_maxseg;               /* maximum segment size */
    int     t_srtt;                 /* smoothed round-trip time */
    int     t_rttvar;               /* variance in round-trip time */

    int     t_rxtshift;             /* log(2) of rexmt exp. backoff */
    u_int   t_rttmin;               /* minimum rtt allowed */
    u_int32_t t_rttupdated;         /* number of times rtt sampled */
    u_int32_t max_sndwnd;           /* largest window peer has offered */

    int     t_softerror;            /* possible error not yet reported */
    /* out-of-band data */
    char    t_oobflags;             /* have some */
    char    t_iobc;                 /* input character */
    /* RFC 1323 variables */
    u_char  snd_scale;              /* window scaling for send window */
    u_char  rcv_scale;              /* window scaling for recv window */
    u_char  request_r_scale;        /* pending window scaling */
    u_char  requested_s_scale;
    u_int32_t ts_recent;            /* timestamp echo data */

    u_int32_t ts_recent_age;        /* when last updated */
    tcp_seq last_ack_sent;
    /* RFC 1644 variables */
    tcp_cc  cc_send;                /* send connection count */
    tcp_cc  cc_recv;                /* receive connection count */
    tcp_seq snd_recover;            /* for use in fast recovery */
    /* experimental */
    u_int32_t snd_cwnd_prev;        /* cwnd prior to retransmit */
    u_int32_t snd_ssthresh_prev;    /* ssthresh prior to retransmit */
    u_int32_t t_badrxtwin;          /* window for retransmit recovery */
};

struct  xinpcb_n {
    u_int32_t               xi_len;         /* length of this structure */
    u_int32_t               xi_kind;                /* XSO_INPCB */
    u_int64_t               xi_inpp;
    u_short                 inp_fport;      /* foreign port */
    u_short                 inp_lport;      /* local port */
    u_int64_t               inp_ppcb;       /* pointer to per-protocol pcb */
    inp_gen_t               inp_gencnt;     /* generation count of this instance */
    int                             inp_flags;      /* generic IP/datagram flags */
    u_int32_t               inp_flow;
    u_char                  inp_vflag;
    u_char                  inp_ip_ttl;     /* time to live */
    u_char                  inp_ip_p;       /* protocol */
    union {                                 /* foreign host table entry */
        struct  in_addr_4in6    inp46_foreign;
        struct  in6_addr        inp6_foreign;
    }                               inp_dependfaddr;
    union {                                 /* local host table entry */
        struct  in_addr_4in6    inp46_local;
        struct  in6_addr        inp6_local;
    }                               inp_dependladdr;
    struct {
        u_char          inp4_ip_tos;    /* type of service */
    }                               inp_depend4;
    struct {
        u_int8_t        inp6_hlim;
        int                     inp6_cksum;
        u_short         inp6_ifindex;
        short           inp6_hops;
    }                               inp_depend6;
    u_int32_t               inp_flowhash;
};

#define SO_TC_STATS_MAX 4

struct data_stats {
    u_int64_t       rxpackets;
    u_int64_t       rxbytes;
    u_int64_t       txpackets;
    u_int64_t       txbytes;
};

struct xgen_n {
    u_int32_t   xgn_len;            /* length of this structure */
    u_int32_t   xgn_kind;       /* number of PCBs at this time */
};

#define XSO_SOCKET  0x001
#define XSO_RCVBUF  0x002
#define XSO_SNDBUF  0x004
#define XSO_STATS   0x008
#define XSO_INPCB   0x010
#define XSO_TCPCB   0x020

struct  xsocket_n {
    u_int32_t       xso_len;        /* length of this structure */
    u_int32_t       xso_kind;       /* XSO_SOCKET */
    u_int64_t       xso_so; /* makes a convenient handle */
    short           so_type;
    u_int32_t       so_options;
    short           so_linger;
    short           so_state;
    u_int64_t       so_pcb;     /* another convenient handle */
    int             xso_protocol;
    int             xso_family;
    short           so_qlen;
    short           so_incqlen;
    short           so_qlimit;
    short           so_timeo;
    u_short         so_error;
    pid_t           so_pgid;
    u_int32_t       so_oobmark;
    uid_t           so_uid;     /* XXX */
};

struct xsockbuf_n {
    u_int32_t       xsb_len;        /* length of this structure */
    u_int32_t       xsb_kind;       /* XSO_RCVBUF or XSO_SNDBUF */
    u_int32_t       sb_cc;
    u_int32_t       sb_hiwat;
    u_int32_t       sb_mbcnt;
    u_int32_t       sb_mbmax;
    int32_t         sb_lowat;
    short           sb_flags;
    short           sb_timeo;
};

struct xsockstat_n {
    u_int32_t       xst_len;        /* length of this structure */
    u_int32_t       xst_kind;       /* XSO_STATS */
    struct data_stats   xst_tc_stats[SO_TC_STATS_MAX];
};

But for the Device you need to copy some other headers of the kernel, I don't know why the headers aren't in the device sdk (maybe if you use them Apple will not approve your app, I don't know, but that doesn't matter).
You can copy the missing headers from the simulator SDK to your project. Or you can change the header path to the simulator SDK. (I copied the headers).
If you copy the headers you will need change some include declaration.
You don't need all the inet.c code. You only need these functions:

*

*protopr

*inetprint

*inetname

Then inside those functions you will see the printf with the data parsed, you can add that in a dictionary.
Here is my code. You can see a class named: DHInet  with two method that return a NSArray with a list of NSDictionary with the information of the connections.
I hope you find it useful, and if anyone wants to give me a hand in improving the code, so be it, I need to clean the code, because it has a lot of ifdef that are not necessary.


text:
Q: Returning N vectors of type int from C++ to matlab via mexfunction? I am trying to return a vector back to matlab using the mex function. I declare a return pointer as,
double *retPtr = NULL;

Then the return code is as follows:
plhs[0] = mxCreateDoubleMatrix(N, 1, mxREAL);
retPtr = mxGetPr(plhs[0]);

for (int i = 0; i < N; i++)
{
retPtr[i] = forest->predictLabel(&(testData[i*M]), M);
}

The return type is a vector , but I keep on getting the error:
Error   1   error C2440: '=' : cannot convert from 'std::vector<_Ty>' to 'double'

I there a problem the way I declare the pointer. Any help would be appreciated.
Regards,
Eric

A: If you change
retPtr[i] = forest->predictLabel(&(testData[i*M]), M);

to
retPtr[i] = i;

then it will compile and run, returning a vector to MATLAB.
Of course, you probably didn't want a vector simply counting from 0 to N-1.  But you will have to figure out the C++ code to get the numbers you want.  None of us have any idea what your forest object or predictLabel function are doing.

To actually return N different vectors, you can pack them in a cell array (this allows the size to vary).
plhs[0] = mxCreateCellMatrix(M, 1);

for (int i = 0; i < N; i++)
{
    std::vector<int> results = forest->predictLabel(&(testData[i*M]), M);
    mxArray* ithCell = mxCreateDoubleMatrix(results.size(), 1, mxREAL);
    retPtr = mxGetPr(ithCell);
    for (int j = 0; j < results.size(); ++j)
        retPtr[j] = results[j];
    mxSetCell(plhs[0], i, ithCell);
}


text:
Q: Java Design Pattern for different variation of same input to be converted into common output I have a scenario where there is a service aggregator, lets take for example skyscanner or kayak or Google flights. If you see, they all ask basic details like what is source, destination, date and number of passengers, once you select the flight from a particular service provider, let's say for example expedia, you are are redirected to expedia with prefilled details that was sent across by service aggregator
Now the name of parameters sent from the source system may vary and on the destination we have to convert it into same POJO.
One option I was thinking of was Factory pattern, based on channel, I would return an object which would transform the source params to a common POJO.
Other design pattern that I feel similar is Strategy Design Pattern, to create a ExtractionStrategy based on Context
Is there any other apt design patter to solve this problem?

A: IMHO keeping the implementation as simple as possible, I would suggest you to do go with a simple factory pattern.
Define a factory service just to perform 2 operations:

*

*Getting specified Map of all the parameters like source, dest. date etc...

*Now a simple method transformModel(Map, SourceAgg Type)
Define a parent class which has common fields of your POJO(say BasePOJO) and then extend all other types of source aggregator POJOs(assuming all would be having different field names etc). Since each of your source agg. classes would be having their own logic to create POJO specific to that type of source aggregator.
To link each source class impl. maintain an enum of: (sourceType, sourceAggClass)
ex:

enum sourceAgg{
      (EXPEDIA, ExpediaModelImpl),
      (VIA, ViaModelImpl);    }

All you have to do is get the implementation based on the source aggregator key(say EXPEDIA) from the enum, since you have the bean name in the context you can easily invoke the transformModel function for each type. The object returned by transformModel from each of the source agg. classes would be of type BasePOJO, it becomes easy to handle as formal parameters.
In future, if you want to add new source aggregator, all you have to do is just write the transform model of that class and add in the enum mappings, that's it!
PS: This is my 2nd answer on SO, Suggestions most welcome.


text:
Q: ModelState.AddModelError - How can I add an error that isn't for a property? I am checking my database in Create(FooViewModel fvm){...} to see if the fvm.prop1 and fvm.prop2 already exist in that combination; if so, I want to add an error to the modelstate, then return the whole view.  I tried:
public ActionResult Create(FooViewModel fvm){
    if (ThatComboAlreadyExists(fvm)) {
      ModelState.AddModelError("Model", "There is already one like that");
      return View(fvm);
    }
}

...but I get no display of errors in the Html.ValidationSummary, which is where I assume they would appear.  I have the suspicion that "Model" is not the right key, but I haven't been able to find anything a la Google.

A: Putting the model dot property in strings worked for me: ModelState.AddModelError("Item1.Month", "This is not a valid date");

A: I eventually stumbled upon an example of the usage I was looking for - to assign an error to the Model in general, rather than one of it's properties, as usual you call:
ModelState.AddModelError(string key, string errorMessage);

but use an empty string for the key:
ModelState.AddModelError(string.Empty, "There is something wrong with Foo.");

The error message will present itself in the <%: Html.ValidationSummary() %> as you'd expect.

A: You can add the model error on any property of your model, I suggest if there is nothing related to create a new property.
As an exemple we check if the email is already in use in DB and add the error to the Email property in the action so when I return the view, they know that there's an error and how to show it up by using
<%: Html.ValidationSummary(true)%>
<%: Html.ValidationMessageFor(model => model.Email) %>

and
ModelState.AddModelError("Email", Resources.EmailInUse);

A: Try Using Below Answer for consistent Output Format :- new ValidationProblemDetails()
if (!ModelState.IsValid) {
ModelState.AddModelError("ErrorKey", "ErrorValue");
return BadRequest(new ValidationProblemDetails(this.ModelState));
}

Output Format:
{
    "errors": {
        "ErrorKey": [
            "ErrorValue"
        ]
    },
    "title": "One or more validation errors occurred.",
    "status": 400,
}


text:
Q: Where to verify if password needs a rehash in PHP? I got the following code and nothing is getting inserted into my database and I can't figure out why.. is the password_needs_rehash() function at it's right spot?
I got a test where I echo out the new generated with a Javascript alert and it shows a new hash but the new hash is not getting inserted into the database. There must be a error in my logic but I can't find it.
<?php
session_start();
include 'mysqli.php';

$userID = strtolower($_POST['userID']);
$passwordFromForm = $_POST['password'];
$_SESSION['userID'] = $userID;

//Select the password from the requested userID and put into variable
$sql = "SELECT password FROM userdata WHERE userID = '$userID'";
$result = mysqli_query($conn, $sql);
$row = mysqli_fetch_assoc($result);
$passwordFromDatabase = $row['password'];

$verified = password_verify($passwordFromForm, $passwordFromDatabase);

if($verified == 0){
echo '<meta http-equiv="refresh" content="0; URL=index.php?triedLogin" />';

}else{

if(password_needs_rehash($passwordFromDatabase, PASSWORD_DEFAULT, ['cost' => 14])){

    $passwordFromDatabase = password_hash($passwordFromDatabase, PASSWORD_DEFAULT, ['cost' => 14]);

    echo "<script>alert('".$passwordFromDatabase."');</script>";

    $sql = "INSERT INTO userdata ('password') VALUES ('$passwordFromDatabase')";

    //NOW LOGIN WITH NEW PASSWORD
    $sql = "SELECT * FROM userdata WHERE userID = '$userID' AND password = '$passwordFromDatabase'";
    $result = mysqli_query($conn, $sql);

        if(!$row=mysqli_fetch_assoc($result)){
            echo '<meta http-equiv="refresh" content="0; URL=index.php?triedLogin" />';
        } else {
            $_SESSION['ID'] = $row['userID'];
            unset($_SESSION['userID']);
            echo '<meta http-equiv="refresh" content="0; URL=app/index.php" />';
        }

}else{

    $sql = "SELECT * FROM userdata WHERE userID = '$userID' AND password = '$passwordFromDatabase'";
    $result = mysqli_query($conn, $sql);

    if(!$row=mysqli_fetch_assoc($result)){
        echo '<meta http-equiv="refresh" content="0; URL=index.php?triedLogin" />';
    } else {
        $_SESSION['ID'] = $row['userID'];
        unset($_SESSION['userID']);
        echo '<meta http-equiv="refresh" content="0; URL=app/index.php" />';
    }
}
}
?>

A: *

*Make make sure your table field is large enough to hold that value because hash are very long, it will throw errors thus no INSERT.

*You should prepare your statements, I am surprised you don't do this yet you into password hashing.


text:
Q: replace all the characters in string in javascript I am looking for the best and fastest way to change all of the characters in string in javascript or jquery
for example:

abcdefghijklmnopqrstuvwxyz ==> αв¢∂єƒgнιנкℓмησρqяѕтυνωχуz

or

abcdefghijklmnopqrstuvwxyz ==> åߢÐê£ghïjklmñðþqr§†µvwx¥z

.
.
.
<textarea>hello world</textarea>

output: нєℓℓσ ωσяℓ∂

A: I think this could be the best (only) solution for your problem
Replace multiple strings with multiple other strings
You have to map manually every character and replace with the character you want :(

A: Use an object to have the character by character translation, and then call replace with the callback argument:

tran = {
  "a": "α",
  "b": "в",
  "c": "¢",
  "d": "∂",
  "e": "є",
  "f": "ƒ",
  "g": "g",
  "h": "н",
  "i": "ι",
  "j": "נ",
  "k": "к",
  "l": "ℓ",
  "m": "м",
  "n": "η",
  "o": "σ",
  "p": "ρ",
  "q": "q",
  "r": "я",
  "s": "ѕ",
  "t": "т",
  "u": "υ",
  "v": "ν",
  "w": "ω",
  "x": "χ",
  "y": "у",
  "z": "z"
};

let input = document.querySelector("textarea");
let output = document.querySelector("div");
input.addEventListener("input", refresh);

function refresh() {
    output.textContent = input.value.replace(/\S/g, m =>
        tran[m]??m
    );
}

refresh();
<textarea>hello world</textarea>


text:
Q: Call a Redux Action inside a useEffect My objective here is to call an action inside a useEffect.
const ShowTodos = (props) =>{
   useEffect(()=>{
    props.fetchTodos()
   },[])
}
const mapStateToProps = (state)=>{
  return {
    todos:Object.values(state.todos),
    currentUserId:state.authenticate.userId
  }
}

export default connect(mapStateToProps,{fetchTodos})(ShowTodos)

It works fine but I got a warning
React Hook useEffect has a missing dependency: 'props'. Either include it or remove the dependency array  react-hooks/exhaustive-deps.

But if I'm going to add props as my second parameter in my useEffects then it will run endlessly.
My first workaround here is to use the useRef but it seems that it will always re-render thus re-setup again the useRef which I think is not good in terms of optimization.
const ref = useRef();
  ref.current = props;
  console.log(ref)

  useEffect(()=>{
  ref.current.fetchTodos()
  },[])

Is there any other workaround here ?

A: You have to add fetchTodos to dependencies.
const ShowTodos = ({ fetchTodos }) => {
  useEffect(() => {
    fetchTodos();
  }, [fetchTodos])
  ...
}

or like this.
const ShowTodos = (props) => {
  const { fetchTodos } = props;

  useEffect(() => {
    fetchTodos();
  }, [fetchTodos])
  ...
}

A: That is an eslint warning that you get if any of the dependency within useEffect is not part of the dependency array.
In your case you are using props.fetchTodos inside useEffect and the eslint warning prompts you to provide props as a dependency so that if props changes, the useEffect function takes the updated props from its closure.
However since fetchTodos is not gonna change in your app lifecycle and you want to run the effect only once you can disable the rule for your case.
const ShowTodos = (props) =>{
   const { fetchTodos } = props
   useEffect(()=>{
     fetchTodos()
     // eslint-disable-next-line import/no-extraneous-dependencies
   },[])
}
const mapStateToProps = (state)=>{
  return {
    todos:Object.values(state.todos),
    currentUserId:state.authenticate.userId
  }
}

export default connect(mapStateToProps,{fetchTodos})(ShowTodos)

You however can solve the problem without disabling the rule like
const ShowTodos = (props) =>{
   const { fetchTodos } = props
   useEffect(()=>{
     fetchTodos()
   },[fetchTodos])
}

I however will recommend that you know when exactly should you disable the rule or pass the values to the dependency array.


text:
Q: need to help, child-component duplicate after click to link in Angular Work with child-component routes
const SignupRoutes: Routes = [
  { path: 'firstStep', component: FirstStepComponent, pathMatch: 'full' },
  { path: 'secondStep', component: SecondStepComponent, pathMatch: 'full' },
  { path: 'thirdStep', component: ThirdStepComponent, pathMatch: 'full' },
];

const appRoutes: Routes = [
  { path: '', component: LoginComponent },
  { path: 'login', component: LoginComponent },
  { path: 'index', component: IndexComponent },
  { path: 'service', component: ServicesComponent },
  { path: 'indoor', component: IndoorComponent },
  { path: 'invoice', component: InvoiceComponent },
  { path: 'report', component: ReportComponent },
  { path: 'settings', component: SettingsComponent },
  { path: 'shop', component: ShopComponent },
  { path: 'signup2', component: SignupComponent, children: SignupRoutes },
  { path: 'password', component: PasswordComponent },
  { path: 'settings/telephones', component: TelephonesComponent },
  { path: 'settings/password-edit', component: PasswordEditComponent },
  { path: '**', redirectTo: '/login'}
];

My problem is duplicate child components which after clicking on the next step button not replace each other. I get list of child-component as in the screenshot enter image description here
How cai I fix this problem?May be I need somehow to clean old child-components?

A: Change
{ path: '', component: LoginComponent },

to
{ path: '', component: LoginComponent, pathMatch: 'full' },

You need this when a route has an empty path but no child routes.


text:
Q: Creating Item category type throw "6000: A business validation error has occurred while processing your request" error I am using v3-php-sdk, creating items non category type works well.
The problem is when the item is use to be category eg.
Array
(
    [Name] => Item
    [FullyQualifiedName] => Item
    [Type] => Category
)

Then if I call
Item::create($arrayItem)

It generated object like this.
QuickBooksOnline\API\Data\IPPItem Object
        (
            [Name] => Item
            [Sku] =>
            [Description] =>
            [Active] =>
            [SubItem] =>
            [ParentRef] =>
            [Level] =>
            [FullyQualifiedName] => Item
            [Taxable] =>
            [SalesTaxIncluded] =>
            [PercentBased] =>
            [UnitPrice] =>
            [RatePercent] =>
            [Type] => QuickBooksOnline\API\Data\IPPCustomFieldTypeEnum Object
                (
                    [value] => Category
                )

            [PaymentMethodRef] =>
            [UOMSetRef] =>
            [IncomeAccountRef] =>
            [PurchaseDesc] =>
            [PurchaseTaxIncluded] =>
            [PurchaseCost] =>
            [ExpenseAccountRef] =>
            [COGSAccountRef] =>
            [AssetAccountRef] =>
            [PrefVendorRef] =>
            [AvgCost] =>
            [TrackQtyOnHand] =>
            [QtyOnHand] =>
            [QtyOnPurchaseOrder] =>
            [QtyOnSalesOrder] =>
            [ReorderPoint] =>
            [ManPartNum] =>
            [DepositToAccountRef] =>
            [SalesTaxCodeRef] =>
            [PurchaseTaxCodeRef] =>
            [InvStartDate] =>
            [BuildPoint] =>
            [PrintGroupedItems] =>
            [SpecialItem] =>
            [SpecialItemType] =>
            [ItemGroupDetail] =>
            [ItemAssemblyDetail] =>
            [AbatementRate] =>
            [ReverseChargeRate] =>
            [ServiceType] =>
            [ItemCategoryType] =>
            [ItemEx] =>
            [Id] =>
            [SyncToken] =>
            [MetaData] =>
            [CustomField] =>
            [AttachableRef] =>
            [domain] =>
            [status] =>
            [sparse] =>
        )

However, it always throw error for this object, on my research they are saying that we should not pass 0 or negative number for eg. unitprice or other fields but if that's the case the sdk is the one generated this object and I just provide the data I have.
Any idea regarding this?

A: "For Sandbox, category is not enabled by default. You will need to go to this link to enable it on Sandbox: https://sandbox.qbo.intuit.com/app/categorymigration
Try create a free-trial production company, everything should be working correctly"
As per Hao_Lu (Intuit Developer Group)
Click this link for more info.

A: That's because [UnitPrice] => is empty. You will need to pass in some positive value if that's the error message you are getting
Array
(
    [Name] => Item
    [FullyQualifiedName] => Item
    [Type] => Category
    [UnitPrice] => 1
)


text:
Q: Combinatorics - The Students and Grades Problem Suppose there are $20$ students in a classroom, $10$ males and 10 females. How many ways can a teacher distribute exactly $5$ As, $6$ Bs, $5$ Cs, $2$ Ds, and $2$ Fs to the students?
My Logic: $(20 C 5)(15 C 6)(9 C 5)(4 C 2)(2 C 2)$ seems the like the most intuitive answer but then this answer ignores the number of males and females in the class. Rather, if we treat the whole classroom as our sample, then we avoid any extra casework. I may be missing something here though so feel free to enlighten me.

A: Your result looks good.
Another way to obtain the same result is as follows:

*

*Any arrangement of the $20$ students can be interpreted as a possible assignment of grades: $20!$

*Now, cancel out the permutations among each group of students who get the same grade: $5!\cdot 6!\cdot 5!\cdot 2!\cdot 2!$
All together:
$$\frac{20!}{5!\cdot 6!\cdot 5!\cdot 2!\cdot 2!}$$


text:
Q: Change Navigation Controller item color How can I change the color of UINavigationController item?
I use Embed In UINavigationController => UIViewController and I have by default "< Back". I want to delete this "Back" text and change the color of item to white.
I did try the next:
override func viewDidLoad() {
    super.viewDidLoad()

    UINavigationBar.appearance().tintColor = UIColor.whiteColor()
}

inside of the UIViewController inside of which this item appears, but it doesn't help me

A: Use self.navigationController?.navigationBar.barTintColor to change the color
self.navigationController?.navigationBar.barTintColor = UIColor.whiteColor()

A: self.navigationController?.navigationBar.tintColor = UIColor.whiteColor()

A: You can change navigation bar color with following code.
self.navigationController.navigationBar.barTintColor = UIColor.greenColor()

And change Navigation bar text.
self.navigationController.navigationBar.titleTextAttributes = [UITextAttributeTextColor: UIColor.whiteColor()]

Edited
To change Text color of bar button
UIBarButtonItem.appearance().setTitleTextAttributes([UITextAttributeTextColor: UIColor.whiteColor()], forState: UIControlState.Normal)


text:
Q: Coderbyte Challenge 4: Letter Changes - Won't Upper Case I'm having trouble with Coderbyte's challenge
Using the JavaScript language, have the function LetterChanges(str) take the str parameter being passed and modify it using the following algorithm. Replace every letter in the string with the letter following it in the alphabet (ie. c becomes d, z becomes a). Then capitalize every vowel in this new string (a, e, i, o, u) and finally return this modified string.
Here's my code:
function LetterChanges(str) {
str = str.toLowerCase();
var al = "abcdefghijklmnopqrstuvwxyz";
var vo = "aeiou";
var newStr = "";
for (var i = 0;i < str.length;i++) {
    if (al.charAt(al.indexOf(str.charAt(i))) == "z") {
        newStr += "A";
    }
    else if (str.charAt(i) == " "){
        newStr += " ";
    }
    else {
        if (al.charAt(al.indexOf(str.charAt(i))+1) == vo.charAt(vo.indexOf(str.charAt(i)))) {
            newStr += vo.charAt(vo.indexOf(str.charAt(i))+1).toUpperCase();
        }
        else {
            newStr += al.charAt(al.indexOf(str.charAt(i))+1)
        }
    }
}
   console.log(newStr);
}
LetterChanges("Argument goes here")

This is returning the following into the console:
bshvnfou hpft ifsf
but what I need to be returned is:
bshvnfOU hpft Ifsf
I can't figure out why my .toUpperCase() isn't working.  Any help that you can provide is very much appreciated!

A: Your problem isn't that toUpperCase() isn't working, it's that your code never gets to that point.
Your
if (al.charAt(al.indexOf(str.charAt(i))+1) == vo.charAt(vo.indexOf(str.charAt(i))))
never passes, because of that +1. There's no need for that there, and if you remove it, uppercase vowels will appear. There are other problems with your code beyond that point, but I'll let you solve them as part of the challenge :-)

A: Wow, it's crazy looking at the code I wrote a year ago!  Reviewing this question, here's what I came up with (disclaimer: still getting comfortable with ES6):
function convertText (str) {
    const al = 'abcdefghijklmnopqrstuvwxyz';
    return str.toLowerCase().split('').map(letter => {
        if (letter.match(/\W/)) return letter;
        const index = al.indexOf(letter),
            newLetter = (al[index + 1] || al[0]);
        return newLetter.match(/[aeiou]/) ? newLetter.toUpperCase() : newLetter;
    }).join('');
}

And by using character codes:
function letterChanges (str) {
    const v = {d: 69, h: 73, n: 79, t: 85, z: 65};
    return str.toLowerCase().split('').map(l =>
        (l.match(/\W/) ? l : String.fromCharCode(v[l] || l.charCodeAt(0) + 1))
    ).join('');
}

There're probably better ways, but still a fun question!  Thanks again for your help, @MattDiamant

A: Here's my solution. It does not satisfy the z becomes a requirement but it passes Coderbyte's test as seen in the screenshot below.
function LetterChanges(str) {
    return str
        .replace(/[a-z]/gi, c => String.fromCharCode(c.charCodeAt(0) + 1))
        .replace(/[aeiou]/gi, c => c.toUpperCase());
}

// keep this function call here
LetterChanges(readline());

Letter Changes Javascript Solution

A: To account for the non-[a-z] characters can toss this in the if statement and it will account for white space and [^a-z]:
if (letter.match(/[^a-z]/)) return letter;


text:
Q: Why those beads in my Tikz picture overlap each other?
I use Tikz to create this line of beads but this strange things happened in my picture but I really specify the position that can not overlap each other.
    % Rusting Iron
% Author: Jason Waskiewicz
% A "jazzy" picture of the stages of rust (presented for a high school level).
% Iron is red, oxygen is blue and electrons are black. At the left you see
% iron atoms with two oxygen molecules, then the electrons go to the oxygen molecules
% leaving oxygen ions and iron ions which then disolve.
\documentclass[tikz]{standalone}

\usetikzlibrary{positioning}
\usepackage{lmodern}
\newcommand{\tikzmark}[2]{\tikz[remember picture, baseline] \node[inner sep=0pt, outer sep=0pt, anchor=base] (#1) {#2};}

\begin{document}

\begin{tikzpicture}[
        >=stealth,
        %show background rectangle,
        iron/.style={shade, ball color=red, opacity=1.9},
        electron/.style={shade, ball color=green},
        oxygen/.style={shade, ball color=blue},
        B/.style={ball color=yellow},
        A/.style={ball color=violet},
    ]

\foreach \x in {  -155.000000,   -152.500000,    -150.000000,    -147.500000,    -145.000000,    -142.500000,    -140.000000,    -137.500000,    -135.000000,    -132.500000,    -130.000000,    -127.500000,    -125.000000,    -122.500000,    -120.000000,    -117.500000,    -115.000000,    -112.500000,    -110.000000,    -107.500000,    -105.000000,    -102.500000,    -100.000000,    -97.500000,     -95.000000,     -92.500000,     -90.000000,     -87.500000,     -85.000000,     -82.500000,     -80.000000,     -77.500000,     -75.000000,     -72.500000,     -70.000000,     -67.500000,     -65.000000,     -62.500000,     -60.000000,     -57.500000,     -55.000000,     -52.500000,     -50.000000,     -47.500000,     -45.000000,     -42.500000,     -40.000000,     -37.500000,     -35.000000,     -32.500000,     -30.000000,     -27.500000,     -25.000000,     -22.500000,     -20.000000,     -17.500000,     -15.000000,     -12.500000,     -10.000000,     -7.500000,      -5.000000,      -2.500000,      0.000000,   2.500000,   5.000000,   7.500000,   10.000000,      12.500000,      15.000000,      17.500000,      20.000000,      22.500000,      25.000000,      27.500000,      30.000000,      32.500000,      35.000000,      37.500000,      40.000000,      42.500000,      45.000000,      47.500000,      50.000000,      52.500000,      55.000000,      57.500000,      60.000000,      62.500000,      65.000000,      67.500000,      70.000000,      72.500000,      75.000000,      77.500000,      80.000000,      82.500000,      85.000000,      87.500000,      90.000000,      92.500000,      95.000000,      97.500000,      100.000000,     102.500000,     105.000000,     107.500000,     110.000000,     112.500000,     115.000000,     117.500000,     120.000000,     122.500000,     125.000000,     127.500000,     130.000000,     132.500000,     135.000000,     137.500000,     140.000000,     142.500000,     145.000000,     147.500000,     150.000000,     152.500000,    }
\draw [oxygen] (\x,-40.0,0) circle (3.5);

\end{tikzpicture}
\end{document}

I think maybe it is because the radius of the circle so change the radius from 3.5 to 1 but the problem still exists.

so why this happens?
I do generate those position by C program so no number will be wrong I think.
Thank you!

A: Or simply:
\foreach \x in {-155.0,-152.5,...,152.5}
\draw [oxygen] (\x,-40.0,0) circle (3.5);

A: Use the full power of \foreach, by replacing your loop with the following:
\foreach \x in {0,...,123}
\draw [oxygen] (-155+\x*2.5,-40.0,0) circle (3.5);


text:
Q: mysql create multiple select to put max in all rows This is my table with sample data:
Table:PersTrans
+------------+-------------+------+-----+------------+-------+
| Field      | Type        | Null | Key | Default    | Extra |
+------------+-------------+------+-----+------------+-------+
| PersTrID   | char(10)    | NO   | PRI |            |       |
| PersTrSeq  | int(11)     | NO   | PRI | 0          |       |
| PersTrDate | date        | YES  |     | 1001-01-01 |       |
| PersTrPaid | float(9,2)  | YES  |     | 0.00       |       |
+------------+-------------+------+-----+------------+-------+

mysql> select * from PersTrans;
+------------+-----------+-----------+-------------+
| PersTrID   | PersTrSeq | PersTrDate | PersTrPaid |
+------------+-----------+-----------+-------------+
| MOCK       |         1 | 2015-10-10 |     400.00 |
| MOCK       |         2 | 2017-11-07 |      10.00 |
| NAGA       |         1 | 2015-11-11 |     500.00 |
| NASSA      |         1 | 2015-12-16 |     800.00 |
+------------+-----------+-----------+-------------+

I'd like to pick up the maximum PersTrSeq, and attach it to all the records that have the same PersTrId.   What I want:
+------------+-----------+------------+------------+----------------+
| PersTrID   | PersTrSeq | PersTrDate | PersTrPaid | max(PersTrSeq) |
+------------+-----------+-----------+------------+-----------------+
| MOCK       |         1 | 2015-10-10 |     400.00 |              2 |
| MOCK       |         2 | 2017-11-07 |      10.00 |              2 |
| NAGA       |         1 | 2015-11-11 |     500.00 |              1 |
| NASSA      |         1 | 2015-12-16 |     800.00 |              1 |
+------------+-----------+-----------+------------+-----------------+

These two attempts didn't work.  I've looked for other suggestions but haven't found anything helpful.
mysql> SELECT *, max(PersTrSeq) from PersTrans where PersTransId = 'Mock' group by PersTrSeq;
+------------+-----------+------------+------------+----------------+
| PersTrID   | PersTrSeq | PersTrDate | PersTrPaid | max(PersTrSeq) |
+------------+-----------+-----------+------------+-----------------+
| MOCk       |         1 | 2015-10-10 |     400.00 |              1 |
| MOCK       |         2 | 2017-11-07 |      10.00 |              2 |
+------------+-----------+-----------+------------+-----------------+

mysql> SELECT *, max(PersTrSeq) as maxseq from PersTrans group by PersTrId;
+------------+-----------+------------+------------+--------+
| PersTrID   | PersTrSeq | PersTrDate | PersTrPaid | maxseq |
+------------+------------+-----------+------------+--------+
| MOCK       |         1 | 2015-10-10 |     400.00 |      2 |
| NAGA       |         1 | 2015-11-11 |     500.00 |      1 |
| NASSA      |         1 | 2015-12-16 |     800.00 |      1 |
+------------+-----------+-----------+------------+---------+

Can anyone offer a single query that will get the result I'm looking for?

A: Following query will work:
select *,
       (select max(PersTrSeq) from PersTrans p2
        where p2.PersTrId = p1.PersTrId
       ) as maxSeq
from PersTrans p1;

A: If I understand what you want, you want the same number of records as the actual data, substituting the max(PersTrSeq) for all rows with a certain PersTrID.
SELECT
    `PerTrID`,
    (SELECT max(`PersTrSeq`) FROM `PersTrans` b WHERE b.`PersTrID = a.`PersTrID`) as `PersTrSeq`,
    `PersTrDate`,
    `PersTrPaid`,
from `PersTrans` a


text:
Q: ¿Cómo ingresar una fecha en una clase? intento ingresar una fecha pero me dice que no puedo convertir un string a Date.
per.setFecha_nacimiento("20-07-1998");     <--- cual es el formato indicado?

gracias de antemano.

A: Si tu variable fecha_nacimiento es tipo Date entonces tienes que mandarle un objeto tipo Date y no un String. Utiliza:
SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy");
String dateInString = "20-07-1998";
try {

            Date date = formatter.parse(dateInString);
            per.setFecha_nacimiento(date);

        } catch (ParseException e) {
            e.printStackTrace();
        }


text:
Q: AngularJS 2 Typescript interface I have a service for handling users operations and an interface for the user object.
user.service.ts
import {Injectable} from 'angular2/core';

export interface User {
  name: string;
  email?: string;
  picture?: string;
}

@Injectable()
export class UserService {
  me: User;

  constructor() {

  }

  setUser(user: User) {
    this.me = user;
  }
}

In my login component I try to set the user with the profile returned from the login service but I get this error:

Property 'firstName' does not exist on type '{}'.

login.component.ts
import {Component} from 'angular2/core';

import {User, UserService} from './services/user.service';
import {LinkedinService} from './services/linkedin.service';

declare const IN: any;

console.log('`Login` component loaded asynchronously');

@Component({
  selector: 'Login',
  providers: [
    UserService,
    LinkedinService
  ],
  template: require('./login.html')
})
export class LoginComponent {
  me: User;

  constructor(public linkedinService: LinkedinService, public userService: UserService) {
    this.me = userService.me;
  }

  ngOnInit() {
    console.log('hello `Login` component');
  }

  login() {
    this.linkedinService.login()
      .then(() => this.linkedinService.getMe()
      .then(profile => this.userService.setUser({ name: profile.firstName })));
  }
}

linkedin.service.ts
import {Injectable} from 'angular2/core';

declare const IN: any;

@Injectable()
export class LinkedinService {
  constructor() {
    IN.init({
      api_key: 'xxxxxxxxxxx',
      authorize: true
    });
  }

  login() {
    return new Promise((resolve, reject) => {
      IN.User.authorize(() => resolve());
    });
  }

  getMe() {
    return new Promise((resolve, reject) => {
      IN.API.Profile('me').result((profile) => resolve(profile.values[0]));
    });
  }
}

I'm trying to import the User interface from UserService and use inside the LoginComponent but I don't know what I'm doing wrong. Any idea? I am not sure if I have to use the User interface inside the LoginComponent, is that right?

A: Narrow in on the code :
  .then(() => this.linkedinService.getMe())
  .then(profile => this.userService.setUser({ name: profile.firstName })));

The type of profile is driven by the response of this.linkedinService.getMe(). Seems like it is something like Promise<{}>. It does not have the member firstName. Hence the error:
Property 'firstName' does not exist on type '{}'.

Fix
Check to the code / signatures of linkedinService. This has nothing to do with the user.service.ts file that the question contains
Update
Focus in on the code:
 getMe() {
    return new Promise((resolve, reject) => {
      IN.API.Profile('me').result((profile) => resolve(profile.values[0]));
    });
  }

The value returned is driven by what is being passed to resolve. So make sure profile.values[0] has the right type. Alternatively provide the hint to the compiler:
 getMe() {
    return new Promise<{firstName:string}>((resolve, reject) => {
      IN.API.Profile('me').result((profile) => resolve(profile.values[0]));
    });
  }


text:
Q: Eclipse opening files with full path when debugging PHP I have a local PHP server that has xdebug installed alongside eclipse with Xdebug JIT setup.  Everything is working great except one significantly annoying problem.
The problem is that every time I hit a breakpoint in my PHP script, Eclipse opens the php file with the full path rather than the workspace-relative one.  This creates two files that are open, which isn't a problem except setting breakpoints within the absolute file don't properly display in the code tab (they show up in the breakpoint list though), and setting or removing breakpoints between the different files are path specific - so you can't interact with breakpoints from the other file representation.  Also, jumping to a new file opens in the same tab.  I would like eclipse to use the tabs I already have open, which i think would happen if it was not using absolute paths to open the files.
I've tried setting up path maps in the PHP server configuration, but they didn't seem to have any effect.  I'm open to any suggestions to try.
Thanks!

A: You need to set up path mappings to map files of your project to the server running php with x-debug
http://www.eclipse.org/pdt/help/html/path_mapping.htm


text:
Q: Clearing the graphics of a transparent panel C# I have a WebBrowser control with a transparent panel over the top of it, what I am trying to do is draw a rectangle on the transparent panel around the element in the page that the mouse is hovering over.
So far I have everything working except the panel is not being cleared before drawing the next rectangle so I end up with rectangles everywhere.
heres the code Im using.
paneGraphics = drawingPane.CreateGraphics();

Rectangle inspectorRectangle;

inspectorRectangle = controller.inspectElement();

paneGraphics.DrawRectangle(new Pen(Color.Blue, 1), inspectorRectangle);

drawingPane.Invalidate();

I've tried using drawingPane.clear() but that just turns the screen white.

A: Take a look at the OpenPandora project's code
public class TransparentPanel : Panel
{
    Timer Wriggler = new Timer();

    public TransparentPanel()
    {
        Wriggler.Tick += new EventHandler(TickHandler);
        this.Wriggler.Interval = 500;
        this.Wriggler.Enabled = true;
    }

    protected void TickHandler(object sender, EventArgs e)
    {
        this.InvalidateEx();
    }

    protected override CreateParams CreateParams
    {
        get
        {
            CreateParams cp = base.CreateParams;

            cp.ExStyle |= 0x00000020; //WS_EX_TRANSPARENT

            return cp;
        }
    }

    protected void InvalidateEx()
    {
        if (Parent == null)
        {
            return;
        }

        Rectangle rc = new Rectangle(this.Location, this.Size);

        Parent.Invalidate(rc, true);
    }

    protected override void OnPaintBackground(PaintEventArgs pevent)
    {
        // Do not allow the background to be painted
    }
}

A: Did you try:
graphics.Clear(Color.Transparent);


text:
Q: Python in-place complement operator Python has the usual bitwise operators, like ~, &, |, etc. and in-place operators like +=, &=, etc. to simplify expressions like:
a = a & 34234
a = a + 577

To:
a &= 34234
a += 577

Despite the complement operator ~ being an unary function, and not following the same structure because it isn't used with two values (like a and 34234), can expressions like these be simplified with another type of operator?
a = ~a # not bad at all

# Still easy to code but seems redundant
self.container.longVariableName.longName = ~self.container.longVariableName.longName

A: It's excruciatingly obscure, but:
self.container.longVariableName.longName ^= -1

does the job, so long as the values you're dealing with are integers.  "Are integers" is required so that there's an exploitable mathematical relation between the ~ and ^ operators.
Why it works:

*

*Bitwise complement is the same as xor'ing with an infinite string of 1 bits.

*Python maintains the illusion that integers use an infinite-width 2's-complement representation, so that -1 "is" an infinite string of 1 bits.

A: If you are only concerned about doing this for attributes of object instances, you could write a method like:
def c(obj, atr):
    setattr(obj,atr,~getattr(obj,atr))

and then use it like:
c(self.container.longVariableName, 'longName')

I think that @TimPeters answer is much better, but thought I'd provide this in case it is useful to anyone in the future who needs to do this with non-integers are is happy to only work with instant attributes


text:
Q: jquery mobile page fluctuating on ajax reponce load I am working with a mobile application in which
first page has
Html

121212

123233

232323

4323423

when user click on "li" then he/she entered on next page which will retrieve data related to selected "li" via Ajax.
this is almost going good..
But when Ajax response come page is fluctuating 2 times.
Means one time page loading, next time page totally white and then again showing page with Ajax response.
Why ???
J query
 $("clickOnLi").click(function(){
        var id= $(this).val(); //get the selected li value
        $('.loadingGif').css({ 'display':'block' });
        $("#ulShowContent").html(''); // to remove old inner HTML to show new result html
        var dataString = 'selectedid='+id;
        $.ajax({
            type: "POST",
            url: remoteUrl+"handler.php",
            data : dataString,
            cache: true,
            success: function(response) {
                if(response){
                    $('.loadingGif').css({ 'display':'none' });
                    $("#ulShowContent").html(response);
                }
                }
        });
    })

**and the result will show in this html**

            data 1

            data 2

A: You will need to change how you deal a page change and AJAX call.
What I have understand from your question, after click on LI element, page change is initialized and AJAX call is sent to a PHP server.
You will need to change this logic. Page fluctuations are cause by AJAX call which is executed during the transition from one page to an another.
This can be fixed like this:

*

*On a first page remove HREF attribute from a list element

*Add a click event to every list element

*AJAX call should be executed on click event, at a same time show your custom loader (or use a default one)

*When server side data is retrieved you need to store it so it can be accessed from an another page. Here you will find my other ANSWER where you can find various methods of storing data during page transitions, or find it HERE, just search for a chapter called: Data/Parameters manipulation between page transitions (your best bet is a localstorage).

*Initialize a page change with changePage function

*During a pagebeforeshow event (page is not yet displayed) append new data to the new container

*When second page is finally shown everything will be there and


text:
Q: How to request an access token with OAuth2.0? I'm still learning on how to use REST API. Right now I want to integrate a FatSecret Rest API for my mobile apps development. I'm currently stuck at step 2 here.
This is my current code which I referred from HERE (under CLIENT CREDENTIALS GRANT TYPE section):
import requests, json
import urllib3

urllib3.disable_warnings()

token_url = "https://oauth.fatsecret.com/connect/token"

test_api_url = "https://platform.fatsecret.com/rest/server.api"

#client (application) credentials
client_id = "<CLIENT_ID>"
client_secret = "<CLIENT_SECRET>"

#step A, B - single call with client credentials as the basic auth header - will return access_token
data = {'grant_type': 'client_credentials',
        'scope': 'basic'}

access_token_response = requests.post(token_url, data=data, verify=False, allow_redirects=False, auth=(client_id, client_secret))

print(access_token_response.headers)
print(access_token_response.text)
print(access_token_response.status_code)

tokens = json.loads(access_token_response.text)

print("access token: " + tokens['access_token'])

#step B - with the returned access_token we can make as many calls as we want

api_call_headers = {'Authorization': 'Bearer ' + tokens['access_token']}
api_call_response = requests.get(test_api_url, headers=api_call_headers, verify=False)

print(api_call_response.text)

But I got these errors:
{'Date': 'Wed, 03 Nov 2021 14:13:17 GMT', 'Content-Type': 'application/json; charset=UTF-8', 'Transfer-Encoding': 'chunked', 'Connection': 'keep-alive', 'Set-Cookie': 'AWSALB=ulzLdAF+yzvlb1zyySg3WOSoBgvDZVL924yxgKUcgcXfDccOCZVe+toy32y9oHStYz3ljYQBgSuXCZvC5bKSALd5nRVnsmb/kOipLY7EcSG5qUjcDUkkfkRxbtjj; Expires=Wed, 10 Nov 2021 14:13:16 GMT; Path=/, AWSALBCORS=ulzLdAF+yzvlb1zyySg3WOSoBgvDZVL924yxgKUcgcXfDccOCZVe+toy32y9oHStYz3ljYQBgSuXCZvC5bKSALd5nRVnsmb/kOipLY7EcSG5qUjcDUkkfkRxbtjj; Expires=Wed, 10 Nov 2021 14:13:16 GMT; Path=/; SameSite=None; Secure', 'Cache-Control': 'no-store, no-cache, max-age=0', 'Pragma': 'no-cache', 'Server': 'Kestrel', 'X-Powered-By': 'ASP.NET'}
{"error":"invalid_client"}
400
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-24-9611470e9c26> in <module>()
     24 tokens = json.loads(access_token_response.text)
     25
---> 26 print("access token: " + tokens['access_token'])
     27
     28 #step B - with the returned access_token we can make as many calls as we want

KeyError: 'access_token'

I've already tried some other solutions on this platform but most of them would return this error like {"error":"invalid_request"} or {"error":"invalid_client"}.
I'm not sure what went wrong? Is it the OAuth2.0? Should I use other oauth? Can someone kindly help me how to get through this. Thank you in advance.

A: Two things:

*

*The error (invalid_client) sounds like the client_id is not recognized by the service. I would suggest trying curl (see the example they listed) to make sure the service provides a good response to your credentials before trying to get it to work in your script.

*Without seeing the variable "tokens", I cannot tell if the JSON conversion was successful or not. I would check the type of tokens to see if the JSON was successfully converted and if that key exists.


text:
Q: Loop two arrays in javascript I have a issue with two loops.
yellow=[
         {
          beta: {
               id: '25',
               name: 'tata'
           }
         }
        ]
home=[
       {
          house : [
          {
             title: 'alpha',
             name : 'Vik',
          },
          {
             title: 'alpha1',
             name : 'Vik1',
          },
        ]
      }]

I want this :
villa=[
        {
            beta:{
            id: 'toto', name: 'tata'
            },
          title: 'alpha',
          name : 'Vik'
        },
        {
            beta:{
            id: 'toto', name: 'tata'
            },
          title: 'alpha1',
          name : 'Vik1'
        }
      }
     ]

Sorry I have edit the array
I tried with a look with a loop with home.push(yellow) but the result is wrong.
Can you help me ?
Thanks

A: Try to do this

Assume the yellow array has only 1 item

const yellow=[{beta: {id: '25', name: 'tata'}}];
const home=[{title: 'alpha', name : 'Vik'},
 {'alpha1', name : 'Vik1'} ];

// Assume the yellow array has only 1 item
const result = home.map((item)=>{
  return {...item,...yellow[0]}
});

To Loop two array's and Assume the two arrays have the same length

const yellow=[{beta: {id: '25', name: 'tata'}}];
const home=[{title: 'alpha', name : 'Vik'},
 {'alpha1', name : 'Vik1'} ];

// Assume the yellow array has only 1 item
const result = home.map((item,index)=>{
  return {...item,...yellow[index]}
});

A: Well, if your home value was correct, like:
yellow = [{beta: {id: '25', name: 'tata'}}];
home = [{title: 'alpha', name : 'Vik'},{title: 'alpha1', name : 'Vik1'}];

Then I believe what you're looking for would look like this:
home.reduce((res, h) => {
    yellow.forEach(y => {
        h.beta = y.beta;
        res.push(h)
    });
    return res;
}, []);


text:
Q: How to rotate a CAShapeLayer arc around a circle? I have the two CAShapeLayers forming the following display:

They are created with this piece of code:
CALayer *layer = [loadingView layer];
CAShapeLayer *circle = [CAShapeLayer layer];
[circle setPath:[[UIBezierPath bezierPathWithOvalInRect:CGRectMake(5, 5, loadingView.bounds.size.width - 10, loadingView.bounds.size.height - 10)] CGPath]];
[circle setStrokeColor:[UIColorFromRGB(0xffffff, .15) CGColor]];
[circle setLineWidth:5];
[circle setFillColor:[[UIColor clearColor] CGColor]];
[layer addSublayer:circle];

CAShapeLayer *arc = [CAShapeLayer layer];
[arc setPath:[[UIBezierPath bezierPathWithArcCenter:CGPointMake(27, 27) radius:22 startAngle:1.25*M_PI endAngle:1.75*M_PI clockwise:YES] CGPath]];
[arc setStrokeColor:[UIColorFromRGB(0xffffff, .8) CGColor]];
[arc setLineWidth:5];
[arc setFillColor:[[UIColor clearColor] CGColor]];
[layer addSublayer:arc];

I'd like for the smaller, opaque arc to retain its size and spin around the circle indefinitely. I've tried applying a number of transform.rotation animations that I found on other answers, however the arc ends up spinning into unpredictable directions.
I've also tried raising strokeStart and strokeEnd of the arc at the same rate, which gets the effect I want at first but is unable to proceed cyclically due to the nature of those properties.
That being so, how to perform this effect?

A: By default, the origin of the coordinate system in a shape layer is at the point (0,0), and its bounds have 0×0 dimensions; when you give it a path, neither of those attributes change automatically. The arc you're giving it is centered at (27, 27), so when you rotate the layer the drawn arc is rotating around the layer's actual center, which is a point 27 points above and to the left of the center of the arc.
Your best option is to change the way you're creating the arc shape and positioning its layer. Instead of creating the Bézier path with a center of (27, 27), give it a center of (0, 0)—i.e. the origin of the layer—and set the arc layer's position to (27, 27) within its parent layer.

A: Your best bet here would be to rotate your entire circle. Rotate loadingView around its center and you'll get the effect you want. You'll gain the added benefit of being able to even modify the stroke length very easily without messing up your rotation.


text:
Q: Text spilling out of div - overflow: auto not working if you go here and click on a thumbnail, and then on one of the tags, you'll see my problem. For the tags that have too much text and overfow, it's not putting in a scrollbar. I can't put a fixed width because the first part, the title, varies from one submission to the other.
Here's the css for the part that's supposed to put in the scroll when needed.
#scroll-pane{
left: -3px;
position: relative;
width: 100%;
overflow: auto;
font-family:helvetica;
font-size:11px;
color:#fff;
}

Any ideas? I'm sure this is an easy question for you guys.
PeeHaa:
(function($) {
    $('#tag_info1').each(function() {
        var container = $(this);
        var total_height = container.height();
        var content_height = parseInt($('span.tag_title', container).outerHeight(true), 10) + parseInt($('span.tag_submission', container).outerHeight(true), 10);
        var p_height = 0;
        p_height+=parseInt($('span.tag_submission_text', container).css('padding-top'), 10);
        p_height+=parseInt($('span.tag_submission_text', container).css('padding-bottom'), 10);
        p_height+=parseInt($('span.tag_submission_text', container).css('margin-top'), 10);
        p_height+=parseInt($('span.tag_submission_text', container).css('margin-bottom'), 10);
        p_height+=parseInt($('span.tag_submission_text', container).css('borderTopWidth'), 10);
        p_height+=parseInt($('span.tag_submission_text', container).css('borderBottomWidth'), 10);

        $('span.tag_submission_text', this).height(total_height-content_height-p_height);
    });
})(jQuery);

Tried to get it to work with mine, but to no avail :(

A: The overflow: auto does work. It just isn't there.
You've added the overflow: auto; to the paragraph.
The paragraph doesn't know what the height is. If you add it to the container it will work.
Or give a height to the paragraph.
I've setup a demo which shows how to calculate the remaining height. To be able to set the correct height on your paragraph.

A: I've no problem on Firefox.
But when you use overflow: auto; You must use it on the container, for example a div.
EDIT:
Ok, I understand your problem.
Currently you are using height: 180px; on the container. If you try something like min-height: 100px; and overflow: auto; on the text container, you can fix the size of the text container.
So your text container will have the same height but the container is extendable if the title is bigger.
I don't know if it's clear but if you want I can try to re-explain.

A: I had a similar problem with a div with height as well as max-height specified - it just wouldn't put a scroll bar even though overflow: auto was specified. It worked after I specified min-height in addition to the height and max-height values.


text:
Q: How to add text in multiple lines in message field of UIAlertView     The AlertView should look like this.

 AlertView Message:

     Please provide one of the following parameters to find the doctors.
                     Speciality
                     Location
                     Insurance

A: Use \n for a line break.
... message:@"1st line of message\n2nd line of message\n\n\n5th line of message" ...

A: The UIAlertView can be cusomised :
Some info here
Customizing UIAlertView
and here
http://www.iphonedevsdk.com/forum/iphone-sdk-development/1704-uitextfield-inside-uialertview.html
However, I think what you want is to build a custom view, or (more simply) use an UIActionSheet - that's the device designed for the purpose!


text:
Q: Как на wordpress woocomerce добавить описание в товар? Всем привет! Есть у меня проект на wordpress woocomerce. По умолчанию описание выводится только на полноценной странице с товаром. А я хочу добавить в выводимый товар описание (состав) среди перечня товаров:

не подскажите, как это можно сделать?
Желательно, чтобы была возможность редактирования из админки.
Может в woocomerce уже есть для этого готовые решения?

A: Можно попробовать выводить краткое описание под товаром, надо добавить код в functions.php
    add_action( 'woocommerce_after_shop_loop_item_title', 'my_add_short_description', 9 );
function my_add_short_description() {
   echo '' . the_excerpt() . '
';
}

Или вот еще попробуйте вывод краткого описания товара
<?php echo apply_filters( 'woocommerce_short_description', $post->post_excerpt ) ?>


text:
Q: Access Web interface of docker ngrok When I used ngrok.exe , I can use this command for setting webhook
fetch("http://127.0.0.1:4040/api/tunnels/) to get this page
I switch to ngrok docker
So, I run ngrok docker by using
docker run --net=host -it -p 127.0.0.1:4040:4040 -e NGROK_AUTHTOKEN=29yEfUG2cgRDobuv15dKkY65ho2_7BRb72Bog882rfDZTx4ZE ngrok/ngrok:latest http 7001

output after run
but I cannot access this page What should I do for setting docker ? pls help

A: I found the answer. change --net = bridge and map 4040:4040. Use url localhost:4040/api/tunnel to access data


text:
Q: Object created in lambda expression not stored With below code snippet,
String[][] users = {user1, user2, user3, user4, user5};

Queue<Form> formList = new ArrayBlockingQueue<>(5);

Executor executor = Executors.newCachedThreadPool();
executor.execute(() -> {
    System.out.println(Thread.currentThread().getName());
    for(String[] user: users) {
        Form f = new Form(user[0], user[1], user[2], user[3], user[4]);
        formList.add(f);
    }
});
System.out.println(formList);

I want to stored all form created inside lambda in formList (queue). But it gives me empty queue at the end. Any suggestion

A: You're asking the executor to execute a task on another thread. This may take time to spin up the necessary thread(s) and perform the work, and in the mean time, your main thread has already printed the current content of formList (i.e. nothing).
To be able to print the result of your tasks, you need to wait until the tasks are completed, for example by shutting down the ExecutorService and awaiting termination, or by using ExecutorService.submit instead of Executor.execute, and collect the returned futures and use get on all those futures to await their completion. There also a lot of other options, like using a CompletionService, or CompletableFuture, etc.


text:
Q: FullSimplify applied to equations: not simplifying though apparently it should I tried to Fullsimplify
$$ e^x(1-x)=0$$
to the equation
$$1-x=0$$
However the command
 FullSimplify[E^x (1 - x) == 0]

just gives
$$e^x x = e^x $$
Probably this does not matter for the specific equation. But in general it can cause a great loss of time.
Can anyone help?

A: FullSimplify[E^x (1 - x) == 0, Element[x, Reals]]

x == 1

And, strangely enough,
FullSimplify[E^x (1 - x) == 0, whattheheck]

x == 1

Also
Assuming[Element[x, Reals], FullSimplify[E^x (1 - x) == 0]]

x == 1

Reduce[E^x (1 - x) == 0, x]

x == 1

FullSimplify[E^x (1 - x) == 0, TransformationFunctions -> {Automatic, Reduce}]

x == 1

A: Try:
Simplify[E^x (1 - x) == 0, E^x != 0]

This tells Mathematica that it can assume that E^x is not zero.


text:
Q: Unable to turn off DirSync I went through the Hybrid Setup configuration, unaware that this would enable DirSync. I now want to disable AD synchronization again.
When I go to the Azure AD Admin Center and disable directory synchronization for our domain, the switch will go back to Activated right after it was deactivated.
I also tried disabling DirSync through PowerShell:
Set-MsolDirSyncEnabled -EnableDirSync $false -Verbose

This only results in the unhelpful error message:

Set-MsolDirSyncEnabled : You cannot turn off Active Directory synchronization.

A: After DirSync has been enabled for a domain, it can take up to 24 hours until you're able to disable it again.

*

*I can't disable DirSync "You cannot turn off Active Directory Synchronization"

*Unable to deactivate DirSync
In our specific case, we were able to disable it after approximately 12 hours.


text:
Q: Prove that line segments are parallel. Prove using slope of lines that line segment joining the midpoint of $\overline { AB}$ and $\overline{AC}$ in $\Delta ABC$ is parallel to $\overline {BC.}$
Need to prove using slope of lines means I can prove slope of both the lines are equal, So they are parallel.
But here i don't know how to assume coordinates of all the points.

A: By locating your coordinate axes with origin at B and the x-axis pointing along BC, you can assume that B has coordinates (0,0) and C had coordinates (c,0) for some c and A has coordinates (a,h) for some a and h.
Then the midpoint of BA is (a/2, h/2) and the midpoint of CA is ( (a+c)/2, h/2 ). The line joining these two points then has slope zero, which is the same as the slope of BC.


text:
Q: IIS URL Rewrite - Reordering Parameters I have a requirement to rewrite URL's from an older version of my site to the format of the new version:
Old:
/param1/param2/param3/param4/param5
New:
/param3/param4/param5?a=param1&b=param2
The requirements for pattern matching are that param2 should be only numbers and that params 3-5 are optional.
I came up with this rule:
<match url="([^/]+)/([0-9]+)/?([^/]+)/?([^/]+)/?([^/]+)/?([^/]+)/" />
<action type="Redirect" url="{R:3}/{R:4}/{R:4}?a={R:1}&b={R:2}" />

Which works OK if all params are present but if they aren't it breaks it. Examples:
/hello/world = ?a=hello&b=world
/hello/world/foo = foo?a=hello&b=world
/hello/world/foo/bar = foo/bar?a=hello&b=world
/hello/world/foo/bar/test = foo/bar/test?a=hello&b=world

Is this possible with URL Rewrite?


text:
Q: Is there a way to build a dynamic navigation/menu based on registered routes in Angular 2? I'm currently struggling to find a way to build a dynamic navigation based on routes registered in the application.
As far as I see there is no simple way to get a list of all routes using Router or RouteRegistry classes.
But, there is a private _rules property inside of RouteRegistry class, but unfortunately with no getter for it.
Is there any specific reason why I can't access this parameter outside the RouteRegistry?
Any help would be appreciated.

A: You can store the routes in an array outside of the component so you can pass it to @RouteConfig(...) and also load into your component and analyze it to generate the menu.
The router is currently reworked therefore things that currently aren't that easy might become better soon.


text:
Q: Android: Error when creating build **I got an error when creating build and error. I had already done to cross check is google play installed or not.  **
Error:Execution failed for task ':app:processDebugGoogleServices'.
> No matching client found for package name 'com.xyz'

This is my project gradle file source code
buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.1.3'

        // Add this line
        classpath 'com.google.gms:google-services:3.0.0'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        jcenter()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

This is my build.gradle(Module.App) source code
apply plugin: 'com.android.application'

android {
    compileSdkVersion 23
    buildToolsVersion "23.0.3"

    defaultConfig {
        applicationId "com.xyz"
        minSdkVersion 15
        targetSdkVersion 23
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:23.4.0'
    compile 'com.android.support:design:23.4.0'
    compile 'com.android.support:support-v4:23.4.0'
    compile 'com.google.firebase:firebase-messaging:9.4.0'
    compile 'com.google.android.gms:play-services:9.4.0'
}
apply plugin: 'com.google.gms.google-services'


text:
Q: Oledb Datareader can't read excel cell data of 656 characters i have been trying to read excel using oledb data reader,everything  is ok but i have problem reading one excel column content which has cell data of more than 600 characters. oledb datareader gives empty string after read operation.but when i tried to shorten that cell data it successfully read the data. Any fix for this problem?
Thanks.


text:
Q: SequelizeConnectionError: The server does not support SSL connections I am trying to connect my project with PostgreSQL but show this error. Please help me
I have installed Postgres.app and for GUI PgAdmin.
Unhandled rejection SequelizeConnectionError: The server does not support SSL connections
        at /Users/inamur/Documents/Project/project-api/node_modules/sequelize/lib/dialects/postgres/connection-manager.js:186:20
        at Connection.connectingErrorHandler (/Users/inamur/Documents/Project/project-api/node_modules/pg/lib/client.js:203:14)
        at Connection.emit (events.js:223:5)
        at Connection.EventEmitter.emit (domain.js:475:20)
        at Socket.<anonymous> (/Users/inamur/Documents/Project/project-api/node_modules/pg/lib/connection.js:90:21)
        at Object.onceWrapper (events.js:313:26)
        at Socket.emit (events.js:223:5)
        at Socket.EventEmitter.emit (domain.js:475:20)
        at addChunk (_stream_readable.js:309:12)
        at readableAddChunk (_stream_readable.js:290:11)
        at Socket.Readable.push (_stream_readable.js:224:10)
        at TCP.onStreamRead (internal/stream_base_commons.js:181:23)

This is my .env file
JWT_SECRET='UserNews'
DB_LINK='postgres://root:root@localhost:5432/SCROLL001?ssl=true'

This is connection file.
const sequelize = new Sequelize(process.env.DB_LINK, {
  dialect: 'postgres',
  protocol: 'postgres',
  dialectOptions: {
    ssl: {
      require: 'true'
    }
  }
});

A: You haven`t used dialectOptions correctly.
Just make the following changes:
const sequelize = new Sequelize(process.env.DB_LINK, {
  dialect: 'postgres',
  protocol: 'postgres',
  dialectOptions: {
    ssl: true,
    native:true
  }
});

native flag for using a native library or not.In the case of 'pg' -- set this to true will allow SSL support, default value is false. reference link

A: It is recommended to use SSL for connections in production applications. You can continue to use an SSL connection using while circumventing it locally using:
const sequelize = new Sequelize(process.env.DB_LINK, {
  dialect: 'postgres',
  protocol: 'postgres',
  ssl: process.env.DB_ENABLE_SSL,
  dialectOptions: {
    ssl: process.env.DB_ENABLE_SSL && {
      require: true
    }
  }
});

A: I have solved the issue.
const sequelize = new Sequelize(process.env.DB_LINK, {
  dialect: 'postgres',
  protocol: 'postgres',
  dialectOptions: {}, //removed ssl
});

Change the DB Link
DB_LINK='postgres://root:root@localhost:5432/SCROLL001'


text:
Q: Similarity Amongst Recipes Using Ingredients and Reviews/Descriptions I'm still toying with things and just learning this, so please forgive any incorrect terminology.
My toy data set is a collection of recipes with a fairly significant overlap in ingredients. I'm using these as my features, and using Pearson squared distance as described in Programming Collective Intelligence to determine the correlation between recipes. I'm not looking to "train" anything; I currently would just like to compare the recipes in my corpus and find $X$ nearest and $Y$ farthest neighbors.
I thought it'd be fun to expand this, and include people's reviews/comments on the recipes as part of the distance calculation, leading to a closer association between recipes that were both described as "sweet" or "tart" or "sour". I don't know how to do this along with the other features though; I've found examples of bags-of-words for similarity, but I can't seem to find any information about combining it with other features.
Is this a valid approach, and is there some terminology that I should be looking for? Thanks.


text:
Q: Dictionary as thread-safe variable I have a class (singleton) and it contains a static Dictionary
private static Dictionary<string, RepositoryServiceProvider> repositoryServices = null;

in the instance of this class I populate the dictionary (can occur from multiple threads). At first I had just
        RepositoryServiceProvider service = null;
        repositoryServices.TryGetValue(this.Server.Name, out service);
        if (service == null) {
          service = new RepositoryServiceProvider(this.Server);
          repositoryServices.Add(this.Server.Name, service);
        }

then I got some exceptions as Item already added so I changed it to:
        RepositoryServiceProvider service = null;
        repositoryServices.TryGetValue(this.Server.Name, out service);
        if (service == null) {
          lock (padlock) {
            repositoryServices.TryGetValue(this.Server.Name, out service);
            if (service == null) {
              service = new RepositoryServiceProvider(this.Server);
              repositoryServices.Add(this.Server.Name, service);
            }
          }
        }

and padlock is in the class:
private static readonly object padlock = new object();

is this thread safe? or its overcomplicated? or should I use ConcurentDictionary?

A: IF you can use ConcurrentDictionary - it is in several situations faster than your approach because it implements most operations lock-free while being thread-safe.
EDIT - as per comments:
The term "most operations lock-free" is a bit too general...
Basically it means reduced contention ... thus in some cases more efficiency compared to a situation with one global lock, i.e. accessing a second bucket while the first bucket is locked works as if there was no lock from the POV of the accessing code... although that means a lock local to that bucket... in real-world applications it delivers much better performance than a global lock - esp. with multi-core.


text:
Q: ASP.Net FAQ library control Can someone advise if there is an ASP.NET control that i can use to create an FAQ section on my existing website.
I can build it myself but i was hoping there's an existing library i can just plug in.

A: One way to do it would be using an accordion or the jquery version

A: I used jquery ui accordion control in one of the website i worked on. I would go for server controls only if it's  absolutely necessary. If your FAQ content gonna be static, you can try jquery ui accordion
http://jqueryui.com/demos/accordion/


text:
Q: CMap in c# with 4 parameters I'm porting a c++ MFC class in c# and i have a problem.
The c++ class have a
CMap<int,int,CString,CString>MapIndexNote;

How can i create the equivalent in c#  ? I have read about Dictionnary and Hastables, but i have difficulty with 4 parameters.
Thanks a lot,
Nixeus

A: The equivalent is Dictionary<int, string>.
Looking at the definition of CMap you can see that the 2nd and 4th types only exist to let you specify whether the 1st and 3rd types are passed by reference or by value.
C# will do the right thing semi-automatically: because all value types including int are passed by value, whereas reference types including string are passed as (reference-counted) references (however note that a 'reference' doesn't mean the same thing in C# as in C++).


text:
Q: Why won't my table column respect a max-width of 50%? I am trying to get a table column to expand to fill its contents, up until it's taking 50% (or any arbitrary %) of the width of the whole table. I've set every cell in the column, including the header, to have max-width: 50%; in its css style.I've verified that the rule isn't being overridden by another max-width.
Fixed pixel amounts for max-width work fine. Only percents seem to be failing to take effect.
I've tried simplifying it to a reproducable example to see if some other obscure layout or css quirk is causing the problem, and I'm still able to reproduce it.
JSFiddle: http://jsfiddle.net/8Lmtvzur/1/
HTML:

            Entry Header 1
            Entry Header 2
            Entry Header 3
            Entry Header 4

            Entry First Line 1
            Duis sollicitudin ipsum diam, cursus tristique lorem placerat.
            Entry First Line 3
            Entry First Line 4

            Entry Line 1
            Duis sollicitudin ipsum diam, cursus tristique lorem placerat.
            Entry Line 3
            Entry Line 4

            07/07/2014 11:51 am
            Duis sollicitudin ipsum diam, cursus tristique lorem placerat.
            Entry Last Line 3

                Nullam consectetur pretium tristique. Vestibulum facilisis dapibus vulputate. Sed et arcu ac arcu pretium porttitor. Nullam quis ante.

                Donec at condimentum nunc. Maecenas in arcu ligula. Etiam dictum metus massa, eu dignissim nibh tempor a. Maecenas.

                Donec ac turpis felis. Sed blandit dignissim convallis. In hac habitasse platea dictumst. Pellentesque pretium, sem ac pellentesque gravida, velit erat semper nisi, placerat posuere dui augue non nunc. Curabitur id augue at turpis vestibulum suscipit. Suspendisse lacinia imperdiet metus sit amet lobortis. Proin nec mi lectus. Nam rutrum maximus felis quis congue. Vivamus nec augue felis.

            03/18/2015 11:05 am

            blah
            testing 1 2 3

                4 56

CSS:
table {
    border-spacing: 0;
    border-collapse: collapse;
}

table tr td, table tr th {
    font-size: 10.6667px;
    font-family: Osaka, verdana, sans-serif;
    vertical-align: top;
    border: 1px #DDDDDD solid;
    padding: 2px;
}

td.asdf, th.asdf {
    max-width: 10%;
}

A: Try using width instead:
http://jsfiddle.net/gd77gxcc/
max-width is not defined in the current standards for table elements so it can't be relied upon:

In CSS 2.1, the effect of 'min-width' and 'max-width' on tables, inline tables, table cells, table columns, and column groups is undefined.

http://www.w3.org/TR/CSS21/visudet.html#propdef-max-width

CSS 2.1 explicitly leaves the behavior of max-width with  undefined. Therefore any behavior is CSS2.1-compliant; newer CSS specifications may define this behavior, so Web developers shouldn't rely on a specific one now.

https://developer.mozilla.org/en/docs/Web/CSS/max-width


text:
Q: WPF Button remove "blur" from button Hi  I'm trying to personalizate the button in  my wpf
cause when user is mousing over the button it shows the "default style"
as in this image bellow

As I don't want to show the deful blue and border element when Mouse is over in a  button, then I created this style to my button
<Style x:Key="Simple" TargetType="Button">

    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="Button">
                <Border SnapsToDevicePixels="True" CornerRadius="3" Background="{TemplateBinding Background}" BorderBrush="#399bff" BorderThickness="0">
                    <Border.Effect>
                        <DropShadowEffect ShadowDepth="0" BlurRadius="0"></DropShadowEffect>
                    </Border.Effect>

                    <Grid SnapsToDevicePixels="True">

                        <Path SnapsToDevicePixels="True" Width="9" Height="16.5" Stretch="Fill"  HorizontalAlignment="Left" Margin="16.5,0,0,0"  Opacity="0">

                        </Path>
                        <Path SnapsToDevicePixels="True" x:Name="PathIcon" Width="8" Height="15"  Stretch="Fill"  HorizontalAlignment="Left" Margin="17,0,0,0">

                        </Path>

                        <ContentPresenter SnapsToDevicePixels="True" Content="{TemplateBinding Content}" ></ContentPresenter>
                    </Grid>
                </Border>
                <ControlTemplate.Triggers>
                    <Trigger Property="IsMouseOver" Value="True">
                        <Setter Property="Background" Value="Transparent"></Setter>
                        <Setter Property="BorderBrush" Value="Transparent"></Setter>
                        <Setter Property="Opacity" Value="0.8"></Setter>
                        <Setter Property="SnapsToDevicePixels" Value="True"></Setter>
                    </Trigger>
                </ControlTemplate.Triggers>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

But it is creating some kind of blur or border in my button as  you  can see in the
NF-e button (left Blue one)  in this image

It should be as in the CT-e button (right orange one)
What is wrong with  my XAML style ?
Edit
The button XAML code
<Border  HorizontalAlignment="Left" VerticalAlignment="Top" Margin="10 10 5 5" BorderThickness="0" Width="150" Height="150" Background="#992086bf" CornerRadius="10">
        <Button Style="{StaticResource Simple}" Click="GoToNFeEntrada" Background="Transparent" BorderBrush="Transparent">
            <Grid Width="150" Height="150">
                <fa:ImageAwesome Icon="File" Width="50" Foreground="White" VerticalAlignment="Top" Margin="0 30 0 0"></fa:ImageAwesome>
                <Label VerticalAlignment="Bottom" Margin="10 0 0 5" FontSize="15" Foreground="White">NF-e</Label>
            </Grid>
        </Button>
    </Border>

A: The solution was removing this line
<Border.Effect>
     <DropShadowEffect ShadowDepth="0" BlurRadius="0"></DropShadowEffect>
</Border.Effect>

This effecting was creating some border in the content


text:
Q: I want to install tensorflow version 1.14 in Google colab but failed I need to test a code in Google colab which is not supported in tf2(for tf.ceil is not supported in tf2), so I want to install tensorflow in version 1.14. I use pip3 and pip to install tensorflow, all of them install tf successfully, but as I do this:
import tensorflow as tf
tf.__version__

It returns:
'2.2.0-rc3'

And I have clear sys.path:
import sys
sys.path

It returns:
[]

How can I install tensorflow in version 1.14?

A: The easiest way to ensure you work with TF v1 is to simply run the
%tensorflow_version 1.x

line before you import TensorFlow.
Colab already builds TF from source so Google recommends against using pip to install TF as you may incur performance problems.

A: If sys.path is empty, your Python environment is in a very bad state. You should reset your VM (Runtime -> Factory reset Runtime) and then run the following:
!pip install tensorflow==1.14

Once you do this, you will have tensorflow 1.14 installed:
import tensorflow
print(tensorflow.__version__)

1.14.0

Be aware that reseting your VM will cause you to lose all program state from your current session.


text:
Q: Explanation for a joke about a three-legged dog that walks into a bar I came across this joke on the internet:

A three-legged dog walks into a bar and says to the bartender, 'I'm looking for the man who shot my paw'

It is meant to be a "dad joke" but I don't understand it. What does it mean?

A: The meaning of "paw" is an animal's foot, it sounds like "pa" (an informal word for dad/father).
In cowboy movies, back in the 1940s-50s, there was always the good guy and the bad guy. The bad guy would nearly always be an outlaw, a bandit, a notorious gunfighter or a corrupt sheriff. The movie audience would know him by his black cowboy hat.  The good guy, would often be a person who had suffered a wrong in the past.
At the beginning of the movie, the bad guy would burst into the saloon and announce dramatically to the patrons of said bar: I'm looking for a man named McCallister. Does anyone know where he is?  Cue scrambling of tables, chairs scraping and crashing onto the ground as people fled from the inevitable gunfight.

The pun plays on this well-known trope and on the stereotypical American drawl; the vowel in "pa" and "paw" would be drawn out, i.e. /pa:/ and /pɔ/,  the latter of which is only similar to the British English pronunciation /pɔː/ but close enough so that everyone gets the joke.

A: Paw is a non-standard way of saying father, used in certain parts of usually rural areas.
But obviously a three-legged dog is missing one of his "paws", hence the joke.


text:
Q: Sign in as different user in SharePoint 2013 I use SharePoint 2013 and I need to change my current user in my SharePoint site.
How can I change my current user?
How can I add sub menu (sign in as different user) to my menu ?

A: There are several solutions to your problem as Microsoft has removed the Sign in as different user link.

*

*Start your browser as a different user

*Use the _layouts/closeConnection.aspx?loginasanotheruser=true page

*Edit the Welcome.aspx to include the link again (Sign in as Different User and SharePoint 2013)

*Use JavaScript as a Bookmarklet (SharePoint 2013 – Sign in as Another User)

Official MSDN article about this problem: "Sign in as Different User" menu option is missing in SharePoint Server 2013. And remember: It's a feature, not a bug ;-)

A: •Locate the file \15\TEMPLATE\CONTROLTEMPLATES\Welcome.ascx and open in a text editor.
•Add the following element before the existing element with the id of "ID_RequestAccess":
<SharePoint:MenuItemTemplate runat="server" ID="ID_LoginAsDifferentUser"
 Text="<%$Resources:wss,personalactions_loginasdifferentuser%>"
 Description="<%$Resources:wss,personalactions_loginasdifferentuserdescription%>"
 MenuGroupId="100"
 Sequence="100"
 UseShortId="true"
/>

•Save the file and close.
•Open your SharePoint site.
You will get an option for Sign In as Different User below "About Me" option

A: I am aware of 5 workarounds:
– Running the browser as the user you want to log in. https://support.microsoft.com/en-us/kb/2752600
– Accessing the following URL "http://siteurl/_layouts/closeConnection.aspx?loginasanotheruser=true" by which you will be able to login as another user.
https://support.microsoft.com/en-us/kb/2752600
– Making a bookmarlet. Find how to do this here.
– Modify the "Welcome.ascx" control. You can find details about this here. This solution has two major inconvenients. Firstly, it is server scoped: the button will appear on every site collection of every web application. And secondly, the control can be overridden while applying a patch to SharePoint.
– Make a custom action. This gives the button back and is a clean way to do it.
Step by step guide on my blog.

A: Unfotueanatly the Sign as a different user has been removed in SharePoint 2013
But you can

*

*Start Internet Explorer with Run as a different user option, by holding the Shift key when you right-click on a program icon.

*Provide the different user credential.

*Navigate to your SharePoint portal.

Also, there is a workaround to show Sign as a different user in SharePoint 2013 as SharePoint 2010 option by following the mentioned steps at Sign in as a different user in SharePoint 2013

A: One workaround option is:
Start Internet Explorer by using the 'Run as different user option', and then go to the SharePoint site.
The 'Run as different user option' is visible if you hold the Shift key when you right-click a program icon.

A: Use the below URL in your browser, which will prompt for login.
http://<yourservername>/_layouts/closeConnection.aspx?loginasanotheruser=true

There is also a Chrome extension for this, refer this post:
http://spshell.blogspot.com/2018/07/sharepoint-20132016-sign-in-as.html


text:
Q: How to make a slush generator I have been trying to make a slush generator today with no luck.. I followed a couple of tutorials online and thought that I did everything right. However, when I run the generator it doesn't do anything.. I am not sure what I need to fix. Please let me know if you can spot my problem.. The files can be found here https://github.com/ryanswapp/slush-swappticon
slushfile.js
/*
 * slush-swappticon
 * https://github.com/ryanswapp/slush-swappticon
 *
 * Copyright (c) 2014, Ryan Swapp
 * Licensed under the MIT license.
 */

'use strict';

var gulp = require('gulp'),
    install = require('gulp-install'),
    conflict = require('gulp-conflict'),
    template = require('gulp-template'),
    rename = require('gulp-rename'),
    _ = require('underscore.string'),
    inquirer = require('inquirer');

function format(string) {
    var username = string.toLowerCase();
    return username.replace(/\s/g, '');
}

var defaults = (function () {
    var homeDir = process.env.HOME || process.env.HOMEPATH || process.env.USERPROFILE,
        workingDirName = process.cwd().split('/').pop().split('\\').pop(),
        osUserName = homeDir && homeDir.split('/').pop() || 'root',
        configFile = homeDir + '/.gitconfig',
        user = {};
    if (require('fs').existsSync(configFile)) {
        user = require('iniparser').parseSync(configFile).user;
    }
    return {
        appName: workingDirName,
        userName: format(user.name) || osUserName,
        authorEmail: user.email || ''
    };
})();

gulp.task('default', function (done) {
    var prompts = [{
        name: 'appName',
        message: 'What is the name of your project?',
        default: defaults.appName
    }, {
        name: 'appDescription',
        message: 'What is the description?'
    }, {
        name: 'appVersion',
        message: 'What is the version of your project?',
        default: '0.1.0'
    }, {
        name: 'authorName',
        message: 'What is the author name?',
    }];
    //Ask
    inquirer.prompt(prompts,
        function (answers) {
            if (!answers.moveon) {
                return done();
            }
            answers.appNameSlug = _.slugify(answers.appName);
            gulp.src(__dirname + '/templates/**')
                .pipe(template(answers))
                .pipe(rename(function (file) {
                    if (file.basename[0] === '_') {
                        file.basename = '.' + file.basename.slice(1);
                    }
                }))
                .pipe(conflict('./'))
                .pipe(gulp.dest('./'))
                .pipe(install())
                .on('end', function () {
                    done();
                });
        });
});

package.json
{
    "name": "slush-swappticon",
    "description": "A simple AngularJS with ui-router generator",
    "version": "0.1.1",
    "homepage": "https://github.com/ryanswapp/slush-swappticon",
    "author": {
        "name": "Ryan Swapp",
        "email": "ryancswapp@gmail.com"
    },
    "repository": {
        "type": "git",
        "url": "git://github.com/ryanswapp/slush-swappticon.git"
    },
    "bugs": {
        "url": "https://github.com/ryanswapp/slush-swappticon/issues"
    },
    "licenses": [{
        "type": "MIT",
        "url": "https://github.com/ryanswapp/slush-swappticon/blob/master/LICENSE"
    }],
    "main": "slushfile.js",
    "engines": {
        "node": ">= 0.10.26",
        "npm": ">=1.4.3"
    },
    "scripts": {
        "test": "echo \"No tests\""
    },
    "dependencies": {
        "slush": ">=1.0.0",
        "gulp": "^3.6.2",
        "gulp-template": "^0.1.1",
        "gulp-install": "^0.1.4",
        "gulp-conflict": "^0.1.1",
        "gulp-rename": "^1.2.0",
        "underscore.string": "^2.3.3",
        "inquirer": "^0.4.1",
        "iniparser": "^1.0.5"
    },
    "keywords": [
        "slushgenerator"
    ]
}

A: You don't have moveon question but you are still checking it's answer.
Remove this part of code:
if (!answers.moveon) {
    return done();
}


text:
Q: Pass two ids in a table with checkboxes I have been struggling with creating the Roles in my application, I have installed the gem Rolify and it created a model Role in which this is the code:
 class Role < ActiveRecord::Base
 has_and_belongs_to_many :users, :join_table => :users_roles
 has_many :abilities
 end

It also created automatically the joined table users_roles which stores the id of the user and the id of the role that exist in my database. I created 3 roles Admin - Patient - Doctor. My question is how could I pass values to this :users_roles table with a check-boxes in the registration
%% The code in my registration how could I modify it

    <%= f.label :roles %>
    <% Role.all.each do |role| %>
        <%= check_box_tag "user[role_ids][]", role.id, @user.role_ids.include(role.id)%>
        <%= role.name %>

    <% end %>

So that in the users_roles table every time i Check Patient for example it makes a connection with my user_id and the role_id in that table
I do not have a roles controller first of all, secondly in my User controller this is my code
 class UsersController < ApplicationController

    before_filter :authenticate_user!
    load_and_authorize_resource

    def index
      @users = User.all
    end

    def show
       @user = User.find(params[:id])
    end

    def update
    @user = User.find(params[:id])

    current_user.update(user_params)
    end
    def user_params
      params[:user].permit(
          {:role_ids => []}
      )
    end
 end

Here is the code generated in HTML from the checkboxes

    Roles

        <input id="user_role_ids_" name="user[role_ids][]" type="checkbox" value="1" />
        admin

        <input id="user_role_ids_" name="user[role_ids][]" type="checkbox" value="2" />
        patient

        <input id="user_role_ids_" name="user[role_ids][]" type="checkbox" value="3" />
        doctor

Thanks in advance!

A: Only saw your HTML today, but this is sure to confuse the browser. Seeing this you should change your View code to include the id of your role in the name parameter, i.e.
  <%= check_box_tag "user[role_ids][#{role.id}]", role.id, @user.role_ids.include(role.id)%>

which might do the trick. Look at the resulting params hash to see if this helps.