text:
Q: Adding text to beginning of each array element I have an array which contains the contents as follows:
["ZS125-48ATab", "STR125YBTab", "KS125-24Tab", "ZS125-50Tab", "DFE125-8ATab", "ZS125-30Tab", "HT125-8Tab", "HT125-4FTab", "STR50Tab"]

Is it possible to append a # symbol to the front of each element in the array.
Thanks.

A: Example for ES6
var arr = ['first', 'second', 'third'];
arr = arr.map(i => '#' + i);

Result:
console.log(arr); // ["#first", "#second", "#third"]

A: for(var i=0;i<array.length;i++){
    array[i]="#"+array[i];
}

A: You can do it like this :
array = ('#' + array.join('#')).match(/#[^#]*/g) || []; // null || []

The following trick works as well, but I wonder why split ignores the first sharp...
array = ('#' + array.join('#')).split(/(?=#)/);

Indeed, I rather expected this scenario : "#a#b#c" -> ["", "#a", "#b", "#c"].
Anyway, I prefer the second method since match returns null in case of failure.

A: Iterate over the array and just add #
var arr = [your array];

for (var i=arr.length; i--;) {
    arr[i] = '#' + arr[i];
}

FIDDLE
In newer browsers you could do
arr = arr.map(function(e) {return '#' + e});

A: Simple & sweet in ES6 as,
array.map((line) => `#${line}`);

A: Use the forEach method(reference)
var array = ["ZS125-48ATab", "STR125YBTab", "KS125-24Tab", "ZS125-50Tab", "DFE125-8ATab", "ZS125-30Tab", "HT125-8Tab", "HT125-4FTab", "STR50Tab"];
array.forEach(function(element, index) {
    array[index] = '#' + element;
});

A: The following code would do the job:
var t = ["ZS125-48ATab", "STR125YBTab", "KS125-24Tab", "ZS125-50Tab", "DFE125-8ATab", "ZS125-30Tab", "HT125-8Tab", "HT125-4FTab", "STR50Tab"];

    for(var i=0;i<t.length;i++){
        t[i] = "#"+t[i];
    }

See demo here


text:
Q: People keep crashing when playing or joining my room, how can I prevent that from happening? I have a room that is pretty full of props, circuits, gadgets, and makerpen shapes, but when people try to join, they either crash to their dorm room, or get laden with excessive lag that eventually crashes them shortly after loading in.
The platforms that are most affected seem to be PSVR and Quest players. They may have to attempt several times to join the room before actually being able to join.
So far I've reduced the ink usage in the room down to 70% by removing some extra details and circuits but they're still encountering problems loading in and playing the game.
What are some things I can do to make the room easier to load?

A: There is a known bug right now that is causing lower-end hardware to have issues with loading really high detailed rooms with people already in them.  I believe the team has identified what it is and is working on a solution.
In the mean time, encourage quest and PSVR players to join the room privately.  Its not ideal, but typically will work.  My theory is there is something to do with time-out when loading a room.  You have to load all of the detail of a room, then start getting data about every player's movement in the room.  And getting that double-hit of data might be too much for PSVR or Quest, and it either times out and kicks you back to dorm, or crashes.

redpajama_set_name: RedPajamaStackExchange


text:
Q: The best way to get one single field in one line of code with ActiveRecord (Rails 4) I just want to get a scalar data (like int, string, etc.) from one field of a row.
If there is no row in the DB, I want it to be a nil.
The line of code below works well if there is a row:
User.select(:email).where(***).first.email

But there isn't, it will raise "NoMethodError: undefined method `email' for nil:NilClass".
So I must use ActiveSupport's "try" method.
User.select(:email).where(***).first.try(:email)

Or I must use pluck + Array#first instead.
User.select(:email).where(***).pluck(:email).first

But both of these two codes are a little bit lengthy to me.
Is there any better way to do this? If there is an interface like below, I'll be very happy.
User.where(***).field(:email)
# => returns "abc@example.com" or nil

A: I would do
(user = User.select(:email).where(***).first) && (user.email)

this will return either the email address of the user, or nil if there is no user.

A: If you only need one row then you should use find_by. So you can refactor you code like this.
User.find_by(***).try(:email)


text:
Q: Generating XML data from a row value having multiline data I need one help in SQL to generate XML file.
I  have one table which has one column with multiline row data.
Table Name: table1
Column Name: col1
1 Row Data is like below:
VALUE1
VALUE2

VALUE3
VALUE4

I need to generate below XML file.
<col1>
    <value>VALUE1</value>
    <value>VALUE2</value>
    <value>.</value>
    <value>VALUE3</value>
    <value>VALUE4</value>
</col1>

I have used below query to format the row data.
select
        level,
        case
            when regexp_substr(a.col_trimmed_value, '[^' || CHR(10) || ']+',  1, level) is not null
                THEN substr(regexp_substr(a.col_trimmed_value, '[^' || CHR(10) || ']+',  1, level), 1, 200)
            ELSE '.'
            END as ROW_VALUE
from (
    select
        col1              as col_original_value
        ,replace(rtrim(ltrim(replace(col1,CHR(10),'#s1p@2l3t#'),'#s1p@2l3t#'),'#s1p@2l3t#'),'#s1p@2l3t#',CHR(10)) as col_trimmed_value
    from
        table1
    )a
connect by level <=  length ( a.col_trimmed_value ) - length(replace( a.col_trimmed_value, CHR(10)) ) + 1
;

Expected Result :
LEVEL   ROW_VALUE
==================
1   VALUE1
2   VALUE2
3   .
4   VALUE3
5   VALUE4

Actual Result :
LEVEL   ROW_VALUE
==================
1   VALUE1
2   VALUE2
3   VALUE3
4   VALUE4
5   .

Can someone please help me to solve this issue?
Thank you in advance.

A: You can use a regular expression pattern that handles empty elements:
select
        level,
        case
            when regexp_substr(a.col_trimmed_value, '(.*?)(' || CHR(10) || '|$)', 1, level, null, 1) is not null
                THEN substr(regexp_substr(a.col_trimmed_value, '(.*?)(' || CHR(10) || '|$)', 1, level, null, 1), 1, 200)
            ELSE '.'
            END as ROW_VALUE
from (
...

You can also simplify that a bit so you only apply the regular expression once:
select
        level,
        coalesce(
          substr(regexp_substr(a.col_trimmed_value, '(.*?)(' || CHR(10) || '|$)', 1, level, null, 1), 1, 200),
          '.')
        as ROW_VALUE
from (
...

LEVEL
ROW_VALUE

1
VALUE1

2
VALUE2

3
.

4
VALUE3

5
VALUE4

db<>fiddle
If you end up with exactly the XML you showed in the question then the order doesn't matter; the child <value> nodes are unordered. But you might be adding the level as an attribute or something.

From the output you added as an answer, it looks like you might have CHR(13) in the value too (i.e. CRLF, not just LF). Changing the regex pattern ought to fix that:
regexp_substr(a.col_trimmed_value, '(.*?)(' || CHR(10) || CHR(13) || '?|$)', 1, level, null, 1), 1, 200)

db<>fiddle with and without that change.


text:
Q: Docuasign REST API re-enable e-signature user account I am trying to write some REST api functions to perform some basic user administration.  I cannot seem to find the secret sauce for re-enabling a closed e-signature user, using either the Admin API or the E-signature API.
I saw a post that said just send the create user POST with the same username and email, but every time I do that, I get a new e-signature user, and not a reactivated closed user.  I would appreciate any tips anyone could share.
Thanks
BL

A: Perhaps try issuing an Update User request, which allows you to specify the userId of the user account you want to (re)activate. For example:
PUT /accounts/{{accountId}}/users

{
    "users": [{
        "userId": "00000000-0000-0000-0000-000000000000",
        "sendActivationEmail": "send"
    }]
}


text:
Q: Count and group on occurrences of keys and their values I have a MongoDB collection that looks like this:
[{
        "installer": "anthony",
        "tester": "bob"
    }, {
        "installer": "chris",
        "tester": "anthony"
    }, {
        "installer": "bob",
        "tester": "dave"
    }, {
        "installer": "anthony",
        "tester": "chris"
    }, {
        "installer": "chris",
        "tester": "dave"
    }
]

I am trying to use aggregate so I can count how many times each name appears within each field and retrieve the following result:
[{
        "name": "anthony",
        "installer": 2,
        "tester": 1
    }, {
        "name": "bob",
        "installer": 1,
        "tester": 1
    }, {
        "name": "chris",
        "installer": 2,
        "tester": 1
    }, {
        "name": "dave",
        "installer": 0,
        "tester": 2
    }
]

This is the query that I have completed so far, the problem is that it returns only the name and installer count without the tester count. I could run this query twice (one for installer and one for tester) but I would like to find a way how to return both counts at once.
db.data.aggregate([
    {
        "$group": {
            "_id": "$installer",
            "installer": { "$sum": 1 }
        },
        "$project": {
            "name": "$_id",
            "installer": 1,
            "_id": 0
        }
    }
])

What changes to my query are needed so I can get both the installer and tester counts of each person?

A: You basically want $cond to select whether to pass 1 or 0 to the $sum accumulator in the $group pipeline, and an initial value as an "array" for both fields using $unwind to create a copy of the document for each person.
db.data.aggregate([
  { "$addFields": {
    "val": ["$installer","$tester"]
  }},
  { "$unwind": "$val" },
  { "$group": {
    "_id": { "_id": "$_id", "val": "$val" },
    "installer": {
      "$max": {
        "$cond": [
          { "$eq": ["$installer","$val"] },
          1,
          0
        ]
      }
    },
    "tester": {
      "$max": {
        "$cond": [
          { "$eq": ["$tester","$val"] },
          1,
          0
        ]
      }
    }
  }},
  { "$group": {
    "_id": "$_id.val",
    "installer": { "$sum": "$installer" },
    "tester": { "$sum": "$tester" }
  }}
])

To counter the case where a given document could have both the same "installer" and "tester" values we actually should aggregate on the "document" per the emitted "val" as a first step. Using the $cond inside a $max accumulator makes this case a "single" document instead of "two", being one for each array entry.
The other case of course is to simply return the "set" of values by applying $setUnion against the initial list to avoid the duplication in such an instance:
db.data.aggregate([
  { "$addFields": {
    "val": { "$setUnion": [["$installer","$tester"]] }
  }},
  { "$unwind": "$val" },
  { "$group": {
    "_id": "$val",
    "installer": {
      "$sum": {
        "$cond": [
          { "$eq": ["$installer","$val"] },
          1,
          0
        ]
      }
    },
    "tester": {
      "$sum": {
        "$cond": [
          { "$eq": ["$tester","$val"] },
          1,
          0
        ]
      }
    }
  }}
])

I added a document to your source as :
{ "installer": "jack", "tester": "jack" }

In order to illustrate the result.
As for $cond, it is a "ternary" or if..then..else condition, where the arguments are "first" if for a condition to evaluate as Boolean, then being the value to return when true and else as a value to return when the condition is false.
It can be alternately written like:
"$cond": {
  "if": { "$eq": ["$installer","$val"] },
   "then": 1,
   "else":  0
}

But the original "array" syntax is a bit more brief to write for simple expressions. Most people would still recognize the "ternary" for what it is, but if you think it makes the code clearer then you can used the "named keys" form instead.
The result of course is the 1 is only returned when the field is present in the document, giving the correct counts:
/* 1 */
{
    "_id" : "jack",
    "installer" : 1.0,
    "tester" : 1.0
}

/* 2 */
{
    "_id" : "dave",
    "installer" : 0.0,
    "tester" : 2.0
}

/* 3 */
{
    "_id" : "bob",
    "installer" : 1.0,
    "tester" : 1.0
}

/* 4 */
{
    "_id" : "chris",
    "installer" : 2.0,
    "tester" : 1.0
}

/* 5 */
{
    "_id" : "anthony",
    "installer" : 2.0,
    "tester" : 1.0
}

Adding the initial "array" to the document can alternately be done using $project if your MongoDB version does not support $addFields. The only difference is "explicitly" including the other fields that are required later:
{ "$project": {
  "tester": 1,
  "installer": 1,
  "val": { "$setUnion": [["$installer","$tester"]] }
}}

And if your MongoDB is still actually older than MongoDB 3.2 which allows that notation of an "array", then you can use $map instead from MongoDB 2.6 and upwards:
{ "$project": {
  "tester": 1,
  "installer": 1,
  "val": {
    "$setUnion": [
      { "$map": {
        "input": ["A","B"],
        "as": "a",
        "in": {
          "$cond": [{ "$eq": ["$$a", "A"] }, "$installer", "$tester"]
        }
      }
    ]
  }
}}

Again using $cond to alternately select which value to present as the array elements.
Also, you really should avoid doing things like adding a $project to the end of statements. You can of course do it, but it does mean that all results of the previous pipeline stage are being "run through again" in order to make the additional changes. For something as trivial as changing "_id" to "name", it's generally better practice to simply accept that the "grouping key" is called _id and leave it at that.
As the result of $group, it actually is the "unique identifier" for which _id is the common nomenclature.


text:
Q: Apache solr process killed automatically I am using Apache Solr for one of my Drupal sites. I start my Apache Solr with Java -Jar -Xmx256M start.jar to fix the memory limit. I run my Apache in screen, but at times i see that my instance of Apache solr gets stopped/killed automatically. In my dev server i find it very hard to start it manually. Is there any fix to stop the instance getting killed automatically?
By the way the following are some of the warning i get in the console
"solrconfig.xml:  is deprecated and no longer recommended used."
"WARNING:  and  configuration sections are deprecated (but still work). Please use  instead."
Thanks.

A: I had this problem initially as well. I solved it by starting a screen session as root and starting Solr within that session. Also try adding a nohup before the java command and see if that works.


text:
Q: Password field is not populated i have password textbox in that when user click on remeber me i want to populate name and password in respective textboxes only name is getting populated not password
i am storing name and password in cookies
i set textmode as password of textbox
also i have forms authentication
i also tried
txtpwd.Attributes.Add(value,txtpwd.text)

but no success
any help
appreciated

A: You can set the password value by setting its value attribute:
txtpwd.Attributes["value"] = "password";

A: This sounds like a by-design security feature.  "Remember me" is a matter for setting a cookie, not for rendering a password in plain text in the HTML being delivered to the client.  Never "show" a password.
Edit: In fact, you shouldn't even have the actual password to render.  If you're storing passwords in plain text, please do the world a favor and stop it.  One-way hashing is the only way to go for storing passwords.

A: You can't pre-populate a into a password field... and for good reason!
You should either remember that they chose to "Remember Me" and log them in automatically or leave remembering credentials to the browser!


text:
Q: Using useState and useEffect error update state when using reducer in useMemo not working I try to update data in the state, but I got error back
The error happens when the page refresh
const [local, setLocal] = React.useState(initialState || []);
React.useEffect(() => {
    getLocal();
}, []);
const getLocal = async () => {
    try {
        let lo = await _getData();
        if (lo != null) {
            setLocal(pre=>({...pre, ...lo});
        }
    } catch (err) {
        console.log(err);
    }
};
const [state, dispatch] = React.useReducer(reducer, local);
const store = React.useMemo(() => ({...state, dispatch}), [state]);

Type of error ...
ERROR  Warning: React has detected a change in the order of
Hooks called by App. This will lead to bugs and errors if not fixed.

   Previous render            Next render
   ------------------------------------------------------
1. useState                   useState
2. useMemo                    useEffect
   ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^


text:
Q: Create equal length vectors from time series based upon factor in R I have a data frame that is something like this:
time type count
1   -2    a     1
2   -1    a     4
3    0    a     6
4    1    a     2
5    2    a     5
6    0    b     3
7    1    b     7
8    2    b     2

I want to create a new data frame that takes type 'b' and creates the full time series by filling in zeroes for count. It should look like this:
time type count
1   -2    b     0
2   -1    b     0
3    0    b     3
4    1    b     7
5    2    b     2

I can certainly subset(df, df$type = 'b') and then hack the beginning and rbind, but I want it to be more dynamic just in case the time vector changes.

A: We can use complete from tidyr to get the full 'time' for all the unique values of 'type' and filter the value of interest in 'type'.
library(tidyr)
library(dplyr)
val <- "b"
df1 %>%
    complete(time, type, fill=list(count=0)) %>%
    filter(type== val)
#   time  type count
#  <int> <chr> <dbl>
#1    -2     b     0
#2    -1     b     0
#3     0     b     3
#4     1     b     7
#5     2     b     2

A: With base R:
df1 <- data.frame(time=df[df$type == 'a',]$time, type='b', count=0)
df1[match(df[df$type=='b',]$time, df1$time),]$count <- df[df$type=='b',]$count

df1
    time type count
1   -2    b     0
2   -1    b     0
3    0    b     3
4    1    b     7
5    2    b     2


text:
Q: Measurability of a point process or random measure at a measurable subset
*

*Suppose     $\xi$ is a point process
on $(S, B(S))$, where $S$ be locally
compact second countable Hausdorff
space equipped with its Borel
σ-algebra $B(S)$.
I was wondering if $\xi(A), \forall
    A \in B(S)$ is measurable, i.e. an
integer-valued random variable? So
that, for example, it makes sense to
talk about   $ E ( \xi(A) )$? If not, are there some cases when it is true?

*More generally, same questions for a
random measure instead of a point
process?

*If the answers to the above
questions are yes, can we say a
point process or random measure is a
stochastic process with index set
being the $\sigma$-algebra $B(S)$?

Thanks and regards!


text:
Q: ASP.Net Server Side code, does it keep running after user logged out? To give this question context we have an ASP.Net MVC Project which requires you to be authenticated to use the system (typical saas product). The project includes an inactivity timer which will log the user out if they leave the screen alone for too long.  The project is an SPA type project and Web API is used to get/post relevant data.
I am currently having to develop a routine that archives a potentially huge amount of data and the process itself is fine. What I'm not sure of is once the process is started, a post is sent to web api and the server side code starts running, does it continue to run if the inactivity timeout occurs or the user logs out manually for some reason?
I assume it would but I don't like to rely on assumptions.
EDIT: For example
For below comments/answers. Screen will have a list of tickboxes for the data they wish to archive so is not a set list of data so this project does need to process the task.
The following code is on the client side when running (checks etc omitted and data variable contains all true/false values for ticks):
self.Running = true;
self.showProgress();

http.ajaxRequest("post", "/api/archive/runarchive", data)
   .done(function () {
        self.Running = false;
   })
   .fail(function () {
        self.Running = false;
        app.showMessage("You do not have permission to perform this action!");
});

For reference the showProgress function used to pick up progress to display on screen. This is also run when accessing the screen in case an archive process is still running it can be displayed:
self.showProgress = function () {
        http.ajaxRequest("get", "/api/archive/getarchiveprocess")
        .done(function (result) {
            if (result.ID == -1) {
                $("#progressBar").hide();
                $("#btnArchive").show();
                if (self.Running) setTimeout(self.showProgress, 2000);
                else app.showMessage("The Archive Process has finished.");
            }
            else {
                $("#progressBar").show();
                $("#btnArchive").hide();
                $("#progressBarInner").width(result.Progress + '%');
                $("#progressBarInner").attr("data-original-title", result.Progress + '%');
                setTimeout(self.showProgress, 2000);
            }
        });
    };

Server Side:
[HttpPost]
public void RunArchive(dynamic data)
{
    // Add table row entry for the archive process for reference and progress
    // Check each tick and update tables/fields etc
    // Code omitted as very long and not needed for example
    // table row for reference edited during checks for showProgress function
}

So basically I'm asking if the RunArchive() function on the controller will keep running until it's finished despite user logging off and being unauthenticated in some way. I'm aware any IIS, App Pool refresh etc would.

A: It sounds like web api is the one doing the heavy work and once that starts it will continue to run regardless of what happens on the UI side of things.
This being said, there is a timeout for webapi requests that you can control in web.config.
You might want to consider another alternative. Whenever you're talking about heavy processing tasks, you're better offloading those to another service.
Your API is supposed to be responsive and accessible by your users and it needs to respond fast to allow for a better experience. If you get 100 users doing heavy work, your API will basically crumble.
The API could simply send commands to a queue of stuff that needs to be run and another service can pick them up and execute them. This keeps your API lightweight while the work is still being done.
You're talking about archiving which probably involves a database and there is no reason why you can't have something else do that job.
You could keep track of jobs in the database, you could build a table which holds statuses and once a job is done, the external service changes the status in the database and your UI can then show the result.
So the API could work like this:

*

*add message to queue

*add job details to db with status of "new" for example and a unique id which allows the queue item to be linked to this record.

*Service B picks up the job from the queue and updates status in db to "running".

*Job finishes and Service B updates status to "complete".

*the UI reflects these statuses so the users know what's going on.

Something like this should would make for a better user experience I would think.
Feel free to change whatever doesn't make sense, it's a bit hard to give suggestions when you don't know the details of what needs to be done.
This Service B could be a windows service for example or whatever else you want that can do the job. The user permissions come into play in the beginning only, a work item would be added to the queue only if the user has the permission to initiate that. This gives you the certainty that only authorized jobs are added.
After that, Service B won't care about user permissions and will do the job to the end irrespective about users being logged in or not.
This is largely guess work at this point, but you should be able to get an idea of how to do this.
If you have more specific requirements you should add those to the initial question.

A: Even if the process isn't killed by the user logging out, you also need to consider that IIS can recycle app pools, and by default is set to do so once a day, as well as on memory contention, either of which will kill your long running process.
I would highly recommend you check out Hangfire.io, which is designed to help with long running processes in ASP.Net sites.


text:
Q: Transferred efficient multiplication algorithm from MATLAB to Fortran does not match Related to this question Thanks to the idea of @veryreverie, I was eventually able to multiply the block diagonal matrix by a vector with some modifications. (Matrix structure is at the end of post). However something is wrong. When I run the algorithm in MATLAB, there no issues.
The difference in direct multiplication and my result of C'*x - bn is within 1e-15 range due to machine addition non-associativity. However, when trying the same thing in Fortran it differs significantly, up to NaN value:
f90 code:
module RHS
implicit none
contains
subroutine RHS_eval(m,n,C,MM,q,LAP,BCterm,ADV,bn)

real*8, intent (in) :: x(:),C(:,:)
real*8, intent (out) :: bn(:)
integer*8 :: row, col
integer*8, intent (in) :: m,n

integer*8 :: offset, blkSz, blkShft, i
integer*8 :: xstart, ystart

bn = 0

bn(1:(m-1)*(n-1)) = bn(1:(m-1)*(n-1)) + x(1:(m-1)*(n-1));
bn(1:(m-1)*(n-1)) = bn(1:(m-1)*(n-1)) - x(m:(m-1)*n);

blkSz = m;
offset = (m-1)*(n);
blkShft = m-1;

do i = 1,(n-1)
    xstart = offset + blkSz*(i-1)+1;
    ystart = (i-1)*(m-1)+1;
    bn(ystart:ystart+blkShft-1) = bn(ystart:ystart+blkShft-1) - x(xstart:xstart+blkShft-1);
    bn(ystart:ystart+blkShft-1) = bn(ystart:ystart+blkShft-1) + x(xstart+1:xstart+blkShft);
enddo

end subroutine RHS_eval

end module RHS

MATLAB code:
n = 15; m = 10;
x = (10*rand((m-1)*n+(n-1)*m,1));
bn = zeros((n-1)*(m-1),1);

bn(1:(m-1)*(n-1)) = bn(1:(m-1)*(n-1)) + x(1:(m-1)*(n-1));
bn(1:(m-1)*(n-1)) = bn(1:(m-1)*(n-1)) - x(m:(m-1)*n);

blkSz = m;
offset = (m-1)*(n);
blkShft = m-1;

for i = 1:(n-1)
    xstart = offset + blkSz*(i-1)+1;
    ystart = (i-1)*(m-1)+1;
    bn(ystart:ystart+blkShft-1) = bn(ystart:ystart+blkShft-1) - x(xstart:xstart+blkShft-1);
    bn(ystart:ystart+blkShft-1) = bn(ystart:ystart+blkShft-1) + x(xstart+1:xstart+blkShft);
end

We take the transpose of matrix C and multiply from RHS by a vector. There is no need to store the matrix since its structure is known.

Fixed a tiny bit, at early iterations it kinda works as expected, the number shown is the difference between matmul and my multiplication algo
maxval(abs(bn - matmul(transpose(C),(x))))

But starting at around 60th step starts to blow up

This issue only happens for the case when m and n are not equal


text:
Q: Where should I ask a question about office maintenance? (Specifically, magnetic door holder) I googled "maintenance stack exchange", but obviously that had undesired results :)
Where can/should I ask questions about office maintenance? I'm leaning toward Home Improvement, but I hoped there might be a better option I'm not aware of.
The specific question is about some magnetic door holders (magnets at the top that keep the door open and release if there is a fire).  My hope is that there is a simple switch somewhere to turn these on, but I don't know what to look for.

A: Home Improvement seems the best bet here, and I don't think that the situation of an "office" environment will make your question off-topic:

Ask about...

*

*Questions you would typically ask a home contractor.

*Which tools, materials, and best practices for home improvement task.

*Identifying the source or cause of a problem within your home.

*National building codes (of any country).

*Installation, maintenance, and repair of major appliances.

*Carpentry and woodworking.


text:
Q: Net::SSH::Exception: curve name mismatched (`' with `nistp256') Using -
Ruby-2.7.3
Rails - 6.1.3
Use Capistrano gem for deployment but it throws below error -
/var/home/username/.rvm/gems/ruby-2.7.3@appname/gems/net-ssh-6.1.0/lib/net/ssh/transport/openssl.rb:144:in read_keyblob': curve name mismatched (' with nistp256') (Net::SSH::Exception) 1: from /var/home/username/.rvm/gems/ruby-2.7.3@appname/gems/sshkit-1.21.2/lib/sshkit/runners/parallel.rb:11:in block (2 levels) in execute'
/var/home/username/.rvm/gems/ruby-2.7.3@appname-6/gems/sshkit-1.21.2/lib/sshkit/runners/parallel.rb:15:in rescue in block (2 levels) in execute': Exception while executing on host carbonite: curve name mismatched (' with nistp256') (SSHKit::Runner::ExecuteError) (Backtrace restricted to imported tasks) cap aborted! SSHKit::Runner::ExecuteError: Exception while executing on host carbonite: curve name mismatched (' with `nistp256')
Caused by:
Net::SSH::Exception: curve name mismatched (' with nistp256')


text:
Q: Using AsyncTask to download an XML file I've been working on a simple weather app - and I'm using the Google Weather API. I'm trying to download the XML file and build the UI based on the info in it.
I try using AsyncTask to download the XML file and then parse it - but something's not working! When I run the code I don't have any error / the app starts but the info from the xml file is not shown!
Here's the code:
    package com.android.weatherApp;

public class WeatherAppActivity extends Activity {

    static String url="http://www.google.com/ig/api?weather=";
    static final String KEY_FORCAST_INFO="forcast_information";
    static final String KEY_CITY="city";
    static final String KEY_CURRENT_CONDITIONS="current_conditions";
    static final String KEY_CONDITION="condition";
    static final String KEY_TEMP="temp_c";
    static final String KEY_ICON_SRC="icon";
    static final String KEY_FORCAST_COND="forecast_conditions";
    static final String KEY_DAY_WEEK="day_of_week";
    static final String KEY_LOW_TEMP="low";
    static final String KEY_HIGH_TEMP="high";
    Document finalDoc;
    XMLParser xmlParser;
    private TextView currentWeather;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        downloadXMLFile task=new downloadXMLFile();
        task.execute("New+York");

    }

    private class downloadXMLFile extends AsyncTask<String,Void,String>
    {
        @Override
        protected String doInBackground(String... params) {

            String xml=null;

            try{
                DefaultHttpClient httpClient=new DefaultHttpClient();
                HttpPost httpPost=new HttpPost(url+params[0]);
                HttpResponse httpResponse = httpClient.execute(httpPost);
                HttpEntity httpEntity=httpResponse.getEntity();
                xml=EntityUtils.toString(httpEntity);

            }
            catch(UnsupportedEncodingException e)
            {
                e.printStackTrace();
            } catch (ClientProtocolException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            return xml;
        }

        @Override
        protected void onPostExecute(String xmlString)
        {
            Document doc = null;
            DocumentBuilderFactory dbf= DocumentBuilderFactory.newInstance();

            try {
                DocumentBuilder db = dbf.newDocumentBuilder();
                InputSource is=new InputSource();

                is.setCharacterStream(new StringReader(xmlString));
                doc=db.parse(is);

            } catch (ParserConfigurationException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (SAXException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            finalDoc=doc;

            NodeList nl=finalDoc.getElementsByTagName(KEY_CURRENT_CONDITIONS);
              NodeList nl2=finalDoc.getElementsByTagName(KEY_FORCAST_COND);
              currentWeather=(TextView)findViewById(R.id.currentState);
              TextView currentTemp = (TextView)findViewById(R.id.tempC);
              TextView currentLocation=(TextView)findViewById(R.id.currentLocation);
              currentLocation.setText("Iasi");

              for(int i=0;i<nl.getLength();i++)
              {
                Element e= (Element)nl.item(i);
                String cs=xmlParser.getValue(e, KEY_CONDITION).toUpperCase();
                currentWeather.setText(cs);

                String temperature=xmlParser.getValue(e, KEY_TEMP);
                currentTemp.setText(temperature);

                String logoImg=xmlParser.getValue(e, KEY_ICON_SRC).toLowerCase();

                if(logoImg.equals("/ig/images/weather/sunny.gif"))
                {
                    ImageView img=(ImageView)findViewById(R.id.wImg);
                    img.setImageResource(R.drawable.sun);
                }

              }

              for(int i=0;i<nl2.getLength();i++)
              {
                Element e=(Element)nl2.item(i);
                TextView day1=(TextView)findViewById(R.id.day1);
                day1.setText("TOMORW");
                TextView day2=(TextView)findViewById(R.id.day2);
                TextView day3=(TextView)findViewById(R.id.day3);
                ImageView img1=(ImageView)findViewById(R.id.day1Logo);
                ImageView img2=(ImageView)findViewById(R.id.day2Logo);
                ImageView img3=(ImageView)findViewById(R.id.day3Logo);
                TextView highTemp1=(TextView)findViewById(R.id.day1MaxTemp);
                TextView highTemp2=(TextView)findViewById(R.id.day2MaxTemp);
                TextView highTemp3=(TextView)findViewById(R.id.day3MaxTemp);

                String d1=xmlParser.getValue(e, KEY_DAY_WEEK).toUpperCase();
                String t=xmlParser.getValue(e, KEY_HIGH_TEMP); //get the max value of temperature - Fahrenheit
                int tempF=Integer.parseInt(t); // make the string a number
                float tC=(float) ((5./9)*(tempF-32)); // calculate the Celsius value of temperature
                tempF=(int)tC; // get only the Int value
                t=Integer.toString(tempF); // transform the temperature value back to string

                switch(i)
                {
                case 1:
                    highTemp1.setText(t);
                    break;
                case 2:
                    highTemp2.setText(t);
                    day2.setText(d1);
                    break;
                case 3:
                    highTemp3.setText(t);
                    day3.setText(d1);
                    break;
                }
              }
        }

    }

Please if you can tell me what am I doing wrong.
Thanks!

A: First, your url variable contains "http://www.google.com/ig/api?weather=" not "http://www.google.com/ig/api?weather=New+York" so the xml content is empty.
Try something like this in doInBackground method :
String currentUrl = url;
if(params.length>0 && params[0]!=null)currentUrl+= params[0];

I see that you instanciate your Views inside a loop. You must instanciate them inside your onCreate method or onStart method. Doing this, you will instanciate these variables after your activity is created and you will gain performance.

A: In your manifest, have you added <uses-permission android:name="android.permission.INTERNET"/> ?
Can you put Log.i("test",xmlString); in your onPostExecute and see in your log the result ?


text:
Q: Who calls onStartup(ServletContext) method on Spring DynamicRegistrationBean DynamicRegistrationBean is used to register servlets and filters in the ApplicationContext and this registration happens in onStartup(..) method.
Per ServletContextInitializer(which DynamicRegistrationBean implememts) Java Docs...

This interface is primarily designed to allow
  "ServletContextInitializers" to be managed by Spring and not the
  Servlet container.

My question is, when does spring call onStartup(..) method on DynamicRegistrationBean bean.


text:
Q: One query causes 3 connections on socket.io When a user visits a webpage, node.js fires up the io.sockets.on("connection", ..) event three times. I'd like to avoid this because it performs a SQL query, and I don't want to do it 3 times per visitor.
One of it seems to be my client side JS - I commented out all except the socket.io connection line in the client JS, and I still see 2 connection events fired in node.js.
What could be the cause?


text:
Q: SCP equivalent in chef I am trying to scp a file from a server to another server both on Azure. This is the command I want to replace:
cp /tmp/openvpn/EasyRSA-3.0.4/pki/reqs/server.req jkirby29@40.121.47.3:/tmp

I have tried remote_file already, I am not sure of anything else that is even close to what I need. Is this one of those where I need to put it in a bash block? I am new to chef so excuse my lack of knowledge.

A: This is not really something Chef supports. The remote_file resource does support SFTP, but it expects to be pulling from a remote server, not pushing as this is. In general this kind of approach leads to a lot of complexity when scaling up/out, like when you need to push to a dozen machines instead of just one, so you need to work out which IPs, which might be changing, etc etc. You can use an execute or script resource to do it as written though, if that's really what you want.


text:
Q: Textarea auto-resize to fit content when resizing browser window I want to create a textarea that expands or contracts to fit the content as the browser window is resized. So when the browser window width increases, the height of the textarea should decrease so that it is as tall as the content; when the browswer window width decreases, the height of the textarea should increase to show all of the content. Here's what I have now, with reference to textareas that expand with content input:
var tx = document.getElementsByTagName("textarea");
for (let i = 0; i < tx.length; i++) {
  tx[i].setAttribute("style", "height:" + (tx[i].scrollHeight) + "px;overflow-y:hidden;");
  window.addEventListener("resize", autoResize(tx[i]));
}

function autoResize(el) {
  el.style.height = "auto";
  el.style.height = (this.scrollHeight) + "px";
}

How do I get this to work?
*Edit: clarifying what I mean by auto-resize
*Edit 2: I checked related questions but they all address how textareas resize with user input, whereas I'm asking how they resize when the browser window is resized. I'm new to Javascript so I don't know how to apply these solutions to my problem.

A: If you want the textarea to expand depending on browser window, u can use viewport units.
Vh stands for 1% of the viewport height and vw for 1% of the viewport width.
100vh //100% of the viewport height
100vw //100% of the viewport width


text:
Q: What is required by a process to set its uid to 0 (root)? I am completely new to *NIX based OSes. One of the things that baffles me is that a process or program may execute setuid(0) and then perform privileged operations and revert back to its normal uid.
My question is what is the mechanism in *NIX to prevent any arbitrary process from possessing root ?
If I write a simple C program that calls setuid(0) under what conditions will that call succeed and under what conditions will it fail ?

A: In addition to the user id, a process is also associated with an effective user id. When a setuid root program like su is executed, the effective uid is set to 0, but the real uid stays the same. The effective uid is, as the name says, the uid that is used for permission checks, the real uid just tells "who we really are". A process with an effective uid equal to zero can successfully call setuid(0) to change the real uid to zero.

A: The basic idea is that a process may only reduce its privileges. A process may not gain any privileges. There is one exception: a process that executes a program from a file that has a setuid or setgid flag set gains the privileges expressed by this flag.
Note how this mechanism does not allow a program to run arbitrary code with elevated privileges. The only code that can be run with elevated privileges is setuid/setgid executables.
The root user, i.e. the user with id 0, is more privileged than anything else. A process with user 0 is allowed to do anything. (Group 0 is not special.)
Most processes keep running with the same privileges. Programs that log a user in or start a daemon start as root, then drop all privileges and execute the desired program as the user (e.g. the user's login shell or session manager, or the daemon). Setuid (or setgid) programs can operate as the target user and group, but many switch between the caller's privileges and their own additional privileges depending on what they're doing, using the mechanisms I am going to describe now.
Every process has three user IDs: the real user ID (RUID), the effective user ID (EUID), and the saved user ID (SUID). The idea is that a process can temporarily gain privileges, then abandon them when it doesn't need them anymore, and gain them back when it needs them again. There's a similar mechanism for groups, with a real group ID (RGID), an effective group ID (EGID), a saved group ID (SGID) and supplementary groups. The way they work is:

*

*Most programs keep the same real UID and GID throughout. The main exception is login programs (and daemon launchers), which switch their RUID and RGID from root to the target user and group.

*File access, and operations that require root privileges, look at the effective UID and GID. Privileged programs often switch their effective IDs depending on whether they're executing a privileged operation.

*The saved IDs allow switching the effective IDs back and forth. A program may switch its effective ID between the saved ID and the real ID.

A program that needs to perform certain actions with root privileges normally runs with its EUID set to the RUID, but calls seteuid to set its EUID to 0 before running the action that requires privileges and calls seteuid again to the EUID change back to the RUID afterwards. In order to perform the call to seteuid(0) even though the EUID at the time is not 0, the SUID must be 0.
The same mechanism can be used to gain group privileges. A typical example is a game that saves high scores of local users. The game executable is setgid games. When the game starts, its EGID is set to games, but it changes back to the RGID so as not to risk performing any action that the user isn't normally allowed to do. When the game is about to save a high score, it changes its EGID temporarily to games. This way:

*

*Because the high score file requires privileges that ordinary users don't have, the only way to add an entry to the high score file is to play the game.

*If there's a security vulnerability in the game, the worst that it can do is grant a user permission to the games group, allowing them to cheat on high scores.

*If there's a bug in the game that doesn't result in the program calling the setegid function, e.g. a bug that only causes the game to write to an unintended file, then that bug doesn't allow cheating on high scores, because the game doesn't have the permission to write to the high score file without calling setegid.

What I wrote above is describes a basic traditional Unix system. Some modern systems have other features that complement the traditional Unix privilege model. These features come in addition to the basic user/group effective/real system and sometimes interact with it. I won't go into any detail about these additional features, but I'll just mention three features of the Linux security model.

*

*The permission to perform many actions is granted via a capability rather than to user ID 0. For example, changing user IDs requires the capability CAP_SETUID, rather than having user ID 0. Programs running as user ID 0 receive all capabilities unless they go out of their way, and programs running with CAP_SETUID can acquire root privileges, so in practice running as root and having CAP_SETUID are equivalent.

*Linux has several security frameworks that can restrict what a process can do, even if that process is running as user ID 0. With some security frameworks, unlike with the traditional Unix model and capabilities, a process may gain privileges upon execve due to the security framework's configuration rather than due to flags in the executable file's metadata.

*Linux has user namespaces. A process running as root in a namespace only has privileges inside that namespace.

A: In order for setuid(some_uid) to work, the following conditions need to be met:

*

*The executable's file needs to be owned by some_uid1.

*The executable's file needs to have the setuid permission.

The setuid permission can be granted or removed with chmod:
chmod u+s execuables_file_name
chmod u-s execuables_file_name

The setuid permission can be seen when displaying the file permissions as the execute permission will be replaced by an s if the setuid permission is granted.
> ll execuables_file_name
-rwsrwxr-x 1 root root 0 Sep 30 17:23 execuables_file_name*

If for some reason the owner user doesn't have execute permissions, then it will be displayed as a capital S instead:
> ll execuables_file_name
-rwSrwxr-x 1 root root 0 Sep 30 17:23 execuables_file_name*

Note that scripts are an entirely different beast.
A thorough guide to permissions.
1. setuid(some_uid) will also succeed if transitioning to the user id that started the process


text:
Q: Express server GET request userId I want to create an GET API route for taskuser/getallusers?userId='' .
I want to get all tasks that are assigned to a specific user. But when i test this call (http://localhost:4000/api/taskuser/getalltasks?userId=5bfe4af425ddde2b04eb19c6) but no error ?
I still get all tasks assigned to any user. can someone tell me what goes wrong ?
Model taskuser:
const mongoose = require('mongoose');

const TaskuserSchema = new mongoose.Schema({
task_name:{
    type: String,
    required: true,
    minlength: 1,
    unique: true,
},
userId: {
    type: mongoose.Schema.Types.ObjectId,
    required: true,
  },
task_category: String,
task_xpreward: Number,
task_completed: Boolean,
task_difficulty: Number,
task_city : String,
});

Api route:
router.get('/getalltasks/:userid', cors(),async(req,res) => { // Add /:userid
 var userid = req.params.userid;
 Taskuser.find({ userId: userid}, function(err, tasks) {
  // if there is an error retrieving, send the error.
  // nothing after res.send(err) will execute

  if (err)
      res.send(err);

  res.json(tasks); // return all tasks that are in JSON format

 });
});

Edit: new api route

A: You should update the code to :
router.get('/getalltasks/:userid', cors(),async(req,res) => { // Add /:userid
var userid = req.params.userid;
Taskuser.find({ userId: userid}, function(err, tasks) {
    // if there is an error retrieving, send the error.
    // nothing after res.send(err) will execute
    if (err)
        res.send(err);

    res.json(tasks); // return all tasks that are in JSON format

  });
});

Documentation : https://mongoosejs.com/docs/api.html#model_Model.find

A: Change your api route file to this:
router.get("/getalltasks", cors(), async (req, res) => {
  var userid = req.params.userId;
  Taskuser.find({ userId: userid }, function(err, tasks) {
    var userid = req.params.userId;

    // if there is an error retrieving, send the error.
    // nothing after res.send(err) will execute
    if (err) res.send(err);
    res.json(tasks); // return all tasks that are in JSON format
  });
});


text:
Q: How to maximize python efficiency? I am working on a Code Signal practice interview question and my code passes 16/19 tests but the ones it is failing the rest due to exceeding the allowed time limit.
I tried using set() instead of a list but then the count method doesn't work, and since I'm extremely new to python I don't know a better alternative.
def firstNotRepeatingCharacter(s):
    list = []
    num = '_'
    for i in s:
        list.append(i)
    for i in list:
        if list.count(i) <= 1:
            num = i
            return num
    return num

A: If you're using Python 3.7+, where dict keys are insertion-ordered, you can use collections.Counter:
from collections import Counter
def firstNotRepeatingCharacter(s):
    return next((char for char, count in Counter(s).items() if count == 1), '_')

With prior versions of Python, you can use collections.OrderedDict to keep track of the counts instead:
from collections import OrderedDict
def firstNotRepeatingCharacter(s):
    counts = OrderedDict()
    for char in s:
        counts[char] = counts.get(char, 0) + 1
    return next((char for char, count in counts.items() if count == 1), '_')

so that firstNotRepeatingCharacter('aababdcbcea') returns: 'd'
Both of the above code snippets have a time complexity of O(n), as opposed to O(n ^ 2) in your solution due to your use of the list.count method in a loop.

A: You can have a dictionary to mantain counter of each character and check which char count is 1. This computes in O(N), your solution takes O(N^2) due to list.count() method
def firstNotRepeatingCharacter(s):
    num = '-'
    d = {}
    for i in s:
        d[i] = d.get(i, 0) + 1

    for i in s:
        if d[i] == 1:
            return i
    return num


text:
Q: RESTful URL design for unauthenticated requests I want to provide the ability for resetting a user`s password. This call obviously must not require authentification.
First I thought of something like this:
DELETE /users/{id}/password: generates a reset token that gets sent to the user via email
POST /users/{id}/password: requires the new password and a valid reset token in the body
But the problem is, the application or website cannot provide me the ID of the user, because all it can ask the user for is his email address.
There are a number of other (unauthenticated) calls to our API, where the ID is not present and the user is only identified by its email.
We discussed the following solutions in our team:

*

*Replacing the ID in the URL with the users email

*Cut out the ID from the URL and provide the email with query parameters

If I had to choose between those two, I would take the first one, because I think it is not RESTful to provide something essential with query parameters, as they always represent something optional, like filtering a resource.
Are there better ways to design these URLs or is replacing the ID with the users email just fine concerning REST contraints?

A: POST /passwordResets
{
    "emailAddress": "bob@example.com"
}

Then you have the flexibility to reset by userId also, and you can track the resets just like any other resource for auditing purposes.
Of your two options, the first isn't awful if you can use an email address to uniquely identify a user. It's conceptually wrong, though, because there should be one canonical location for each resource, and now you have two - /users/bob/password and /users/bob@example.com/password.
The second option is just wrong. /users/password is not meaningful. The direct implication of /users is that the next path element is a user. /users/password is closer to RPC than REST.


text:
Q: How to get a count of values in a Pandas DataFrame column within groups? I have a DataFrame with a structure like this:
df = pd.DataFrame({
        'id': ['123', '123', '123', '456', '456', '789'],
        'type': ['A', 'A', 'B', 'B', 'C', 'A']
     })

id
type

123
A

123
A

123
B

456
B

456
C

789
A

How can I get a count of each type grouped by id, and create a new column for each unique type?
The resulting DataFrame I'm looking for would look like this:
df = pd.DataFrame({
        'id': ['123', '456', '789'],
        'A': [2, 0, 1],
        'B': [1, 1, 0],
        'C': [0, 1, 0]
    })

id
A
B
C

123
2
1
0

456
0
1
1

789
1
0
0

Thank you for any help and guidance.

A: You can do:
out = df.groupby(['id','type']).size().unstack().fillna(0).astype(int).rename_axis([None])

or as @Quang Hoang suggested, simply as
out = pd.crosstab(df['id'], df['type']).rename_axis([None])

Output:
type  A  B  C
123   2  1  0
456   0  1  1
789   1  0  0

A: You can use function for each column using pd.apply.
For example if you want to count values of column "c" you can do this:
New_column = df["C"].apply(count)

New_column is a series of column "c" counts.

A: Another way by aggregating:
df.groupby(['id', 'type']).agg(count=('type', len)).reset_index().pivot(index='id', columns='type', values='count').fillna(0)

type    A   B   C
id
123 2.0 1.0 0.0
456 0.0 1.0 1.0
789 1.0 0.0 0.0


text:
Q: How to prevent Notepad++ search to loop? I like when a search functionality tells me there's no more results when reaching the end of the file, rather than looping to the beginning of the file.
How can I do that in Notepad++? I can't find this option in the preferences menu.

A: Uncheck Wrap around when searching.


text:
Q: Aligning two DIVs with images side by side and making responsive I'm really hoping someone can help me here as I've been working on this for days now and don't have any hair left to pull out!!!!
I'm working on a Wordpress site and trying to get the logo and an image to line up side by side and be somewhat responsive. I've got it working perfectly in Firefox and Chrome  using 'display: inline-flex' but know that wont work for Safari width 700px - 960px or iPad portrait view where in both cases the logo and image stack on top of one another.
They should remain side by side until the screen width gets down to 700px then I'm happy for them to stack.
If anyone could help me out with the code required to get this working cross browsers I'd REALLY appreciate it.
Here is the site
I don't think it complicates matters but the code for the logo is PHP rather than straight HTML, the code for the advert at the bottom is HTML (added by me)
        <?php
        $use_header_banner = et_get_option( 'lucid_468_header_enable', 'false' );
    ?>

        <div id="logo-area"<?php if ( 'on' == $use_header_banner ) echo ' class="header_banner clearfix"'; ?>>
            <a href="<?php echo esc_url( home_url( '/' ) ); ?>">
            <?php
                    $color_scheme = et_get_option( 'lucid_color_scheme', 'Orange' );
                    $color_scheme = ( 'Orange' == $color_scheme ) ? '' : '-' . strtolower( $color_scheme );
                    $logo = ( ( $user_logo = et_get_option('lucid_logo') ) && '' != $user_logo ) ? $user_logo : get_template_directory_uri() . "/images/logo{$color_scheme}.png";
                ?>
                <img src="<?php echo esc_url ( $logo ); ?>" alt="<?php echo esc_attr( get_bloginfo('name')) ; ?>" id="logo"/>

            <?php if ( 'on' == $use_header_banner ){ ?>

                    <?php
                    if ( ( $lucid_468_header_adsense = et_get_option('lucid_468_header_adsense') ) && '' != $lucid_468_header_adsense ) echo( $lucid_468_header_adsense );
                        else { ?>
                           <a href="<?php echo esc_url(et_get_option('lucid_468_header_url')); ?>"><img src="<?php echo esc_attr(et_get_option('lucid_468_header_image')); ?>" />
                    <?php } ?>

            <?php } ?>

Which ends up looking like this

Here is all the associated CSS
#pt-header {
    margin-bottom: -2px;
    }

#logo-area img {
    float: left;
    padding-bottom: 11px;
    padding-top: 20px;
    clear: both;
}

.container #logo-area {
    margin-bottom: 0px;
    text-align: center;
}

#head-ad img {
    padding-left: 40px;
}

img {
    height: auto;
    max-width: 100%;
    width: auto;
}

@media only screen and ( min-width: 700px ) and ( max-width: 960px ) {
#pt-header {display: inline-flex;}
}

Thanks for looking.

A: Thanks to everyone who looked, I've now sorted this using the responsive grid system link


text:
Q: What is Wordpress' custom post type 'Logs'? I'm in index.php and I'm trying to create a list of links to the archive pages for three custom post types I've registered. Here's what I have so far:
// Get custom post types, excluding Wordpress' built-in ones

$cpts = get_post_types( array(
    '_builtin' => false
));

// Get a name and a link to the archive page of each custom post type

foreach( $cpts as $cpt ) {
    $name = get_post_type_object( $cpt )->labels->name;
    $link = get_post_type_archive_link( $cpt );
    echo "$name";
}

The code works well except that, in addition to the three custom post types I've registered, a fourth one comes up whose $name is Logs and the $link is my site's homepage url.
What is this 'Log' post type? Is it Wordpress' default Post? Shouldn't the _builtin => fakse parameter for get_post_types exclude it already? If not, how do I exclude it?

A: Like mmm suggested in the comments, 'Logs' is a custom post type created by a plugin I'm using, which means that the correct answer is there is no default Wordpress' custom post type. I hope it's clearer now.


text:
Q: UUID displayed instead of username For some reason, all of this has been fixed, somehow. Thank you @null (Science fiction & fantasy mod) for changing it to 'Alex' and letting me change my name on other sites.
I've found a bug where my profile name appears as my UUID instead of my name…

It happens for:

*

*Movies and TV

*Physics

*Electrical Engineering

*Super user

*Puzzling

*Programmers

Is this a bug or is this just me being inactive and having only 101 rep on those sites?
And for some sites, the default StackExchange icon is displayed (ex. Software Recommendations)


text:
Q: Why has an basic Umbraco site taken over my Azure site as startup site? My website at Azure suddenly started showing a basic "Umbraco welcome site" instead of my website hosted on azure. I do not know why, Umbraco is not included in my sourcefiles as far as I know.
When I do http://www.mywebsitename.com it works fine and my azure website gets loaded, but when I dont include 'www'; http://mywebsitename.com - it just shows the "Windows Azure Accelerator for Umbraco" page saying:
"The Windows Azure Accelerator for Umbraco is designed to enable Umbraco applications to be easily run on Windows Azure. The accelerator has been designed to enable you to rapidly deploy Umbraco applications and updates to your application without redeploying a full Windows Azure Service Package. For more information about the accelerator, please visit the CodePlex site located here."
I do not know why this behaviour suddenly happened, how can I get rid of it? I think maybe this behaviour started when I played around with some storage-blobs

A: Is your DNS set correctly for the URL without the 'www.' and is your Azure app listening for both www. and the empty subdomain? Sounds to me like the URL without www. is hitting a different application.


text:
Q: Force Chrome to use external font in CSS It took me a long time to figure out, that Chrome always prefers local installed fonts over a font with the same name that is linked in the css (See also https://stackoverflow.com/a/27704394/1099519). My problem is how to figure out, to force Chrome not to do so.
On my page https://www.amon.cc/ I use "Roboto Light" from Google Fonts (https://fonts.google.com/specimen/Roboto), like this:
<link href="//fonts.googleapis.com/css?family=Roboto:300" rel="stylesheet" type="text/css" />

In my CSS file the font is declared like this:
body{
  ...
  font-family:Roboto,...;
  font-weight:300;
 ....
}

Which works perfectly fine in FF, IE, Edge:

But the font is always thicker in Chrome:

The reason: On my private Windows 10 and also on by business computer the font "Roboto" is pre-installed on Windows: Robot Regular, Robot Condensed. But there is no Roboto Thin or Robot Light, so it seems Chrome has a fallback to Roboto Regular.
When deleting the Robot fontset from Windows, Chrome uses the declared web font and displays it the way I want it. I could not figure out, how to "force" Chrome not to use the local installation and instead use the on the CDN.
However, Chrome can display the Roboto font in all different variants on the https://fonts.google.com/specimen/Roboto website (even with my local installed Robot font). I couldn't find out the trick how this has been done.

A: You can rename the font in your CSS and still use the distant woff file. For example:

@font-face {
  font-family: 'RobotoBis';
  font-style: normal;
  font-weight: 300;
  src: local('Roboto Light'), local('Roboto-Light'), url(http://fonts.gstatic.com/s/roboto/v15/Pru33qjShpZSmG3z6VYwnRJtnKITppOI_IvcXXDNrsc.woff2) format('woff2');
  unicode-range: U+0100-024F, U+1E00-1EFF, U+20A0-20AB, U+20AD-20CF, U+2C60-2C7F, U+A720-A7FF;
}

@font-face {
  font-family: 'RobotoBis';
  font-style: normal;
  font-weight: 300;
  src: local('Roboto Light'), local('Roboto-Light'), url(http://fonts.gstatic.com/s/roboto/v15/Hgo13k-tfSpn0qi1SFdUfVtXRa8TVwTICgirnJhmVJw.woff2) format('woff2');
  unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2212, U+2215, U+E0FF, U+EFFD, U+F000;
}
h1 {
  font-family: RobotoBis;
}

Hello world !

But the dark side of this method is that Google can change the font URL in the future (that is mainly probable). So host you own font files to avoid this problem.
And of course, it can be apply only for the websites you own and where you can customize the CSS...

A: It took sometime to figure out this mess. This problem occurred to me when I updated chrome.
To solve this problem in my mac. I have opened the font app and delete the Roboto font and reinstalled it from https://www.fontsquirrel.com/fonts/roboto-2014. It has fixed my problem.


text:
Q: Having issues with printing an array in c I'm having issues on printing an array, that's what I'm doing:
#include <stdio.h>

#define DIM 5

int main () {

    double data[DIM] = {128.5, 131.4, 133.2, 127.1, 130.9};

    printf("%lf", data[DIM]);

    return 0;
}

The answer is always 0.000000.
I've also tried to put the values separately, like this:
#include <stdio.h>

#define DIM 5

int main () {

    double data[DIM];
    data[0]=128.5;
    data[1]=131.4;
    data[2]=133.2;
    data[3]=127.1;
    data[4]=130.9;

    printf("%lf", data[DIM]);

    return 0;
}

And still the answer is always 0.000000.
Could someone please help. Thank you in advance!

A: As 4386427 and 500 - Internal Server Error pointed out, there are two issues at work here.

*

*You are trying to print an out-of-bounds index. When you make an array of length 5, indexes go from 0 to 4.

*More importantly, there is no specific "print array" function that I am aware of. Your best bet is to create a loop that prints each element of the array.

void printDoubleArray(double arr[], int length)
{
    printf("[");
    if (length > 0)
    {
        printf("%f", arr[0]);
    }
    for (int i = 1; i < length; i++)
    {
        printf(", %f", arr[i]);
    }
    printf("]\n");
}

A: In this call
printf("%lf", data[DIM]);

you are trying to output a non-existent element of the array with the index DIM while the valid range of indices for the array is [0, DIM). This record means that 0 is included in the range as a valid index and DIM is excluded from the range.
As a result the call of printf invokes undefined behavior.
Also you should use the conversion specifier f instead of lf. The  length modifier l does not have an effect used with the conversion specifier f. So it is just redundant.
You can not output a whole array except character arrays (by means of the conversion specifier s).
To output the whole array you need to use a loop as for example
for ( size_t i = 0; i < DIM; i++ )
{
    printf( "%.1f ", data[i] );
}
putchar( '\n' );

Here is a demonstrative program.
#include <stdio.h>

#define DIM 5

int main(void)
{
    double data[DIM] = { 128.5, 131.4, 133.2, 127.1, 130.9 };

    for ( size_t i = 0; i < DIM; i++ )
    {
        printf( "%.1f ", data[i] );
    }
    putchar( '\n' );

    return 0;
}

The program output is
128.5 131.4 133.2 127.1 130.9

A: C, the language itself, does not have array bounds checking.  You want the element one past the end?  sure thing.  You want the element a million past the end?  sure you can ask for that too (who knows what will happen but you can ask for it)
If your compiler supports it, you can get more robust error reporting.  Not C standard but helpful nonetheless.
GCC:
Compile with -fsanitize=address and at run-time the sanitizer will catch this overrun:
=======================
==220715==ERROR: AddressSanitizer: stack-buffer-overflow on address 0x7ffed8db4988 at pc 0x559ba54babcc bp 0x7ffed8db4920 sp 0x7ffed8db4910
READ of size 8 at 0x7ffed8db4988 thread T0
    #0 0x559ba54babcb in main /tmp/overrun.c:9

clang:
In addition to the run-time sanitizer (-fsanitize=address), Clang can also point out your problem at compile time:
    printf("%lf", data[DIM]);
                  ^    ~~~
overrun.c:7:5: note: array 'data' declared here
    double data[DIM] = {128.5, 131.4, 133.2, 127.1, 130.9};
    ^
1 warning generated.


text:
Q: Does auto-sharding in MongoDB work on shards with many small collections/small databases In the MongoDB documentation for auto-sharding it says: "Sharding is performed on a per-collection basis. Small collections need not be sharded."
Our business has many databases (~100), with many small collections (~30), each with a document count of 1 - 3000. Our DB system is looking at approximately 100,000,000 page views per month.
In that scenario will sharding ever activate since the collections are never big enough even though the DB usage and site traffic is certainly high enough to require load balancing. From the docs I can't seem to find a clear answer.

A: Whether it makes sense to shard depends a little bit on whether you have mostly writes or reads to the database. Sharding is primarily used for write-scaling, but if you are not doing a lot of writes, then simply using replicasets with "slaveOkay" for the reads might work just as well.
From the numbers that you provided you seem to get about 9 million documents, but are they large documents? If they easily fit in memory, then there is most likely not even going to be a need for replicasets besides for failover capabilities.

A: This is hard to answer without knowing more about your use case, but I'll give it a shot.
Are you sure sharding is what you need?  What does your insert rate look like?
If you are going to have a static set of data, or even a relatively static set, then you probably don't need to shard, you could simply use more secondaries and enable slaveOK reads.  The reads will be distributed to the various secondaries and scale up your read capacity.
If that is not the case, and you do need to shard, then there are options.  But first, to explain briefly and at a high level how automatic sharding works:
The mongos process is responsible for splitting and migrating chunks in general.  These are two separate operations - splitting and balancing.

*

*Splits occur when the mongos sees that a certain portion of the
maximum chunk size has been written, it initiates a split if there is
in fact enough data to warrant it.  Over time, with enough data
written, the number of chunks grows.

*Balancing occurs when there is an imbalance of chunks (currently 8 in
2.0, though moving to a more dynamic heuristic in 2.2).  The balancer migrates the chunks around the shards until  a balance is achieved.

So, you need to be writing enough data relative to the max chunk size (default is 64MB in 2.0) to generate the chunks needed for the balancer to move them around appropriately.  If that is not going to happen with your data, then you can look at:

*

*Decreasing the chunk size (has drawbacks too - http://www.mongodb.org/display/DOCS/Sharding+Administration#ShardingAdministration-ChunkSizeConsiderations)

*Manually split/move the chunks

For the manual instructions see:
http://www.mongodb.org/display/DOCS/Splitting+Shard+Chunks
http://www.mongodb.org/display/DOCS/Moving+Chunks


text:
Q: Push a variable in a vector in Matlab How to push a variable in a vector in Matlab?
Something like this:
A = [5 2 3];
push(A, 7);
% A = [5 2 3 7]

Thanks.

A: I found the answer.
Use this:
A = [A, 7];

Or this:
A(end + 1) = 7;

A: If you want to stack it vertically you can use
A = [A; 7]

but for this to be executed, A should of same dimentions as next argument.
for example if
A=[1,2
   3,4]

you can stack a vector of length 2 in A as
A = [A;5,6]


text:
Q: Difference between performing INSERT INTO vs Using MERGE INTO I started working on a project that already has some scripts running and while I was looking some of the scripts that have already been done I encountered an scenario that looks something like this.
DROP TABLE IF EXISTS #Persons
SELECT PersonId = 1, Firstname = 'Joaquin', LastName = 'Alvarez'
INTO #Persons
DECLARE @inserted table (PersonId INT, Firstname VARCHAR(50), Lastname VARCHAR(50))

MERGE INTO dbo.Persons P USING #Persons TP ON 1 = 0 -- Forcing mismatch
        WHEN NOT MATCHED THEN
        INSERT
        (
             PersonId,
             Firstname,
             Lastname
        )
        VALUES
        (
             TP.PersonId,
             TP.Firstname,
             TP.LastName
        )

OUTPUT INSERTED.PersonId, INSERTED.Firstname, INSERTED.LastName
INTO @inserted;

My Question here is why they would use the merge into and force the mismatch just to perform an insert, they could have done the same without it with something like this.
DROP TABLE IF EXISTS #Persons
SELECT PersonId = 1, Firstname = 'Joaquin', LastName = 'Alvarez'
INTO #Persons
DECLARE @inserted table (PersonId INT, Firstname VARCHAR(50), Lastname VARCHAR(50))

INSERT INTO Persons
OUTPUT INSERTED.PersonId, INSERTED.Firstname, INSERTED.LastName
INTO @inserted
VALUES (1, 'Joaquin', 'Alvarez')

The first option is faster than the last one? or they're bot the same? This is the first time I see the merge into used this way.

A: You would really need to ask the person who wrote the code.  But I can think of two and a half reasons.
The first is that the original code was both an INSERT and UPDATE so the author used MERGE to handle the code.  As the code was tested or as requirements changed, the person who wrote it realized that the UPDATE was not needed, but left the MERGE.
The half reason is that someone wrote the code expecting UPDATEs to be needed over time, so tried to future-proof the code.
The second reason is that the author may simply prefer MERGEs over UPDATEs and INSERTs because it is one statement that is more powerful than either of those individually.  So, they simply always use MERGE.

A: There are two big differences I can think of that may have caused the query to be written as MERGE:
1. MERGE allows column references in the OUTPUT clause that are not in the inserted table. Admittedly, the current query does not have that, but it is possible that other references were originally there or intended to be added.
2. Halloween Protection is much more efficient on MERGE.
Paul White goes into detail in his excellent article on this, but basically, when executing a INSERT/WHERE NOT EXISTS, this forces the optimizer to add a Table Spool to ensure correct results. A MERGE usually does not require this, as the optimizer can see what you are trying to do: fill the empty holes in the primary key.
I note that your query does not have a NOT EXISTS semantic, but again, it is possible that it was intended ast some point to have it.

As you state, #Person is entirely pointless here. Even with MERGE you can still do that from a constructed table, eg.
MERGE INTO dbo.Persons P
USING (
    SELECT *
    FROM (VALUES (1, 'Joaquin', 'Alvarez') ) AS v(PersonId, Firstname, LastName)
) TP ON 1 = 0 -- Forcing mismatch
        WHEN NOT MATCHED THEN
        INSERT (PersonId, Firstname, Lastname)
        VALUES (TP.PersonId, TP.Firstname, TP.LastName)
OUTPUT INSERTED.PersonId, INSERTED.Firstname, INSERTED.LastName
INTO @inserted;


text:
Q: Error with Protobuf while compiling Tensorflow I am currently trying use Tensorflow's shared libraries in a non-bazel project.
So I built the .so file using:

bazel build //tensorflow:libtensorflow.so

Then I loaded the dependencies as described here.
I added the following flags to my Makefile:

CFLAGS += -I/home/alpy/tensorflow/bazel-genfiles
      CFLAGS += -I/home/alpy/tensorflow/
      CFLAGS += -I/home/alpy/tensorflow/tensorflow/contrib/makefile/downloads/eigen-latest/
LDFLAGS += -L../resources/
LDFLAGS += -ltensorflow.so

When I do this, I get this rather strange error:
In file included from /home/alpy/tensorflow/tensorflow/core/public/session.h:22:0,
                 from ../src/conversion.h:14,
                 from ../src/conversion.cpp:1:
/home/alpy/tensorflow/bazel-genfiles/tensorflow/core/framework/graph.pb.h:143:3: error: 'PROTOBUF_DEPRECATED_ATTR' does not name a type
   PROTOBUF_DEPRECATED_ATTR void clear_version();
   ^
/home/alpy/tensorflow/bazel-genfiles/tensorflow/core/framework/graph.pb.h:144:3: error: 'PROTOBUF_DEPRECATED_ATTR' does not name a type
   PROTOBUF_DEPRECATED_ATTR static const int kVersionFieldNumber = 3;
   ^
/home/alpy/tensorflow/bazel-genfiles/tensorflow/core/framework/graph.pb.h:145:3: error: 'PROTOBUF_DEPRECATED_ATTR' does not name a type
   PROTOBUF_DEPRECATED_ATTR ::google::protobuf::int32 version() const;
   ^
/home/alpy/tensorflow/bazel-genfiles/tensorflow/core/framework/graph.pb.h:146:3: error: 'PROTOBUF_DEPRECATED_ATTR' does not name a type
   PROTOBUF_DEPRECATED_ATTR void set_version(::google::protobuf::int32 value);
   ^
/home/alpy/tensorflow/bazel-genfiles/tensorflow/core/framework/graph.pb.h:273:37: error: no 'void tensorflow::GraphDef::clear_version()' member function declared in class 'tensorflow::GraphDef'
 inline void GraphDef::clear_version() {
                                     ^
/home/alpy/tensorflow/bazel-genfiles/tensorflow/core/framework/graph.pb.h:276:54: error: no 'google::protobuf::int32 tensorflow::GraphDef::version() const' member function declared in class 'tensorflow::GraphDef'
 inline ::google::protobuf::int32 GraphDef::version() const {
                                                      ^
/home/alpy/tensorflow/bazel-genfiles/tensorflow/core/framework/graph.pb.h:280:66: error: no 'void tensorflow::GraphDef::set_version(google::protobuf::int32)' member function declared in class 'tensorflow::GraphDef'
 inline void GraphDef::set_version(::google::protobuf::int32 value) {

BTW, I loaded protobuf as it was described on the page I linked above.

A: I think the problem is resolved as described here: Google Groups discussion
Just add a new CFLAG:
-DPROTOBUF_DEPRECATED_ATTR=""


text:
Q: bloqueado en mi primer programa en python Estoy aprendiendo a programar en python. En el curso nos piden un programa en el que el usuario tiene tres oportunidades para introducir una contraseña, dando igual las minusculas y las mayusculas.
estoy tremendamente atascado en las tres opprtunidades y en las mayusculas, minusculas.
me encantaria que alguien me ayudase, explicandome la respuesta, para poder aprender.
de momento he escrito esto
contraseña = "condicional"
respuesta = input("introduzca su clave: ")

for i in range (0,1,2):
    if respuesta == contraseña:
        print ("contraseña correcta", respuesta )
    else:
        print ("contraseña incorrecta", respuesta)
        respuesta = input("introduzca su clave: ")
        if respuesta == contraseña:
            print ("contraseña correcta", respuesta )
        else:
            print ("contraseña incorrecta", respuesta)
            respuesta = input("introduzca su clave: ")
            if respuesta == contraseña:
                print ("contraseña correcta", respuesta )
            else:
                print ("contraseña incorrecta", respuesta)

A: contraseña = "condicional"

respuesta = input("introduzca su clave: ")
if contraseña.upper()==respuesta.upper():
    print ("contraseña correcta", respuesta )
else:
    print ("contraseña incorrecta", respuesta)
    for i in range(2):
        respuesta = input("Introduzca su clave: ")
        if contraseña.upper()==respuesta.upper():
            print ("contraseña correcta", respuesta )
            break
        else: print ("contraseña incorrecta", respuesta)

En este codigo se hace en primer lugar, comprobar si en el primer intento el usuario aserta en la contraseña, esto se comprueba con un if, la funcion .upper() hace que la palabra tenga todas las letras en mayuscula, asi da igual si pones minusculas o mayusculas, siempre se va a comparar las frases entre mayusculas. Si el usuario no asierta en el primer intento, se inicia un for loop con 2 iteracion ya que son los intentos restante que le quedan al usuario.

A: este es el programa quew he hecho
clave="condicional"
respuesta=(input("ingrese su clave: ")).lower
cont =0
while clave!=respuesta and cont <3:
        print('respuesta erronea: ', respuesta)
        respuesta=input ("introduzca su clave: ")
        cont +=1

if clave == respuesta:
     print('respuesta correcta: ', respuesta)

A: Para llevar la cuenta de las repeticiones usamos la variable intentos, que parte en 3. Cuando llega a cero, significa que se hicieron tres intentos fallidos. Un valor distinto de cero señala que se ingresó la contraseña correcta.
Controlamos el ciclo comparando la respuesta ingresada contra la contraseña guardada. Inicializamos respuesta con None para garantizar que sea distinta de cualquier contraseña válida.
Al salir del while, el valor de intentos nos dirá si se ingresó la contraseña válida.
contraseña = "condicional"
respuesta = None
intentos = 3
while intentos and respuesta != contraseña:
    respuesta = input("introduzca su clave: ").lower()
    if respuesta != contraseña:
        print ("contraseña incorrecta", respuesta)
        intentos -= 1

if intentos:
    print("contraseña correcta", respuesta)

A: La forma más compacta que puedes hacer:
contraseña = "condicional"
for i in range(3):
    respuesta = input("Introduce contraseña: ")
    if respuesta.lower() == contraseña.lower():
        print("Contraseña correcta")
        break
    else:
        print("Contraseña incorrecta:", respuesta)


text:
Q: $\int _{-\infty }^{\infty }\dfrac{dx}{x^{2}+1}$ with using Residue theorem I solve this question with using Residue theorem.
$$\int _{-\infty }^{\infty }\dfrac{dx}{x^{2}+1}$$
I think

\begin{align}P\cdot V\int _{-\infty }^{\infty }\dfrac{dx}{x^{2}+1}&=2\pi i\left(\operatorname{Res}_{z=i}\left\{ \dfrac{1}{z^{2}+1}\right\}+\operatorname{Res}_{z=-i}\left\{ \dfrac{1}{z^{2}-1}\right\}\right)\\&=2\pi i\left( \lim _{z\rightarrow i}\left\{ \dfrac{1}{z+i}\right\} +\lim _{z\rightarrow -i}\left\{ \dfrac{1}{z-i}\right\} \right)\\&=2\pi i\left( \dfrac{1}{2i}+\left( -\dfrac{1}{2i}\right) \right) \\ &=0\end{align}
But answer is $\pi$. This is answer.
I don't know where I wrong. Please tell me.

A: You should only take into account those singularities with imaginary part greater than $0$. So, you will get $2\pi i\times\frac1{2i}$, which is indeed equal to $\pi$.

A: If I may expand on @JoséCarlosSantos's point, the idea is to use an "infinite semicircular contour", either counterclockwise on $\Im z\ge0$ or clockwise (thereby inducing a $-$ sign) on $\Im z\le0$. We thereby enclose the pole at $i$ or $-i$ respectively; either can be used, so "only one pole counts" isn't an arbitrary or special-pleasing statement. The pole at $\pm i$ can be used to evaluate the integral as$$\pm2\pi i\lim_{z\to\pm i}\frac{z\mp i}{z^2+1}=\pm2\pi i\lim_{z\to\pm i}\frac{1}{z\pm i}=\frac{\pm2\pi i}{\pm2i}=\pi.$$In fact, your original calculation can be salvaged: if we induce the sign change required of the contour enclosing the pole at $-i$, we're counting the integral twice (once with each contour), so the correct reuslt is $\tfrac122\pi i\left(\frac{1}{2i}\color{blue}{+}\frac{1}{2i}\right)=\pi$.

A: If you want to know why, in applying the residue theorem to calculate the principal value, you only need take the residue at the pole with positive imaginary part, You need to appl the residue theorem with care.  You first choose a closed contour that traces the real axis, say from $-M$ to $+M$, and then circle back from $+M$ to $-M$ following a large semicircle or rectangle either above the real axis or below the real axis.  In doing so it will enclose one or other of the two poles at $z = \pm i$ but not both.  If I call this curve $\gamma$ you then have, from the residue theorem,
$$\int_{-M}^M \frac{1}{1+z^2} dz \pm \int_\gamma \frac{1}{1+z^2} dz = \pm 2\pi i \times
R \tag{1} \label{E1}$$
where $R$ is the residue at whichever pole is enclosed, either at $z=i$ or $z=-i$.   The  sign ambiguity reflects the fact that in one choice, where  $\gamma$ is taken above the real axis, the curve is traced counter clockwise so the plus sign is appropriate, and in the other the curve is traced clockwise so the minus sign becomes appropriate.
You then need to show that as $M \to \infty$ the integral along $\gamma$ has limit zero.  This allows you to conclude that the integral along the axis, in the limit, is $\pm 2\pi i R$.
The trick is that the $\gamma$ integral often only converges to zero in one case and not the other.  However, in this case you are lucky and the $z^2$ means you get a zero limit along the curve in either case and hence we should end up with either sign in \eqref{E1}, take the plus sign and $R$ to be the residue at $z = i$ or the minus sign and the residue at $z=-i$.  This then gives the answer you wanted.


text:
Q: Is it worth the effort to use culture invariant string formatting in single-culture applications? Sometimes, we need to stuff an integer ID into a string, for example when generating HTML form <select> items.
Calling int.ToString() can result in digits outside the range [0-9] in certain cultures. For that reason, you need to specify the invariant culture in culture-spanning apps (e.g. int.ToString(CultureInfo.InvariantCulture)).
Is it worth taking care and doing that even if it is known that the application will only run in one specific western culture (e.g. German)? It seems to be the "correct" thing to do. Or is that effort not well spent?
Update: It appears that integer formatting is almost immune to culture anyway. My assumption was wrong but I'll keep the text for context.

A: Since the output will be exactly the same, this is a pretty subjective choice. If you know the application only ever will run in one specific culture, then I would say leave it out for simplicity.
But if the application might be ported to multiple cultures, I would say leave it in. Even if you know all cultures you port to all have the same integer formatting, you should not require that all readers of the code know that, and without the knowledge, the code looks like a subtle bug. So make the intention clear in the code that the value is supposed to be invariant rather than culture specific.

A: I would say yes.
The problem is even if the people are all in germany that doesn't nesacerally mean they will be running german versions of windows. People immigrate and sometimes bring their computers with them, people run english versions of windows because other software is broken on german versions of windows.
As you say this is not too much of an issue with ints but it's a big issue with floating point numbers.

A: Even if you never intend to run on another system or in another culture, once that fact changes, and you may be surprised how often that happens, stating the invariant culture in this case marks your intent, which will help future maintainers of your code, whom might be yourself.
In other words; if being implicit doesn't properly convey your intent, be explicit.


text:
Q: How do I filter a list with date and time values by only extracting specific times each day? I have a list of days and times in column A. Column B is a dollar value for each time value.

I want to get a specific time for each day and list the price in the next column. I have this right now:

The formula for column J is this:
=filter(A11:B,(mod(A11:A,1)*24)>=4.5,(mod(A11:A,1)*24)<=4.6)

This formula filters 4:30AM and the price associated with it.
Formula for column L is this:
=filter(A11:B,(mod(A11:A,1)*24)>=9.5,(mod(A11:A,1)*24)<=9.6)

Which filters only 9:30AM for each day and the price that goes with it.
As you can see, the dates stop matching when column J is 8/12/2021 and column L is 8/13/2021. This is because column L didn't have 9:30AM for 8/12/2021 so it skipped to 8/13/2021.
How can I make so that one of the columns skip a date if the other column doesn't match that time? I don't know if I explained that well but in the example above, column J should skip 8/12/2021 because column L didn't have 8/12/2021.
Another way of dealing with this issue is perhaps using UNIQUE and FILTER formulas but I'm not sure how that could be done. Any help would be greatly appreciated!
Here's a link to the spreadsheet: https://docs.google.com/spreadsheets/d/1TvP0_UsYJbLb5bscx2e4nTEnSkP5roBZpP8aIGdl414/edit?usp=sharing

A: I'm not 100% sure, but if you need to filter values so the time element is 09:30 and 04:30, then hide values where a date only occurs once (ie. no 09:30 value or no 04:30 value), you could use:
=arrayformula(filter(
filter(A11:B,(round(mod(A11:A,1)*24,2)=9.5)+(round(mod(A11:A,1)*24,2)=4.5)),
countif(int(filter(A11:A,(round(mod(A11:A,1)*24,2)=9.5)+(round(mod(A11:A,1)*24,2)=4.5))),int(filter(A11:A,(round(mod(A11:A,1)*24,2)=9.5)+(round(mod(A11:A,1)*24,2)=4.5))))>1)
)

Adjust >1 at the end to whatever logic you need (=2, <>1 etc).
You can also add sort() around everything if you need to.
Explanation:
It turns out that mod(A11,1)*24 doesn't round particularly well, so I suggest round(mod(A11:A,1)*24,2).
Therefore to filter the date/times for 9.30am and 4.30am, you can apply:
round(mod(A11:A,1)*24,2)=9.5
and
round(mod(A11:A,1)*24,2)=4.5
like this:
=arrayformula({filter(A11:B,(round(mod(A11:A,1)*24,2)=9.5)+(round(mod(A11:A,1)*24,2)=4.5))})

filter is usually AND but to get OR condition it's filter(A:B,(A=1)+(A=2))
This gets the dates only:
=arrayformula(int(filter(A11:A,(round(mod(A11:A,1)*24,2)=9.5)+(round(mod(A11:A,1)*24,2)=4.5))))

Then this counts how many times a date appears:
=arrayformula(countif(int(filter(A11:A,(round(mod(A11:A,1)*24,2)=9.5)+(round(mod(A11:A,1)*24,2)=4.5))),int(filter(A11:A,(round(mod(A11:A,1)*24,2)=9.5)+(round(mod(A11:A,1)*24,2)=4.5)))))

Combining the elements gets the solution.
I'll add a tab to your sheet.

A: You could filter each list on finding a match for each date (integer part of datetime) in the other list:
In J:
=filter(A11:B,(mod(A11:A,1)*24)>=4.5,(mod(A11:A,1)*24)<=4.6,isnumber(match(int(A11:A),int(filter(A11:A,(mod(A11:A,1)*24)>=9.5,(mod(A11:A,1)*24)<=9.6)),0)))

In L:
=filter(A11:B,(mod(A11:A,1)*24)>=9.5,(mod(A11:A,1)*24)<=9.6,isnumber(match(int(A11:A),int(filter(A11:A,(mod(A11:A,1)*24)>=4.5,(mod(A11:A,1)*24)<=4.6)),0)))

Note
Plz see Aresvik's answer for a possibly better approach to rounding, but note that 4:30 (3/16) actually has an exact representation as a binary decimal so rounding errors aren't an issue here.


text:
Q: All images in XPS look identical when loaded from a byte array I have a window:
<Window x:Class="WpfTest.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Width="150" Height="100"
        MouseLeftButtonDown="OnClick">
    <StackPanel Orientation="Horizontal">
        <Image Source="{Binding Image1}" />
        <Image Source="{Binding Image2}" />
    </StackPanel>
</Window>

codebehind:
public partial class MainWindow
{
    public MainWindow()
    {
        InitializeComponent();
        DataContext = new
        {
            Image1 = Convert.FromBase64String("iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAABHNCSVQICAgIfAhkiAAAAAlwSFlzAAALEwAACxMBAJqcGAAAAKhJREFUWIXtltEJgzAURU+l7Qg6S+kiHaOLdBL9EgKlEzhTUrA/fkgM+Ah5FeUdCAmSvHvUEAKGsaQBHOCBsVALU81GIuAKBsfNxWGnhIAHLhLTDAJwXRMYlcKTmZVy2CrnzHUvYIie3YHnvwQGoCtRa7e/oJ2NUxtZzOZfwARMwARMIPcknPOY+lvOYrsPpAS+inlBIvBRFHhLJmlcyz3QA3WxVzEOww83D06TNQuS8AAAAABJRU5ErkJggg=="),
            Image2 = Convert.FromBase64String("iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAABHNCSVQICAgIfAhkiAAAAAlwSFlzAAALEwAACxMBAJqcGAAAAPFJREFUWIXtlksKwjAURY9iBQcORLArcOAanLsChQ7dggtwU0JBBKduxIF7aAt1YJy0iUnz8UcuPGhKbt55r2kIREW1lQI5UAC1pyjFmqkJQO4xcTPyZrKeBKAAEhNSC5XAUAdQB0ouzdkPnEyrgYVno1hnBWyRd7WTdBvplfaOfmeAyTsAZLG2LeAnNyHADbgAlRhf/eA8pGvhERgpvAsDvzPAXOEbA+euADYn4dOzBHbiORHjqcarytkCMKkgM5j7/X+ByydQqZP/4x2wOQcynwDxPiADqCTvfKk0ATgFBDiaTApxLS+AAzDzVkrU3+gOjt+/W2ggWToAAAAASUVORK5CYII="),
        };
    }

    private void OnClick(object sender, MouseButtonEventArgs e)
    {
        using (var xps = new XpsDocument(@"1.xps", FileAccess.Write))
            XpsDocument.CreateXpsDocumentWriter(xps).Write((Visual)this.Content);
    }
}

As you can see, it displays two images and writes itself to an XPS file on mouse click.
This is what I see on the screen:

This is what I get in the XPS:

So the first image is displayed instead of the second one. In fact, if I have multiple images, all of them are replaced with the first one in the resulting XPS.
However, if instead of byte[] I set image's source to a file URL, then XPS correctly displays all the images.
What is going on?

A: Investigation shows, that when Image.Source is assigned to a byte array, ImageSourceConverter class is used by WPF to convert the array to the proper ImageSource. BitmapFrame.Create() is called inside to perform the actual bitmap loading. So this code have absolutely the same effect:
var view = new StackPanel
{
    Orientation = Orientation.Horizontal,
    Children =
    {
        new Image { Source = BitmapFrame.Create(new MemoryStream(pic1Bytes), BitmapCreateOptions.None, BitmapCacheOption.Default) },
        new Image { Source = BitmapFrame.Create(new MemoryStream(pic2Bytes), BitmapCreateOptions.None, BitmapCacheOption.Default) },
    }
};
using (var xps = new XpsDocument(@"1.xps", FileAccess.Write))
    XpsDocument.CreateXpsDocumentWriter(xps).Write(view);

However, if I load image using BitmapImage class, the problem no longer exists. This code works both on screen and in XPS:
private static BitmapSource ImageFromBytes(byte[] bytes)
{
    var bmp = new BitmapImage();
    using (var stream = new MemoryStream(bytes))
    {
        bmp.BeginInit();
        bmp.CacheOption = BitmapCacheOption.OnLoad;
        bmp.StreamSource = stream;
        bmp.EndInit();
    }
    return bmp;
}

// usage example:
new Image { Source = ImageFromBytes(picBytes) }

This is probably a bug in ImageSourceConverter. One could create a custom converter using ImageFromBytes inside to continue using XAML binding.


text:
Q: Can 2 matrices performing the same linear transformation be unequal? If $\Bbb R^m,\Bbb R^n,\Bbb R^o,\Bbb R^p$..., are all different vector spaces, and $A,B,C,D,E$ are transformation matrices.
And there are 2 linear transformations performing the same mapping
$$\phi:\Bbb R^n\to \Bbb R^m,\\\gamma:\Bbb R^n\to \Bbb R^m$$
$$\phi(x)=Ax,\\\gamma(x)=Bx$$
Now let there be 3 other transformations:
$$\phi_1:\Bbb R^n \to \Bbb R^o,\\\phi_2:\Bbb R^o \to \Bbb R^p,\\\phi_3:\Bbb R^p \to \Bbb R^m$$ And
$$\phi_1(x)=Cx,\\\phi_2(x)=Dx,\\\phi_3(x)=Ex$$
Let $$\gamma(x)=\phi_3(\phi_2(\phi_1(x)))\\ \Longrightarrow B=EDC$$
Now if both $\phi$ and $\gamma$ perform the same linear transformation, wrt. the same bases. will $A$ and $B$ be equivalent? Is there a simple way to prove this?
Another way to probably frame this question: 'Is a matrix performing a particular linear transformation always unique?'
Based on the answers I've gotten, if I can equate $Ax=Bx$, can I say $A$ and $B$ are equivalent matrices? Regardless of what they are composite of?

A: Suppose that $A$ and $B$ are different. Then $B=A+M$.
Since $Ax=Bx$ we have that $Ax=(A+M)x$
Then $Ax=Ax+Mx$
$0=Mx$ for all $x$
$M$ is a zero matrix. So $B=A$

A: The answer is yes: The matrix representation of a linear transformation with respect to particular bases is unique. To see this, let $\mathcal{B}$ and $\mathcal{C}$ be bases for $\mathbb{R}^n$ and $\mathbb{R}^m$ respectively, and $T: \mathbb{R}^n \rightarrow \mathbb{R}^m$ a linear transformation. I assume you know that there exists a matrix representation of $T$ with respect to $\mathcal{B}$ and $\mathcal{C}$, so we only show uniqueness. Suppose $M$ and $M'$ are matrices such that for all $x \in \mathbb{R}^n$
$$[T(x)]_{\mathcal{C}} = M[x]_{\mathcal{B}} = M'[x]_{\mathcal{B}}.$$
We get $(M-M')[x]_{\mathcal{B}} = 0$ for all $x$, which means that $M-M' = \mathbf{0} \implies M = M'$.
EDIT based on addendum to the question: Notice that it is important that the relation holds for all $x$ in order to conclude that $M-M' = \mathbf{0}$. If you have $Ax = Bx$ for all $x$, we have $A = B$. You should make sure you understand why that is.


text:
Q: Hiding the console window in a system() call Continuing from this question
With each system call, the function constructs a set of parameters and sends them off to another program that is just console-based. Is there a way I can make it so that no console window pops up for each call?
I've done a search but the ones that aren't a linker issue just aren't working for me. For instance, I tried the _execl call and System::Diagnostics::Process^ myProcess = gcnew System::Diagnostics::Process; but they aren't working.
The _execl will bring a console window up, scroll a bunch of stuff (from the program I called I guess), then close the my app and not even do what it was supposed to do.
The System::Diagnostics::Process^ myProcess = gcnew System::Diagnostics::Process; doesn't seem to execute what I want either because the output folder that should contain files, contains nothing.
So I'm open for ideas.

A: The CreateProcess API gives you the control you need.  For example:
#include <windows.h>

using namespace System;

int main(array<System::String ^> ^args)
{
    STARTUPINFO         si;
    PROCESS_INFORMATION pi;
    TCHAR               cmdLine[MAX_PATH] = L"myOtherApp.exe -with -some -args";

    ::ZeroMemory(&si, sizeof(si));
    si.cb = sizeof(si);

    ::CreateProcess(NULL, cmdLine, NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi);

    Console::ReadLine();
    return 0;
}

With the CreateProcess flags set to 0 as above, the secondary app does not open its own console window, and writes its output to the parent's window.  To silence the secondary app entirely, look at other CreateProcess flags, e.g. CREATE_NO_WINDOW.


text:
Q: Tangent cones at zero and infinity to minimal surfaces Let $n \geq 2$, and let $M^n \subset \mathbf{R}^{n+1}$ be a minimal surface with $0 \in M$ and finite ($n$-dimensional) area growth:
$\operatorname{limsup}_{R \to \infty} R^{-n} \lVert M \cap B_R \rVert < \infty$. Let $\mathbf{C}_0$ be a tangent cone to $M$ at the origin, and $\mathbf{C}_\infty$ be a tangent cone 'at infinity', meaning obtained by blowing down $M$.
To narrow the problem down, let us assume that the cone at infinity is regular outside the origin: $\operatorname{sing} \mathbf{C}_\infty = \{ 0 \}$.
The two cones are related via the monotonicity of the area functional, which gives
\begin{equation}
\tag{1}\label{1}
\lVert \mathbf{C}_0 \cap B_1 \rVert \leq \lVert \mathbf{C}_\infty \cap B_1 \rVert;
\end{equation}
equality occurs exactly when $\mathbf{C}_0 = M = \mathbf{C}_\infty$.
Question. Can anything else be said about the pair $(\mathbf{C}_0,\mathbf{C}_\infty)$? Is there a pair of cones $(\mathbf{C}_a,\mathbf{C}_b)$ which satisfies \eqref{1} strictly but is not a 'blow-up/blow-down' pair?
For clarification, some (families of) examples of pairs $(\mathbf{C}_0,\mathbf{C}_\infty)$ can be collated from the literature:

*

*Hardt and Simon constructed foliations which yield the pairs $(\Pi,\mathbf{C})$, where $\mathbf{C}$ is an arbitrary regular area-minimising cone and $\Pi$ is an $n$-dimensional plane;

*White constructed minimal surfaces $M$ with $0 \in \mathrm{sing} M$, and given blowdown cone $\mathbf{C}_\infty = \mathbf{C}$; this yields pairs $(\mathbf{C}_0,\mathbf{C}_\infty)$ where $\mathbf{C}_0$ is not a plane, but some hypotheses on $\mathbf{C}$ are required.

A: The first question is open-ended but I think see what you are getting at with the second question. If you are really looking at smooth embedded minimal hypersurfaces, then the answer is yes there do exist such pairs.
All we have to do is find any singular minimal cone that is not the limit of smooth embedded surfaces. This is because we will take $\mathbf{C}_a = $ a plane and a plane has density 1 and a singular cone must have density $> 1$.
But it's easy to find a singular minimal cone that cannot be the limit of smooth embedded surfaces, just take something with boundary as a current or mod 2 flat chain. The simplest is a cylindrical cone with a triple junction cross section.