text:
Q: Limiting number of concurrent processes scheduled by condor I'm using condor to do batches of ~100 processes for a few hours. After these processes are finished, I need to start the next batch of runs with results from the first batch, and this process is repeated tens of times. My condor pool is >100 cores, and I'd like to limit my condor cluster to only do 100 processes at a time, so that condor only starts working on the next process after one of the first processes is finished. Is this possible?

A: This sounds like you're just running a job that checkpoints, and then the next job reads in that checkpoint and does some stuff and writes out a new checkpoint, etc 10 times.  I'm not sure why you need to break it up the way you have, why not just have a wrapper script that looks for a checkpoint file and uses it, or starts from scratch?
The other option is to use the "Requirements" in your submission file and list only 100 machines or cores that your job can be run on.  Something like:
Requirements =  (machine == "astrolab01") || (machine == "astrolab02") || (machine == "astrolab03")

will ensure you never run more than 3 jobs at once.  Unless those machines have multiple cores, then you need to do something like:
Requirements =  (name == "slot1@astrolab01") || (name == "slot1@astrolab02")

A: You need to use the DAG Manager - this allows you to define parent-child relationships between jobs so that you can wait for results from the first job before starting the second job.
DAGman also has a MAX_JOBS_RUNNING setting which limits the total number of active jobs for you.
This is all documented in section 2.10 of the 8.4 manual. You will likely need to use a script of some sort to build the DAG file, and have a location available to store interim results from the runs - it's not possible for jobs to pass data directly from parent to child. The output is gathered from the first run into the work directory, then that's sent to the next job from the work directory.


text:
Q: iText - Missing background color in table with rowspan and page break I'm using flying-saucer-pdf-itext5 (v 9.0.7) and iText (v 5.5.6) to generate PDF from given XHTML file. I have a big table in XHTML with a couple of rowspans and with CSS style (background color).
Simplified XHTML snippet:

    United Kingdom
    Ambleside
    38,726
    30,546

This style is applied correctly for all rowspans, except one - which is split to 2 pages by page break (see picture).

What i'm doing wrong? Or it is a bug in flying-saucer / iText?

redpajama_set_name: RedPajamaStackExchange


text:
Q: how to write a php variable on a mysql query I need to write my php variables correctly.
$query2 = mysqli_query($con,"SELECT * FROM palettes LIMIT '$starting_number, $palettes_per_page'");

A: I don't think you want single quotes on your LIMIT parameters.  One way is to use . to concatenate strings.
Since $starting_number and $palettes_per_page are integers, you do not need to escape them.  If they were strings, wrap them in mysqli_real_escape_string or mysqli_escape_string to escape special characters.
$query2 = mysqli_query( $con,
             "SELECT * FROM palettes LIMIT " .
             $starting_number .
             "," .
             $palettes_per_page );

A: Just remove the single quote, because double quote can read variable's value
$query2 = mysqli_query($con,"SELECT * FROM palettes LIMIT $starting_number, $palettes_per_page");

Hope this works for you

A: You could use parameterized queries which also prevent any need to use mysqli_real_escape_string
$stmt = $conn->prepare("SELECT * FROM palettes LIMIT ?, ?'");
$stmt->bind_param("ii", $starting_number, $palettes_per_page);
$stmt->execute();


text:
Q: Calculating the average using names on a pivot table I'm trying to have the pivot table calculate the average number of employees underneath each supervisor for a specific region. However pivot tables are unable to average out text strings. In the example below, within one region I have 5 supervisors but they all have different numbers of employees under them, some have 1 or 2. But all together there are 7 employees for that region. I need it to average out the number of employees per supervisor: so 7/5 = 1.4 would be the average. Is there any way you can create a count of employee divided by the amount of unique supervisors using a pivot table?
Number of Supervisor to Employee

A: OK well not very elegant I know but this would do it. Add a helper column which works out the fraction of a supervisor available to each employee (e.g. 2 employees per supervisor = 1/2, 3 employees = 1/3 etc.) starting in D2:-
=1/COUNTIFS($A$2:$A$20,A2,$C$2:$C$20,C2)

Then you can put the sum of these and the count of any column into a pivot table, putting Region as the row variable, and simply a manual formula to work out the ratio starting in J2:-
=IFERROR(I2/H2,"")

Note:- You can use GetPivotData to get the totals from the pivot table if you prefer. You could also use an array formula to list the distinct values of Region and not use a pivot table, but the pivot is quicker.


text:
Q: JQuery style and Ajax not work properly on new host After moving to VPS server this code not apply jQuery style, just not formatted dropdown autocomplete list... autocomplete shows all selected values in non-formated style, but at the same time show alert 'No search results'

Please advise what is the possible reason that this code stop works properly
<?php
require_once ("pg_conn.php");
$array[]="";
?>
<!DOCTYPE html>

<meta charset="utf-8">
<title></title>
<link rel="stylesheet" type="text/css" href="style.css" />

<link rel="stylesheet"  type="text/css" href="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.10.3/themes/sunny/jquery-ui.css">

            <form method="get" action="acmp.php" >

                    Street:

                    <input type="text" placeholder="Street name" required="required"
                    id="street" name="street" onchange="sendForm(this.form)">

A: Replace http with https:
<link rel="stylesheet"  type="text/css" href="https://ajax.aspnetcdn.com/ajax/jquery.ui/1.10.3/themes/sunny/jquery-ui.css">


text:
Q: Array pointer issue in C - array only contains last value I'm trying to add (well, append really) the letters in the alphabet to an empty char array. However, I appear to run into some sort of pointer issue I don't understand, as my array contains only the last character. I tried moving the letter char outside of the for loop, but the compiler didn't like that. I also looked on here about how to create a list of all alphabetical chars, and one of the better answers was to type them all in 1 at a time. However, my problem means I don't fully understand for loops and pointers in C, and I want to.
#include <stdio.h>

int main(void) {

    char *empty_list[26];

    for (int i = 0; i < 26; i++){
        char letter = i + 65;
        empty_list[i] = &letter;
    }

    printf("%s", *empty_list);

    return 0;
}

A: The main problem is your declaration:
char *empty_list[26];

defines an array of 26 pointers to characters. In your current code you assign each element in the array the address of the variable letter. Since that is out of scope when you print it is luck that it prints out the last one, it could equally have printed out garbage or crashed if the code between was complex. It could also have printed out additional garbage after the letter with what you already have since there is no way of knowing whether there is a string terminating character (\0) after the letter. In your existing code printf("%s", *empty_list); prints the first pointer from the array as a null terminated string, which if you ignore the loss of scope and assume the memory contents are still around, will be the last value from the loop since all pointers in your array point to the memory that letter was stored at and that memory has the last value from the loop.
If your intention was to create an array with the letters then it should be:
char empty_list[27];

It needs to be 27 as you need to leave space for the string terminating character at the end. One way to fill that in would be to use:
empty_list[26] = '\0';

after the end of your for loop and before you print the contents of the array (do not include the asterisk here - because it is an array the compiler will automatically take the address of the first element):
printf("%s", empty_list);

As brothir mentioned in the comments when you assign the value of the letter to the element in the array it should be without the ampersand:
empty_list[i] = letter;

A: There are a few things wrong with your code.
Firstly, the type of empty_list is presently an array of pointers to char, when it really should be an array of char, since your intent is to print it out as if it were the latter in the call to printf after your loop.  char empty_list[26]; is the correct declaration.
Secondly, in your loop, you assign &letter when all you need is letter. Heck, you don't even need the intermediate variable letter. Just empty_list[i] = i + 'A'; will suffice.
Lastly, you are passing empty_list to printf to satisfy a format specifier %s, which expects a null-terminated string. What you need to do is add another element to empty_list and set that to zero:
char empty_list[27];
// populated 0..25 with 'A'..'Z' in your code...

empty_list[26] = '\0';

printf("%s\n", empty_list);
// Output: ABC...Z

A: With the above help (much appreciated), my working code to create an array of letters in C is below:
#include <stdio.h>

int main(void) {

    // create an array with 1 extra space for null terminator
    char empty_list[27];

    // add null terminator so string knows when it's finished.
    empty_list[26] = '\0';

    for (int i = 0; i < 26; i++){
        // add 65 to get ASCII value for 'A'
        char letter = A + i;
        // insert each char into the array sequentially
        empty_list[i] = letter;
    }

    printf("%s", empty_list);

    return 0;
}


text:
Q: How to use MySQL REGEXP in the WHERE of a JOIN statement I have two tables A and B
Table A has columns: ID and POST
Table B has columns: ID, POST_ID and UPPERS
I want to select all records where a.POST matches the regex
'\\[cd(i|b)?(=[a-z0-9]+)?\\].+\\[/cd(i|b)?\\]'

and JOIN table B on a.ID = b.POST_ID where b.UPPERS matches the regex
'(\\|[0-9]+\\![0-9]{4}[-]+[0-9]{2}[-]+[0-9]{2} [0-9]{2}:[0-9]{2}:[0-9]{2},){1,}'

I came up with the following statement but it is not returning any row even when the columns contains the contents matching the regex
SELECT a.*,b.*
FROM a JOIN
     b
     ON b.POST_ID=a.ID
WHERE a.POST RLIKE '\\[cd(i|b)?(=[a-z0-9]+)?\\].+\\[/cd(i|b)?\\]' AND
      b.UPPERS REGEXP '(\\|[0-9]+\\![0-9]{4}[-]+[0-9]{2}[-]+[0-9]{2} [0-9]{2}:[0-9]{2}:[0-9]{2},){1,}'

Summary:
I want to select records where a users has sent contents that matches this regex
 '\\[cd(i|b)?(=[a-z0-9]+)?\\].+\\[/cd(i|b)?\\]'

and then check if that very post has received at least two ups(or likes) using the regex
'(\\|[0-9]+\\![0-9]{4}[-]+[0-9]{2}[-]+[0-9]{2} [0-9]{2}:[0-9]{2}:[0-9]{2},){2,}'

which can be broken down as simply:
a prefix pipe: |
a user id: [0-9]+
an exclamation mark: !
a datetime: [0-9]{4}[-]+[0-9]{2}[-]+[0-9]{2} [0-9]{2}:[0-9]{2}:[0-9]{2}
and a sufix: ,
NOTE: {2,}  simply to check how many times the match occurs

Please can someone point me in the right direction as to what am doing wrong.
Sample table datas:
Table A
ID    | POST
23  match found [cd=plain]6h+#gtyr[/cd]
24       match found [cd]65#%gte2!iu[/cd]
25       match found [cdi]*tre&y^g82u[/cdi]
26       no match found *tre&y^g82u
27       no match found rtyure99
28       match found [cdb]aha87ulchr[/cdb]

Table B
ID  |   POST_ID     |   UPPERS

4       24              |98!2018-02-10 22:43:03,
                    |35!2018-02-08 20:42:09,
                                            |3!2018-02-05 02:05:07,

5       26              |2!2018-02-10 22:43:03,
                    |30!2018-02-08 20:42:09,

6       25              |21!2018-02-10 22:43:03,

7       27              |23!2018-02-10 22:43:03,
                    |11!2018-02-08 20:42:09,

NOTE: POST_ID in table B is a foreign key referencing ID of table A

A: If you don't mind, I'm actually going to answer the question that lies beneath your actual question. I'm sure we could work through why the regular expression is not working as you expect, but it begs the question: why use regular expressions for such a simple task?
It happens a lot that people first just use a database to stash stuff that is the same format that appears in the code. But if you take a little time to break down your data in a meaningful way, you can unlock a lot of power from humble MySQL.
Think about the question you want this query to answer:

*

*Which posts that match certain criteria have been upped?

As you already realized, that suggests two tables - one to store information about the posts, and another to store information about who upped them. To make your queries fast and easy, think about which attributes of the information are going to show up in your where clause.
You want posts that are enclosed by certain markup. To make your search more efficient, put the markup tag in its own column:
CREATE TABLE `posts` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `tag` enum('cd','cdi','cdb') DEFAULT NULL,
  `tag_value` varchar(11) DEFAULT NULL,
  `content` text NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

for the data you list above, the table might look something like:
+-----+------+-----------+-------------+
| id  | tag  | tag_value | content     |
+-----+------+-----------+-------------+
|  23 | cd   | plain     | 6h+#gtyr    |
|  24 | cd   | NULL      | 65#%gte2!iu |
|  25 | cdi  | NULL      | *tre&y^g82u |
|  26 | NULL | NULL      | *tre&y^g82u |
|  27 | NULL | NULL      | rtyure99    |
|  28 | cdb  | NULL      | aha87ulchr  |
+-----+------+-----------+-------------+

It takes a little more work to put your data IN (this is where your regex powers are better applied, as you create the INSERT), but now you can do all sorts of things with it quite easily. I used an ENUM for the tag column, because that is extra-fast to search on. If you have a large number of tags or don't know what they will all be, you can just use a VARCHAR instead.
So how to you track UPPERS? That part gets very easy. All you need is a table with a row for each time someone ups something:
CREATE TABLE `uppers` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `user_id` int(11) DEFAULT NULL,
  `post_id` int(11) DEFAULT NULL,
  `time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

Currently when someone ups something, you have to go find the relevant record, append new data to it, then save it back. Now you can just slap a record into the table. The time will be set automatically; all you need to insert is the user_id and post_id. Some of your data might look like:
+----+---------+---------+---------------------+
| id | user_id | post_id | time                |
+----+---------+---------+---------------------+
|  2 |      98 |      24 | 2018-02-10 15:23:03 |
|  3 |      35 |      24 | 2018-02-10 15:23:23 |
|  4 |      27 |      24 | 2018-02-10 15:23:43 |
|  5 |       2 |      26 | 2018-02-10 15:24:16 |
|  6 |      30 |      26 | 2018-02-10 15:24:28 |
+----+---------+---------+---------------------+

Now you can harness the power of the MySQL engine to capture all the information you need:
All posts with the desired tags:
SELECT * FROM posts where tag IN ('cd', 'cdi', 'cdb')

All post with the desired tags and at least one up:
SELECT posts.*, uppers.user_id, uppers.time
    FROM posts
    INNER JOIN uppers ON posts.id = uppers.post_id
    WHERE tag IN ('cd', 'cdi', 'cdb')

That will return a row for each post-upper combination. The INNER JOIN means it will not return any posts that don't have a match in the uppers table. This may be what you are looking for, but if you want to group the ups together by post ID, you can ask MySQL to group them for you:
SELECT posts.*, COUNT(uppers.user_id)
    FROM posts
    INNER JOIN uppers
    WHERE tag IN ('cd', 'cdi', 'cdb')
    GROUP BY posts.id

If you want to rule out duplicate ups by the same user, you can easily only count unique user id's for each post:
SELECT posts.*, COUNT(DISTINCT uppers.user_id)
    FROM posts
    INNER JOIN uppers
    WHERE tag IN ('cd', 'cdi', 'cdb')
    GROUP BY posts.id

There are many functions like COUNT() you can use to work with the data that gets grouped together. You could MAX(uppers.time) to get the time of the most recent up for that post, or you can use functions like GROUP_CONCAT() to put the values together in a long string.
The bottom like is that by breaking down your data into its fundamental pieces, you allow MySQL (or any other relational database) to work much more efficiently, and life gets much, much easier.


text:
Q: Symfony access control for site root I have created a site with firewall access controls that force users to log in to access any content i.e.
 - { path: ^/, roles: IS_AUTHENTICATED_FULLY}

Now the client wants a splash page at the root of the website i.e www.sitename.com.
I have this page mapped to DefaultController::indexAction, however I cannot work out how to allow IS_AUTHENTICATED_ANONYMOUSLY access to this page as there is no path name i.e www.sitename.com/splash-page to hang the access control off.
Can I even do this?

A: You can secure all the URLs except the homepage URL:
# app/config/security.yml file
security:
    ...
    access_control:
        # Logged in
        - { path: ^/(.+), roles: IS_AUTHENTICATED_FULLY }
        # no authentication for the homepage:
        - { path: ^/$, roles: IS_AUTHENTICATED_ANONYMOUSLY }

The regular expression ^/(.+) will match every URL than contains something after /.
The regular expression ^/$ will match the URL than contains nothing after / (/ is the end of the string).
And the homepage URL have to be declared in a routing.yml file:
homepage:
    pattern: /
    defaults: { _controller: ACMEBundle:Default:homepage }


text:
Q: Unexpected result from Python function when using floats I have to create a Python class which change a numeric amount to french text.
I found a class which do this work but when the float is 50.4 per example, it returns "Cinquante units et 399.
The function toText takes 3 parameters: the float to convert, the unit, the decim.
def tradd(num):
    global t1,t2
    ch=''
    if num==0 :
        ch=''
    elif num<20:
        ch=t1[num]
    elif num>=20:
        if (num>=70 and num<=79)or(num>=90):
            z=int(num/10)-1
        else:
            z=int(num/10)
        ch=t2[z]
        num=num-z*10
        if (num==1 or num==11) and z<8:
            ch=ch+' et'
        if num>0:
            ch=ch+' '+tradd(num)
        else:
            ch=ch+tradd(num)
    return ch

def tradn(num):
    global t1,t2
    ch=''
    flagcent=False
    if num>=1000000000:
        z=int(num/1000000000)
        ch=ch+tradn(z)+' milliard'
        if z>1:
            ch=ch+'s'
        num=num-z*1000000000
    if num>=1000000:
        z=int(num/1000000)
        ch=ch+tradn(z)+' million'
        if z>1:
            ch=ch+'s'
        num=num-z*1000000
    if num>=1000:
        if num>=100000:
            z=int(num/100000)
            if z>1:
                ch=ch+' '+tradd(z)
            ch=ch+' cent'
            flagcent=True
            num=num-z*100000
            if int(num/1000)==0 and z>1:
                ch=ch+'s'
        if num>=1000:
            z=int(num/1000)
            if (z==1 and flagcent) or z>1:
                ch=ch+' '+tradd(z)
            num=num-z*1000
        ch=ch+' mille'
    if num>=100:
        z=int(num/100)
        if z>1:
            ch=ch+' '+tradd(z)
        ch=ch+" cent"
        num=num-z*100
        if num==0 and z>1:
           ch=ch+'s'
    if num>0:
        ch=ch+" "+tradd(num)
    return ch

def trad(nb, unite):
    global t1,t2
    x=int(nb)
    y=int((nb-x)*1000)
    t1=["","un","deux","trois","quatre","cinq","six","sept","huit","neuf","dix","onze","douze","treize","quatorze","quinze","seize","dix-sept","dix-huit","dix-neuf"]
    t2=["","dix","vingt","trente","quarante","cinquante","soixante","soixante-dix","quatre-vingt","quatre-vingt dix"]
    if x==0:
        ch="zéro"
    else:
        ch=tradn(abs(x))
    if x>1 or x<-1:
        if unite!='':
            ch=ch+" "+unite+'s'
    else:
        ch=ch+" "+unite

    if x<0:
        ch="moins "+ch
    return ch

def toText(nb, unite="Dinar", decim="millime"):
    x=int(nb)
    y=(nb-x)*1000
    z=int(y)

    if  y > 1:
        text_amount=trad(x,unite)+" et "+str(z)+" "+decim+"s"
    elif y==1:
        text_amount=trad(x,unite)+" et "+str(z)+" "+decim
    elif y==0:
        text_amount=trad(x,unite)+" et zéro "+decim
    return text_amount

if __name__=='__main__':

    print toText(45.4,"dinar")

A: This is simply everyone's favorite old friend, floating-point error.
The lines:
x=int(nb)
y=int((nb-x)*1000)

end up doing:
(50.4-50)*1000
# try this in your interpreter: 399.9999999999986

50.4 cannot be exactly represented with a (53-bit) floating-point number.  You will need to adjust accordingly via string formatting or rounding.

A: Instead of z=int(y) try using z=int(round(y,0)). That should round your 399.99... to 400.
>>> int(round((50.4-50.)*1000, 0))
400

A: As the other answers already say, you cannot represent exactly floating point exactly with float, therefore 50.4 is printed as you see.
You can try to use the package decimal: it is able to represent floating point exactly and you might be able to get the expected result

A: The problem is that 50.4 cannot be represented exactly:
>>> print('{:.47f}'.format(50.4))
50.39999999999999857891452847979962825775146484375

The fault is in the definition of the toText function. The lines:
x=int(nb)
y=(nb-x)*1000
z=int(y)

will result in z being 399 instead of 400.
If you want to give more "user-friendly" output you'd have to manually check whether the fractional part is "strange" and rounding accordingly.

A: You could use round
def toText(nb, unite="Dinar", decim="millime"):
    x=int(nb)
    y=(nb-x)*1000
    z=int(round(y))


text:
Q: Changing the color of a selected CTreeCtrl item? (VS2008, MFC, feature-pack)
Using a CTreeCtrl, I need to have the selected item "better" highlighted when the control looses focus.
My Tree is created with the "TVS_SHOWSELALWAYS" option in the resource editor, but the color is not visible enough.
I already have code to change the items colors via the custom draw message (NM_CUSTOMDRAW) like this :
void MyTree::OnCustomDraw(NMHDR* pNMHDR, LRESULT* pResult)
{
    NMTVCUSTOMDRAW *pcd = (NMTVCUSTOMDRAW   *)pNMHDR;
    switch ( pcd->nmcd.dwDrawStage )
    {
    case CDDS_PREPAINT:
        *pResult = CDRF_NOTIFYITEMDRAW;
        break;

    case CDDS_ITEMPREPAINT :
        {
            HTREEITEM   hItem = (HTREEITEM)pcd->nmcd.dwItemSpec;

            if ( this->IsSelected(hItem ))
            {
                pcd->clrText = GetSysColor(COLOR_HIGHLIGHTTEXT);
                pcd->clrTextBk = GetSysColor(COLOR_HIGHLIGHT);
            }

            *pResult = CDRF_DODEFAULT;// do not set *pResult = CDRF_SKIPDEFAULT
            break;
        }
    }
}

It's working, but is seems to be overkill for a simple task as this.
I think I must be missing something obvious to do this without having to do this.
Anything simpler ?
Thanks.

A: apart from the custom drawing that you already do, you could also set the state TVIS_DROPHILITED for all selected items. But I'm not sure if that's really what you want, especially if your tree control also is a drop target.
You could also try to set the theme of the tree control to explorer:
SetWindowTheme(hTreeControl, L"Explorer", NULL);

This makes the tree control look exactly as in the windows explorer with the same colors. Maybe those are more to your liking.

A: You could set your selected item's text to bold using SetItemState and TVIS_BOLD. You wouldn't need custom draw for this and less code is always better.

A: You could replace the this->isSelected with pcd->nmcd.uItemState & CDIS_SELECTED

A: One minor missing detail from the original posting is the message map entry for the custom OnCustomDraw handler is:
ON_NOTIFY_REFLECT(NM_CUSTOMDRAW, OnCustomDraw)

Kudos to Max for providing the OnCustomDraw implementation.


text:
Q: Reverse Levenshtein distance In levenshtein distance you ask the question, given these two strings, what is their levenshtein distance. How would you go about taking a string and a levenshtein distance and generating all the strings within that levenshtein distance. (It would also take in a character set). So if i pass in a string x and a distance d. then it would give me all the strings within that edit distance, including d-1 and d-2....d-n; (n < d).
Expected functionality:
>>> getWithinDistance('apple',2,{'a','b',' '})
['applea','appleb','appel','app le'...]

Please note that the program is able to produce app le as space is included in the character set.

A: There's a data structure that does this called the Levenshtein automaton. You construct it from a set of strings (which may have only one member) and a fixed distance k, and then you can query it for all strings with distance at most k of any of the strings it stores. A Python implementation is discussed here.
Alternatively, you can do a depth-limited search with backtracking for such strings.


text:
Q: C++ string to char* array struct I have been pulling my hair out on this particular issue and would like some advice. I have the following struct:
struct MqlStr // MQL String Array
{
int               len;
char              *string;
};

this is being passed to a function as a pointer from an external application as such:
MT4_EXPFUNC double __stdcall CheckExecutionRequests(MqlStr* RequestInfo)

within the function i am generating a number of string values that i need to assign to varies elements of the MqlStr array. the following works fine:
RequestInfo[1].string = "1";
RequestInfo[2].string = "2";

but when i use strcpy to get my generated string value into the array, it overwrites the entire array with the value i copied. for example:
string field1 = value.substr(Demark + 1, Demark2 - Demark - 1);
strncpy(RequestInfo[1].string, field1.c_str(), field1.size());

string field2 = value.substr(Demark + 1, Demark2 - Demark - 1);
strncpy(RequestInfo[2].string, field2.c_str(), field2.size());

if field1 = 1 and field2 = 2 then the entire RequestInfo[] array would be equal to 2 (the last value copied)
can someone point me in the right direction?

A: RequestInfo[1] = "1";

is not doing what you think. It's either
RequestInfo[1].string = "1";

if RequestInfo is a vector of MqlStr objects containing at least 2 elements, or
RequestInfo->string = "1";

if RequestInfo is a pointer to a single MqlStr object.

A: Have you allocated enough space for the .string pointers in your RequestInfo elements? strncpy is not allocating the space for you, use strdup for that.

A: You need to manage MqlStr memory in a safe manner, this can happen by using a standard container like std::string or by writing methods to allocate and deallocate the internal memory.
Here is an example of a simple class that manages its internal memory:
#include <cstdlib>
#include <iostream>
#include <string.h>
#include <sstream>

struct MqlStr
{
public:
    int    len;
    char  *string;

    MqlStr() { init   (); }
   ~MqlStr() { dealloc(); }
    void assign(std::string& str) {
        dealloc();
        string = new char[str.length() + 1];
        strncpy(string, str.c_str(), str.length());
        string[str.length()] = 0;
        len = str.length();
    }
    void dealloc() {
        if(string != 0) delete [] string; init();
    }

private:
    void init() { string = 0; len = 0; }
         MqlStr(const MqlStr &);
    void operator= (const MqlStr &);
};

double CheckExecutionRequests(MqlStr* RequestInfo)
{
    static int callCount = 0;
    std::ostringstream stringstream; stringstream<<"callCount: "<<callCount++;
    std::string field1 = stringstream.str();
    RequestInfo->assign(field1);
    return 1.0;
}

int main(int argc, char** argv)
{
    MqlStr s[5];

    std::cout<<"First call"<<std::endl;
    for(unsigned i = 0; i < sizeof(s)/sizeof(s[0]); ++i)
        CheckExecutionRequests(s + i);

    for(unsigned i = 0; i < sizeof(s)/sizeof(s[0]); ++i)
        std::cout<<"MqlStr["<<i<<"].string = "<<s[i].string<<std::endl;

    std::cout<<"Second call"<<std::endl;
    for(unsigned i = 0; i < sizeof(s)/sizeof(s[0]); ++i)
        CheckExecutionRequests(s + i);

    for(unsigned i = 0; i < sizeof(s)/sizeof(s[0]); ++i)
        std::cout<<"MqlStr["<<i<<"].string = "<<s[i].string<<std::endl;

    return EXIT_SUCCESS;
}

The second execution of CheckExecutionRequests with the same MqlStr instances will not corrupt the memory.
An extension to the code can be preallocation of the string size, and only reallocating the memory in the assign method if the new str.length > this.maxLength (preallocated length different from the string size).
The copy constructor and assignment operator are currently disabled, because they can cause problems if not implemented properly while managing internal memory on the heap.
A simpler solution would be to write your struct using a standard container as follows:
struct MqlStr
{
public:
    std::string string;
}

And then just assign the string you get for the fields to MqlStr string.


text:
Q: Html/Javascript: Is it possible to set text style.display = "none" by default? With the way I have my html and javascript set up right now, I have it so when the page loads up and shows up all the text under each button. You can click the button to hide and show the text right below it.
Is it possible to make it so all the text does NOT show up by default?
I was thinking you would have to make e.style.display = "none" by default but I'm not sure how/where to in this particular case.

<input type="button" onclick="return toggleMe('para1')" value="Toggle">

blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah

<input type="button" onclick="return toggleMe('para2')" value="Toggle">

blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah

<input type="button" onclick="return toggleMe('para3')" value="Toggle">

blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah

A: if you add the following styles to your page, the paragraphs will be hidden by default.

A: make a class for each element you want hidden by defaut, i.e

some hidden text

more hidden text

A: CSS
First, add this bit of code in order to have a CSS class to make things hidden.

And then, add this class to whichever elements you want hidden by default.   For example,

Also, here's a short DEMO on how you might shorten all that code using jQuery.   There's a toggleClass() function that you can use to easily add / remove (toggle) a class.


text:
Q: Why does rand() produce the same value when seeded with 1 and UINT_MAX? Here's some code:
#include <iostream>

int main() {
    srand(1);
    std::cout << rand() << "\n";
    srand(UINT_MAX);
    std::cout << rand() << "\n";
}

This produces the following output:
16807
16807

Why do these two seeds produce the same result? The entire sequence of values they produce on successive rand() calls is also identical. The range of possible values is too large for this to be a pure coincidence. Is it:

*

*An accident of the implementation of rand() (and if so, I'm curious what that might be)

*By design (and if so, why?)

(Possibly related: the seeds 10, 100, 1000, 10000, and 100000 produce 168070, 1680700, 16807000, 168070000, and 1680700000 respectively.)

A: A very simple usable random number generator is a Lehmer number generator. This RNG is maybe the simplest to implement in software, which is still usable, so probably it has the most issues with randomness, and most easy to analyze.
The number 16807 (aka the fifth power of 7) is associated with Lehmer RNG, because it was used in one of the earliest implementations in 1988 - apparently still in use today!
The formula for Nth random number is (using ^ for exponentiation):
R(n) = (seed * (16807 ^ n)) mod (2 ^ 31 - 1)

If you set seed = 1, n = 1:
R(1) = 16807 mod (2 ^ 31 - 1) = 16807

If you set seed = 2 ^ 32 - 1:
R(1) =
    (2 ^ 32 - 1) * 16807 ≡ (expressing 2^32 = 2^31 * 2)
    ((2 ^ 31 - 1) * 2 + 1) * 16807 ≡ (distributive law)
    (2 ^ 31 - 1) * 2 * 16807 + 1 * 16807 ≡ (modulo 2^31-1)
    16807

Here the equality of the first number in the random sequence is because the modulo-number in the Lehmer RNG is almost a power of 2 (2^31-1), and your seed is also almost a power of 2 (2^32-1).
The same would happen for seed = 2^31.

A: tl;dr: rand() is known to be that bad.
The actual values are implementation defined. I get the following values on my platform:
seed:          1 : 41
seed: 4294967295 : 35
seed:         10 : 71
seed:        100 : 365
seed:       1000 : 3304
seed:      10000 : 32694

rand() can be relied on to look somewhat random to a casual user in a hurry. It is not portably suitable for anything else.
The implementation usually use a low quality generator (most often Linear Congruential with bad constants).
The required numeric range is 0...32767, and while implementation may they usually don't exceed that - so you can expect many seeds to result in the same value.
For C++ modern, see <random> for reliable options.

A: This depends on the implementation of you random number generator.
See What common algorithms are used for C's rand()?
for common implementations.
Usually the space of possible seed values is much shorter than your UINT_MAX.
It could be that 1 and UINT_MAX are mapped to the same internal seed.
Often Linear congruential generator are used for rand(), then the first generated random number depends like
first_random_number  = (seed * const + another_const)  % third_constant

on the seed. This explains the dependence you found.

A: I don't see a good reason why the unfortunate correlation that you observed would be designed into the implementation of rand that you're using. It's most likely an accident of the implementation as you suggest. That said, I would also consider it a coincidence, that you can produce correlation with exactly those inputs. Another implementation could have other sets of unfortunate inputs.

if so, I'm curious what that might be

If your implementation is open source, then you can find out by reading the source. If it's proprietary you could still find a mention of the algorithm in some documentation, or if you're a customer, you could ask the implementer.

A: As stated here, If seed is set to 1, the generator is reinitialized to its initial value and produces the same values as before any call to rand or srand.
Also note that Two different initializations with the same seed will generate the same succession of results in subsequent calls to rand.


text:
Q: Outlook - Linked Image cant be displayed I have tried all the solution provided by Microsoft but none of it works.

*

*Modify BlockHTTPimages in registry (Don't have this in my registry)

*Changes Trust Center settings

*Change Internet Options (Do not save encrypted pages to disk)

My organization is using IMAP/ SMTP server but I don't think the issue is related to the server. This issue only occur to Outlook application, but in web, it works fine.
Linked image cant be displayed

A: Based on my research, i find an article about the error and it's suggested that you could try to change the below registry to check if there're any differences:

Modify BlockHTTPimages in registry (Don't have this in my registry)

By the way, if you didn't find it, you can create it manually. References: The Linked image cannot be displayed error in an Outlook email message.
(It should be noted that if you modify the registry by mistake, serious problems may occur. Please back up the registry before operation.)


text:
Q: Proof of Besov space embeddings: $B_{p, \infty}^{s+\varepsilon}$ is continuously embedded in $B_{p, 1}^s$ Let's consider the Besov spaces $B_{p,q}^s$, $p,q \in [1,\infty]$, $s\in \mathbb{R}$ and $\varepsilon >0$. I keep coming across that $B_{p, \infty}^{s+\varepsilon}$ is continuously embedded in $B_{p, 1}^s$, i.e. there exists an constant $C$ with $\|\cdot\|_{B_{p,1}^s} \leq C\|\cdot\|_{B_{p, \infty}^{s+\varepsilon}}$, but unfortunately I have no idea how to prove it. Could anybody give me a hint (or proof)?

A: After some thought, I came to the following proof. I hope firstly that it is correct and secondly that it may be able to help others.
$$ \begin{align*}
\|f\|_{B_{p,1}^s} &= \sum_{j \geq -1} 2^{js} \|\Delta_j f\|_{L^p} \\ &= \sum_{j \geq -1} 2^{-j(s+\varepsilon- s)} 2^{j(s+\varepsilon)} \|\Delta_j f\|_{L^p} \\ &= \sum_{j\geq -1} 2^{-j\varepsilon} 2^{j(s+\varepsilon)} \|\Delta_j f\|_{L^p} \\ &\leq \sum_{j\geq -1} 2^{-j\varepsilon} \sup_j 2^{j(s+\varepsilon)} \|\Delta_j f\|_{L^p} \\ &= \sum_{j\geq -1} 2^{-j\varepsilon} \|f\|_{B_{p, \infty}^{s+\varepsilon}} \\ &= C_{\varepsilon} \|f\|_{B_{p, \infty}^{s+\varepsilon}}
\end{align*}.$$


text:
Q: Left Join And vs Where on Second Table Is there any difference in the output between these two queries?
Both tables only have one column - id.
Table A: {1,2,3,4,5};
Table B: {5,6,7,8,9}
Select *
from tableA
left join tableB on tableA.id = tableB.id
where tableB.id = 5;

Select *
from tableA
left join tableB on tableA.id = tableB.id and tableB.id = 5;

A: Yes, the difference is that on the first one, if the left join doesn't find a match for A in B, it will leave the row, and then remove it using the WHERE clause. In other words, it will be equivalent to an INNER JOIN, because B.id is always null if there is no match.
For the second query, by contrast, if the query doesn't find a match for A in B using both conditions, it will leave the A row and put nulls in B.id for all non-matching rows.
WITH a(id) AS (VALUES (1), (2), (3), (4), (5)),
     b(id) AS (VALUES (5), (6), (7), (8), (9))
SELECT *
FROM a
LEFT JOIN b ON a.id = b.id
WHERE b.id = 5;

WITH a(id) AS (VALUES (1), (2), (3), (4), (5)),
     b(id) AS (VALUES (5), (6), (7), (8), (9))
SELECT *
FROM a
LEFT JOIN b ON a.id = b.id AND b.id = 5;


text:
Q: sort floats in angularjs (ng-repeat) in Angular-DataTables I am using angularjs v1.4.0
I saw this topic  but the correct answer doesn't work for me.
$scope.dtColumnDefs = [
DTColumnDefBuilder.newColumnDef(6)
    .withOption('type', 'number')
    .renderWith(function(data, type, full) {
        if (type == 'sort') {
            var value = data.match();
            value = parseFloat(value[0]);
            return value.toString().length != data.length ? value+0.0001 : value;
        }
        return data
    })
];

If i use this code:

*

*My sort is for the first 3 digits.

*I can't use stoppropagation in the table.


text:
Q: only run javascript function after certain date I've got some code for a daily countdown timer which counts down to 12 noon every day. I want to exclude weekends which I've done like this:
if((t.total<=0) || (day === 0) || (day === 6)){
                clearInterval(timeinterval);
                document.getElementById('deadline_Container').style.display = "none";
            }
        }

However, I also need to do this for a certain date, so that the countdown won't show between 20.12. to 27.12. for example. Not sure how to do this for a specific date?
This is my whole code:

Hours

Minutes

Seconds

A: To check if one date is between two other, use bigger than and smaller than:
if(firstDate < actualDate && lastDate > actualDate){
    //your code
}

To check only one, you can use .getTime() or .valueOf() and compare them:
comparableDate.getTime() == actualDate.getTime()
comparableDate.valueOf() == actualDate.valueOf()

If you only need to compare the date(not the time) I think .setHours(hour, min, sec, milisec) would be helpful:
var dateWithoutTime = actualDate;
dateWithoutTime.setHours(0,0,0,0);

A: You could add an extended condition to check the day and the month:
const dayOfMonth = today.getDate();
const month = today.getMonth() + 1;
if ((t.total <= 0) || (day === 0) || (day === 6) || (dayOfMonth >= 20 && dayOfMonth <= 27 && month == 12)) {
    ...

The full code would be:

var today = new Date(new Date().getTime());
var deadline = new Date(Date.UTC(today.getFullYear(), today.getMonth(), today.getDate(), 11, 59, 59));

function time_remaining(endtime) {
  var t = endtime - new Date();
  var seconds = Math.floor((t / 1000) % 60);
  var minutes = Math.floor((t / 1000 / 60) % 60);
  var hours = Math.floor((t / (1000 * 60 * 60)) % 24);
  return {
    'total': t,
    'hours': hours,
    'minutes': minutes,
    'seconds': seconds
  };
}

function run_clock(id, endtime) {
  var clock = document.getElementById(id);
  if (null === clock) {
    return;
  }
  var hours_span = clock.querySelector('.hours');
  var minutes_span = clock.querySelector('.minutes');
  var seconds_span = clock.querySelector('.seconds');

  function update_clock() {
    var t = time_remaining(endtime);
    hours_span.innerHTML = ('0' + t.hours).slice(-2);
    minutes_span.innerHTML = ('0' + t.minutes).slice(-2);
    seconds_span.innerHTML = ('0' + t.seconds).slice(-2);
    day = today.getDay();
    const dayOfMonth = today.getDate();
    const month = today.getMonth() + 1;
    if ((t.total <= 0) || (day === 0) || (day === 6) || (dayOfMonth >= 20 && dayOfMonth <= 27 && month === 12)) {
      clearInterval(timeinterval);
      document.getElementById('deadline_Container').style.display = "none";
    }
  }
  update_clock();
  var timeinterval = setInterval(update_clock, 1000);
}
run_clock('clockdiv', deadline);


text:
Q: Rails JS delegation event triggering on load? I am trying to remove some value from session on click, but It seems like It gets triggered without clicking ( on reload ).
This is my code (coffee + erb):
  $(document).on "click", ".top-bar[data-chatbox-id='<%=chat.id%>'] .fa-times", (e) ->
    $box_position = $("div.chat_box[data-chatbox-id='<%=chat.id%>']").position().left
    $("div.chat_box[data-chatbox-id='<%=chat.id%>']").remove()

    ## ################### LINE BELOW IS THE ONE CAUSING PROBLEMS #######
    <% session[:chatrooms].delete(chat.id) %>

    chats = $('.chat_box')
    chats.each (index, element) =>
      if $(element).position().left < $box_position
        $(element).css( 'right', '-=' + 310 + 'px' )

After reloading session seems to get cleared - shouldn't it be triggered only on a click?
The only thing that comes to my mind is that: "If the selector is null or omitted, the event is always triggered when it reaches the selected element.", but I create the selected element earlier using:
$(document.body).append("<%= j render '/chatrooms/chatroom' %>")

A: That's because you are evaluating the session deletion in runtime and that's not what you wanna. You want to execute the deletion on click event.
In order to do that you can perform an Ajax request on click which calls the session deletion in a controller level.


text:
Q: Mongoose.findOne doesn't return anything, why? I need to return the search results from     Mongoose.findOne     to variable
results = Lang.findOne({page: params.page,lang: params.lang, param: params.param}, function(err, lang) {
  if( err || !lang) {
    console.log("No translation!");
  } else {
    return lang.trans;
  };
}

Is there a way to do this? I tried several hours to find a solution with async. functions and nothing ...
I also found articles where it was said that this is impossible, but is there any alternative for realize this?
It's really important to me because I need this to my multilingual project, I need to get the translation:
 res.render('index',{titleGen : req.__({page:'home', lang:req.locale, param:'hello'})});

A: Here is the solution:
exports.getLang = getLang = function(params,callback){

    console.log('received: '+params.page+' + '+params.lang+' + '+params.param);
    Lang.findOne({page: params.page, lang: params.lang, param: params.param},function(err, lang){
        if(err)
            console.log(err)
        else{
            callback(lang.trans);
        }
    });
}

and routing:
 router.get('/', function(req, res) {
    req.__({page:'home', lang:req.locale, param:'hello'},function(text){
        res.render('index',{titleGen : text });
    })
});


text:
Q: How to change the key which is inside an Object: JavaScript let object1 = { "hello" : [5, 12, 8, 130, 44], "hello1" : [7, 12, 8, 130, 44]};

const oldKey = "hello";
const newKey = "hello4;
const index = Object.keys(object1).findIndex(e => e === oldKey);
Object.keys(object1)[index] = newKey;

console.log(object1);

The key is not changing here for some reason.

A: Begin by setting new key value to old key
then delete the old key

const object1 = { "hello" : [5, 12, 8, 130, 44], "hello1" : [7, 12, 8, 130, 44]};

const oldKey = "hello";
const newKey = "hello4";
object1[newKey]=object1[oldKey];
delete object1[oldKey];

console.log(object1);

edit: now that you changed from const object1 to let object1 there is another way!!

let object1 = { "hello" : [5, 12, 8, 130, 44], "hello1" : [7, 12, 8, 130, 44]};

const oldKey = "hello";
const newKey = "hello4";
object1 = Object.fromEntries(Object.entries(object1).map(([k, v]) => [k === oldKey ? newKey : k, v]))
console.log(object1);


text:
Q: pasarela de pagos paypal sinceramente nunca he tenido que hacer una pasarela de pagos ni con paypal ni tarjeta ni nada de esto y no sé que hacer.
Estoy intentando hacer que en la web, tras seleccionar varios productos en una ventana, en la siguiente me aparecen los productos seleccionados con su cantidad correspondiente (tipo carrito de la compra) y el total a pagar y me dicen que el método de pago tiene que ser paypal.
He creado un botón de paypal el cual lo he insertado a la web, pero no sé cómo tendría que hacer para pasar el precio total de los productos seleccionados para comprar a la pasarela de pagos de paypal.
HTML del botón

Total Priceing:

            <input type="checkbox" id="aceptarCondiciones" name="aceptarCondiciones" onChange="comprobar(this)"> To continue, you must accept the conditions

          <form action="https://www.paypal.com/" method="post" target="_blank">
            <input type="hidden" name="cmd" value="_s-xclick">
            <input type="hidden" name="hosted_button_id" value="62NHHVTUB76D6">
            <input id="btn-submit" class="btn btn-info pos-btn" value="Submit Form" type="submit" border="0" name="submit" alt="Contratar" disabled>

            <button class="btn btn-secondary">Cancel</button>
          </form>

JQuery para sacar el Total
function sumar(valor) {
newvalor = parseFloat(valor); // Convertir el valor a un entero (número).

//Muestra el valor total de la suma de los precios de todas las especies
total = parseFloat(total) + newvalor;

// Colocar el resultado de la suma en el control "span".
document.getElementById('spTotal').innerHTML = total + " €";

}
Y lo que estoy intentando es pasar el valor de la variable total al paypal para que se realice el pago correspondiente, pero no sé cómo hacer para que cuando me envíe a PayPal me pase el valor del precio total.
Si me pudierais ayudar os lo agradecería.
Muchas gracias


text:
Q: What is wrong with the following code snippet? I'm currently trying out some of the code from the book called, "Programming Collective Intelligence", building a document classifier and I ran into this error cause by docclass.py. Can anyone tell me how to debug such problems?
def __init__(self,getfeatures,filename=None):
    self.fc={}
    self.cc={}
    self.getfeatures=getfeatures
def incf(self,f,cat):
    self.fc.setdefault(f,{})
    self.fc.setdefault(cat,0)
    self.fc[f][cat]+=1
def incc(self,cat):
    self.cc.setdefault(cat,0)
    self.cc[cat]+=1
def train(self,item,cat):
    features=self.getfeatures(item)
    for f in features:
        self.incf(f,cat)
    self.incc(cat)

I am getting the following error:
>>> import docclass
>>> c1=docclass.classifier(docclass.getwords)
>>> c1.train('the quick brown fox jumps over the lazy dog','good')

Traceback (most recent call last):
  File "<pyshell#32>", line 1, in <module>
    c1.train('the quick brown fox jumps over the lazy dog','good')
  File "docclass.py", line 36, in train
    self.incf(f,cat)
  File "docclass.py", line 17, in incf
    self.fc[f][cat]+=1
KeyError: 'good'

A: The KeyError exception is telling you that the dictionary has no such key:

Raised when a mapping (dictionary) key is not found in the set of existing keys.

Looking at the code, it appears that
self.fc.setdefault(cat,0)

should be
self.fc[f].setdefault(cat,0)


text:
Q: Windows 7 Installation progress bar in VB Winforms
As you can see the progress bar there, I am trying to create that same progress bar in VB WinForms. I was able to find an image of the blue bar line and just put it into a picturebox on the form, but I can't get the shiny thing to come out. You can see the exact animation here: http://www.youtube.com/watch?v=00nbQEvA1yg#t=10s
Any help is appreciated.

A: If you don't have a moving image type like gif or if you don't have a video version of loading animation, you simply have no way to get it moving properly. Only way would be creating a similar animation using DirectX or OpenGL from scratch or rendering a video of that and embedding it to your form, which are not simple at all.
Also you should not forget about copyright!


text:
Q: box all equations of align environment, but not the equation numbers I want to box (like \boxed{} of package amsmath or \Aboxed{} of package mathtools) the entire block of equations from an align (or eqnarray) environment, but not the equation labels. How can I do that? (I saw this in a book and thought that LaTeX should be able to do that too.)

A: Two options; the first one using the empheq package, and the second one using the interaction between empheq and tcolorbox for fancyer designs:

The code:
\documentclass{article}
\usepackage{amsmath}
\usepackage[many]{tcolorbox}
\usepackage{empheq}
\usetikzlibrary{shadows}

\tcbset{
  highlight math style={
    enhanced,
    colframe=red!60!black,
    colback=yellow!50,
    arc=4pt,
    boxrule=1pt,
    drop fuzzy shadow
  }
}

\begin{document}

\begin{empheq}[box=\fbox]{align}
a&=\sin(z)\\
E&=mc^2 + \int_a^b x\, dx
\end{empheq}

\begin{empheq}[box=\tcbhighmath]{align}
a&=\sin(z)\\
E&=mc^2 + \int_a^b x\, dx
\end{empheq}

\end{document}


text:
Q: Are the number of available web-domains limited? If there is a finite number of IPv4-addresses does that mean that there is also a finite number of web-domains ?

A: Each element of a domain name separated by [.] is called a "label".
The maximum length of each label is 63 characters, and a full
domain name can have a maximum of 253 characters.
Alphanumeric characters and hyphens can be used in labels,
but a domain name must not commence or end with a hyphen.
Further, uppercase and lowercase letters are treated as equivalent.
So, maximum of 252 characters, with at most 4 labels,
so at least 3 dots.
This gives as limit 26^250, which is rounded to :
5.5378x10^353.
A nice limit.

A: In a word no
The length of a DNS name is limited to 255 octets. There is this link which explains all that in reasonable detail.
So if you figure in the number of letters in the (English) alphabet along with numbers you end up with a near infinite number of DNS names. When you add in other languages you get even closer to Infinity... ;-)
Note that the number of IPv4 addresses has nothing to do with the "web domains." Also IPv4 has been superseded by IPv6 which has a lot more IP addresses available, by several orders of magnitude.
In other words web domains are just another way of saying DNS names and DNS names don't rely on IP addresses, they merely refer to them. The IP address can change and as long as the DNS record that points to a specific IP address reflects the change www.mydomain.com will still work just fine.


text:
Q: Share Content between Web and Mobile Website I am creating a mobile version of my website. It is nothing fancy, just a few pages. I would like to be able to share the content in both form, without having to update it in two places. Is the easiest way to do this with CSS? Or can I create some sort of XML or text file and read it in both sites?
Here is what I ended up using:
<!--[if IE]>
<link rel='stylesheet' href='ie.css' type='text/css' />
<![endif]-->
<link rel='stylesheet' media='screen and (max-device-width: 480px)' href='mobile.css' type='text/css' />
<link rel='stylesheet' media='screen and (min-device-width: 481px)' href='standard.css' type='text/css' />

<meta name="viewport" content="width=device-width; initial-scale=1.0; maximum-scale=1.0; user-scalable=0;"/>

This works for:
Windows IE 8,
Windows Firefox 3.6.7,
Mac Safari 5.0.2,
Mac Firefox 3.0.6,
iPhone 4 Safari,
Android Web Browser (Emulator)
You have to put everything in this order otherwise it will not work. You also have to make sure that the standard.css has all the same css attributes as the mobile.css. For instance, if in mobile you say #myitem { border:1px solid black; } but you do not want a border for #myitem in the standard view, you have to put #myitem { border:none; } inside standard.css, otherwise Mac Firefox will pickup the value from the mobile.css file and show a border on the item.

A: CSS is your best bet.
By using media queries you can decide which stylesheet to use to display your content.
 <link rel="stylesheet" media="screen and (min-device-width: 800px)" href="800.css" />
 <link rel='stylesheet' media='screen and (min-width: 701px) and (max-width: 900px)' href='css/medium.css' />

This link may help you: http://css-tricks.com/resolution-specific-stylesheets/

A: If you really want to share the entire content of the page and just have things positioned and styled differently, CSS is your best bet. If you want to serve a "mobile-optimized" version of the page, obviously CSS won't let you do much about that. In that case, there are a lot of options, such as storing the real meaty "content" in a database or static files and generating a page with the relevant data through PHP or equivalent, or do the same with a source XML file and generate the page through XSLT.


text:
Q: Populating django-taggit field with **kwargs / a string I have a custom command to populate Django objects with JSON data that is working mostly the way I want, but I'm having a problem with django-taggit fields. After parsing all of my data and outputting it in JSON, the genres look like this in my JSON objects:
"genres": "latin pop, pop, singer-songwriter",

django-taggit takes a comma-separated list of tags, which is what this is. But when I run the below custom command, nothing is put in the genres = TaggableManager() field from my model.
import json
import dateparser
from django.db import IntegrityError
from django.core.management.base import BaseCommand, CommandError
from concerts.models import Concert, Venue

class Command(BaseCommand):
    help = "Load JSON concert data"

    def add_arguments(self, parser):
        parser.add_argument('concert_file', type=str)

    def handle(self, *args, **options):
        with open(options['concert_file']) as f:
            data = json.load(f)
        for concert in data:
            try:
                venue = Venue.objects.get(name=concert['venue'])
            except Venue.DoesNotExist:
                print "Can't find venue! " + concert['venue']
                pass
            del concert['venue']
            try:
                Concert.objects.create(venue=venue, **concert)
            except IntegrityError:
                print concert['slug'] + ": This concert already exists!"
                pass
                # if the slug unique contrainst fails, just pass this concert

How can I get the genres field to populate the way I want?

A: Here's what I figured out in case anyone else ever runs into this problem:
class Command(BaseCommand):
help = "Load JSON concert data"

def add_arguments(self, parser):
    parser.add_argument('concert_file', type=str)

def handle(self, *args, **options):
    with open(options['concert_file']) as f:
        data = json.load(f)
    for concert in data:
        try:
            venue = Venue.objects.get(name=concert['venue'])
        except Venue.DoesNotExist:
            print "Can't find venue! " + concert['venue']
            pass
        del concert['venue']
        try:
            Concert.objects.create(venue=venue, **concert)
            print concert['slug'] + ": Concert created!"
        except IntegrityError: # if slug already exists
            print concert['slug'] + ": This slug already exists!"
            pass
            # if the slug unique contrainst fails, just pass this concert
        try:
            new_concert = Concert.objects.get(slug=concert['slug'])
            genres = concert['genres'].split(", ")
            for genre in genres:
                new_concert.genres.add(genre)
        except KeyError or AttributeError: # if no genres key exists
            pass

The answer, as you might expect, was in the docs. I checked out the django-taggit documentation, specifically on the API, and then adapted the standard tag adding in my last try/except statement above.
A bonus (for me) of this code is that even if the concert already exists, this code will update the genres field anyway.


text:
Q: Run System( ) CMD commands with Admin rights I'm trying to find a way to run CMD commands as Administrator in my C++ code.
i.e:
system("taskkill /im mygame.exe");

This won't work and it will pop up an "Error: Access Denied" Message.
If I run Windows CMD as Admin and execute the same command directly, it will work perfectly.
So what would be a way to use CMD as Administrator automatically in C++?
I've read some other threads on here but nothing I can directly relate/ get from them.
Examples are very appreciated.

A: The correct answer is to launch via a helper EXE manifested with requireAdministrator.
Your helper program reads:
#include <process.h>
int main(int argc, char **argv, char **env) {
    return _spawnve(_P_WAIT, argv[1], argv + 1, env);
}

You will not be able to start your own child process with CreateProcess or system(). You must start the helper program with:
ShellExecute(hwnd, "helper.exe", "whatever you were going to pass to system()", NULL, NULL, 0);

Where hwnd is some window you have (pass NULL if you have no visible window).
Ref1: How do I force my .NET application to run as administrator?
Ref2: https://msdn.microsoft.com/en-us/library/bb756929.aspx
Ref3: https://msdn.microsoft.com/en-us/library/windows/desktop/bb776886%28v=vs.85%29.aspx

A: The usual way would be to use runas:
system("runas /user:Administrator@domain \"taskkill /im mygame.exe\"");


text:
Q: Inserting data into table variable I want to know if it's possible to insert data into a table variable from a select query. When using a variable table before I have inserted the values and typed them myself.
I have come up with the following select query that displays the latest comment for a repair order. It returns 37 records and I wanted to know if it's possible to insert those into a variable table.
SELECT
    a.CH_REPREF, a.CH_DATE, a.CH_CRTIME,
    b.[Latest Customer Comment], a.CH_CRUSER, a.CH_CCOMMNT
FROM
   (SELECT
        CH_REPREF,
        MAX(CH_REPREF1) As [Latest Customer Comment]
    FROM
        dbo.V_CSRPCH
    WHERE
        CH_CCOMMNT IS NOT NULL
        AND CH_CCOMMNT NOT LIKE 'X'
    GROUP BY
        CH_REPREF) b,
   (SELECT
        CH_REPREF, CH_DATE, CH_CRTIME, CH_REPREF1,
        CH_CRUSER, CH_CCOMMNT, CH_ACCOUNT
    FROM
        dbo.V_CSRPCH) a
WHERE
    CH_REPREF1 = [Latest Customer Comment]
    AND CH_ACCOUNT = 'DDCHC'

I have started the table variable with the following, but am stuck whether it's possible to fill it with the data returned by the select query:
Declare @tbl_last_customer_comment TABLE
(CH_REPREF nvarchar(10),
CH_DATE smalldatetime,
CH_CRTIME nvarchar(8),
Latest int,
CH_CRUSER nvarchar(8),
CH_CCOMMNT text)

A: just do it as 'constant' table-
INSERT INTO @tbl_last_customer_comment
SELECT a.CH_REPREF, a.CH_DATE, a.CH_CRTIME,b.[Latest Customer Comment],a.CH_CRUSER,a.CH_CCOMMNT
FROM (SELECT CH_REPREF, MAX(CH_REPREF1) As [Latest Customer Comment]
FROM dbo.V_CSRPCH
WHERE CH_CCOMMNT IS Not Null AND CH_CCOMMNT Not Like 'X'
GROUP BY CH_REPREF) b,
(SELECT CH_REPREF, CH_DATE, CH_CRTIME,CH_REPREF1, CH_CRUSER, CH_CCOMMNT, CH_ACCOUNT
FROM dbo.V_CSRPCH) a
WHERE CH_REPREF1 = [Latest Customer Comment] AND CH_ACCOUNT = 'DDCHC'


text:
Q: Problema con una lista en soap web service java estoy haciendo una aplicación que implementa Soap WebService en jDeveloper, la cuestión es que necesito listar en un jTable la información de una tabla llamada Pacientes alojada en mi base de datos, para esto tengo una aplicación para el servidor y otra para el cliente. en la del servidor tengo el siguiente método para listar:
public static List listar(){
           List<Paciente> listaPaciente = new ArrayList<>();
            String sql = "select * from paciente";

            try {
                con = conectar.getConnection();

                ps = con.prepareStatement(sql);
                rs = ps.executeQuery();
                while(rs.next())
                {
                    Paciente p = new Paciente();
                    p.setId(rs.getInt(1));
                    p.setDocumento(rs.getString(2));
                    p.setNombre(rs.getString(3));
                    p.setCorreo(rs.getString(4));
                    p.setTelefono(rs.getString(5));
                    p.setGenero(rs.getString(6));
                    listaPaceinte.add(p);
                }
            } catch (Exception e) {

            }

            return listaPaciente;

            }

en la aplicación cliente simplemente implemento el wsdl y se me generan todos los metodos alojados en mi servidor, pero a la hora de llamar el metodo listar tengo el siguiente incoveniente.
 public void listarPacientes()
    {
       DafaultTableModel modelo = (DefaultTableModel)guiListarP.jTablePacientes.getModel();

              // ACA ES EL ERROR
              List<Paciente> lista =  pacienteSW.listar();

               Object[]object = new Object[5];
               for(int i = 0; i < lista.size(); i++)
               {
                   object[0] = lista.get(i).getDocumento();
                   object[1] = lista.get(i).getNombre();
                   object[2] = lista.get(i).getCorreo();
                   object[3] = lista.get(i).getTelefono();
                   object[4] = lista.get(i).getGenero();
                   modelo.addRow(object);
               }

               //guiL.jTableListar.setModel(modelo);
                //modelo.fireTableDataChanged();

    }

me dice que Error(144,61): incompatible types: java.util.List<java.lang.Object> cannot be converted to java.util.ArrayList<serviciosweb.Paciente>
sericiosweb es el paquete que se me genero automáticamente al implementar el servidor en mi cliente, al igual que pacienteSW.
clase a la cual pertenece pacienteSW
package serviciosweb;

import java.util.List;

import javax.jws.Oneway;
import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.jws.WebResult;
import javax.jws.WebService;

import javax.xml.bind.annotation.XmlSeeAlso;
import javax.xml.ws.Action;
import javax.xml.ws.RequestWrapper;
import javax.xml.ws.ResponseWrapper;

/**
 * This class was generated by the JAX-WS RI.
 * JAX-WS RI 2.3.0-b170214.1743
 * Generated source version: 2.2
 *
 */
@WebService(name = "PacienteSW", targetNamespace = "http://serviciosWeb/")
@XmlSeeAlso({ ObjectFactory.class })
public interface PacienteSW {

    /**
     *
     * @param arg0
     * @return
     *     returns int
     */
    @WebMethod
    @WebResult(targetNamespace = "")
    @RequestWrapper(localName = "agregarPaciente", targetNamespace = "http://serviciosWeb/",
                    className = "serviciosweb.AgregarPaciente")
    @ResponseWrapper(localName = "agregarPacienteResponse", targetNamespace = "http://serviciosWeb/",
                     className = "serviciosweb.AgregarPacienteResponse")
    @Action(input = "http://serviciosWeb/PacienteSW/agregarPacienteRequest",
            output = "http://serviciosWeb/PacienteSW/agregarPacienteResponse")
    public int agregarPaciente(@WebParam(name = "arg0", targetNamespace = "") Paciente arg0);

    /**
     *
     * @param arg1
     * @param arg0
     * @return
     *     returns int
     */
    @WebMethod
    @WebResult(targetNamespace = "")
    @RequestWrapper(localName = "modificarPaciente", targetNamespace = "http://serviciosWeb/",
                    className = "serviciosweb.ModificarPaciente")
    @ResponseWrapper(localName = "modificarPacienteResponse", targetNamespace = "http://serviciosWeb/",
                     className = "serviciosweb.ModificarPacienteResponse")
    @Action(input = "http://serviciosWeb/PacienteSW/modificarPacienteRequest",
            output = "http://serviciosWeb/PacienteSW/modificarPacienteResponse")
    public int modificarPaciente(@WebParam(name = "arg0", targetNamespace = "") Paciente arg0,
                                 @WebParam(name = "arg1", targetNamespace = "") String arg1);

    /**
     *
     * @param arg0
     * @return
     *     returns serviciosweb.Paciente
     */
    @WebMethod
    @WebResult(targetNamespace = "")
    @RequestWrapper(localName = "buscarPaciente", targetNamespace = "http://serviciosWeb/",
                    className = "serviciosweb.BuscarPaciente")
    @ResponseWrapper(localName = "buscarPacienteResponse", targetNamespace = "http://serviciosWeb/",
                     className = "serviciosweb.BuscarPacienteResponse")
    @Action(input = "http://serviciosWeb/PacienteSW/buscarPacienteRequest",
            output = "http://serviciosWeb/PacienteSW/buscarPacienteResponse")
    public Paciente buscarPaciente(@WebParam(name = "arg0", targetNamespace = "") String arg0);

    /**
     *
     * @param arg0
     */
    @WebMethod
    @Oneway
    @RequestWrapper(localName = "eliminarPaciente", targetNamespace = "http://serviciosWeb/",
                    className = "serviciosweb.EliminarPaciente")
    @Action(input = "http://serviciosWeb/PacienteSW/eliminarPaciente")
    public void eliminarPaciente(@WebParam(name = "arg0", targetNamespace = "") String arg0);

    /**
     *
     * @return
     *     returns java.util.List<java.lang.Object>
     */
    @WebMethod
    @WebResult(targetNamespace = "")
    @RequestWrapper(localName = "listar", targetNamespace = "http://serviciosWeb/", className = "serviciosweb.Listar")
    @ResponseWrapper(localName = "listarResponse", targetNamespace = "http://serviciosWeb/",
                     className = "serviciosweb.ListarResponse")
    @Action(input = "http://serviciosWeb/PacienteSW/listarRequest",
            output = "http://serviciosWeb/PacienteSW/listarResponse")
    public List<Object> listar();

}

Espero me puedan ayudar, Gracias.


text:
Q: MySQL: Best way to handle user balance? Short question:
What's the best way to handle user balance and user transactions?
I'd probably create a transaction table where I'd log every transaction and then select over it to get the actual user balance. But wouldn't that be slow after thousand of transactions by the same user? Would a view speed the things up?
Or should I store the user balance in the user table and update it with a mysql transaction while I'm inserting in the transactions table?
Dont't panic. I"m not planing to handle real money.

A: Yes, calculating the balance on the fly from all the transactions would be quite slow; a view would make queries easier to write, but won't have much impact on performance (a view is just a shorthand, it's not an actual table).
You should go with the second method: put the current balance in the account or user table, separate from all the transactions, and update it whenever you add a transaction.

A: You can use triggers for this.  Whenever new record is added to transactions table, trigger updates users table.


text:
Q: "pruning file" - is that my compiler or GNU Make? A target in my makefile looks like this:
.moc/moc_plmviewsetup.cpp: C:/Users/User1/Desktop/A/PROJ/src/PasaHmiExtension/pasahmiextension_global.h \
        C:/Users/User1/Desktop/A/PROJ/qt5binaries/include/QtCore/qglobal.h \
        C:/Users/User1/Desktop/A/QNX_SDK/target/qnx6/usr/include/stddef.h \
        ...

And the output of GNU make is:
  Considering target file '.obj/moc_plmviewsetup.o'.
   File '.obj/moc_plmviewsetup.o' does not exist.
    Considering target file '.moc/moc_plmviewsetup.cpp'.
     File '.moc/moc_plmviewsetup.cpp' does not exist.
      Pruning file 'C:/Users/mureadr/Desktop/A/HMI_FORGF/src/PasaHmiExtension/pasahmiextension_global.h'.
      Pruning file 'C:/Users/mureadr/Desktop/A/HMI_FORGF/qt5binaries/include/QtCore/qglobal.h'.
      Pruning file 'C:/Users/mureadr/Desktop/A/QNX_SDK/target/qnx6/usr/include/stddef.h'.
      ...

*

*What does pruning mean?

*What is doing it: my compiler or GNU make?

*Why does pruning occurr?

*What is the relevance of pruning happening?

A: Answer from GNU Make mailing lists, posted by @djthoms:

On Tue, 2007-05-01 at 08:41 -0700, Hiebert, Darren (MS) wrote:

What are the reasons that dependencies are pruned when evaluating
    whether to build a target?

Hi Darren;
Pruning happens when make thinks that it has already evaluated those
  targets and determined that they are not rebuildable, AND make has not
  run any rules so that their state could be changed since they were
  last examined.  It's a way to short-circuit what can be a long,
  complex computation.
Without seeing your makefile it's hard to tell why your targets might
  be considered prunable when they shouldn't be.


text:
Q: AtrributeError: 'NoneType' object has no attribute 'data' & TypeError: 'str' object is not callable I am trying to get weather information from a town, and have 2 items print out from that list. However, when i try to run the code, I get this error:
Traceback (most recent call last):
    File "/home/pi/Desktop/python/PyWeather.py" line 4, in <module>
        bostonweather = pywapi.get_weather_from_weather_com('UKXX1701', units = 'metric')
    File "/home/pi/Desktop/python/pywapi.py" line 239, in get_weather_from_weather_com
        'wind')[0].getElementsByTagName(tag2)[0].firstChild.data
AtrributeError: 'NoneType' object has no attribute 'data'

This is my code:
import pywapi
import string

bostonweather = pywapi.get_weather_from_weather_com('UKXX1701', 'metric')
print ("In Boston, Lincolnshire it is currently: ") + string.ascii_lowercase(bostonweather['current_conditions']['text'] + (" and ") + string.ascii_lowercase(bostonweather['current_conditions']['temperature'] + ("C.\n"))

//EDIT
I've just reran my program and it just threw a "TypeError: 'str' object is not callable" error instead.
Error message:
Traceback (most recent call last):
    File "/home/pi/Desktop/python/PyWeather.py" line 5, in <module>
       print ("In Boston, Lincolnshire it is currently: ") + string.ascii_lowercase(bostonweather['current_conditions']['text'] + (" and ") + string.ascii_lowercase(bostonweather['current_conditions']['temperature'] + ("C.\n"))
TypeError: 'str' object is not callable

Any clue on what to do?

A: You're trying to call string.lowercase(blabla) and that's where you get TypeError
You should do
print "In Boston, Lincolnshire it is currently: " + bostonweather['current_conditions']['text'].lower() + " and " + bostonweather['current_conditions']['temperature'].lower() + ("C.\n")

A: Try to make all strings before you print
import pywapi

bostonweather = pywapi.get_weather_from_weather_com('UKXX1701', 'metric')
print ("In Boston, Lincolnshire it is currently: " + str(bostonweather['current_conditions']['text']).lower() + " and " + str(bostonweather['current_conditions']['temperature']).lower())


text:
Q: How to create a nested object JSON in arduino i'm doing with nrf24l01 network. i want to storage value from sensor node ( like id, value temp, value humid) in JSON string like this one.
my string:
{
    "1": {//this is a ID from node
            "Temp": "value",
            "Humid": "value"
        },
    "2": {
         "Temp": "value",
         "Humid": "value"
     }
}

i can create a object and add value from temp and humid, but i dont know how to create "1" /* ID /*
My code
void loop()
{
  network.update();
  if(network.available())
  {
    RF24NetworkHeader header;
    network.read(header, &pack0, sizeof(pack0));
    if (header.from_node == 1)//this is the ID , return 1, 2, ....
    {
      object["ID"] = header.from_node;
      value["Temperature"] = pack0.temperature;
      value["Humidity"] = pack0.humidity;
      value["Soil"] = pack0.soil;
      serializeJsonPretty(object, Serial);
      Serial.println("");    }
    else if (header.from_node == 2)
    {
      object["ID"] = header.from_node;
      value["Temperature"] = pack0.temperature;
      value["Humidity"] = pack0.humidity;
      value["Soil"] = pack0.soil;
      serializeJsonPretty(object, Serial);
      Serial.println("");
    }
  }
}

A: You can use createnestedobject, also remember that you are creating nested json objects in a loop so you need to take care of the size of your Json document (256).
EDIT: For example when your nested object exceeds a fixed value, You can use clear() function to clear the JSON object.
#define MAX_ELEMENTS 10

int receive_count = 0;
StaticJsonDocument<256> doc;
JsonObject object = doc.to<JsonObject>();

void loop()
{
    network.update();
    if (network.available())
    {
        RF24NetworkHeader header;
        network.read(header, &pack0, sizeof(pack0));
        if (header.from_node)
        {
            JsonObject ID = object.createNestedObject(String(header.from_node));
            ID["Temperature"] = pack0.temperature;
            ID["Humidity"] = pack0.humidity;
            ID["Soil"] = pack0.soil;
            serializeJsonPretty(object, Serial);
            Serial.println("");
            receive_count++;
            //reset counter if reached and clear object
            if (receive_count >= MAX_ELEMENTS)
            {
                doc.clear();
                object = doc.to<JsonObject>();
                receive_count = 0;
            }
        }
    }
}


text:
Q: MySQL: which default collation should I set to cover all european characters? I noticed that my schema can't print some strings with regional characters, such as è, ù and other accents or symbols.
The manager app is a Java servlet, it has no such problems. It uses the jdbc driver.  So I thought the cause could be this default collation: utf8 - utf8_general_ci.
After a research I discovered that these characters can't be saved within the utf8 bytes.
Should I use utf8-mb4, utf-16, utf-32 or another?  Which is the minimal best one to support all european chars (no cyrillic, arabic and asian)?
For example, this chosen answer suggest utf8mb4_unicode, but I don't see if it's really the minimal best to cover all the characters I need.
What's the difference between utf8_general_ci and utf8_unicode_ci

A: One should use CHARACTER SET utf8 or utf8mb4 for the encoding.  utf8 covers all of Europe and most of the rest of the world.  utf8mb4 covers all the worlds languages. utf8 is a subset of utf8mb4.
One can use different COLLATIONs depending on the ordering you desire.  Spanish, for example, (with utf8_spanish2_ci or utf8mb4_spanish2_ci) plays games with ll that other languages do not.  utf8_latvian_ci treats Ķ as a different character than K; others do not.
If you are not worrying about detailed language differences, then I recommend ..._general_ci or ..._unicode_ci or ..._unicode_520_ci if you have the latest version of MySQL.  These three collations primarily differ as follows:

*

*general:  Only one character is tested for comparisons.  This does not allow for ll to be treated as a separate letter.  This one is slighty faster.

*unicode:  This is derived from an older Unicode standard.  This handles "combining" accents 'correctly'.

*unicode_520:  This is based on a newer standard.  Emojis are treated as distinct.

*unicode_...:  More may come in later versions of MySQL.

It does not matter what your application does, however, you must

*

*Tell MySQL what encoding the client has: ?useUnicode=yes&characterEncoding=UTF-8

*Establish CHARACTER SET utf8 (or utf8mb4) on each column or table.

*If you are using web pages, set charset=UTF-8 in the meta tag.


text:
Q: How can I run Linux and/or Windows on my Mac without Boot Camp or breaking these rules? I would like to run Windows (XP preferred) games and Linux on my MacBook Pro I got from school. However, there are some rules I have to follow. If I need to I will try to further clarify the rules, since they are in Swedish and there isn't a perfect translation.

*

*I cannot use Boot Camp. This is because Windows machines get viruses 24/7 and there are no viruses on Mac. Furthermore, we are using Visual Studio for about half the things we do through a virtual machine. Perfect for debugging, performance and "virtual machines don't get viruses", right? At least that's what my teachers think.

*I cannot change the default setup of the computer. In Swedish this basically tells me I cannot even start it up because then I will mount the drive, and make changes in RAM, and use the processor, and move electrodes from the battery and so on. They're telling me that that's way to specific, though, and that we aren't allowed to change the operating system files. I think we break that rule with each update, install or setting we ever touch.

*I may not use any program without first showing a receipt. The original casing, CD and the CD key isn't enough. A license like GNU is ok, though.
I basically need a way to boot into a USB drive or CD, with the ability to use network and DX9 to play games on Windows. Linux support isn't as crucial since OS X does have a lot of Linux support already. I've tried other ways of working around the rules like running games in Wine but I can't get DX9 based games to work and the FPS is terrible.
They have the right to check the computer at any time to see if there is something bad there. Swapping a harddrive will definately be noticed.

A: What are the penalties you get from not following these rules? This sounds way too strict.

This is because Windows machines get viruses 24/7

This is factually wrong. If you pay attention to which websites you visit and which files you open, you won't get a virus, ever. There are people who run their systems without anti-virus software and they do just fine.

and there are no viruses on Mac

This is also wrong. While the chance to get infected might be lower, there are viruses for OS X, yet less common.

You have to run a native system in order to run games or anything that needs performance. While you can theoretically boot from a removable disk and use that, you will most probably see even worse performance than on a virtualized instance.
Currently I see the following ways for you:

*

*Break the rules: Get another hard disk, use this for whatever you want to do, and keep the original. Swapping hard disks is nothing that would void the warranty (I guess) maybe not that easy (depends on the model). It depends on how often you might have to change it. And because you're breaking the rules, it's your risk if something happens.

*Try it in a virtual machine, try different software (VMware, VirtualBox, Parallels), maybe some provide better performance.

*Make a clone of your original hard disk using Clonezilla or Carbon Copy Cloner. Then, setup your system the way you want it. If you need to, you can restore from the Clonezilla backup. There will be no evidence of you changing the system.

A: I don't think there's actually any way to do this without breaking rule #3 at least, since presumably your Linux disro won't have a recept.
Anyway, your options for being undetectable are: boot off a USB(/Firewire/eSATA?) drive, make a complete image of the drive and then install the new OS, then copy the image back when you're finished, or use a VM.
The first option is probably best, since the only performance penalty is likely to be longer load times. Swapping drive images might be more time-consuming (would probably take the best part of an hour each time). The VM solution won't generally work for games, or at least newer ones, since they usually require direct access to the graphics hardware (there is some basic OpenGL support in VirtualBox, at least enough to run Unreal Tournament 2004 reasonably playably, and I've heard that some DirectX support exists too, but I haven't tested it); the same goes for VMware.

A: Without knowing exactly what you'll need to do on it, Id think a virtual machine is about the only way to run Windows XP without using Bootcamp on a Mac.
VMWare and Parallels allow you to easily run Windows with some decent performance and keep it quarantined within the VM. VirtualBox is a free alternative but I dont think it has quite the features or performance benefits of the other two. Do you need a receipt for free software?
What if you just use remote desktop and login and screen share with an actual PC? Or another alternative, you can boot Ubuntu with a thumb drive. Ill bet someone has found a way to do that on a mac.
There seems to be an awful lot of misinformation coming from your teacher so I'd suggest you not take their ideas as the only options. I dont get the reason for developing for Windows on a Mac. That makes no sense to me. You can develop almost any code natively so why even run Visual Studio. Just use an IDE like Eclipse with C#.


text:
Q: How to create a flow or apex to check if an agent is available that I can call as an action in Einstein Chat Bot I'm a new junior developer/admin (six months) and I am lost. I am building Einstein bot for the first time.
The scenario is if there are no agents online then customers will be able to create a case. I have that set-up for three dialogue using the standard No Agent dialogue in Einstein bot but I have a fourth dialogue where if there are no agents available then customers can either create a case or request for a callback. (It will create a case that has the highest level priority in the queue so  Agents will be able to call that customer)
I can't reference the default No Agent dialogue box which checks if there are agents online then redirects them to create a case because I need to attach another option for a callback.
So I need to set-up a new dialogue that will act as a No Agent Dialogue for the callback which means I need to be able to check if agents are online or not. Which means I need to create either a Flow or Apex that I can call to check if there agents available and I am stumped.
I've been trying to research this for hours but I haven't seen any documentation for this.
Does anyone have any suggestions or resources I can check out so I can solve this one? I could really use some advice.

A: I tried to implement the Apex solution of this article https://org62.my.salesforce.com/sfc/p/#000000000062/a/0M000000B9UO/Ye2gB_LiNeo.BaVh16aU0tzEAyAkFNUNzsjPLSm21J4
But I am getting an error on the Class 'CookbookBot_CheckAgentAvailability'
The error "Method does not exist or incorrect signature: void getButtonAvailabilityForTransfer(String, String) from the type CookbookBot_REST_Utils "
Could someone please help me out?
I wonder if there any any solution in flow as well
Thanks a lot

A: It may be late, but this link its helpfull
https://org62.my.salesforce.com/sfc/p/#000000000062/a/0M000000B9UO/Ye2gB_LiNeo.BaVh16aU0tzEAyAkFNUNzsjPLSm21J4


text:
Q: Custom Tab Widget Plugin Creation for Qt designer We're building a custom tab widget for our project and I'm creating a Designer plugin for it.  I'm having trouble getting the same functionality as the standard tab widget.
I'd like to have our widget mimic the same behavior to:
1) allow changing tab inside of designer by clicking the tabs
2) show "browned out" properties (e.g., if no tabs are on the widget)
I've created a collection and property extension for the widget, and I've got it to add/insert/delete tabs, but I haven't been able to find out how to do these two things.
Is the source code for the tab widget plugin available somewhere?  Or does anyone know how which methods to attach to the widget from designer to do this?

A: I found the Designer source under the QtSDK folder and located the piece that appears to deal with clicks.  it looks like what they do is when the plugin creates the widget they attach an event handler to the widget using installEventFilter().
The handler then checks for left mouse clicks and sends a command to designer to set the currentIndex property to the correct value.
The source to check it out is in qdesigner_tabwidget.cpp.


text:
Q: ASP.NET MVC : Attends / Likes Post I have an Event with info about it on a Display Event View. On that view, I am trying to to make Attend functuality, similar to Liking, but I have little problems. My logic is very simple and I would like to keep it so:  on click, it will increase int Attends by 1, but ...
First-I am getting inside the if(events==null)... And second is there a way to make it clickable once per User?
Here is my code:
Model:
    [Key]
    public int Id { get; set; }
    public string EventName { get; set; }
    ...
    public int Attends { get; set; }

Event Create Action:
    //POST: Event/Create
    [HttpPost]
    public ActionResult Create(EventViewModel model)
    {
        if (ModelState.IsValid)
        {
          using (var database = new EventSpotDbContext())
            {
              var events = new Event(model.EventName,...);
                ...
                events.Attends = 0;
                database.Events.Add(events);
                database.SaveChanges();
                return RedirectToAction("Main");
            }
        }
        return View(model);
    }

Event Attend Action:
 public ActionResult Attend(int? id)
    {
        using (var database = new EventSpotDbContext())
        {
            var events = database.Events.FirstOrDefault(a => a.Id == id);
            if (events == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            events.Attends += 1;
            database.SaveChanges();
        }
        return RedirectToAction("Details");
    }

Event Details Action:
    //GET: Event/Details
    public ActionResult Details(int? id)
    {
         using (var database = new EventSpotDbContext())
        {
           var events = ...   .First();
           return View(events);
        }
    }

Details View
            @model EventSpot.Models.Event
            ...
            @Html.ActionLink("Attend Event", "Attend", "EventController", new {@id=Model.Id} )
            @Model.Attends

A: @Html.ActionLink("Attend Event", "Attend", "EventController", new {@id=Model.Id}, null )

the isse that he was dealing with {@id=Model.Id} as html attributes not route attributes


text:
Q: Loading data from a text file into a DataGridView and saving 1) How can I get a specific string from a text file to call back to datagrid
I would like the format to be identical to this:
ronald fernando banker's village philippines 8460999
jeniffer corpuz bulacan,pandacan philippines 8460564

I only want the strings:
phillippines and 8460999
bulacan,pandacan 8460564

to be added to a specific point on a DataGridView
2) Would I put all of these values onto different rows?
3) Is it possible to append these to a text file?
so the text files already had this
John Cruz
Manila, Philippines
18
june 28, 1990

and add this additional data string
Mary Rose Hanford
Manila, Philippines
25
march 27, 1999

A: You could use the String.Format method.
See the MSDN here: http://msdn.microsoft.com/en-us/library/fht0f5be(v=vs.80).aspx


text:
Q: No ZF2 como setar um valor em um Zend\Form\Element\Text na view? O Form:
$this->add(array(
            'name' => 'valor',
            'type' => 'Text',
            'attributes' => array(
                    'required' => true,
                    'class' => 'form-control',
                    'maxlength' => '100'
            ),
            'options' => array(
                          'value' => 10, //Coloquei este valor de propósito
            )
    ));

A view:
$form->get('valor')

print_r() do form de valor:
Zend\Form\Element\Text Object (
  [attributes:protected] => Array (
        [type] => text
        [name] => valor
        [required] => 1
        [class] => form-control [maxlength] => 100
   )
   [label:protected] => [labelAttributes:protected] => Array ()
   [labelOptions:protected] => Array ( )
   [messages:protected] => Array ( )
   [options:protected] => Array ( [value] => 10 ) [value:protected] =>
   )

?

A: Você deve definir este valor no controller:
$form->setData(['valor' => 'meu valor']);
E, apesar de ser uma gambiarra, você pode utilizar este código acima antes do $form->prepare na view.
Caso você queira definir um valor padrão, em vez de colocar o 'value' dentro do options, coloque dentro dos atributos:
$this->add(array(
    'name' => 'valor',
    'type' => 'Text',
    'attributes' => array(
        'required' => true,
        'class' => 'form-control',
        'maxlength' => '100',
        'value' => 10
    ),
    'options' => array(
    )
));


text:
Q: How to add missing months to a column of a data frame? I have a dataframe with a "month" column that has a number in it but I'm missing all the other months of the year because they have 0 data in it.
So I would like to have all the months of the year and put 0 to the months that have no data.
Here is an example of my data frame:

(I have a "yearmonth" column (2015 jui -2022 mai) & "month" column  & "year" column & an "n" column.)
Can you help me ? Thanks in advance!

A: If you have set your locale to French (using Sys.setlocale()) this will output the completed dataframe, with the month-names in French, using complete from tidyverse:
# copy of the data -----------------------
df <- structure(list(yearmonth = c("2015 jui", "2015 aoû", "2015 sep",
"2015 nov", "2015 déc", "2016 fév", "2016 mar", "2016 avr",
"2016 jul", "2016 aoû", "2016 oct", "2016 nov", "2017 fév",
"2017 jui", "2017 jul", "2017 aoû", "2017 nov", "2017 déc",
"2018 avr", "2018 mai", "2018 aoû", "2018 sep", "2019 jan",
"2019 fév", "2019 mar", "2019 jul", "2019 aoû", "2019 sep"),
month = c(6, 8, 9, 11, 12, 2, 3, 4, 7, 8, 10, 11, 2, 6, 7,
8, 11, 12, 4, 5, 8, 9, 1, 2, 3, 7, 8, 9), year = c(2015,
2015, 2015, 2015, 2015, 2016, 2016, 2016, 2016, 2016, 2016,
2016, 2017, 2017, 2017, 2017, 2017, 2017, 2018, 2018, 2018,
2018, 2019, 2019, 2019, 2019, 2019, 2019), n = c(1, 2, 1,
1, 1, 1, 1, 1, 1, 1, 3, 1, 1, 1, 1, 2, 2, 1, 1, 1, 2, 1,
1, 3, 3, 1, 1, 1)), row.names = c(NA, -28L), class = "data.frame")

# answer ----------------------------------
library(tidyverse)

df %>% complete(year = 2015:2019, month = 1:12, fill = list(n = 0)) %>%
  mutate(date = as.Date(paste(year, month, "01", sep = "-")),
         yearmonth = format(date, format = "%Y %b")) %>%
  filter(between(date, as.Date("2015-06-01"), as.Date("2022-05-01"))) %>%
  select(-date)

#> # A tibble: 55 × 4
#>     year month yearmonth     n
#>    <dbl> <dbl> <chr>     <dbl>
#>  1  2015     6 2015 Jun      1
#>  2  2015     7 2015 Jul      0
#>  3  2015     8 2015 Aug      2
#>  4  2015     9 2015 Sep      1
#>  5  2015    10 2015 Oct      0
#>  6  2015    11 2015 Nov      1
#>  7  2015    12 2015 Dec      1
#>  8  2016     1 2016 Jan      0
#>  9  2016     2 2016 Feb      1
#> 10  2016     3 2016 Mar      1
#> # … with 45 more rows

Created on 2022-06-19 by the reprex package (v2.0.1)


text:
Q: Install issue screen is balck I tried installing ubuntu 15. On my Lenovo pc but when I click install in the grub menu the screen just goes black.

A: I had something similar some years back with an Acer laptop. It came back to a hardware driver issue and I had to go to another screen, (by holding down ctrl-alt and pressing F1, F2, F3 or whatever), to find out what it was and stop the process to continue the installation.
Might be worth checking unless someone else knows better.


text:
Q: How can I dynamically use useReducer (or another alternative) in order to prevent writing multiple, repetitive lines of code? I am writing a program so that a business can display their services, as well as set the prices for each, according to size of item. At the 'Options' component, I am using a useReducer (where I imagine I'll have to create hundreds of 'cases' inside of the useReducer, named after each service). At the 'Service' component, I am using a Formik form to be able to save the values passed to each 'Service'.
This is the 'Options' component, with a userReducer to set prices. Loops over a list of hundreds of services to render hundreds of 'Service' components
const reducer = (state, action) => {
    switch (action.type) {
      case 'SET_SMALL_PRICE': //do I have to create hundreds of these with different ids for each?
        return {
          ...state,
          smallPrice: action.payload,
        }
      default:
        return state
    }
  }

//really long list that will be looped over
serviceList.map(item => (

//do I have to pass hundreds of values here,
//one for each of the hundreds of 'Service'?
  <Context.Provider value={{ smallPrice, bigPrice }}>
    <Service
       key={service.id}
       id={service.id}
       name={service.name}
    />)
  <Context.Provider />

'Service' component. There will be hundreds of these, and they each need to have prices set separetely (smallPrice, smallPrice2, smallPrice3 ... ?)
//In case I would pass down hundreds of items through context
//in the other component, I thought of passing each an ID
//and then destructure these conditionally
//like `smallPrice${props.id}`. Doesn't work unfortunately.
const { smallPrice } = useContext(Context)

<Formik
   initialValues={{

//gets this value through Context. also would have
//to have ids added conditionally (through props, perhaps)
     smallPrice: smallPrice, //smallPrice1, smallPrice2 ?
   }}
   onSubmit={(values, { setSubmitting }) => {

//e.g SET_SMALL_PRICE_3 perhaps?
       dispatch({ type: 'SET_SMALL_PRICE', payload: values.smallPrice,})
            setTimeout(() => {
              setSubmitting(false)
            }, 400)
   }}>
       <Form>

//also change the name here so that it won't affect a different service
         <Field name="smallPrice" type="text" />
       </Form>
<Formik/>


text:
Q: Displaying non Roman characters in Ubuntu Touch Not sure whether someone already asked this question before, but I failed to get any in AskUbuntu search and on google search.
I bought a Ubuntu Edition Meizu phone recently. But it is not displaying UTF-8 (non English, non European) characters. It looks more like an Ubuntu phone specific issue, as displaying characters for different languages failed from multiple apps (webbrowser and dekko were tested so far). I couldn't find any specific instruction on how to resolve the issue.
So would really appreciate if someone can help me displaying non-Roman characters on Ubuntu Touch.

A: Okay, the goal is to get additional fonts into the ~/.fonts directory.
For example, the fonts from the ttf-indic-fonts-core package (http://packages.ubuntu.com/vivid/ttf-indic-fonts-core).
Install the Terminal app on the phone or connect to the phone via ssh or adb.
Create the ~/.fonts directory:
mkdir -p ~/.fonts

Get the package (select other mirror from http://packages.ubuntu.com/vivid/ttf-indic-fonts-core if necessary):
wget http://de.archive.ubuntu.com/ubuntu/pool/main/t/ttf-indic-fonts/ttf-indic-fonts-core_0.5.14ubuntu1_all.deb

Extract the package into temporary ttf directory:
dpkg -x ttf-indic-fonts-core_0.5.14ubuntu1_all.deb ~/ttf

Move fonts into ~/.fonts:
mv ~/ttf/usr/share/fonts/truetype/ ~/.fonts

Remove temporary directory:
rm -r ~/ttf

Close and reopen the browser.
Tested in web browser on BQ phone with text তূহীন; તૂહીન; തൂഹീന; తూహీన; ತೂಹೀನ; தூஹீந. But for this one: ਤੂਹੀਨ, there is some other package needed.
(to figure out which package, I use Ubuntu desktop and gradually remove font packages until Firefox stops rendering the desirable text)


text:
Q: How to use npm packages as ES6 modules loaded by the browser in 2021? I'm a JavaScript beginner. I do not use a "bundler".
For a few days now I've been trying to use moment.js and other date-time libraries in some JavaScript by importing it using ES6 modules (ESM).
I have a JS module I wrote, which is transpiled from TS, and that has this line:
import moment from "../lib/moment/src/moment.js"

My module is itself loaded via an import from a <script type="module" > tag, which works.
I've discovered that the moment package contains what looks like "source" code in its src folder which seems to look more like the JS/TS I'm accustomed to, and has a "default export" at the bottom.
So I'm referencing that "source" version in my transpiled JS module. This gets me past a couple of errors I was getting:

The requested module 'blah' does not provide an export named 'default'

And

Cannot set property 'moment' of undefined (at moment.js:10)

And leaves me stuck with loading the other modules its dependent upon, because I guess, their file extensions are missing.

GET https://blah/lib/moment/src/lib/locale/locale net::ERR_ABORTED 404 (moment.js:37)

After 3 days tearing my hair out I feel like I have been fighting a battle I shouldn't be attempting at all.
I would expect in 2021, what with widespread ESM browser support, that this would just work, but I've tried 5 different date-time libraries and had no success.
I assume the 404s have occurred because the moment authors are NOT expecting people to be using their library like this, so they left off the file extensions knowing full well that it wouldn't load in a browser??
Am I supposed to add an extra step in my client-side build process, Gulp, to add the extensions back on in the moment source code??
Or am I doing something else wrong?
Is it perhaps that everyone uses a "bundler" and these tools fix all this stuff somehow and so these issues never arise for 99% of web devs??
Thanks in advance.

A: You want to import a bundled version of the lib to be able to do that. Try:
import from 'https://unpkg.com/moment@2.29.1/dist/moment.js' ;

You can download the bundled version and add to your project. Don't forget to put the license as well and check if they are at least MIT or similar.
If you want to refer to the source code you will certainly need to build that. Specifically with libs that are using typescript.