text:
Q: How to change the parent working directory from which my executable is run? My project is a command-line application in Haskell and uses the opt-parse applicative package to handle parsing of command line options.
I am trying to implement a functionality which can change the working directory of the shell from which the command was run.
For example, I want to do something like
$ program foo

and have the shell change to a specified directory my program has associated with the passed option foo.
$ program foo
input 'foo'; now changing to directory '~/mydirectories/foodirectory'
[~/mydirectories/foodirectory]$

I attempted to implement this functionality using the setCurrentDirectory function from the directory package, however this does not appear to affect the working directory in the shell from which the directory is run; no change in the working directory appears. I am imagining that it is setting some kind of internal-to-the-program working directory, as I see no change in the shell from which the executable was run.
Is it possible to have my program change directories in this manner? Such directory-switching functionality would improve the convenience of using my application.
How can I implement directory-switching functionality from a command-line executable?

A: In general, you can't do this. No program can change its parent process's directory, no matter what language it's written in, using standard UNIX interfaces. A program can only change its own directory (and, by extension, the initial working directory of any programs it subsequently starts).
However, with the shell's active participation, you can make something very similar. Consider instructing your users to run a shell function such as the following:
# this wrapper works on any POSIX shell, but will avoid setting a global variable "dir" if
# the active shell (like bash, ksh, or even dash) supports local variables.
chdirWithMyHaskellProgram() {
    local dir 2>/dev/null || \
      declare dir 2>/dev/null || \
      : "current shell does not support local variables; proceeding anyhow"
    dir="$(myHaskellProgram "$@")" && cd -- "$dir"
}

...will cause chdirWithMyHaskellProgram --foo-bar to call myHaskelProgram --foo-bar, and change to the directory named in the output of same, if and only if the exit status indicates success.

Consider having myHaskelProgram --eval emit the source code to the above function. If you implemented this, then your user would need to put eval "$(myHaskelProgram --eval)" in their dotfiles, but would thereafter have the desired functionality.


text:
Q: How we can replace space in string with some word(ex:- 'XXX') without using string library in C? I am trying to write a program without using string library in C which can replace the spaces in string with 'XXX'.
I have done this much but did not getting idea after this.
 char buff[100];
 int i;
 char *my_func(char *arr){
     for( i=0;arr[i]!='\0';i++){
         if(arr[i]==' '){
             buff[i]='X';
             break;
         }
         else{
             buff[i]=arr[i];
         }
     }
     buff[i+1]='X';
     buff[i+2]='X';
     return buff;
 }
int main()
{
    char arr[]="This is my string";
    my_func(arr);
    printf("%s",buff);
    return 0;
}

A: You need to track the indices for your source and destination buffers separately, since encountering a space in the source string will cause the resulting string to grow disproportionately.
Those character assignments should be inside inside the loop.
Don't forget to NUL terminate your destination buffer.
Avoid global variables when possible.
#include <stdio.h>

char *replace(char *dest, char *src) {
    size_t j = 0;

    for (size_t i = 0; src[i]; i++) {
        if (src[i] == ' ') {
            dest[j++] = 'X';
            dest[j++] = 'X';
            dest[j++] = 'X';
        } else
            dest[j++] = src[i];
    }

    dest[j] = '\0';

    return dest;
}

int main(void) {
    char arr[] = "This is my string.";
    char buffer[256];

    replace(buffer, arr);

    printf("[%s] --> [%s]\n", arr, buffer);
}

Output:
[This is my string.] --> [ThisXXXisXXXmyXXXstring.]

redpajama_set_name: RedPajamaStackExchange


text:
Q: What's the most efficient way to drop columns (from beginning and end) in pandas from a large dataframe? I am trying to drop a number of columns from the beginning and end of the pandas dataframe.
My dataframe has 397 rows and 291 columns. I currently have this solution to remove the first 8 columns, but I also want to remove some at the end:
SMPS_Data = SMPS_Data.drop(SMPS_Data.columns[0:8], axis=1)

I know I could just repeat this step and remove the last few columns, but I was hoping there is a more direct way to approach this problem.
I tried using
SMPS_Data = SMPS_Data.drop(SMPS_Data.columns[0:8,278:291], axis=1)

but it doesn't work.
Also, it seems that the .drop method somehow slows down the console responsiveness, so maybe there's a cleaner way to do it?

A: You could use .drop(), if you want to remove your columns by their column names
drop_these = ['column_name1', 'column_name2', 'last_columns']
df = df.drop(columns=drop_these)

If you know you want to remove them by their location, you could use .iloc():
df.iloc[:, 8:15]  # For columns 8-15
df.iloc[:, :-5]   # For all columns, except the last five
df.iloc[:. 2:-5]  # For all columns, except the first column, and the last five

See this documentation on indexing and slicing data with pandas, for more information.


text:
Q: Explanation of Self-healing property of CBC (Cipher Block Chaining) Wikipedia:

CBC mode has the self-healing property:  if one block of the cipher is
  altered, the error propagates for at most two blocks.

Made up Example:
Let the block size be 64 bits. The original plaintext is:
3231343336353837  3231343336353837  3231343336353837  • • •

The correct cipher text is:
ef7c4bb2b4ce6f3b  f6266e3a97af0e2c  746ab9a6308f4256 • • •

If the ciphertext is corrupted, with the byte '0x4b' changed to '0x4c':
ef7c4cb2b4ce6f3b  f6266e3a97af0e2c  746ab9a6308f4256  • • •

Then it is decrypted to:
efca61e19f4836f1  3231333336353837  3231343336353837  • • •

Question:
I am having hard time understanding the self-healing property of CBC (Cipher Block Chaining), I thought that a made up example might help but I am now more confused. Any help would be great.

A: Personally, I find the decryption graphics very helpful for such kind of questions. From the Wikipedia (public domain image):

Now let's add some corruption:

The red dots represent partial corrupted inputs, while the solid red line represents complete block corruption.
Some notation before we start: I'll number the original plaintext blocks as p1 through p3, the corrupted ones as p1' through p3', the correct ciphertext blocks as c1 through c3 and the corrupted ones as c1' through c3':
3231343336353837  3231343336353837  3231343336353837  • • •
       p1                p2                 p3

ef7c4bb2b4ce6f3b  f6266e3a97af0e2c  746ab9a6308f4256  • • •
       c1                c2                 c3

ef7c4cb2b4ce6f3b  f6266e3a97af0e2c  746ab9a6308f4256  • • •
       c1'               c2'=c3             c3'=c3

efca61e19f4836f1  3231333336353837  3231343336353837  • • •
       p1'               p2'                p3'=p3

There is also some IV that you have not given in your example.
Let's take a look at the first block: Three bits in the input of the block cipher are changed (0x4b ^ 0x4c = 0x07 = 4+2+1). As a block cipher is designed to be a pseudo random permutation - that is a bijective function being indistinguishable from a random function (without knowledge of the key k) - we get a completely (pseudo) random block as output of the decryption function:
    dec(      c1        ,k) =         p1       XOR IV
<=> dec(ef7c4bb2b4ce6f3b,k) = 3231343336353837 XOR IV
    dec(      c1'       ,k) =         p1'      XOR IV
<=> dec(ef7c4cb2b4ce6f3b,k) = efca61e19f4836f1 XOR IV

As a next step the IV is XORed, so we end up with
    dec(      c1        ,k) XOR IV =         p1
<=> dec(ef7c4bb2b4ce6f3b,k) XOR IV = 3231343336353837
    dec(      c1'       ,k) XOR IV =         p1'
<=> dec(ef7c4cb2b4ce6f3b,k) XOR IV = efca61e19f4836f1

which shows that the whole block was destroyed (complete red block at the bottom).
Now, on to the second block: We start again by decrypting the ciphertext block, which works fine as no corruption has occurred in the block:
    dec(      c2        ,k) =         p2       XOR         c1
<=> dec(f6266e3a97af0e2c,k) = 3231343336353837 XOR ef7c4bb2b4ce6f3b
                                                    ^

Notice that this formula uses non-corrupted blocks everywhere. As a reminder, this block was generated like this during encryption:
             c2      = enc(        p2       XOR         c1      ,k)
<=> f6266e3a97af0e2c = enc(3231343336353837 XOR ef7c4bb2b4ce6f3b,k)

The next step is again the application of the XOR with the previous block (this time not the IV, but c1'). This previous block c1' is corrupted:
    dec(      c2        ,k) XOR       c1'        =         p2       XOR         c1       XOR        c1'
<=> dec(f6266e3a97af0e2c,k) XOR ef7c4cb2b4ce6f3b = 3231343336353837 XOR ef7c4bb2b4ce6f3b XOR ef7c4cb2b4ce6f3b

Now we can actually calculate c1 XOR c1' (the error) as c1 XOR c1' = 0000007000000000 and replace that everywhere:
    dec(      c2        ,k) XOR       c1'        =         p2       XOR 0000007000000000
<=> dec(f6266e3a97af0e2c,k) XOR ef7c4cb2b4ce6f3b = 3231343336353837 XOR 0000007000000000

And at last simplify p2 XOR 0000007000000000 = p2':
    dec(      c2        ,k) XOR       c1'        =         p2'
<=> dec(f6266e3a97af0e2c,k) XOR ef7c4cb2b4ce6f3b = 3231333336353837

You see that the original corruption (0x07) to the first ciphertext block c1' is transferred verbatim to the the second plaintext block p2', but it remains otherwise intact (as is visualized by a mostly white block in the graphic, with a single square being red). This peculiar property of CBC can lead to attacks against real world systems, like padding oracle attacks.
The third block is boring as hell: No inputs to the decryption and XOR have changed, thus p1=p1' and everything is fine there.

A: When decrypting in CBC mode a block is decrypted by first deciphering the block in question using the key, and then XOR it with the previous block in the ciphertext. Take a look at the CBC mode drawing on wiki
As you only need the current and previous block for decryptin in CBC mode, the effect of a changed byte in the ciphertext, would only affect the block it's in, and the following block (if that exists).


text:
Q: How do I add multiple email addresses? Below is the code i'm using.  I'm unable to add multiple addresses using the powershell Emailaddresses parameter. The code works fine if I just put in one email address, but once I add two addresses in the code below it returns exception stating invalid smtp address.
PSCredential credential = new PSCredential(username, password);
WSManConnectionInfo connectionInfo = new WSManConnectionInfo((new Uri(liveIdconnectionUri)), "http://schemas.microsoft.com/powershell/Microsoft.Exchange", credential);
connectionInfo.AuthenticationMechanism = AuthenticationMechanism.Default;

Runspace runspace = System.Management.Automation.Runspaces.RunspaceFactory.CreateRunspace(connectionInfo);
PowerShell powershell = PowerShell.Create();
runspace.Open();
powershell.Runspace = runspace;

var secure = new SecureString();
foreach (char c in textBox5.Text)
{
    secure.AppendChar(c);
}

PSCommand command2 = new PSCommand();
command2.AddCommand("Set-Mailbox");
command2.AddParameter("Identity", "lferrigno");
command2.AddParameter("EmailAddressPolicyEnabled", 0);
command2.AddParameter("EmailAddresses", "SMTP:lferrigno@sscincorporated.com,lou.ferrigno@altegrahealth.com");

powershell.Commands = command2;
powershell.Invoke();

A: This is the code i ended up using since it was a collection.
     string[] smtp = { "SMTP:" + textBox6.Text, 9 + "smtp:" + textBox4.Text + "@sscincorporated.com" };
     command2.AddParameter("EmailAddresses", smtp);

A: The -EmailAddresses parameter takes an array argument (technically a collection of SmtpProxyAddress objects, but that's not important, you can provide it an array and the conversion will be handled autonomatically), but it looks like you're giving it a single string containing multiple addresses. You need to either provide an array argument where each element is an address, or try this:
command2.AddParameter("EmailAddresses","'SMTP:lferrigno@sscincorporated.com','SMTP:lou.ferrigno@altegrahealth.com'");

Even though that's still a string within your C# code, if it's passed to PowerShell as-is, PowerShell will interpret it as an array.
You should also be able to leave out the SMTP: prefixes, because that's the default and will be set automatically if you don't specify a prefix.


text:
Q: Using CSS3 transition flip effects to show a modal dialog? I'd like to show a modal dialog using a 3D flip effect, exactly like the "3D flip (horizontal)" example  in the Effeckt.css library.
However I really don't need the whole Effeckt library, since I just want this one effect. So I've tried to strip out the relevant bits of the library into free-standing CSS and JavaScript.
This is my attempt, but it's not working: http://jsfiddle.net/eJsZx/
As the JSFiddle demonstrates, it's only showing the overlap - not the modal itself. This is odd, because the element inspector suggests that the modal should be visible - it has display: block, visibility: visible and zindex: 2000 (higher than the overlay element).
This is the JavaScript:
$('button').on('click', function() {
  $("#effeckt-modal-wrap").show();
  $("#effeckt-modal-wrap").addClass('md-effect-8');
  $("#effeckt-modal-wrap").addClass("effeckt-show");
  $('#effeckt-overlay').addClass("effeckt-show");

  $(".effeckt-modal-close, .effeckt-overlay").on("click", function() {
    $("#effeckt-modal-wrap").fadeOut();
    $('#effeckt-modal-wrap').removeClass("effeckt-show");
    $("#effeckt-modal-wrap").removeClass('md-effect-8');
    $('#effeckt-overlay').removeClass("effeckt-show");
  });
});

What am I doing wrong?

A: There were a couple of issues in the code.
First, your styles were missing the following:
.effeckt-show .effeckt-modal {
    visibility: visible;
}

This was causing the modal to remain invisible.
Once the dialog was visible, the dialog would rotate in just fine, however when being dismissed it would not rotate out.  This was due to the following line:
 $("#effeckt-modal-wrap").removeClass('md-effect-8');

If you want to remove this class, it would need to be done after the animation is complete otherwise the 3d effect is lost.  It doesn't necessarily need to be removed, but that depends on what the rest of your content needs.
The final issue was that the wrapper, on completion of the fadeout, was getting its local style set to display: none.  Because of this, the second time showing the dialog would cause it to simply appear because it was moving from display: none to display: block.  There are a couple of options here.

*

*Use CSS to animate the fade in/out.

*Use window.setTimeout after calling $.show on the element to give the dom a chance to update.

The final result: Working Fiddle


text:
Q: How to use the multiprocessing module on python to execute a spatial join? I have several shapefiles of the entire Amazon rainforest each with millions of polygons (they are fairly detailed and take some time to draw on ArcMap). I need each of these shapefiles to be spatially joined with another shapefile called landuseA (which, itself, is a very big file). Given how computer intensive this task is, I would like to use the multiprocessing module on python to improve performance. How do I do this?
I have read the blog post by Esri on the multiprocessing module, but I cannot figure out how I can use their example to write a script that will use multiple processors to execute a spatial join. Blog post is here: http://blogs.esri.com/esri/arcgis/2012/09/26/distributed-processing-with-arcgis-part-1/
If you have other suggestions for how this task might be better accomplished, feel free to share that too.


text:
Q: ASP .NET CORE WEB API & Angular Displaying an image in Angular from the WWWROOT on the server The part of my server works as it should, I manage to upload photos into the WWWROOT
But I try to make a call to these images in the client but it does not show me the image.

In the Angular UI I did the INPUT TEXT but I want to convert it to img with src but when I do that it doesn't show me the image

Controller:
 formProfile:FormGroup = new FormGroup({});
  isReadonly:boolean = true;
  user!:User;

  constructor(private userService:UserService,private formBuilder:FormBuilder,
    private alert:AlertService,private router:Router,public validationService:ValidationService) { }

  ngOnInit(): void {
    this.user = this.userService.getUser();

    this.formProfile = this.formBuilder.group({
      fullName:[''],
      userName:[''],
      password:[''],
      email:[''],
      photoUrl:['']
    })
  }

  updateUser(){
    this.userService.updateUser(this.user.id,this.user)
    .subscribe(()=>{
      this.alert.success("Editing was done successfully");
      localStorage.setItem("user", JSON.stringify(this.user));
      this.router.navigate(['/home']);
    },(e) => {
      this.validationService.registerValidation(e); // change it
    })
  }

HTML:

My Profile

                <form [formGroup]="formProfile" (ngSubmit)="updateUser()">

                    Full Name:

                    <input type="text" formControlName="fullName"
                           class="form-control" id="FullName" placeholder="Full Name" [readonly]="isReadonly"
                           [(ngModel)]="user.fullName">

                    Email:

                    <input type="email" formControlName="email"
                         class="form-control" id="Email" placeholder="Email" [readonly]="isReadonly"
                          [(ngModel)]="user.email">

                    User Name:

                    <input type="text" formControlName="userName"
                         class="form-control" id="UserName" placeholder="User Name" [readonly]="isReadonly"
                          [(ngModel)]="user.userName">

                    Password:

                    <input type="text" formControlName="password"
                         class="form-control" id="Password" placeholder="Password" [readonly]="isReadonly"
                          [(ngModel)]="user.password">

                    Photo:

                    <input type="text" formControlName="photoUrl"
                         class="form-control" id="photo" placeholder="Photo" [readonly]="isReadonly"
                         [(ngModel)]="user.photoUrl">

                    Change your Profile

                        <button type="submit" class="btn btn-primary mb-1">Submit</button>

                </form>

A: The code you are showing has some problems, you are using ngModel having reactive forms approach already set up. I always recommend using reactive forms, is more customizable and you have control over your form in your code.
Try refactoring your code by removing all ngModel bindings, after that,  populate your form, I see you already have formControlName on each of the controls, do it like this:
setForm(): void {
  this.formProfile.setValue({
     fullname: this.user.name,
     username: this.user.username,
     password: this.user.password,
     theImage: this.user.src
     // ... etc
  })
}

Or you could also update individually each form control using patchValue like so:
this.formProfile.get('fullname').pathValue(this.user.name);
// ...

Also, the image src you are getting back is missing in your frontend app, the backend is just giving you the name of the image, not the image itself, you should have that image in your assets folder, or the backend should provide the url of the image where is hosted.
If you wanna know more about reactive forms in Angular, I recommend reading the docs


text:
Q: D3: Force Layout with fixed Y ranges - Reducing link overlap I have created a graph where each node fits into one of the fixed y ranges. I am using a force layout to display the graph but I don't know how to ensure that the minimum of crossed links occurs - some crossing will be inevitable. I think it is a combination of gravity, force, linkDistance etc. but none of my changes seem to work
The graph is located at:
http://plnkr.co/edit/wyWjk37mkDCWcwpZvzxe?p=preview
The ideal configuration is

But it often comes out as a mess:

Any thoughts would be really appreciated

A: Take a look at this example.
This is your example, but a little bit modified. The basic idea is to do forced layout in two passes:

*

*first will allow a little bit more relaxed way of layout: nodes will be allowed to deviate from their "level"; this will allow spontaneous jumping one over another to achieve better link layout (less intersection)

*second will "return" nodes to their respective level

Key portions of the code:
Custom force:
  graph.nodes.forEach(function(o, i) {
    o.y += (y(o.level) - o.y) * k;
  });

Layout definition:
  var force = d3.layout.force()
    .charge(-1000)
    .gravity(0.2)
    .linkDistance(30)
    .size([width, height])

Calling force.start() two times:
force
  .nodes(graph.nodes)
  .links(graph.links)
  .on("tick", tick)
  .start();

setTimeout(function() {
  first = 0;
  force.start();
}, 6000);

Variable "first":
var first = 1;
  if(first) {
    var k = e.alpha;
  }
  else{
    var k = 10 * e.alpha;
  }

Screenshot after first pass:

After second pass:

I'll try to improve the example, this is a little bit "dirty" development prototype, but I don't have time right now, maybe tomorrow.
EDIT: NOTE: I just noticed that actually the data is constant, and, however, the layout differs from simulation to simulation. This doesn't have to be that way. It can be much more deterministic. I'll try to fix that too tomorrow. I'll also do better chaining layouts with "end" event.

A: The force layout algorithm implemented in D3 doesn't really allow you to do that. It doesn't try to minimise the number of links that cross -- there are other force-directed layout implementations (such as Fruchterman-Reingold) that do explicitly do this, but they're not implemented in D3.
So the short answer is that while you may be achieve a result that's suitable for a particular case, to do this in general, you would have to choose an alternative force layout implementation. There is a Fruchterman-Reingold implementation for sigma.js if you can use other graphing libraries.


text:
Q: Oracle DB Query Issue : Same query different behaviour Below is my Query. In one Oracle DB (11.2.3.0) this is giving me error but in other same Oracle DB below query is working fine. Not able to understand this different behavior.
Output from one DB
SQL> select id  from cag where greeting_id=1111100001 for update;

ERROR at line 1:
ORA-01722: invalid number

Output from other DB
SQL> select id from cag where greeting_id=1111100001 for update;

ID - 9111100001

Is there any DB internal setting?

A: You are storing numbers in a varchar2 column. That is not good practice, for many reasons including performance, but particularly because it causes data issues like this.
If the column is only ever supposed to contain numbers then make it an actual number column.
If it is a general column that is expected to hold numeric and other data then you should really reconsider the design anyway and put the different types of data in separate columns of the right type. It looks like it's expected to always be a number though - you wouldn't expect an ID to have a varying type.
In the meantime, to query a string column you need to avoid implicit conversion. At the moment when you do:
select id  from cag where greeting_id=1111100001;

the database has to convert every string in the greeting_id column into a number before comparing it with 1111100001, and it is that implicit conversion from string to number that is throwing the error - because you have values in the column that cannot be implicitly converted. In one database all the column values can be converted; on the other at least one value cannot. If you aren't expecting that then look at the data to see if someone has stored something unexpected like 'none' or 'invalid' or 'unknown', or even a decimal fraction with the wrong decimal separator.
If you have to stick with a string when look for a string - compare column data with values and literals of the same type:
select id  from cag where greeting_id='1111100001';

The correct approach is to make the column the correct data type though.


text:
Q: SQL Group By and Count on two columns I have a MySQL table with data as:-
country | city
---------------
italy   | milan
italy   | rome
italy   | rome
ireland | cork
uk      | london
ireland | cork

I want query this and group by the country and city and have counts of both the city and the country, like this:-
country | city   | city_count | country_count
---------------------------------------------
ireland | cork   |          2 |             2
italy   | milan  |          1 |             3
italy   | rome   |          2 |             3
uk      | london |          1 |             1

I can do:-
SELECT country, city, count(city) as city_count
FROM jobs
GROUP BY country, city

Which gives me:-
country | city   | city_count
-----------------------------
ireland | cork   |          2
italy   | milan  |          1
italy   | rome   |          2
uk      | london |          1

Any pointer to getting the country_count too?

A: You can use a correlated sub-query:
SELECT country, city, count(city) as city_count,
       (SELECT count(*)
        FROM jobs AS j2
        WHERE j1.country = j2.country) AS country_count
FROM jobs AS j1
GROUP BY country, city

Demo here

A: You can just do it in subquery on results.
  SELECT jm.country, jm.city,
       count(city) as city_count,
       (select count(*) from jobs j where j.country = jm.country) as country_count
    FROM jobs jm
    GROUP BY jm.country, jm.city

SQL Fidlle example

A: Use Self Join Instead.
select a.country,a.city,b.city_count,c.country_count
from jobs a
inner join (select count(1) as city_count, city
    from jobs
    group by city
) b on a.city = b.city
inner join (select count(1) as country_count, country
    from jobs
    group by country
) c on a.country = c.country
group by country,city

A: i have written answer at that time Giorgos Betsos posted answer the same as my code so i have written in CTE also
we can achieve result in lot ways but here is the 2 solutions and second query is less complicated
declare @Table1 TABLE
    ([country] varchar(7), [city] varchar(6))
;

INSERT INTO @Table1
    ([country], [city])
VALUES
    ('italy', 'milan'),
    ('italy', 'rome'),
    ('italy', 'rome'),
    ('ireland', 'cork'),
    ('uk', 'london'),
    ('ireland', 'cork')
;

First way
   ;with CTE AS (
    select T.country,T.city,count(T.city)TCity from @Table1 T
    group by country,city )
    select C.country,C.city,C.TCity,T.T from CTE C INNER JOIN (select count(country)T,country from @Table1 group by country )T
    ON T.country = C.country
    GROUP BY c.country,c.city,c.TCity,t.t

Second way
SELECT country, city, count(city) as citycnt,
           (SELECT count(*)
            FROM @Table1 AS TT
            WHERE T.country = TT.country) AS countrycnt
    FROM @Table1 AS T
    GROUP BY country, city


text:
Q: Ignore background noise? I am making a voice recognition software for my computer but I have some problems:
1) Is there a way to ignore background noise? I want the program to end when there is x amount of time without noise but background noise could keep it awake indefinitely.
2) same thing but reverse, I want it to start when it hears a voice but loud enough background noise will start it as well.

A: Sorry, I can't provide any code, only pseudocode. You can create en enum, or a list, of possible phonemes spoken. Activate the program only when the ADSR pattern of the phoneme is recognized, with volume as a secondary indicator, to separate "background" phonemes. If the background noise is so loud that it interferes with the recognition of the phoneme, then it shouldn't be considered a background sound in the first place.
Aah = 1
Ahh = 2
Ehh = 3
...
if soundEvent == true:

    if phoneme.type = Aah:
    what_i_said = "a"
...


text:
Q: Approaching Dynamic Programming I have written a small program to calculate the factorial of a number using Dynamic Programming Technique.
#include<stdio.h>

int fact(int n)
{
    int f[n],i;
    f[0] = 1;

    for(i=1;i<=n;i++)
        f[i] = i * f[i-1];
    return f[n];
}

int main(void)
{
    printf("\n Factorial of %d is %d ",5,fact(5));
    return 0;
}

Is the approach of memorization correct? Because, dynamic programming involves recursion. But I have not included it here. So I am not sure of my approach.

A: Yes, your approach of solving the problem is a very simple case of Dynamic Programming, where you store previously solved sub-problems to help you solve the actual problem. While the example you provided would be considered Dynamic Programming, it usually isn't called Memoization
When someone says Memoization, it usually involves in a top-down approach of solving problems, where you assume you have already solved the sub-problems by structuring your program in a way that will solve sub-problems recursively.
You store, or memoize, the results of these sub-problems so that they will not be computed multiple times.
Let me illustrate Memoization through an example:
Here is a simple example of computing the nth Fibonacci of a number:
int fib(int n)
{
   if (n <= 1)
      return n;
   return fib(n-1) + fib(n-2);
}

The above code uses recursion to solve sub-problems (fib(n-1) and fib(n-2)) so that fib(n) can be solved in the end. It assumes that fib(n-1) and fib(n-2) are already solved in the way that it is structured.
Though this code looks elegant, the running time is exponential, because you can solve fib(i), where i is a number less than n, multiple times. You can look at the diagram presented here to see the tree generated by this problem: http://www.geeksforgeeks.org/program-for-nth-fibonacci-number.
To avoid the unnecessary re-computation, Memoization is used to optimizes run-time by using memory.
Here is an optimized example of computing the nth Fibonacci number using Memoization:
/*Global array initialized to 0*/
int a[100];

int fib(int n)
{
    /*base case*/
    if (n <= 1)
        return n;
    /*if fib(n) has not been computed, compute it*/
    if (a[n] == 0) {
        a[n] = fib(n - 1) + fib(n - 2);
    }
    */Otherwise, simply get a[n] and return it*/
    return a[n];
}

As you can see, the overall structure is not that much different from the recursive solution, but it runs linear time instead of exponential time because fib(i) will only be computed only if we have not computed already.
If I were to use your approach, Dynamic Programming, for the Fibonacci problem, it would look something like this:
 int fib(int n)
 {
   /* just like the array you declared in your solution */
   int f[n+1];
   int i;

   /* set up the base cases, just like how you set f[0] to 1*/
  f[0] = 0;
  f[1] = 1;

   for (i = 2; i <= n; i++)
   {
       /* using previously solved problem to solve further problems*/
       f[i] = f[i-1] + f[i-2];
   }
     /*return the final result*/
   return f[n];
}

There are more subtle differences, trade offs, and implications between Dynamic Programming and Memoization. Some consider Memoization a subset of Dynamic Programming. You can read more about the difference here:
Dynamic programming and memoization: bottom-up vs top-down approaches

A: Yes this is dynamic programming : going from base cases up to final case. Of course your example (factorial) is too simple so you have been able to simplify many things by yourself : you eliminated the recursion and never use a test in the memoization. But anyway that's it.
For the general scheme of memoization see http://en.wikipedia.org/wiki/Memoization.
For explanation about Dynamic programming see http://en.wikipedia.org/wiki/Dynamic_programming, you will be able to read the section about Fibonacci sequence and its computation using a bottom-up approach.


text:
Q: Are absolute extrema only in continuous functions? The Extreme Value Theorem says that if $f(x)$ is continuous on the interval $[a,b]$ then there are two numbers, $a≤c$ and $d≤b$, so that $f(c)$ is an absolute maximum for the function and $f(d)$ is an absolute minimum for the function.
So, if we have a continuous function on $[a,b]$ we're guaranteed to have both absolute maximum and absolute minimum, but functions that aren't continuous can still have either an absolute min or max?
For example, the function $f(x)=\frac{1}{x^2}$ on $[-1,1]$ isn't continuous at $x=0$ since the function is approaching infinity, so this function doesn't have an absolute maximum.
Another example: suppose a graph is on a closed interval and there is a jump discontinuity at a point $x=c$, and this point is the absolute minimum.
The extreme value theorem requires continuity in order for absolute extrema to exist, so why can there be extrema where the function isn't continuous?

A: This is a difference between necessary and sufficient conditions, see here.
The extreme value theorem states that continuity on a closed interval is sufficient to ensure that the function attains a maximum and minimum. However, this condition is not necessary. Consider
$$
f(x) = \begin{cases}
1, \text{ for $x=0$} \\
0, \text{ elsewhere}.
\end{cases}
$$
Clearly, $\max(f)=1$, $\min(f)=0$, but $f$ is discontinuous at $x=0$.

A: First of all, $f(x) = x^{-2}$ isn't well defined on the domain $[-1,1]$, specifically where $x = 0$, so you can't really say that it is discontinuous. But if you assign it any value at $x = 0$, so $f(0) := c$ for $c \in \mathbb{R}$, it is discontinuous.
Then, as shown by yourself, continuity isn't needed to find a function on an interval $[a,b]$ having absolute extrema. This is reflected by the extreme value theorem, because it only guarantees extreme values for a continuous, real function on an interval $[a,b]$, but does not say that a function, having such extreme values, necessarily is continuous.

A: Semi-continuous functions have this property.


text:
Q: Centralizer of a group is the intersection of Stabilizers Let $C(S)=\{g\in G\mid gs=sg,\,\forall s\in S\}$. (This set is called the centralizer of $S$ in $G$.) I need to show that it is a subgroup by recognizing it as an intersection of stabilizers under some action of $G$. I know I have to use conjugation, but I don't have idea how to proceed. Any ideas or suggestions?

A: Let $G$ act on itself by conjugation. The stabilizer of $x \in G$ under this action is the set $G_x = \{s \in G : s \cdot x = sxs^{-1}=x \}$. The centralizer of $G$ in $G$ is the set $C(G) = \{c \in G: cg = gc \text{ for all } g \in G\}$. Note that we can rewrite the centralizer as $C(G) = \{c \in G: cgc^{-1} = g \text{ for all } g \in G\}$. Now show what $\bigcap_{x \in G} G_x$ is as a set and the solution should be clear.

A: We can rewrite this as $C(S)=\{g\in G\mid gsg^{-1}=s,\,\forall s\in S\}$ with $C(S)$ being the set of all elements in $G$ which commute with every other member. Now $1\in C(S)$, since $1h=h1$ $\forall h\in G$, and so then $\forall h\in S$. Now for two elements $a,b\in C(S)$ we have $\forall s\in S$, $asa^{-1}=s$ and $bsb^{-1}=s$. Now note
$$a^{-1}(asa^{-1})a=(a^{-1}a)s(a^{-1}a)=1s1=s$$
and
$$s=a^{-1}sa$$
Hence $s=a^{-1}sa=asa^{-1}$ and $C(S)$ is closed under inverses, that is if $a\in C(S)$ so is $a^{-1}\in C(S)$.
Now check it is closed under products.
\begin{align}
(ab)s(ab)^{-1}&=(ab)s(b^{-1}a^{-1})\\
&=a(bsb^{-1})a^{-1}\\
&=asa^{-1}\quad\,\,\,\,\text{since $b\in C(S)$}\\
&=s\qquad\quad\ \ \text{since $a\in C(S)$}
\end{align}
therefore $ab\in C(S)$, and $C(S)$ is closed under product taking. Hence $C(S)\subseteq G$.
The fact that $C(S)$ is a subgroup of $G$ follows by looking at how $G$ acts on its elements by group actions. The stabilizer of $s$ in $G$ is defined as the set $G_s=\{g\in G\mid g\cdot s=s\}$. To show it's a group first note $1\in G_s$ since $1\cdot s=s$. Now, if $a\in G_s$,
\begin{align}
s&=1\cdot s \\
&=(a^{-1}a)\cdot s \\
&=a^{-1}\cdot (a\cdot s)\\
&=a^{-1}\cdot s\qquad\quad\text{since $a\in G_s$}
\end{align}
and so $a^{-1}\in G_s$ also. Now check products: if $a,b\in G_s$ then
\begin{align}
(ab)\cdot s&=a\cdot (b\cdot s)\\
&=a\cdot s\quad\quad\,\,\text{since $b\in G_s$}\\
&=s\qquad\quad\ \,\,\text{since $s\in G_s$}
\end{align}
Hence $G_s$ is a subgroup of $G$.


text:
Q: Definition of lexicographic sum
Let $T$ be a nonempty ordered set considered as an index set. Let
  $(P_{t})_{t\in T}$ be a family of pairwise disjoint nonempty ordered
  sets that are all disjoint from $T$. We define lexicographic sum
$L\{P_{t}\ |\ t\in T\}$ to be the union $\bigcup _{t\in T}P_t$ ordered
  by $p_1\leq p_2$ iff

*

*There are distinct $t_1, t_2\in T$ with $t_1<t_2$, so that $p_i\in P_{t_i}$, or

*There is a $t\in T$ so that $p_1,p_2\in P_t$ and $p_1\leq_{P_t}p_2$.

  (Ordered Sets (Bernd Schröder) p. 173)

What does the condition on $T$ achieve here? Why must $P_t\cap T=\emptyset$ for all $t\in T$? Also, given an arbitrary nonempty family of nonempty pairwise disjoint ordered sets $(X_i)_{i\in I}$, how does one ensure that the disjointness condition actually holds for the index set $I$?

A: I concur with the sentiment in the comment that I see no reason for $T$ to be disjoint from $P_t$. As a definitional point, a family $(P_t)_{t \in T}$ is a shorthand itself for some function $f$ defined on $T$ that maps $t$ to some set $f(t)$ in the universe of sets, denoted by $P_t$. We're using the axiom schema of replacement (in ZF) to justify this "sloppiness".
As to ensuring disjointness, for a set $A$ and sets $t \neq t'$ we have that $A \times \{t\}$ is disjoint from $A \times \{t'\}$ (by the definition of pairs) but both are essentially copies of $A$ (any order structure can trivially be copied over bijectively). So we never lose generality by assuming sets to be pairwise disjoint in such contexts.


text:
Q: How long would it take to integrate Facebook Connect with a website? I have a website where users can buy deals posted by the site owner/admin and I would like to integrate Facebook Connect with it.  Can you please answer the following:

*

*What tasks are involved with integrating Facebook Connect?

*How difficult would it be for a programmer to integrate Facebook Connect?

*How long would it take for an average programmer to integrate Facebook Connect?

A: I think it's a bit difficult, yes, but it's not impossible. It shoud be about 2-5 days to study, understand, make tests and make it works (it also depends on how much you know of the facebook platfrm):
Here is a tuorial I wrote:

http://www.barattalo.it/facebook-connect-tutorial/

it explains how to give the facebook login and how to post on users' wall.

A: There are multiple good tutorials available.  I would say an average programmer (with some familiarity in JavaScript) would be able to do this fairly easily.

*

*Facebook Connect Wiki

*How to quickly add Facebook Connect
I have integrated Facebook Connect into 2 sites and the time it took varied from 3 days to 2 weeks.  The time requirement depends on the size of the application you are integrating.  It only took me 3 days to integrate Facebook Connect into a new site which did not have any existing users.

A: Putting in a Facebook connect or login button can be pretty easy now since there are some copy-and-paste solutions out there. If you're looking for a copy/paste solution that does some pretty simple members-only page protection, you can try this Facebook Login tool. It's free and gives some basic analytics, I think.

A: My point of view Facebook connect can be implemented by average programmer with in 2-3 hours If you aware about Facebook document and sound knowledge of API Key Secret.
Following documents that help for integrating Facebook into websites.
Document use PHP for server-side programming and HTML/JavaScript for client-side code. These examples are very straightforward and easily translatable to other languages.
Facebook Developer Tutorials.
This article shows few steps that describes how to integrate Facebook Connect into your
existing site.

A: efpa is brilliant for this, its easy to use and saves you hours, it would take you less than 20 min, there is a really good youtube tutorial on this, they use efpa to create a web application, let users connect using their facebook accounts and then present them their home feed, from creating a facebook app to writing the code in 20 min;
http://www.youtube.com/watch?v=ri8io0bmKOc
btw efpa stand for (Easy Facebook PHP API), the library was written to make facebook intergration easy and usable by anyone. Check out their documentations page http://labs.gurron.com/projects.php?proj=efpa&pg=docs


text:
Q: Configure SMTP host using YAML file in Spring boot I am trying to configure an SMTP host for my Spring boot application.
I have this code in my application-dev.yml file:
 mail:
    host: smtp.gmail.com
    port: 465
    username: myemail@gmail.com
    password: mypassword

However, when I am trying to send an email I get this exception:
Caused by: javax.mail.MessagingException: Could not connect to
SMTP host: smtp.gmail.com,
port: 465, response: -1

Also, I have generated this code with JHipster and I am not sure whether I should modify something else or this is enough to configure a SMTP host.
After changing the port to 587, I am getting this:
org.springframework.mail.MailSendException:
Failed messages:    com.sun.mail.smtp.SMTPSendFailedException: 530 5.7.0 Must issue
a STARTTLS command first. jm6sm60863600wjb.27 - gsmtp

A: I have used following YAML configuration for sending mail via Gmail
spring:
  mail:
    default-encoding: UTF-8
    host: smtp.gmail.com
    username: <Gmail username>
    password: <Gmail password>
    port: 587
    properties:
      mail:
        smtp:
          auth: true
          starttls:
            enable: true
    protocol: smtp
    test-connection: false

A: I made the following changes and now it works fine:
 mail:
    host: smtp.gmail.com
    port: 587
    username: mymail@gmail.com
    password: mypassword
    protocol: smtp
    tls: true
    properties.mail.smtp:
        auth: true
        starttls.enable: true
        ssl.trust: smtp.gmail.com

A: I believe you got the port wrong. I believe it's 587
Updated
Now we need to set StartTLS
add
mail:
  host: smtp.gmail.com
  port: 587
  username: myemail@gmail.com
  password: mypassword
  properties:
    starttls.enable: true

A: you can try the conf below. It's working in my environment.
  mail:
    debug: false
    host: host
    port: port_number
    properties:
      mail:
        protocol: smtp
        smtp:
          ssl:
            enable: true
            trust: "*"
          auth: false
          starttls:
            enable: true
            required: false


text:
Q: How do i know the position and length of modified bytes in a file when compared to original file? I have a file lets assume a text file containing text ABCDEF and later the file is modified to ABcDEF. How would i compare the modified file to the original to know that the file is modified at a position and length of modification done in bytes. The file could be any type, I specified text file as an example.

A: For your example you can just read files content as strings and compare every char in "for(int=0..." loop, so "i" would be your position.
For more complex changes in file, you have to use some diff algoritm, as Robert says.


text:
Q: How can I animate a View to fly in from the bottom of the screen? I'm trying to figure out how to have a view. Let's call it ThirdView. It should slide up from the bottom of the screen when a user clicks a particular button on SecondView.

A: You'll want to create the ThirdView in your SecondView and present it as a modal view, passing in the secondView in the constructor. This will be the easiest way of animating it in the way you would like.
var thirdView = new ThirdView(secondView);
this.PresentModalViewController(thirdView, true);

In your third view, you'll want to call the passed-in SecondView and call:
secondView.DismissModalViewControllerAnimated(true);

A: Here is a complete working example.  It is a tad simpler than in chrisntr's answer...though the above example is what I used to figure everything out.
The coolest thing about this method is that for an artistic custom UI (like the one I am building for a game), there is no off-the-shelf UI elements like the TabBar, Navigation bars, etc.  The most creative applications don't use standard UI stuff.
In your main.cs file, in your finishedlaunching block:
ViewController myUIV = new ViewController();
window.AddSubview(myUIV.View);
window.MakeKeyAndVisble();

And then in a new code file add this code:
using System;
using System.Drawing;
using MonoTouch.UIKit;

namespace AnimationTest
{

    public class ViewController : UIViewController
    {
        UIButton uib = new UIButton(new RectangleF(100, 100, 40, 40));
        public override void ViewDidLoad()
        {
            Console.WriteLine("UI1");
            this.View.BackgroundColor = UIColor.Blue;
            uib.BackgroundColor = UIColor.White;
            uib.TouchUpInside += delegate {
                Console.WriteLine("Hey!");
                var vc2 = new SecondController();
                PresentModalViewController(vc2, true);
            };
            this.View.AddSubview(uib);
            base.ViewDidLoad();
        }
    }

    public class SecondController : UIViewController
    {
        UIButton uib = new UIButton(new RectangleF(100, 100, 40, 40));
        public override void ViewDidLoad()
        {
            this.View.BackgroundColor = UIColor.White;
            uib.BackgroundColor = UIColor.Red;
            uib.TouchUpInside += delegate {
                this.DismissModalViewControllerAnimated(true);
            };

            this.View.AddSubview(uib);
            base.ViewDidLoad();
        }
    }


text:
Q: request additional fields from related object in django queryset say I've got two models, Parent and Child.
Child model has a fk relation to Parent
Class Child(models.Model):
     parent = models.ForeignKey('Parent', related_name='family')

I want to write a queryset for Child and serialize it to geojson, however, I'd also like the queryset to include some additional fields from Parent beyond id. perhaps I'm not clear on select_related().
This offers functionally the same query with no additional fields from Parent:
qs = Child.objects.filter(...).select_related('parent')

props = {
    'geoJson' : serializers.serialize('geojson', list(qs)),
}

if I make it .select_related('parent').values(...) for the fields I want, the view errs on req:
'dict' object has no attribute '_meta'

.select_related('parent').only(...) throws:
Field Child.parent cannot be both deferred and traversed using select_related at the same time

what's the right way to structure that queryset to request extra fields from the related object? what am I misunderstanding about selected_related in queries? thanks
.values() Traceback:
File ".pyenv/versions/3.6.3/lib/python3.6/site-packages/django/core/handlers/exception.py" in inner
  41.             response = get_response(request)

File ".pyenv/versions/3.6.3/lib/python3.6/site-packages/django/core/handlers/base.py" in _legacy_get_response
  249.             response = self._get_response(request)

File ".pyenv/versions/3.6.3/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response
  187.                 response = self.process_exception_by_middleware(e, request)

File ".pyenv/versions/3.6.3/lib/python3.6/site-packages/channels/handler.py" in process_exception_by_middleware
  237.             return super(AsgiHandler, self).process_exception_by_middleware(exception, request)

File ".pyenv/versions/3.6.3/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response
  185.                 response = wrapped_callback(request, *callback_args, **callback_kwargs)

File ".pyenv/versions/3.6.3/lib/python3.6/contextlib.py" in inner
  52.                 return func(*args, **kwds)

File "project/utils/helpers.py" in _decorated
  29.             return view(request, *args, **kwargs)

File ".pyenv/versions/3.6.3/lib/python3.6/site-packages/htmlmin/decorators.py" in minify
  13.         response = f(*args, **kwargs)

File "/causes/views.py" in cause
  197.         'activityJson' : serializers.serialize('geojson', list(qs)),

File ".pyenv/versions/3.6.3/lib/python3.6/site-packages/django/core/serializers/__init__.py" in serialize
  129.     s.serialize(queryset, **options)

File ".pyenv/versions/3.6.3/lib/python3.6/site-packages/django/core/serializers/base.py" in serialize
  81.             self.start_object(obj)

File ".pyenv/versions/3.6.3/lib/python3.6/site-packages/django/contrib/gis/serializers/geojson.py" in start_object
  35.             for field in obj._meta.fields:

A: Your misunderstanding is that this doesn't have anything whatsoever to do with select_related. That method is for making more efficient queries only, and would not in any way affect what data is returned from a serializer.
Django's built-in serializers are very basic, and don't support nested objects like this. If that's what you want, you should use Django REST Framework, which implements much more fully-featured serializers which can serialize nested objects in a variety of ways.


text:
Q: d3.js missing first index when append circles I'm new to using D3 and running - again - in some trouble.
I'm working on a small network, in this case without forces. Now i have the problem, that when adding my circles(my nodes) he skip the first index, and i'm not sure how to solve this.
you can find my complete code here:
https://github.com/katjalennartz/ba
here, i still have all the data
    var circleGroup = svg.selectAll('g')
        .data(users)
        .enter().append('g')
        .attr('transform', function (d) {
            console.log(d) //index 0 ist still there
             return 'translate(' + d.x + ',' + d.y + ')'; })
        .call(d3.drag()
            .on("start", dragstarted)
            .on("drag", dragged)
            .on("end", dragended));

and this is where it goes missing
        .attr("r", function (d) {
            //increase radius if current user
            //index 0 is missing ?
            if (d.id === thisuser) {
                return radius * 2
            }
            else { return radius; }
        })
        .attr("class", "chara")
        .attr("fill", function (d) {
            //set color to red if this user
            let color
            (d.id === thisuser) ? color = "red" : color = "blue"
            return color;
        })
        .style("stroke", "#ffffff");

So, i have no idea, what to do about it and i'm hoping someone here can help me fix it.
if it's important for the code, i'm planning to use update etc. to filter the links.
Thank you!


text:
Q: What do you call someone who gets along with children? What do you call someone who gets along with children/babies?
A simple example:

He is such a ________, he makes all children smile.

A single word noun would be ideal but a phrase is acceptable also. There might be a colloquial word or phrase too.

For example, there is a phrase good mixer which means someone who can get along with everyone [See: second meaning of mixer]. So, what we are looking for is almost like a subtype of this characteristic.
There are words like likeable or easygoing but they are too general.
The closest word I could find is avuncular but it does not sound that suitable for this usage. I have never used this word in this way.

Kind and friendly towards a younger or less experienced person: he was avuncular, reassuring, and trustworthy
[oxforddictionaries]

Also, I'm not sure if we can use avuncular as a gender neutral word for this sense. [Because it is a masculine word for its anthropological sense]. It seems like there isn't a common word as a feminine version. Amicular and materteral is proposed in this previous ELU question: Is there a feminine equivalent to the adjective "avuncular"?

A: Maternal and Paternal work in some cases.

Maternal
-- (of feelings) typical of a caring mother; motherly.
Paternal
-- of or appropriate to a father.

A: I suggest avuncular. Here is part of a discussion of the term at Merriam-Webster Online:

Avuncular derives from the Latin noun avunculus, which translates as "maternal uncle," but since at least the 1830s English speakers have used "avuncular" to refer to uncles from either side of the family or even to individuals who are simply uncle-like in character or behavior.

A: Consider pied piper

a person who entices others to follow him [Collins]

This term has a bit of a dark undertone, often suggesting ... follow him to their doom.
A common, but somewhat mundane phrase is he has a way [or such a way] with children. The specifics of way are left unstated, but it is universally understood to be

ability to get along well or perform well: she has a way with kids; a way with words [Merriam-Webster: 5.b.]

Your sentence might be rephrased

He has such a way with children; he makes them smile.


text:
Q: Consecutive inlines produces space inbetween I have a simple XSL FO with a block containing consecutive inlines.
<fo:block-container span="all">
    <fo:block font-family="Calibri" font-size="12"
      color="#108BA4" line-height="1.15" widows="3" orphans="3"
      keep-with-next="always" span="all">
      <fo:inline font-family="Calibri"
        font-weight="normal" font-size="11" color="#108BA4">Sous-article de 2
      </fo:inline>
      <fo:inline vertical-align="super">nd</fo:inline>
      <fo:inline font-family="Calibri"
        font-weight="normal" font-size="11" color="#108BA4"> génération
      </fo:inline>
    </fo:block>
  </fo:block-container>

Thing is I get some sort of whitespace between "2" and "nd" and probably between "nd" and "génération".
Also because someone is going to ask, I have this in my XSL :
<xsl:strip-space elements="*"/>

Any idea ?
Image of what I get in the PDF

A: You are seeing the effect of the white-space after the "2" in:
      <fo:inline font-family="Calibri"
        font-weight="normal" font-size="11" color="#108BA4">Sous-article de 2
      </fo:inline>

<xsl:strip-space elements="*"/> only applies to your source document. (See the XSLT 1.0 definition at https://www.w3.org/TR/1999/REC-xslt-19991116#strip.) It won't do anything to your stylesheet.
White-space-only text nodes in your stylesheet are stripped automatically (unless they are within an xsl:text element).  Your text node has non-white-space characters, so nothing is being stripped.  If you looked at the result of the XSLT transformation, you'd see the line end and the white-space before the </fo:inline>.  The formatter is reducing that to just a single space for you.


text:
Q: Python property returning property object I have a class like this:
class Foo(object):
    def __init__(self):
        self.bar = property(self.get_bar)

    def get_bar(self):
        return "bar"

print Foo().bar  #this prints <property object at 0x0051CB40>

I've seen How do Python properties work?, How to set a python property in __init__, but they all use the decorator method, which i don't because i want a different name. And I need access to self
How do i get the property to behave?

A: You can do it like this
class Foo(object):
    def __init__(self):
        self.__bar = None

    def get_bar(self):
        return self.__bar

    def set_bar(self, value):
        self.__bar = value

    bar = property(get_bar, set_bar)

foo = Foo()
print foo.bar    # None
foo.bar = 1
print foo.bar    # 1

A: You can also do it like shown here:
class Foo(object):
    def __init__(self):
        self._bar = None

    @property
    def bar(self):
        return self._bar

    @bar.setter
    def bar(self, value):
        self._bar = value

    @bar.deleter
    def bar(self):
        self._bar = None # for instance

which is equivalent to:
class Also_Foo(object):
    def __init__(self):
        self._bar = None

    def get_bar(self):
        return self._bar

    def set_bar(self, value):
        self._bar = value

    def del_bar(self):
        self._bar = None # for instance

    bar = property(fget=get_bar, fset=set_bar, fdel=del_bar, doc=None)

BUT without polluting the class namespace with get and set methods for each attribute.
You retain external direct access to the variable by using ._bar instead of .bar.

A: The object is not instantiated.
class Foo(object):
  def get_bar(self):
    return "bar"

bar = Foo()
print(bar.get_bar)

A: You need to make a minor change:
class Foo(object):

    def get_bar(self):
        return "bar"

    bar = property(get_bar)

print Foo().bar # prints bar

The property needs to be an attribute of the class, not the instance; that's how the descriptor protocol works.

A: My use case required defining bar as a property only under certain conditions, so I took jonrsharpe's advice and moved the definition into __new__ instead:
class Foo(object):
    def __new__(cls):
        cls.bar = property(cls.get_bar)
        return super(Foo, cls).__new__(cls)

    def get_bar(self):
        return "bar"

print(Foo().bar)  #this prints "bar"

However, nothing was gained by this "cleverness". Once the condition was met, the class contained the property. I might as well have defined it as jonrsharpe did.

A: Do the following if you want to do within init()
class Foo(object):
    def __init__(self):
        type(self).bar = property(self.get_bar)

    def get_bar(self):
       return "bar"


text:
Q: LDAP error during Rails5 System tests: Rack app error handling request { POST /login } The LDAP authentication is implemented in Rails using https://github.com/plataformatec/devise/wiki/How-To:-Authenticate-via-LDAP and it works fine.
An attempt to use LDAP during system tests http://guides.rubyonrails.org/testing.html#system-testing has failed:
Rack app error handling request { POST /login }
#<NoMethodError: undefined method `[]' for nil:NilClass>
.../config/initializers/ldap_authenticatable.rb:92:in `ldap'
.../config/initializers/ldap_authenticatable.rb:60:in `bind_to_ldap'
.../config/initializers/ldap_authenticatable.rb:44:in `authenticate!'

The error occurs due to ldap.yml file, it seems the tests cannot read the configuration from the extern file. The workaround to replace the LDAP parameters
LDAP_CONFIG = YAML.load_file("#{Rails.root}/config/ldap.yml")[Rails.env]

def ldap
  ldap = Net::LDAP.new({
    :host => LDAP_CONFIG['host'],
    :port => LDAP_CONFIG['port'],
    ...

with
def ldap
  ldap = Net::LDAP.new({
    :host => 'ldap.domainname.com',
    :port => 636,
    ...

will avoid the error.
Please advise if this is a bug.


text:
Q: Why this javascript effect cannot use in ie7? why this javascript effect cannot use in ie7 ?
http://jsfiddle.net/peap/cb0nesfh/
IE7 NOT work
Why i cannot use this function in ie7
function over(event)
{
    $('.notch2').stop().animate({top: '33px' , opacity: 1}, 100);
    $('.mask').stop().animate({top: '0px' , opacity: 1}, 100);
}

but i can use this on ie 7
function over(event)
{
    $('.notch2').show();
    $('.mask').show();
}

A: IE7 does not support CSS opacity. you will need to have this syntax:
filter: Alpha(Opacity=100);


text:
Q: Missing form data via Ajax I'm trying to hunt down a bug in a register form I have. Every now and then I'll get an error of some undefined indexes. The forms are submitted using $('#theFormId').serialize().
My guess is in some browsers, in some cases .serialize() is missing out blank fields. Are there any reasons anyone knows why .serialize() could be doing this? The fields aren't disabled so I don't think that could be an issue.
I could solve the issue by putting in and !isset($form['theField']) check in (which I probably will anyway) but I'd like to find the reason the field isn't being posted through in the first place.


text:
Q: I cant seem to find whats wrong with this code i just started but i wont draw the canvas Here is the Code:
@Override
public void draw(Canvas canvas) {
    super.draw(canvas);
    drawUPS( canvas);
    drawFPS( canvas);
}

public void drawUPS(@NonNull Canvas canvas){
    String averageUPS = Double.toString(gameloop.getAverageUPS());
    Paint textPaint = new Paint();
    int color = ContextCompat.getColor(context, R.color.white);
    canvas.drawText("UPS" + averageUPS, 100, 100,textPaint);
    textPaint.setColor(color);
    textPaint.setTextSize(50);
}

public void drawFPS(@NonNull Canvas canvas){
    String averageFPS = Double.toString(gameloop.getAverageFPS());
    Paint paint = new Paint();
    int color = ContextCompat.getColor(context, R.color.white);
    paint.setColor(color);
    paint.setTextSize(50);
    canvas.drawText("FPS" + averageFPS, 100, 200,paint);
}

I did everything that is necessary for the canvas to be drawn but it just wont and i dont find any solutions anywhere


text:
Q: Very low VIF values, but extreme high condition index In my multiple linear regression model, all of my explanatory variables have a VIF score, lower then 3, but the highest condition index is 709.
The constant and one of the explanatory variables have 1.00 variance proportion values for this condition index.
What does this mean?
According to the VIF values, my model doesn't have a multicollinearity problem, but I don't know what to do with this high condition index and 1.0 variance proportions.


text:
Q: Facebook sees same keyhashes as being different Recently I've launched my 1st Android app which uses Facebook login. The login worked perfectly until I made the last update. Now, when I try to login, I get the message

The keyhash ABC does not match any stored hashes

But, if I go to My Developer Page > My App, the stored key hash is EXACTLY THE SAME as the one prompted in the error. I can tell you that it's not the display issue, where Facebook displays underscore instead of slash.
Is there anybody that knows how to fix this?

A: It seems like there was an issue reported as bug with Facebook. If you are still experiencing this issue, I recommend that you add your repro steps in a comment to the bug report. Make sure that you comment the exact error message as well as your app ID.
You should also verify that your key-hash extraction command is correct. Since typically this command is a really a series of piped commands, try executing the 1st step of the pipeline separately, to check if it doesn't print errors. Next, try piping the output through the 2nd stage only. Check for errors again, before oyou continue to the next step.


text:
Q: How to assign hostname and portnumber that client connected from? I have this ftserver.c program which is implementing a file transfer server which listens for a client and then responds to the clients request over a data connection. Right now it works  but I have the hostname and port number for the data connection hardcoded. The portnumber has been provided by the client and the server should be able to get the hostname from the client's control connection.
References:http://beej.us/guide/bgnet/output/html/multipage/getaddrinfoman.html
How can I assign the hostname and portnumber dynamically? Thank you.
void error(const char *msg)
{
perror(msg);
exit(1);
}

void startup(int portNumber);
void setupData(char* portNum);

int sockfd, newsockfd, datasock, portno;
char buffer[256]; socklen_t clilen;
struct sockaddr_in serv_addr, cli_addr, port_addr;
struct addrinfo hints, *servinfo, *p;
char ipstr[1000];
struct in_addr ipAddr;
struct sockaddr_in *s;

int main(int argc, char *argv[]){
    int n; char* dataport; char * token; char filename[100];

    if (argc < 2) {
        fprintf(stderr,"ERROR, no port provided\n");
        exit(1);
    }
    portno = atoi(argv[1]);

    startup(portno);

    n = read(newsockfd,buffer,255);
    if (n < 0) error("ERROR reading from socket");
    printf("Here is the message: %s\n",buffer);

    token = strtok(buffer, " ");

    //if client requested a list, setup data connection and send it
    if (strcmp(token, "-l") == 0){
      token = strtok(NULL, " ");
      printf("the token is %s\n", token);
      //dataport = atoi(token);
      dataport = token;
      setupData(dataport);
      //sendList(dataport);
    }
    //if client requested a file, setup data connection and send it
    else if (strcmp(token, "-g") == 0){
      token = strtok(NULL, " ");
      //filename = *token;
      token = strtok(NULL, " ");
      //dataport = atoi(token);
      printf("the data port is %d\n", dataport);
      //setupData(dataport);
      //sendFile(filename, dataport);
    }
    else {
      n = write(newsockfd,"not a valid command",19);
      if (n < 0) error("ERROR writing to socket");
    }

    //close sockets for connection P
    close(datasock);
    close(newsockfd);
    close(sockfd);
    return 0;
}

void startup(int portNumber)
{

 sockfd = socket(AF_INET, SOCK_STREAM, 0);
 if (sockfd < 0)
    error("ERROR opening socket");
 bzero((char *) &serv_addr, sizeof(serv_addr));

 serv_addr.sin_family = AF_INET;
 serv_addr.sin_addr.s_addr = INADDR_ANY;
 serv_addr.sin_port = htons(portNumber);
 if (bind(sockfd, (struct sockaddr *) &serv_addr,
          sizeof(serv_addr)) < 0)
          error("ERROR on binding");
 listen(sockfd,5);
 clilen = sizeof(cli_addr);
 newsockfd = accept(sockfd,
             (struct sockaddr *) &cli_addr,
             &clilen);

 if (newsockfd < 0)
      error("ERROR on accept");
 bzero(buffer,256);
}

void setupData(char* portNum){
  int rv;

  const char* name = "localhost";
  char s[1000];

  memset(&hints, 0, sizeof (hints));
  hints.ai_family = AF_UNSPEC; // use AF_INET6 to force IPv6
  hints.ai_socktype = SOCK_STREAM;

  if ((rv = getaddrinfo(name, "30024", &hints, &servinfo)) != 0) {
        fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(rv));
        exit(1);
  }

  // loop through all the results and connect to the first we can
  for(p = servinfo; p != NULL; p = p->ai_next) {
        if ((datasock = socket(p->ai_family, p->ai_socktype,
                p->ai_protocol)) == -1) {
            perror("socket");
            continue;
        }

        if (connect(datasock, p->ai_addr, p->ai_addrlen) == -1) {
            perror("connect");
            close(sockfd);
            continue;
        }

        break; // if we get here, we must have connected successfully
  }

  if (p == NULL) {
        // looped off the end of the list with no connection
        fprintf(stderr, "failed to connect\n");
        exit(2);
    }

  printf("data connection setup successful\n");
}

A: I have resolved this. By using a simplified version of setting up the data conection, not using getaddrinfo() and using a hostname_to_ip conversion function. Reference: http://www.linuxhowtos.org/data/6/client.c
int setupData(char* hostname, char* portNum){
     int sock_fd; char ip[100];
    struct sockaddr_in srv_addr;

    memset(&srv_addr, 0, sizeof(srv_addr)); /* zero-fill srv_addr structure*/
    /* create a client socket */
    sock_fd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
    srv_addr.sin_family = AF_INET; /* internet address family */
    /* convert command line argument to numeric IP */
    hostname_to_ip(hostname, ip);
    printf("%s resolved to %s" , hostname , ip);

    if ( inet_pton(AF_INET, ip, &(srv_addr.sin_addr)) < 1 )
    {
        printf("Invalid IP address\n");
        exit(EXIT_FAILURE);
    }
    srv_addr.sin_port = htons(atoi(portNum));
    if( connect(sock_fd, (struct sockaddr*) &srv_addr, sizeof(srv_addr)) < 0 )
    {
        perror("connect error");
        exit(EXIT_FAILURE);
    }

    return sockfd;
}


text:
Q: Use serial ID for multiple columns and return it from INSERT I am using Npgsql and I want to be able to do an insert, and if statement that will do an update and then return a value so when ExecuteScalar is called it reads that value.  This was done fine in MSSQL but I'm now trying to support PostgreSQL and I can't seem to get it right.
The SQL is similar to this:
insert into mytable (name, uniquecallid)
values (@name, @uniquecallid);

DO
$do$
BEGIN
IF coalesce(@UniqueCallId,'') = '' THEN
    SET @UniqueCallId = coalesce(@CallIdPad, '')
                     || cast(varchar(50), select currval('mytable_id_seq'));
    UPDATE mytable SET UniqueCallId = @UniqueCallId
    WHERE Id = select currval('mytable_id_seq');
END IF;
END
$do$

select currval('mytable_id_seq');

This errors with a "syntax error near select".
What can I do to get this to return the latest value inserted?
I believe this is a Npgsql issue as when inspecting the SQL that it executes the parameters are replaced with the values but the DO block doesn't have the values in place of parameters.

A: Syntax errors
Immediate causes for the error:
WHERE  id = select currval('mytable_id_seq');
And a missing semicolon at the end of the DO statement:
...
$do$;

Better query
On a closer look, this does not seem to be another case of UPSERT.
It would seem one of the inserted columns needs to depend on multiple input values in combination with the freshly retrieved value for a serial ID. Try this largely simplified statement:
INSERT INTO mytable (id, name, uniquecallid)
SELECT t.id
     , t.name
     , CASE WHEN t.uniquecallid <> '' THEN t.uniquecallid
            ELSE COALESCE(t.callidpad, '') || t.id END

FROM (
   SELECT nextval('mytable_id_seq') AS id
        , '@name'::text             AS name         -- provide values here, once
        , '@UniqueCallId'::text     AS uniquecallid
        , '@CallIdPad'::text        AS callidpad
   ) t
RETURNING id;

An explicit cast to text (or your actual undisclosed data type(s)) is needed.
This is equivalent to the presented code, just with legal syntax and much faster - unless there are triggers or non-standard default values you did not declare ...
Simpler with currval()
On an even closer look, this can be simplified further:
INSERT INTO mytable (name, uniquecallid)
SELECT '@name'::text
     , COALESACE( NULLIF('@UniqueCallId'::text, '')
                , COALESCE('@CallIdPad'::text, '') || currval('mytable_id_seq'))
RETURNING id;

Detailed explanation:

*

*PostgreSQL next value of the sequences?


text:
Q: Mobile DOM stacking order with JavaScript I want to take one DOM element (accordion menu) and put it underneath the content div. I was told in a prior thread to build with the menu on the bottom, but I built it so the sidebar menu is before the content in my markup like so:

   ...

        ...

I am using javascript to detect width, and it is working... some of the time. Not sure why it isn't consistent. Maybe because of the way i am approaching it.
jQuery(window).resize(function(){

    var windowsize = jQuery(window).width();
    if (windowsize < 768) {
        jQuery("#right.span9").insertBefore(jQuery("#sidebar1.span3"));
        } else {
            jQuery("#sidebar1.span3").insertBefore(jQuery("#right.span9"));
        }
});

A: this worked for me.
jQuery(window).load(function(){

if (jQuery(window).width() < 768) {
    jQuery("#right").insertBefore( "#sidebar1" );
    } else {
        jQuery("#sidebar1").insertBefore( "#right" );
    }
});


text:
Q: Getting data using 4 tables I have the following tables:
trendingtopic
  id
  name

trendingtopiccycle
  id
  trendingtopic_id(FK)

tweet
  id
  text
  tt_cycle_id(FK)
  user_id(FK)

user
  id
  rank

I'd like to know if there's a way to retrieve the tweet made from the higher ranked user of each trending topic in an efficient way.
Here's my current query:
  SELECT tt."name",
  MAX(tu."actual_rank") AS rank,tu."name"
  FROM "trendingtopics_twitteruser" tu
  LEFT JOIN "trendingtopics_tweet" tw ON tu."id" = tw."user_id"
  LEFT JOIN "trendingtopics_trendingtopiccycle" ttc ON tw."tt_cycle_id" = ttc."id"
  LEFT JOIN "trendingtopics_trendingtopic" tt ON ttc."tt_id" = tt."id"
  GROUP BY tt."name"

It's not working because, according to Postgresql:' "tu.name" must appear in the GROUP BY clause or be used in an aggregate function'.
If I add tu."name" to the GROUP BY clause, I end up getting something like this:
"106 & Park";0;"910Prince"
"106 & Park";0;"ActressAlexiss"
"106 & Park";0;"AmeliaThirlwall"
"106 & Park";0;"_ArielIvy"
"106 & Park";0;"_AyyeVce"
"106 & Park";0;"barcastuff"
"106 & Park";0.42141;"pareexo"
"106 & Park";0.0363;"khleosupporters"
"#15ThingsAboutMyCrush";0;"_ALoyalLady"
"#15ThingsAboutMyCrush";0.22275;"AmberrNikole"
"#15ThingsAboutMyCrush";0;"a_paigeturner"
"#15ThingsAboutMyCrush";0.33942018;"ArleneAndrea_xo"

But what I want to get is:
"106 & Park";0.42141;"pareexo"
"#15ThingsAboutMyCrush";0.33942018;"ArleneAndrea_xo"

A: Actually, this can easily be done using window functions in a subquery:
SELECT t."topic_name", t."rank", t."user_name"
FROM
    (SELECT tt."name" AS topic_name, tu."actual_rank" AS rank, tu."name" AS user_name,
        row_number() OVER (PARTITION BY tt."name" ORDER BY tu."actual_rank" DESC) user_rank
    FROM "trendingtopics_trendingtopic" tt
    LEFT JOIN "trendingtopics_trendingtopiccycle" ttc ON ttc."tt_id" = tt."id"
    LEFT JOIN "trendingtopics_tweet" tw ON tw."tt_cycle_id" = ttc."id"
    LEFT JOIN "trendingtopics_twitteruser" tu ON tu."id" = tw."user_id") t
WHERE t."user_rank" = 1

Also, I reordered the joins so that you START with the trending topic instead of the twitter user. Since you're trying to get the highest ranked user for the trending topic, makes more sense (to me at least) to start with that as the source table.
For more information regarding window functions and partitioning, go here: http://www.postgresql.org/docs/8.4/static/tutorial-window.html

A: The fastest solution is probably to use DISTINCT ON rather than a window function.
SELECT DISTINCT ON (tt."name")
    tt."name", tu."actual_rank" AS rank, tu."name"
  FROM "trendingtopics_twitteruser" tu
  LEFT JOIN "trendingtopics_tweet" tw ON tu."id" = tw."user_id"
  LEFT JOIN "trendingtopics_trendingtopiccycle" ttc ON tw."tt_cycle_id" = ttc."id"
  LEFT JOIN "trendingtopics_trendingtopic" tt ON ttc."tt_id" = tt."id"
  ORDER BY tt."name", tu."actual_rank" DESC;

By the way, this is untested because you didn't provide statements to actually create and load the tables you described.  If you do provide that sort of thing in the question, people will normally test their answers before posting, and you won't have silly errors to deal with.

A: SELECT tt."name",
  MAX(tu."actual_rank") AS rank,MAX(tu."name") as name_1
  FROM "trendingtopics_twitteruser" tu
  LEFT JOIN "trendingtopics_tweet" tw ON tu."id" = tw."user_id"
  LEFT JOIN "trendingtopics_trendingtopiccycle" ttc ON tw."tt_cycle_id" = ttc."id"
  LEFT JOIN "trendingtopics_trendingtopic" tt ON ttc."tt_id" = tt."id"
  GROUP BY tt."name"


text:
Q: jupyter notebook - change kernels isn't working I have multiple kernels in my notebook, but when changing the kernel it doesn't really change it and still run the original kernel (which I first open the notebook with).
For example, I run the notebook with python 3.6 environment, but when changing the kernel to python 2.7 it stayed with python 3.6.
I'm changing the kernels via jupyter GUI (kernel -> change kernel) and check the path of python using:
!which python

In all environments I installed ipykernel but it doesn't matter which kernel I'm choosing, the path stayed the same (the path of the original kernel which I used to run the notebook).

A: I had the same issue, launching jupyter from the terminal after activating the environment worked for me, I followed the steps as below:

*

*Open anaconda prompt

*Activate environment with conda activate EnvName

*Launch jupyter with jupyter lab


text:
Q: How to retrieve projects in to eclipse Right now im working with android/eclipse.Due to four times interruptions in power supply,i lost my whole projects what ive done so far.How to retrieve my projects into the eclipse?

A: Go to File-> Import-> Existing project into workspace.
Select the root directory of your project. Its done :)

A: You must be having the src/backup in one of your drive of your pc.import them from the specific place again in your workspace of eclipse.


text:
Q: How to ask Safari to automatically enter reader view on SwiftUI macOS app? Since SFSafariViewController is not available. Clicking a url in macOS app usually opens a new tab in macOS's Safari. I'm using below code in SwiftUI to open a website. But code below does not allow me to ask safari to automatically enter reader view.
Is there a way to automatically enter reader view on macOS? (Without user tweaking safari setting)
struct ContentView: View {
    @Environment(\.openURL) var openURL

    var body: some View {
        Button("Visit Apple") {
            openURL(URL(string: "https://www.apple.com")!)
        }
    }
}


text:
Q: Raised container control mouse events from child control I need to get mouse events of a control that owns a PictureBox (not fill docked). The thing is that the mouse events are not raised when the mouse is over the PictureBox.
The solution that I came with is to Handle the PictureBox events and pass it to the control, like this:
    void pictureBox_MouseClick(object sender, MouseEventArgs e)
    {
        //Correct mouse coordinate from PictureBox to control
        Point p = this.PointToClient(Cursor.Position);
        var e2 = new MouseEventArgs(e.Button, e.Clicks, p.X, p.Y, e.Delta);
        this.OnMouseClick(e2);
    }

Is this a good way to solve the problem? I'm afraid that I'm "reinventing the wheel" here.


text:
Q: Google Banner Ad is not displaying in Iphone x
please help me if anyone know it, its not displaying actual ad, just showing test ad, i am trying to display in simulator, is this not display in iphone X simulator, please suggest me

A: You cannot display Real Ad in simulator. Real Ad will be Display in Device only. In simulator you can see only Test Add.


text:
Q: How to use flow_from_directoey() for sub-directories? My directory looks like:
-train->class-1->images
               ->masks
      ->class-2->images
               ->masks
data_generator = ImageDataGenerator()
train_generator = data_generator.flow_from_directory(r'C:\Users\user\project-system\New folder\train\\',target_size=(image_size,image_size),batch_size=batch_size,class_mode='categorical')

How do I define ImageDataGenerator().flow_from_directoey()? I want to load only masks from class-1 and class-2.

A: Based on Keras documentation, flow_from_directory takes the path to a directory & generates batches of augmented data. The target directory should contain one subdirectory per class.  Any PNG, JPG, BMP, PPM or TIF images inside each of the subdirectories directory tree will be included in the generator.
So if you want to load Masks only, you should make your folders like:
-train_masks ->class-1->masks
             ->class-2->masks

-train_image ->class-1->images
             ->class-2->images


text:
Q: Include late person in all-meet-all speed networking rotation The top-voted answer here appears to solve the problem of rotating guests so that everybody meets everybody. But what if one person shows up late? Is there a way to add them to the rotation after it has already started without messing up the rotation for everyone else? Specifically, everyone already there should

*

*never have to sit out more than once

*never have to visit with the same person twice

*meet everyone else who showed up on time

If a solution does not exists, is there an almost-solution?

A: Let $N$ be the number of people at the networking event before the latecomer arrives.
The case where $N$ is odd is dealt with by @antkam in the comments: there is a (rotating) person left out in the ordinary rotation anyway, so we can just have that person meet with the latecomer. This way, there are equally many rounds, all the people from the original group of $N$ meet one another, and everyone participates in every round (from the moment that the late-comer arrives on).
Now consider the case where $N$ is even, where the people have been rotating around a table with one person fixed in place, as described in the linked answer. In this case, we can achieve the following:

*

*the latecomer's addition adds two rounds to the networking game,

*every participant sits out at most two rounds,

*everyone who was on time meets everyone who was on time originally.

(This is a worse solution than you had asked for; but see my explanation at the end.)
The people are rotating around a table with one person in a corner fixed in place. As soon as the late-comer arrives, you designate one chair, also in a corner, on the opposite side of the table from the person fixed in place. You place the newcomer there, and whenever a person from the original group would occupy that seat, they sit that round out instead. Other than that, everyone takes their positions in the original planning.
The original $N - 1$ rounds have the following results:

*

*The latecomer gets to meet someone every round from his arrival on. He fails to meet at least two people: the person fixed in place, and the person who was in the seat opposite him in round 1 (since they missed that round).

*The person fixed in place meets everyone except the latecomer.

*The people rotating fail to meet at most two on-time people: the person immediately before them in the rotation, and the person immediately after them in the rotation. These are the people they would ordinarily have met at the end of the table where the latecomer is sitting.
Once the original rounds are over, line up all the people who failed to meet a person they would otherwise have met, either because they talked to the latecomer or because they had to skip a round. If you line those people up in the original rotation order, the people they haven't talked to are the people they are adjacent to. Therefore, in the remaining two rounds, you can make pairs out of this line, so that everyone gets to meet every person adjacent to them.
You can furthermore pair up the late-comer with two people he hasn't met, to squeeze out as many meetings as you can.
Note that indeed everyone in the original group gets to meet everyone in the original group: if they hadn't met everyone in the original rounds, they would be in the line-up, and therefore meet the one or two people they had not met.
Furthermore, everyone sits out at most two rounds: if you sit out a round during the original rounds, it must be because the latecomer is sitting in your seat; but then you are in the line-up, and therefore have a meeting in at least one of the final two rounds.
Thus this strategy achieves the points outlined above.

Note that this is weaker than you had hoped for, but your demand was a bit optimistic: when $N$ in the original version of the problem shifts from even to odd, two rounds are added to the total number of rounds: everyone sits out a round, and everyone has to meet the new person. Therefore it makes sense that two rounds are added even if someone arrives late.
But then the demand that everyone sits out at most one round becomes too strong: there are 2 more rounds, and therefore $N$ new meeting slots. Of course the newcomer cannot participate in $N$ meetings total, since he already missed at least one. Therefore at least some of the original participants must sit out 2 rounds.

A: Not an answer but too long for a comment.
I just wanna point out the original networking problem (without the late-comer) is equivalent to edge-coloring the complete (undirected) graph $K_n$.  Each edge is a meeting, and edges of the same color are meetings happening simultaneously in one round in the schedule.  The rules of edge-coloring means no node has two edges of the same color, equivalent to no person having two meetings scheduled in the same round.  The schedule length (number of rounds) is the number of colors.
This problem has one of the most beautiful pictorial proofs I have ever come across.  It is constructive and obviously generalizable.
Here is the picture.  See if you can figure out what's going on.  I've always wondered if this proof can be classified as "wordless".  :)
$K_8$">
If you need words, read the caption from the source, or refer to the second paragraph "A complete graph..." of this article.
The text and picture both refer to the case of even $n$, but it's obvious you can drop the center node to get an optimal answer for odd $n$.
I think this assignment is equivalent to the top-voted answer from the other MSE question, with the center node being the stationary person, and the outer edge in a given color being where the moving "array" of people would be "folded" in that round.  Regardless, I offer this as at least a different visualization, from which maybe others can come up with other ways to deal with a late-comer.


text:
Q: Correct fd for a shell prompt I'm making a custom shell in C and I wonder on which fd I should write my prompts.
mycoolshell $

Looking into other classic shells, I found that dash uses STDERR for its prompts. csh and tcsh use STDOUT. For bash, zsh and BSD sh I wasn't able to find anything. I used
% dash 2>file
echo qwe
echo qwe
% cat file
(dashprompt$)
(dashprompt$)

to check dash's prompt fd. Same with csh with csh 1>file but I was unlucky with the other ones.
Is there a standard or POSIX fd for this? Is it ok to use STDIN?

A: If you wish to be Posix compatible, you'll need to write the prompt to stderr. (See the specification of the PS1 environment variable, below.)
Regardless of strict Posix compatibility, stdin is definitely not correct, since it may not allow write operations. stdout is also not a good idea, since it is usually line-buffered. Some shells (including zsh, I believe) write the prompt to a file descriptor connected to the current terminal (such as /dev/tty) which is probably what stderr is opened as if not redirected, although it is not necessarily the same file descriptor. But using /dev/tty or equivalent is non-standard.
The prompt is only printed if the shell is interactive. A shell is interactive, according to Posix, if it is invoked in one of two ways:

If the -i option is present, or if there are no operands and the shell's standard input and standard error are attached to a terminal, the shell is considered to be interactive. (sh utility, Options)

Clearly, you wouldn't want the shell to spew out prompts if you are using it to execute a script. So you need some mechanism to tell if the shell is being used interactively or as a script processor; Posix's requirement seems reasonably accurate. (See the isatty() library function to see one way to do this test.)
That also shows why your test failed to capture the prompt when stderr was redirected to a file. Redirecting stderr causes the shell to be non-interactive so there will not be a prompt. To do the test properly, you need to force the shell to be interactive using the -i option.
Posix requires that the prompt be modifiable by changing the value of the PS1 environment variable. Here's what Posix has to say, including the requirement that the prompt be printed to stderr: (emphasis added)

PS1
Each time an interactive shell is ready to read a command, the value of this variable shall be subjected to parameter expansion and written to standard error. The default value shall be "$ ". For users who have specific additional implementation-defined privileges, the default may be another, implementation-defined value. The shell shall replace each instance of the character '!' in PS1 with the history file number of the next command to be typed. Escaping the '!' with another '!' (that is, "!!" ) shall place the literal character '!' in the prompt. (Shell command language, Shell Variables)

Most shells allow a much richer set of substitutions in PS1. But the fact that the value is subject to parameter expansion allows extensive customisation. That means that (unlike usual variable expansion) parameter and command references appearing in the value of the PS1 variable are expanded every time the prompt is printed.


text:
Q: How to append dynamic data Basically i have a REST api which return a JSON . In this JSON , it return the last viewed topic. For example
{ lastview : ABC }

So i want to insert this to my page

Last viewed topic:

$.getJSON("json link", function(data){
 $('',{
 text: data.lastview
 }).appendTo('.lastview');

But since this data may change after another topic is viewed. What i mean is if user go to another topic name XYZ , the JSON change lastview from ABC to XYZ but the one in web will not ( still ABC ) because it only execute the function one time when the page loads.
So is there anyway to dynamically check the JSON and return correctly when the content changes ( What i mean is when the lastview topic change to XYZ , the one in div will automatically change to XYZ too)
Thanks

A: The setTimeout() method calls a function or evaluates an expression after a specified number of milliseconds.
1000 ms = 1 second.
The function is only executed once. If you need to repeat execution, use the setInterval() method.
setInterval({

$.getJSON("json link", function(data){

$('',
       {

         text: data.lastview

       }).appendTo('.lastview');

 }, 1000);

A: This is a sample of keep requesting and update every 500ms

setInterval(function() {
    // Fake ajax
    data = { lastview: "Page " + Math.floor(Math.random() * 3) };
    // Just for demo

    $("#lastview").empty();
    $("#lastview").append(
        $("").text(data.lastview)
    );
}, 1000);

Last viewed topic:


text:
Q: Simplicial complexes are to PL structures of manifolds as simplicial sets are to what? A simplicial complex is a PL structure for, and thus also homeomorphic to, a manifold if the link of every vertex is a simplicial sphere, for which there exists a definition. (I know that for high dimension, the definition might be untractable to check.) My question now is the same for simplicial sets.
Take for example the simplicial set with one vertex and one nondegenerate edge starting and ending at the vertex. Obviously, the geometrical realisation is $S^1$, but the link of the vertex is empty. In this case, the definition for a simplicial manifold fails.
I would be especially interested in a categorical definition, that is, one in terms of the simplicial set as a functor without much reference to its components.
Edit: I've clarified the question after a few years.


text:
Q: How can I change the shape of the scrollbar in tkinter, python? I use scrollbar widget and I want to change the shape of it.
Here's my questions below.

*

*Can I use the image on the scroll bar?

*How can I modify the color and shape with the options like relief, background, highlightbackground, highlightcolor or highlightthickness? I already tried but not a thing has changed.

from tkinter import *
root = Tk()
root.geometry("640x480")

frame = Frame(root)
frame.pack()

scrollbar = Scrollbar(frame, relief=RAISED, width=20, bd=5, activebackground="yellow", elementborderwidth=10, troughcolor="yellow", highlightbackground="red")
scrollbar.pack(side="right", fill="y")

listbox = Listbox(frame, selectmode="extended", height=10, bg="green", fg="white", yscrollcommand=scrollbar.set)
for i in range(1, 32):
    listbox.insert(END, str(i) + "day")
listbox.pack()

scrollbar.config(command = listbox.yview) # scrollbar와 listbox를 mapping 해줌

root.mainloop()


text:
Q: Ruby base class call child class like in abstract classes In Java, I am used to writing an abstract class that does some setup work and then delegates to the concrete class like this:
public abstract class Base {
    public void process() {
        // do some setup
        //...

        // then call the concrete class
        doRealProcessing();
    }

    protected abstract void doRealProcessing();
}

public class Child extends Base {
    @Override
    protected void doRealProcessing() {
        // do the real processing
    }
}

I am having a hard time doing this in Ruby because I don't have abstract classes or methods. I also read that "you aren't supposed to need abstract classes or methods in Ruby and that I should stop trying to write Java in Ruby".
I would love to know what is the right way to implement the equivalence in Ruby?

A: Welcome to dynamically typed languages!  You were probably nervous about just defining some function that wasn't declared anywhere.  Don't be worried.  It is very easy:
class Base
  def process
     # ...
     real_processing
  end

  def real_processing    # This method is optional!
    raise "real_processing not implemented in #{self.class.name}"
  end
end

class Child < Base
   def real_processing
     # ...
   end
end

b = Child.new
b.process

EDIT: Here's another option for you which avoids the need to have two different method names:
class Base
  def process
    # ...
  end
end

class Child < Base
  def process
    # ...
    super   # calls the process method defined above in Base
    # ...
  end
end

A: Here's how you can do the template pattern in Ruby:
class Template
  def template_method
    perform_step1
    perform_step2
    #do some extra work
  end

  def perform_step1
    raise "must be implemented by a class"
  end

  def perform_step2
    raise "must be implemented by a class"
  end
end

class Implementation < Template
  def perform_step1
    #implementation goes here
  end

  def perform_step2
    #implementation goes here
  end
end

http://andymaleh.blogspot.com/2008/04/template-method-design-pattern-in-ruby.html

A: You don't see much of this in Ruby for this use case, because the pattern

*

*do some household setup ( make a connection to a resource for
instance)

*do something real with it

*teardown household job (f.i. close connection)

is baked into ordinary methods:
# pseudocode:
def a_method(an_argument)
  # do some setup with an_argument
  yield(a_result)
  # do some teardown
end

# use like:
a_method(the_argument){|the_result| puts "real processing with #{the_result}"}


text: Q: Variance in memory reported with perfmon vs Task Manager in Windows I am recording Memory\% Committed Bytes In Use with perfmon every 15 seconds but I see that it doesn't always tie to task manager's reported memory %. They almost always tie but when memory starts to climb on the server, perfmon will show much lower than task manager. Here is a recording of one example. Which is more accurate?


text:
Q: HTML 'required' error firing way too late I have below (much simplified) HTML and javascript code. When I leave the numDig field empty and click on the Save button, the required error shows up over the input field a little too late, and the page redirects. When the page is already redirecting and loading, the required error appears.
Why does this happen and is there a way to fix this? Currently, I can submit the form without filling the required field.
I tried both button and input but they both do the same thing. The required error appears when the page is already redirecting.

<form>

 Enter the number you like

        <input id="numDig" type="number" min="1" max ="6" required>

        <button type="submit" onclick="saveSettings()">Save</button>

</form>

A: You put the fuction in onsubmit for required to take effect properly
<form onsubmit="saveSettings()">

 Enter the number you like

        <input id="numDig" type="number" min="1" max ="6" required>

        <input type="submit">Save</button>

</form>


text:
Q: ObservableList will not display on TableView because of "Duplicate TableColumns" (JAVAFX) I'm trying to display data from my ObservableList into a TableView, which I created in SceneBuilder. The TableView contains three TableColumns. I've given them the exact same name as in the FXML-file.
I've imported them into the Controller like you can see down below [1]
And then I'm trying to run my code. I basically have a song. The song consists of a title, artist and album. I want to display it on each column, but it keeps complaining about:
Duplicate TableColumns detected in TableView columns list with titles 'Song title', 'Artist', 'Album'.
And then crashes.
Anybody know what Im doing wrong?
@FXML
private TableView<Song> defaultTableView;

// 1) Song Title

@FXML
private TableColumn songTitleColumn;

// 2) Song artist

@FXML
private TableColumn songArtistColumn;

// 3) Song album
@FXML
private TableColumn songAlbumColumn;

public void initialize(URL location, ResourceBundle resources) {

    Song song1 = new Song("a lot.mp3");

    Song song2 = new Song("Work Out.mp3");

    Song song3 = new Song("Jesus Walks.mp3");

    Playlist myPlaylist = new Playlist("My awesome playlist");

    myPlaylist.addSong(song1);

    myPlaylist.addSong(song2);

    song1.getSongTitleFromDB();

    song1.getSongArtistFromDB();

    song1.getSongAlbumFromDB();

    myPlaylist.displayAllSongs(defaultTableView,songTitleColumn,songArtistColumn,songAlbumColumn);

    ObservableList<Song> songs = FXCollections.observableArrayList();

    songs.add(song1);

    songTitleColumn.setCellFactory(new PropertyValueFactory<Song,String>("songTitle"));

    songArtistColumn.setCellFactory(new PropertyValueFactory<Song, String>("songArtist"));

    songAlbumColumn.setCellFactory(new PropertyValueFactory<Song, String>("songAlbum"));

    defaultTableView.setItems(songs);

    defaultTableView.getColumns().addAll(songTitleColumn,songArtistColumn,songAlbumColumn);

A: Your fxml file looks something like this:
<TableView fx:id="defaultTableView">
    <columns>
        <TableColumn fx:id="songTitleColumn"/>
        <TableColumn fx:id="songArtistColumn"/>
        <TableColumn fx:id="songAlbumColumn"/>
    </columns>
</TableView>

Since columns is a readonly list property, loading the fxml file results in the columns being added to the TableView. Trying to add them another time to the TableView results in the exception.
You do this in the initialize method:
defaultTableView.getColumns().addAll(songTitleColumn, songArtistColumn, songAlbumColumn);

You need to remove this link or do all of the column creation in the initialize method.