text:
Q: Google Cloud SDK installer fails on Windows 7 (gcloud crashed (UnicodeDecodeError)) My OS is win7. I want to install the clould SDK.
But it "Failed to install". The ERROR message is:
Output folder: C:\Program Files (x86)\Google\Cloud SDK
Downloading Google Cloud SDK core.
Extracting Google Cloud SDK core.
Create Google Cloud SDK bat file: C:\Program Files (x86)\Google\Cloud SDK\cloud_env.bat
Installing components.
Welcome to the Google Cloud SDK!
ERROR: gcloud crashed (UnicodeDecodeError): 'ascii' codec can't decode byte 0xa4 in position 9: ordinal not in range(128)
If you would like to report this issue, please run the following command:
  gcloud feedback
To check gcloud for common problems, please run the following command:
  gcloud info --run-diagnostics
ERROR: Cannot use bundled Python installation to update Cloud SDK in
non-interactive mode. Please run again in interactive mode.
If you really want to run in non-interactive mode, please run the
following command before re-running this one:
 FOR /F "delims=" %i in ( '""C:\Program Files (x86)\Google\Cloud SDK\google-cloud-sdk\bin\gcloud.cmd"" components copy-bundled-python'
 ) DO (
SET CLOUDSDK_PYTHON=%i
)
(Substitute `%%i` for `%i` if in a .bat script.)
Failed to install.

Can someone help me?

A: I Fixed it by re-installing google cloud sdk. (if you can't uninstall just rename folder: C:\Program Files (x86)\Google\Cloud SDK to something else and try installer)
And by setting the CLOUDSDK_PYTHON environment variable to C:\Python27\python.exe (installation folder of python v2.7)

Now installing the app-engine components worked again.
option 2
Check your config: gcloud config list if you see: disable_prompts = True. this is probably why google says the inter-active mode is disabled. if you remove this value it might remove this error.

A: I also had error on Windows 8

ERROR: gcloud failed to load: 'ascii' codec can't decode byte...

*

*I checked my installation path. And it contained non-ascii symbol. So I restarted installer and changed installation path to C:\Program Files\Google\Cloud SDK
Afterwards I've got error

To use the Google Cloud SDK, you must have Python installed and on your PATH.
  As an alternative, you may also set the CLOUDSDK_PYTHON environment variable
  to the location of your Python executable.
  Failed to install.

despite the checked option "Bundled Python" as manual proposes.

*I downloaded from https://www.python.org/downloads/release/python-2714/ and installed latest Python 2.7.14 (Google SDK doesn't work with Python 3)

*The default path to executable was C:\Python27\python.exe, so added it as CLOUDSDK_PYTHON system variable in my Control panel and started again.
Finally it is installed.

A: My local account name contains non-ASCII characters.
I workarounded this issue by creation of new local account with name of ASCII characters only.


text:
Q: How to send push notifications to multiple devices (belonging to one user) if device token changes? The case is this:

*

*A user logs in to the app on their iPhone A

*The user login in to the same app on their iPhone B

Now, in the database, there are 2 tokens for one user, that is correct.
+---------+-------------------+
| user_id |   device_token    |
+---------+-------------------+
|       1 | 1st_device_token1 |
|       1 | 2nd_device_token1 |
+---------+-------------------+

Say, that user deleted the app, installed it again (on both devices) and that means, tokens in APNs changed, therefore in our database, there are 4 unique tokens.
+---------+-----------------------+
| user_id |     device_token      |
+---------+-----------------------+
|       1 | 1st_device_token1     |
|       1 | 2nd_device_token1     |
|       1 | 1st_device_token1_new |
|       1 | 2nd_device_token1_new |
+---------+-----------------------+

Now, a push notification for that user is going to be sent to 4 devices (4 tokens).
If they keep deleting and installing the app (may happen :) ), I would have in the database a large amount of tokens for one user and think, that they have such a vast number of devices, while in reality, there are a lot of invalid tokens.
How to prevent that?

A: Pushwoosh periodically clears its database from invalidated tokens (once per day or so), so having a "vast number" of entries should not be a problem. As for sending pushes to multiple devices of one user, there is a specific Push by UserID feature for this case.
The idea is to set a particular UserID on a login event and reset it to a default value on a logout with the following method:
[[PushNotificationManager pushManager] setUserId:@"external_user_1"]

Once UserID is set, you can send your /createMessage API requests with "users" parameter:
{
  "request": {
    "application": "APPLICATION_CODE",
    "auth": "API_ACCESS_TOKEN",
    "notifications": [{
      "send_date": "now",
      "content": "Hello world!",
      "users":["external_user_1"]
    }]
  }
}

This feature is accessible for all payment plans, so it should be accessible for you.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Highcharts How to bring tooltip above drill up button I have a drill down report, it's tool tip is going behind the drillupbutton. How to bring the tool tip front/above of the drillupbutton?
Fiddlehttp://jsfiddle.net/rvg3dw4q/1/
To replicate drill down parent and place cursor on the last column.

A: you can use the  following:
"tooltip":{"xDateFormat":"%m/%d/%Y",followPointer:true},

updated fiddle
hopefully it helps


text:
Q: Как cымитировать ввод значения в поле, используя консоль браузера? Отсутствует возможность использовать стороннее ПО, но присутствует куча полей которые нужно проверять.
Имеется поле которое принимает положительные чиcла, при вводе отрицательного, выделяется красным и выводит текст ошибки. При вводе отрицательного значения командой $element.value=-1, в поле появляется значение, но поле никак на него не реагирует. Имеется ли другой способ сымитировать ввод так, чтобы получить ожидаемый результат?

A:

document.getElementById('test').value = -1;
document.getElementById('test').dispatchEvent(new Event('input'));
<input id="test" oninput="console.log(this.value)" />

document.getElementById('test').value = -1;
document.getElementById('test').dispatchEvent(new Event('change'));
<input id="test" onchange="console.log(this.value)" />


text:
Q: php mysql category subcategory list link I want to like this
Category1
--Subcat1
--Subcat2
Category2
--Subcat2
I have two tables tbl_cat and tbl_subcat
tbl_cat(id,cat_name)
tbl_subcat(id,cat_id,subcat_name)

cat_id=tbl_cat.id

how to I write the function and display the category and sub-category link

A: You can do like this.
Test data:
create table tbl_cat (id int, cat_name varchar(32));
insert into tbl_cat(id, cat_name) values(1, "category1"), (2, "category2");
create table tbl_subcat (id int, cat_id int, subcat_name varchar(32));
insert into tbl_subcat(id, cat_id, subcat_name) values(1, 1, "subcat11"), (2, 1, "subcat12"), (3, 1, "subcat13"), (4, 2, "subcat21");

Then, PHP script can be written like this:
<?php
$servername = "localhost";
$username = "your_user";
$password = "your_password";
$dbname = "test";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

$sql = "SELECT cat_name, subcat_name FROM tbl_cat LEFT JOIN tbl_subcat ON tbl_cat.id = tbl_subcat.cat_id;";
$result = $conn->query($sql);

$last_category = "";
if ($result->num_rows > 0) {
    // output data of each row
    while($row = $result->fetch_assoc()) {
        $cat_name = $row["cat_name"];
        if ($cat_name != $last_category) {
            echo "Category: " . $cat_name .PHP_EOL;
            $last_category = $cat_name;
        }
        echo "\tSubcategory: " . $row["subcat_name"] .PHP_EOL;
    }
} else {
    echo "0 results";
}
$conn->close();
?>


text:
Q: Incompatibility of MinIO with Laravel version 9 I have a laravel version 9 project and I want to use MinIO driver.
Currently I have to use
$composer require coraxster/flysystem-aws-s3-v3-minio

to install the MinIO driver in laravel. But this command would generate an error:
Problem 1
    - coraxster/flysystem-aws-s3-v3-minio[1.0.0, ..., 1.0.13] require league/flysystem ~1.0 -> found league/flysystem[1.0.0, ..., 1.1.10] but it conflicts with your root composer.json require (^3.12).
    - coraxster/flysystem-aws-s3-v3-minio[1.0.15, ..., 1.0.16] require league/flysystem ^1.0.40 -> found league/flysystem[1.0.40, ..., 1.1.10] but it conflicts with your root composer.json require (^3.12).
    - Root composer.json requires coraxster/flysystem-aws-s3-v3-minio ^1.0 -> satisfiable by coraxster/flysystem-aws-s3-v3-minio[1.0.0, ..., 1.0.16].

I checked that for Laravel version 9 the minimum version of league/flysystem is 3.8.0 while the league/flysystem that is listed in the coraxster/flysystem-aws-s3-v3-minio requirement is version 1.0.40. Any Ideas how I should fix the problem and use MinIO driver with Laravel version 9?


text:
Q: SOLR 9 http response time is very slow while query itself is fast While trying to setup SOLR 9 in docker, I noticed its taking too long to send any request back, even Admin UI is loading extremely slowly, however the QTime in response is not much so solr internal queries is faster, as you can see from screenshot below QTime is just 18ms however request took ~25s to finish.
I tried searching for this issue but couldn't find anything related to this.

Similarly its taking too long to load static files for Admin panel.

PS: Internet speed/connectivity at the client is not an issue here.


text:
Q: If light propagates like waves, why can't I see around corners? I know two different descriptions of how light propagates in space; (1) like particles traveling and reflecting in straight lines. And (2) like waves spreading and interfering in space. And that both these descriptions are true.
It seems to me that scenario (1) is how I perceive the world. I can see things from which the light is reflected into my eyes in a straight line, but I cannot see behind opaque objects, around corners etc.
But if scenario (2) is an equally or more correct description of how light behaves, spreading like waves, filling space, interfering etc.: how come the light hitting my eyes is not equally likely to have travelled from behind objects and around corners? I.e. if this is the true description, all I would expect see is a bright blur, with no way of telling from where the light hitting my eyes have originated.
Any enlightening (zing!) answers much appreciated.
Edit: maybe a clearer way to phrase my question is: can light change direction in empty space by interacting with itself?

A: You do see light around corners. Turn on a light and walk around the corner, do you see light? Of course you do, because the light reflects off of surfaces. Chances are that you can't resolve the source of the light well, if at all, due to interference from the light reflecting off of the myriad of imperfections in surfaces of the wall you're looking at. But if you smooth those out and make a nice mirror, you'll notice that you can resolve quite a lot of detail from around the corner.

A:
If light propagates like waves, why can't I see around corners?

You can. Moreover, you can see the light diffract exactly as a sound wave. The difference is in scale.
Try the following experiment. Take a clean knife, put a small bright LED (e.g. a phone camera flashlight in torch mode) behind this knife. Turn off room light to watch the edge of the knife in the darkness (disturbed only by the LED). You'll see that the edge glows. As you slowly move the LED closer to the edge, you'll see the edge glow brighter until at some point you can see the LED itself.
What you've seen in this experiment is the light from the LED diffracting on the edge of the knife. It appears as if the edge itself emits this light. Similarly you would hear someone shout from behind a lone building: as if the sound is emitted from the edge of the building, not from behind it.

A: Other answers already mention that visible light has a very short wavelength, so we don't normally see around corners just like we hear sounds around corners. And that's a good thing, else we would see a pretty messy world around us!
But we can actually see around corners, and look inside objects, if we use femto-photography, a technique that can "create slow-motion videos of light in motion". I recommend everyone watch this most amazing TED talk: Imaging at a trillion frames per second. They managed to publish a Nature Communications, Recovering three-dimensional shape around a corner using ultrafast time-of-flight imaging, and Nature even produced a cool animation, How to see around corners. The technique is so amazing that some images present diffraction ripples in the wrong direction due to time warp.
Another, very, very cool - but yet mostly theoretical - way to see around objects is the phase-conjugation mirror (see also this and this articles on Scientific American), a technique that relies on the strange effects of non-linear optics to produce a conjugate wave that auto-compensates phase distortion and focus, but as far as I know, only very tiny and frequency-limited mirrors have been built so far.
Light does not interact with itself, from quantum electrodynamics we know that photons cannot couple to each other as they are massless bosons. What happens in a double-slit diffraction experiment is that the photon interacts with itself - or better, the possible pathways throught the slits interfere with each other - as proven by experiments in which the light source is so faint that just a single particle crosses the slits at a time, and still the diffraction pattern persists (see here and here).

A: The bending of waves around corners is known as "diffraction," and its natural length scale is the wavelength of the diffracted wave. So if you want to block the sound from a speaker playing a middle C, with a wavelength in air of about a meter, then you need an obstacle which is many meters across. (A building is a good size.) But to block visible light, with sub-micron wavelength, a millimeter-scale object is a sufficiently enormous obstacle.

A: All light will bend (diffract) around corners and obstacles.
The amount it bends, depends on its wavelength (or frequency). Longer wavelengths (=lower frequency) diffracts a lot more, shorter wavelengths (=higher frequency) diffracts a lot less.
So for example, X rays would diffract a lot less around an obstacle than visible light, but they will still diffract - in fact that's one method used to probe the structure of crystals and large molecules - put them in the path of some X-rays and look at the diffraction patterns it creates.
The problem you have is, that visible light is a pretty small band of wavelengths, that are all fairly short compared to everyday object dimensions. So you won't see big amounts of bending, like your question suggests, or a huge blur around every corner.
If you do the same with longer wavelengths, like radio waves, or WiFi, yes, they bend really well round corners. In fact they can bend round the curvature of the earth too.
That's because:

*

*visible light wavelengths: about 1/1000 of a millimeter (much smaller than everyday objects scale)

*radio wavelengths: about 0.5 m to  10 m (comparable to everyday objects and buildings)

You can see visible light diffract around objects quite easily, even so. There are many experiments and situations where it's plain to the eye. But mostly, their wavelength is small compared to everyday objects and so we usually won't notice the tiny amount of diffraction going on.

A: Light next to the corner will diffract around the corner. Light a little further from the corner will also diffract, although not quite as much. For a narrow slit, there's only a small amount of light diffracting, but as the slit gets larger and larger, there's more and more places to diffract from. You might think that would mean more light diffracting, but all this diffraction gives rise to destructive interference, so the wider the space next to the corner, the narrower the beam of diffracted light (this is related to the uncertainty principle: if you have a very narrow slit, you have low uncertainty where the light is, so you have high uncertainty what direction it goes).
Whether a slit is "narrow" or not is relative to the wavelength. If you're listening to someone in another room and the door is open, the doorway is "small" compared to the wavelength of sound waves, but it's huge compared to the wavelength of visible light, so the amount of light diffraction is insignificant. Wifi uses EM waves with wavelength much larger than that of visible light, so it can go around corners much better.

how come the light hitting my eyes is not equally likely to have travelled from behind objects and around corners

Generally speaking, the amplitude for direct paths is higher than that for bent paths. There are lots of different bent paths and they can have widely varying phases and so interfere destructively with each other. There's only one direct path and nearby paths will have phases that are close to the same, and so will have constructive interference.

A: Light traveling in straight lines is an approximation that works very well most of the time. The most common case where it fails is when light travels through a pinhole or slit. Then it bends a little. This is called diffraction.
You can see an example of light bending when you hold your finger and thumb close together as you look between them at your computer monitor. When they are separated, light goes straight from the monitor to your eye. As they nearly touch, a dark bump seems to grow from your fingers to fill the gap. What is really happening is light that was headed toward your eye is bent away.
It happens all the time, but most of the time, the effect is too small to notice. It sometimes matters when people want to be very precise about where light goes.
One place this matters is in camera lenses. They are designed to bring all light that comes from one point of an object to one point on the sensor. If they don't come to a perfect point, the image is blurry.

Image from Pass My Exams
A lens is a giant pinhole. A big pinhole causes less bending than a small pinhole. But for a really good lens, diffraction is the biggest reason the focus isn't perfect.
Another place it can matter is in a laser beam. People may want a perfectly cylindrical laser beam that never spreads out. Most beams are pretty close, but they do spread over distance. The rays follow a nearly straight hyperbolic path. This kind of beam is called Gaussian. Here you see a sketch of the curved wave fronts. The rays show the direction the wave fronts travel. The rays are always perpendicular to the wave fronts. The spread is usually a fraction of a degree.

Image from the RP Photonics article on Gaussian Beams

Edit - Responding to comments

The blurring in the out-of-focus planes of a camera is not due to diffraction and is equally well described by the particle model of light.

Good point. The picture does not illustrate diffraction. Perhaps this is confusing. It illustrates that if rays from one point on an object do not hit the same point on the sensor, the image will be blurry. Film or sensor at the wrong distance is one way for this to happen. Lens aberrations are another way of getting rays that do not focus at a point.
Even if these are not present, diffraction will prevent a perfect focus.

A lens causes bending primarily by refraction, and again a particle
model describes this exactly.

Refraction is typically derived from the wave model.
Lens design is usually based on ray tracing and refraction, and typically ignores diffraction. Ray tracing is calculated from the surface radii and indices of refraction of the lenses. The effect of diffraction is usually separately calculated from lens diameters. Diffraction is typically treated as a constraint. There is no point to designing a lens where the aberrations are smaller than the diffraction blur circle.
Diffraction can be calculated from the particle model using the uncertainty principle. This is more easily described with a slit. If a particle of light passes through a slit, the uncertainty of the x component of its position the width of the slit. This creates an uncertainty in the x component of its momentum. This means the particle cannot be precisely aimed that the point predicted from ray tracing. Diffraction through a circular aperture is similar, but the calculations is 2-D.

The changing size of a focused beam of light as it propagates is owing to the curved wavefronts, and this is mostly not diffraction. Diffraction is the fact that wavefronts of finite width cannot avoid some spreading even when they are collimated as much as possible.

There is more to a Gaussian beam than the curved wavefronts. The beam cross section has a Gaussian intensity profile. It is brightest in the center, fading away without reaching $0$. This is not exactly like passing through a pinhole, but the non-uniformity is the cause of the curved wavefronts. This is properly described as diffraction.
The picture illustrates what happens when a beam is focused with a lens. Given a good lens, diffraction determines the spot size, and therefore how much that spot is heated. But exactly the same thing determines the angle at which a collimated beam spreads. The picture would be the same except for a larger beam waist and shallower divergance angle. Either way, the rays are hyperbolic.
As an aside, there is an intensity profile with a Bessel function distribution that is perfectly collimated. This can approximately be achieved by passing a Gaussian beam through an axicon lens. This has applications in drilling operations.

A: TL;DR: Visible light - no, but radio waves - yes.
Electromagnetic waves do bend around the corners, if their wavelength is comparable to the size of the object (such as building, for example). Visible light with a typical wave length of a few hundred nanometers is obviously not a good candidate, but for radio waves, which may have wave lengths ranging from centimeters to many kilometers, this is a normal state of affairs. This is why we can use  a radio transmitter inside a room. Exceptionally long wave lengths are even known to travel around the Earth (see Extremely low frequency and Longwave).

A: Here's a way to think about it: Only the light really close to the edge gets bent around the edge. And "really close" means "roughly the wavelength of the light", which, as others have pointed out, is tiny. This means two things.

*

*The amount of light that gets bent around the corner is just tiny, since it's only the light that was so close to the edge. So you can't really see it because it's just not enough light. (Or maybe you can a little bit in a dark room in the experiment with the knife, but in that case that's why you need the room to be dark.)

*All the light that gets bent around the corner to you comes from that tiny strip, so you don't get an image of what's behind the wall, just a negligibly brighter edge of the wall. The key thing about seeing an image is that light is entering your eyeball from different directions, and the edge of the wall means that the only directional variation of the diffracted light is up and down. But again, you can't see it anyway because there's too little of it.

A: *

*can light change direction in empty space by interacting with itself?

No, just like water waves, light waves they pass though each other, add up on the crossing region ( =interference)  and get out as they came in. but light does bend at corners.
In a deeper sense, light does interact with itself according to Huygens optics (a wave is a sum  of point like oscillators), and that's why it creates waves. And when light cannot interact with it's neighbouring light because there's a corner, then the wave bends (that effect is seen in water waves too).

*

*how come the light hitting my eyes is not equally likely to have
travelled from behind objects and around corners?

Because the effect is small but historically demonstrated with visible light by arago/poisson


text:
Q: Laravel 5.5 - Валидация строки внутри объекта, который внутри массива есть request:
`array:2 [
  "alt_tags" => "1"
  "name_pattern" => array:2 [
    0 => "{"label":"Main Title","value":"main_title"}"
    1 => "{"label":"Store Name","value":"store_name"}"
  ]
]`

В классе Request, я пытался валидировать следующим способом, но безрезультатно:
`$labels = \implode(',', [
        'Main Title',
        'Store Name',
    ]);

 $values = \implode(',', [
        'main_title',
        'store_name',
    ]);

 return [
        'alt_tags'        => 'required|boolean',
        'name_pattern'         => 'required|array|min:0|max:2',
        'name_pattern.*.label' => "sometimes|string|in:{$labels}",
        'name_pattern.*.value' => "sometimes|string|in:{$values}",
        ];`

при проверке name_pattern.*.label возвращает NULL:
data_get(request()->all(), 'name_pattern.0') // "{"label":"Main Title","value":"main_title"}"
data_get(request()->all(),'name_pattern.0.label');  // return NULL

Просьба помочь с валидаций строк внутри объекта.


text:
Q: Approximating simple functions by step functions almost uniformly The title says it all. How can we approximate measurable simple functions by step functions almost uniformly in, say, $[0,1]$? Even with the simplest example, $\chi_{A}$, where $A$ is Lebesgue measurable, I cannot do this almost everywhere.
I tried moving to decreasing intersections of open sets, which works out fine, but then moving to finite intersections gives you sets of positive measure where the approximation in norm is not small anymore.

A: Use Lusin's Theorem to find a continuous function that agrees with your simple function off a set of measure less than $\varepsilon$. Now use compactness of $[0,1]$ to write the continuous function as a uniform limit of step functions.


text:
Q: MessageBird reportUrl not triggered I am trying to send a conversation message, I able to receive the message but I didn't get the report, I configured reportUrl, but the report doesn't arrive, why?
I checked into /var/www/apache2/access.log, I got below:
35.246.41.39 - - [01/Jun/2021:11:24:44 +0000] "POST /whatsapp/myWebhookAsync? HTTP/1.1" 200 5327 "-" "MessageBirdHTTPQueue/1622459790-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
my webhook is only simple, I just want to log it into a file, just want to make sure if it really arrives or not
    [HttpPost]
    [Route("/WhatsApp/myWebhookAsync")]
    [AllowAnonymous]
    public async Task myWebhookAsync()
    {
            using (var reader = new StreamReader(Request.Body))
            {
                string _jsonx = await reader.ReadToEndAsync();
                await Helper.SaveLogAsync("CAPTURED --- WhatsAppController.MessageBird_ReportAsync " + _jsonx);
            }

    }


text:
Q: Grouping data and searching for sets of values This is the data frame:
drug_id      illness
    lexapro.1     HD
    lexapro.1     MS
    lexapro.2     HDED
    lexapro.2     MS
    lexapro.2     MS
    lexapro.3     CD
    lexapro.3     Sweat
    lexapro.4     HD
    lexapro.5     WD
    lexapro.5     FN

First, I am going to group the data based on drug_id, and search for availability of HD, Sweat, WD, CD,  MS, and FN in the illness column. Then if illness values are "HD or Sweat or WD", the column "HD" in df2 will receive 1, if the illness values in F1 were MS or HDED, then the MS column in df2 will receive 1, and if illness in FN is 1, then FN in df2 will receive 1. So df2 is like this:
df2:
drug_id       HD      MS    FN
lexapro.1      1      1      0
lexapro.2      0      1      0
lexapro.3      1      0      0
lexapro.4      1      0      0
lexapro.5      1      0      1

I already asked a similar question. however in that question,there were no "or" in searching for values in the column illness.
grouping data in a data-frame, checking for availability of specific values, and updating the second data frame

A: This can be done with a replace call:
repl_dict = {'Sweat' : 'HD', 'WD': 'HD', 'HDED' : 'MS'}
df.illness = df.illness.replace(repl_dict)

Now, use any of the options from your previous answer.
df.set_index('drug_id').illness.str.get_dummies()\
         .sum(level=0).ge(1).astype(int).drop('CD', 1)

           FN  HD  MS
drug_id
lexapro.1   0   1   1
lexapro.2   0   0   1
lexapro.3   0   1   0
lexapro.4   0   1   0
lexapro.5   1   1   0

piRSquared shortened the replacement and groupby to a single line:
df.illness.replace(repl_dict).groupby(df.drug_id)\
         .apply('|'.join).str.get_dummies().drop('CD', 1)

           FN  HD  MS
drug_id
lexapro.1   0   1   1
lexapro.2   0   0   1
lexapro.3   0   1   0
lexapro.4   0   1   0
lexapro.5   1   1   0

Thank you!

A: Another way achieve this
pd.crosstab(df['drug_id'],df['illness']).rename(columns={'Sweat' : 'HD', 'WD': 'HD', 'HDED' : 'MS'}).groupby(lambda x : x,axis=1).sum().gt(0).astype(int).drop('CD',1)
Out[290]:
           FN  HD  MS
drug_id
lexapro.1   0   1   1
lexapro.2   0   0   1
lexapro.3   0   1   0
lexapro.4   0   1   0
lexapro.5   1   1   0


text:
Q: (How) is the covid-19 situation affecting the 1Q20 timeline/roadmap? The Q1 2020 Community Roadmap is on the Blog gave a dense timeline, with plenty of actions planned by SE Inc. to happen in March 2020.
That post was written 20 days ago, and for many people (at least those in the Western hemisphere), the world probably felt very much different 20 days back.
So, just for our own expectation management: do you currently intend to follow up on that initial plan, or have circumstances changed for you in ways that will require staging, delays, significant changes, ...?

Please don't get me wrong: this is not pushing for anything to happen, it is really about understanding the current situation, and what it means for our "joint journey".

A: As you pointed out, things have changed. All Stack employees are now working from home. And while this isn't a big change for many of our employees, most of us now have additional factors to contend with that can end up reducing our ability to move forward with different initiatives at the rate that we had intended and committed to. And we are fortunate to work for a company that has made employee physical and mental health an absolute top priority.
I tried to address this a little in the feature preview post on Question Following the other day:

(Work is well underway, and we are aiming for a release by the end of March. However, current events make it likely that delays may be introduced into the process, so it is hard to give an exact commitment right now).

We do intend to follow up on the different items in the Q1 Roadmap. And as part of our commitment to open communication, we will try to communicate as best as we can if and when plans or commitments are delayed.
We thank you for your understanding and support.


text:
Q: Sql 2005 data migration I have the same database running on two different machines. The DB's make extensive use of Identity columns, and the tables have clashed pretty horribly. I now want to merge these two together before sorting out the undelying issue which I may do by
A) Using GUIDs (unweildy but works everywhere)
B) Assigning Identity ranges, kind of naff, but means you can still access records in order, knock up basic Sql and select records easily, and it identifies which machine originated the data.
My question is, what's the best way of re-keying (ie changing the primary keys) on one of the databases so the data no longer clashes. We're only looking at 6 tables total, but lots of rows ~2M in the 3 tables.
Update - is there any real sql code out there that does this, I know about Identity Insert etc. I've solved this issue in a number of in-elegant ways before, and I was looking for the elegant solution, preferable with a nice TSQL SP to do the donkey work - if that doesn't exist I'll code it up and place on wiki.

A: A simplistic way is to change all keys on the one of the databases by a fixed increment, say 10,000,000, and they will line up.  In order to do this, you will have to bring the applications down so the database is quiet and drop all FK references affected by this, recreating them when finished.  You will also have to reset the seed value on all affected identity columns to an appropriate value.
Some of the tables will be reference data, which will be more complicated to merge if it is not in sync.  You could possibly have issues with conflicting codes meaning the same thing on different instances or the same code having different meanings.  This may or may not be an issue with your application but if the instances have been run without having this coordinated between them you might want to check carefully for this.
Also, data like names and addresses are very likely to be out of sync if there wasn't a canonical source for these.  You may need to get these out, run a matching query and get the business to tidy up any exceptions.

A: I would add another column to the table first, populate that with the new Primary key.
Then I'd use update statements to update the new foreign key fields in all related tables.
Then you can drop the old Primary key and old foreign key fields.


text:
Q: Running Pex with .NET 3.5 projects I'm currently trying to use Pex and Moles with a SharePoint 2010 solution that's written in .NET 3.5.
When adding a test project (by using Pex -> Create parameterized tests) everything seems to work OK.
However, when I try to compile I end up with a massive list of errors (missing namespaces and such) and warnings regarding referenced assemblies not being able to be resolved (such as System.Web which under .NET 4 is no single DLL anymore).
This is due to the projects under test is .NET 3.5 and the Pex test project is .NET 4.0 as far as I understand it, but is it possible to make this combination work at all?

A: If you change the project Target Framework to ".Net Framework 3.5" and then open the project AssemblyInfo.cs file and comment out the following line:
[assembly: SecurityRules(SecurityRuleSet.Level1)]
the project should build. How this affects PEX and its "Explorations" I am not sure. I hope this gets you a little further down the road.

A: The answer is here: http://msdn.microsoft.com/en-us/library/system.reflection.assembly.securityruleset.aspx

"By default, assemblies that you compile with the .NET Framework
  version 4 have level 2 transparency, although you can explicitly make
  them level 1 instead.Assemblies that were compiled with earlier
  versions of the .NET Framework have level 1 transparency"


text:
Q: MySQL - UPDATE one column's values using one query I have this db table:
Items
-------
id  // values: 1,2,3,4,5 ...
name // values: Item1,Item2,Item3,Item4,Item5 ...
order // values: 1, 5, 2, 3, 4 ...

The items are images. The image order is set in an array when dragging the images around, but in order to update the order, I use one UPDATE inside a loop. I was wondering if I could do the UPDATE without using a loop.
I was wondering if I can update the item's order at once, using only one UPDATE query.

A: You can use INSERT (..) ON DUPLICATE KEY UPDATE (..) syntax.
INSERT INTO `table` (`id`, `order`)
VALUES (1, 1), (2, 5), (3, 2), (4, 3), (5, 4)
ON DUPLICATE KEY UPDATE `order` = VALUES(`order`)


text:
Q: Google API ClientID and HTML in an UIWebView I'm developing a webapp with HTML and load it into an simple iphone app with a UIWebview.
This part is working perfectly, but I'm using Goo.gl URL Shortener API and the thing is Google API, in order to get a Client ID, need to specify an Authorized Javascript Origins, but I don't know what I have to enter.
I tried, "http://localhost", it didn't work, the API is not loading.
I tried also with the IOS application type, enter my app bundle ID, and it didn't work neither.
Could someone help me on this?


text:
Q: Doing it right with Google SEO while Dynamically Serving between desktop and mobile I've read the whole thing here on dynamic serving and I understood that setting the correct-http-headers is the key here!
My game plan is simple;
I will have a single url as ".com/myApp" and then I will serve my content dynamically.
As a result,  the mobile people will get "/myApp/index-mobile.php" and the desktop people will get "/myApp/index-desktop.php".  And to handle the traffic, I will have the good old "index.php" sniffing the user-agent and acting like a traffic cop.
The question is where does the following key http header go?
header("Vary: User-Agent, Accept");
Will it go in index.php only?
What about index-mobile & index-desktop php pages. Are there certain things that I need to be worried about in their HTMLs to tell Google that one is a mobile site while the other one is the one serving the desktop populaion. Does canonicals & rel attributes come into play here as mentioned in the do's and don'ts of serving under seperate urls here?
Since serving dynamic content is borderline with "cloaking", I simply do not want to screw things up.
I'd appreciate your expert guidance on this important issue.
Thank you
I don't think I need to include the contents of my index.php, but for the completeness, I'll include it anyway.
<?php

  //  this index.php acts like a traffic cop
  //directing traffic between mobile and desktop users - seamlessly.

  require_once 'includes/Mobile_Detect.php';
  // http://mobiledetect.net/

  $detect = new Mobile_Detect;

  if ( $detect->isMobile() && !$detect->isTablet() ) {
    $user_agent = 'mobile';
  } else {
    $user_agent = 'desktop';
  }

  include ("index-{$user_agent}.php");
  //loads either index-desktop.php or index-mobile.php

  ?>


text:
Q: Aspect Fill on navigation bar image? I'm wanting to achieve the same look as an imageView's aspect fill for my navigation controller's background image.
Currently I'm using this to setup the image:
UINavigationBar.appearance().setBackgroundImage(imageToCache?.resizableImage(withCapInsets: UIEdgeInsetsMake(0, 0, 0, 0), resizingMode: UIImageResizingMode.stretch), for: .default)

UIImageResizingMode.stretch obviously gives me a nasty stretched look. I don't care if the image is getting cut off on the top/bottom, I'm just needing it to be put into the nav bar full sized and what shows shows.
I can't just pass in nil to the resizing mode.
There's also the
init(rawValue:))

option for the resizing mode, but any number I put in there results in there being no image in the background anymore.
Any ideas?
edit:
let picture = passedPerson.pictureURL!

         if let imageFromCache = MainPageVC.imageCache.object(forKey: picture as String as NSString) {

                var titleView = UIImageView()
                titleView.contentMode = .scaleAspectFit
              titleView.image = imageFromCache

        self.navigationItem.titleView = titleView  } else {
        print(picture)
        var requested = URLRequest(url: URL(string: picture)!)

        URLSession.shared.dataTask(with: requested) {data, response, err in

            if err != nil {

                print(err?.localizedDescription)
            } else {

                DispatchQueue.main.async {

                    let imageToCache = UIImage(data: data!)

                    MainPageVC.imageCache.setObject(imageToCache!, forKey: picture as String as NSString)

                    var titleView = UIImageView()
                    titleView.contentMode = .scaleAspectFit
                    titleView.image = imageToCache

                    self.navigationItem.titleView = titleView

                  //  UINavigationBar.appearance().setBackgroundImage(imageToCache?.resizableImage(withCapInsets: UIEdgeInsetsMake(0, 0, 0, 0), resizingMode: UIImageResizingMode.stretch), for: .default)
                }

            }

            }.resume()

The above results in no picture showing up.

A: try with this . hope it you will work
UINavigationBar.appearance().setBackgroundImage(imageToCache, forBarMetrics: .Default)


text:
Q: Insert values 2 ways- 0 rows inserted Trying to add 7 rows in 2 different ways. In both the result is 0 rows inserted.
create table bank
(
  MoveNo INT ,
  Valdate DATE not null,
  Amount NUMBER(9,2),
  Essence varchar2(30)
);

**//First way**
INSERT ALL
  INTO bank (MoveNo, Valdate, Amount, Essence) VALUES (1,'2001/01/01',500,'opening balance')
  INTO bank (MoveNo, Valdate, Amount, Essence) VALUES (2,'2001/01/10',3500,'salary')
  INTO bank (MoveNo, Valdate, Amount, Essence) VALUES (3,'2001/01/10',-460,'cheque 055786')
  INTO bank (MoveNo, Valdate, Amount, Essence) VALUES (4,'2001/01/12',1100,'deposit')
  INTO bank (MoveNo, Valdate, Amount, Essence) VALUES (5,'2001/01/14',-5.50,'account management')
  INTO bank (MoveNo, Valdate, Amount, Essence) VALUES (6,'2001/01/17',-300,'cheque 055787')
  INTO bank (MoveNo, Valdate, Amount, Essence) VALUES (7,'2001/01/19',-867,'credit card')
SELECT 7 FROM BANK;

**//Second way**
INSERT INTO bank (MoveNo, Valdate, Amount, Essence)
          select 1,'2001/01/01',500,'opening balance' from dual
union all select 2,'2001/01/10',3500,'salary' from dual
union all select 3,'2001/01/10',-460,'cheque 055786' from dual,
union all select 4,'2001/01/12',1100,'deposit' from dual,
union all select 5,'2001/01/14',-5.50,'account management' from dual,
union all select 6,'2001/01/17',-300,'cheque 055787' from dual,
union all select 7,'2001/01/19',-867,'credit card' from dual,
SELECT * FROM bank;

A: For both statements, '2001/01/01' is not a DATE it is a string literal. Although Oracle will try to be helpful and implicitly apply the TO_DATE function to the string to convert the string to a date, it does not know the format of the date so it will use the NLS_DATE_FORMAT. You are likely to get an error as the default NLS_DATE_FORMAT is not likely to match YYYY/MM/DD. Instead, you should use a DATE literal or use TO_DATE('2001/01/01', 'YYYY-MM-DD').
The BANK table has zero rows initially, so when you use INSERT ALL ... SELECT 7 FROM BANK the final SELECT will match zero rows and nothing will be inserted. Instead, you want to SELECT ... FROM DUAL which would give you a single row and correspondingly perform each of the INSERTs once:
INSERT ALL
  INTO bank (MoveNo, Valdate, Amount, Essence) VALUES (1, DATE '2001-01-01',  500,    'opening balance')
  INTO bank (MoveNo, Valdate, Amount, Essence) VALUES (2, DATE '2001-01-10', 3500,    'salary')
  INTO bank (MoveNo, Valdate, Amount, Essence) VALUES (3, DATE '2001-01-10', -460,    'cheque 055786')
  INTO bank (MoveNo, Valdate, Amount, Essence) VALUES (4, DATE '2001-01-12', 1100,    'deposit')
  INTO bank (MoveNo, Valdate, Amount, Essence) VALUES (5, DATE '2001-01-14',   -5.50, 'account management')
  INTO bank (MoveNo, Valdate, Amount, Essence) VALUES (6, DATE '2001-01-17', -300,    'cheque 055787')
  INTO bank (MoveNo, Valdate, Amount, Essence) VALUES (7, DATE '2001-01-19', -867,    'credit card')
SELECT 1 FROM DUAL;

For your second query, you have commas between the statements and are missing the final ; statement terminator:
INSERT INTO bank (MoveNo, Valdate, Amount, Essence)
          select 1, DATE '2001-01-01',  500,    'opening balance'   from dual
union all select 2, DATE '2001-01-10', 3500,    'salary'            from dual
union all select 3, DATE '2001-01-10', -460,    'cheque 055786'     from dual
union all select 4, DATE '2001-01-12', 1100,    'deposit'           from dual
union all select 5, DATE '2001-01-14',   -5.50, 'account managment' from dual
union all select 6, DATE '2001-01-17', -300,    'cheque 055787'     from dual
union all select 7, DATE '2001-01-19', -867,    'credit card'       from dual;

Then you can do:
SELECT * FROM BANK;

As a separate statement and it will show 14 rows (7 from the INSERT ALL statement and 7 from the INSERT .. SELECT statement).
db<>fiddle here


text:
Q: How can you set a site-level master page on the Web? I have a SharePoint 2010 site collection that doesn't have publishing features enabled (on purpose), and was wondering if it was possible to set the site's default master page... without using SharePoint Designer.
Microsoft's information about Master Page deployment is somewhat lacking.

A: Append /_layouts/changesitemasterpage.aspx to your site URL. You will get the option you are looking for.


text:
Q: wp_enqueue_style doesn't work First of all, I tried this and didn't work: "https://wordpress.stackexchange.com/questions/89494/how-to-enqueue-the-style-using-wp-enqueue-style/89495#89495".
What I want to do is a plugin with a unique page (options page) and I'm trying to insert in head tag a <link href="my_dir/css/style.css"/>. The prefix of my plugin is easydm and has in the main file the followingo code:
define( 'EASYDM_VERSION', '1.0' );
define( 'EASYDM__MINIMUM_WP_VERSION', '2.1' );
define( 'EASYDM_DIRECTORY_NAME', 'easy-downloader-manager/' );

define( 'EASYDM_ROOT_DIRECTORY', substr( plugin_dir_path( __FILE__ ), 0, strpos( plugin_dir_path( __FILE__ ), EASYDM_DIRECTORY_NAME ) ) );

define( 'EASYDM_PLUGIN_URL', plugin_dir_url( __FILE__ ) );
define( 'EASYDM_PLUGIN_DIR', plugin_dir_path( __FILE__ ) );

define( 'EASYDM_SETTINGS_URL', plugin_dir_url( __FILE__ ).'settings/' );
define( 'EASYDM_SETTINGS_DIR', plugin_dir_path( __FILE__ ).'settings/' );
define( 'EASYDM_SETTINGS_PATH', 'settings/' );

define( 'EASYDM_CSS_URL', plugin_dir_url( __FILE__ ).'css/' );
define( 'EASYDM_CSS_DIR', plugin_dir_path( __FILE__ ).'css/' );
define( 'EASYDM_CSS_PATH', 'css/' );

require_once EASYDM_SETTINGS_DIR.'easydm-functions.php';

register_activation_hook( __FILE__, 'easydm_activation');

add_action( 'wp_enqueue_scripts', 'easydm_add_link_tag_to_head' );

My easydm-functions.php has:
function easydm_add_link_tag_to_head() {
    wp_enqueue_style( 'style', get_plugin_directory_uri().'/'.EASYDM_DIRECTORY_NAME.EASYDM_CSS_PATH.'style.css' );
}

This is my last try, but I tried some other arguments on wp_enqueue_style() function.
Some help?
Thanks
--- editing ---
Here's a possible way to solve. Indeed, I solved partially the problem. Now I need to cut a string which is appended to my link. See that:
https://wordpress.stackexchange.com/questions/219911/enqueue-script-style-plungin-development/219914?noredirect=1#comment322394_219914
--- editing again ---
I found this http://wpcrux.com/wordpress-enqueue-functions-version/ what solve the above new problem... but still not styling my page... I checked if the path is correct, my file is there, is not empty or any error like these.
Any idea?

A: SOLVED!!!
The documentation for wp_enqueue_style function is clear to say that the second argument nedd to be relative path to the root installation WordPress. But as I viewed many examples in tutorials using full path I ignored it. Now, defining this constant and all previous steps everything runs ok.
define( 'EASYDM_CSS_PATH' , str_replace( site_url().'/', '', plugin_dir_url( __FILE__ ) ).'css/' );
and in function:
wp_enqueue_style( 'easydm-style', '/'.EASYDM_CSS_PATH.'style.css', array(), null, 'all' );
So, if someone is tired out to looking for and don't wanna read this all discussion, the final code is:
define( 'EASYDM_CSS_PATH' , str_replace( site_url().'/', '', plugin_dir_url( __FILE__ ) ).'css/' );
add_action( 'admin_enqueue_scripts', 'easydm_add_link_tag_to_head' );

functions file:
function easydm_add_link_tag_to_head() {
    wp_enqueue_style( 'easydm-style', '/'.EASYDM_CSS_PATH.'style.css', array(), null, 'all' );
    wp_enqueue_style( 'easydm-manager', '/'.EASYDM_CSS_PATH.'manager.css', array(), null, 'all' );
}

Where I add two styles. I really hope this help someone. Thank you everyone!

A: Thanks for you sharing. I meet the same issue when adding some styles and scripts but I think the issue you pointed out should not be the root cause, actually, my problem is I should add it to wp_enqueue_scripts action like below

add_action('wp_enqueue_scripts','nz_footer_cumstom_func');

I tried your solution, I think both could work. I mean wp_enqueue_style() could accept a relative path as well as a full file path.


text:
Q: Looking for word in 2D Array I'm trying to get the index (i.e. position of the word in the array) of a word in a 2D Array when a button is pressed. The word that I am looking for is the title of the button pressed.
@IBAction func buttonPressed(_ sender: UIButton) {

    let buttonSelected = sender.currentTitle!
    let findIndex = myArray.firstIndex(of: englishButtonSelected)!

}

when I build the code I get this error:
Cannot convert value of type 'String' to expected argument type '[String]'
The constant "buttonSelected" is a String.
I'm new to swift and still learning. Any help is much appreciated! Thank you!
Using Xcode 11.4

A: You're almost there. firstIndex will return the first index where a given element appears. Because myArray is a [[String]] (2D Array), it's expecting you to put a [String] in, because each element is a [String]. For example:
let myArray = [["A", "B"], ["C"], ["D", "E"]]
let index = myArray.firstIndex(of: ["D", "E"]) // index = 2

If you want to get the 'absolute' index of the button title (in the example above, this would correspond to the index of "C" being 2, or "E" being 4), you can use:
myArray.flatMap { $0 }.firstIndex(of: buttonTitle)

The .flatMap collapses a 2D array into a regular array. If you want to find the index of the button title within its own sub-array, you'll have to loop through the 2D array and check the index of each sub-array for the button title.

A: After some googling, I found out how to find the output I'm looking for. This gave me the exact index in [?][?] format of my 2D Array!
for i in 0..<myArray.count {
    for j in 0..<myArray[i].count {
        if myArray[i][j] == buttonSelected {
            print (i, j)
        }
    }
}


text:
Q: Unable to select dropdown on website in excel vba I am trying to automate a web navigation. I am stuck at selecting the dropdown. This is what I have so far:
the_Start:
    Dim i As Integer
    Dim objIE As Object
    Set objIE = CreateObject("InternetExplorer.Application")
    objIE.Top = 0
    objIE.Left = 0
    objIE.Width = 800
    objIE.Height = 600
    objIE.Visible = True
    objIE.navigate ("https://suit.cibil.com")

    With objIE
        Do While .Busy
            DoEvents
        Loop
        Do While .ReadyState <> 4
            DoEvents
        Loop
    End With

    While objIE.Busy
        DoEvents
    Wend

    If objIE.Busy = False Then

        Set the_input_elements = objIE.Document.getElementsByTagName("select")

        For Each input_element In the_input_elements

            If input_element.getAttribute("name") = "croreAccount" Then
                'MsgBox ("Found croreAccount")
                Set option1 = input_element.getElementsByTagName("option")
                For Each dropdown1 In option1
                    If dropdown1.Value = "1" Then
                        'MsgBox dropdown1.Text
                        dropdown1.Focus
                        dropdown1.FireEvent ("onchange")
                        dropdown1.Click
                        dropdown1.Selected = "selected"
                        dropdown1.Selected = True
                    End If
                Next
            End If

        Next

    End If
End Sub

'This opens the website, and correctly takes me to option tab, but do not select them. Please help as' 'this is extremely repetetive work'

HTML

<select name="croreAccount" class="select" id="croreAccount" style="z-index: 10; opacity: 0;" onchange="changeQuarter(this);">
    <option selected="selected" value="0">Option</option>
    <option value="1">Search</option>
    <option value="2">Summary - Credit Institutions Wise List</option>
    <option value="3">Summary - State/Union Territory</option>
</select>

A: Firstly, you can use the id to target the appropriate select element. You don't need any looping as you can then select the required option using its value attribute. After making your selected by setting the option as selected = True, you need to attach a change HTMLEvent to the parent select element and dispatch it so the node registers the options change and updates
Option Explicit

Public Sub test()

    Dim objIE As Object

    Set objIE = CreateObject("InternetExplorer.Application")

    objIE.Visible = True
    objIE.navigate "https://suit.cibil.com"

    Dim evt As Object

    With objIE

        While .busy Or .ReadyState <> 4: DoEvents: Wend

        .document.querySelector("#croreAccount [value='1']").Selected = True

        Set evt = .document.createEvent("HTMLEvents")
        evt.initEvent "change", True, False

        .document.querySelector("#croreAccount").dispatchEvent evt

        Stop

        .Quit

    End With

End Sub


text:
Q: in Christmas spirit She's been working very hard to get him in Christmas spirit.
Is "in Christmas spirit" the grammatical and natural way to say it?
Also, could someone explain to me what it means to be in Christmas spirit?

A: The sentence is fine, although "... into the Christmas Spirit" may be better.
Getting into the Christmas Spirit means getting into the mood to enjoy Christmas. For some people that may be celebrating the birth of Christ, for some people it means the gathering of family and friends and for some it just means a holiday from work.
Other words are often used with "spirit" to indicate getting into the (normally) happy mood for the occasion. Examples include "getting into the party spirit" or "getting into the holiday spirit".
An alternative phrasing would be "... Christmas Mood" or "... holiday mood" etc.

A: *

*... to get him in the Christmas spirit. Please see spirit:

*The prevailing or typical quality, mood, or attitude of a person, group, or period of time. –
Weather Vane


text:
Q: Check if my app is installed on a Windows Phone I have a few Windows Phone apps in the store and each of my apps has a "More apps" part where I promote all of them. Is it possible to know if they installed one of my apps so I don't show it in the list anymore?

A: Try InstallationManager.FindPackagesForCurrentPublisher: Returns all the app packages with the same publisher ID as the app calling this method, details at https://msdn.microsoft.com/library/windows/apps/windows.phone.management.deployment.installationmanager.findpackagesforcurrentpublisher(v=vs.105).aspx


text:
Q: Subclass Coupling and an example in .NET I have just been reading an article that says:

Subclass coupling. When a base type (usually class) has a number of derived types that extend it, other types should ideally only know about the base type. If all the subtypes share the same public interface (the public members inherited from the base type, overwritten for different behavior in each subclass), then outside "client" types can treat them all the same, as if they were the base class. If this is not so, if a client type knows specifics about the subtypes that exist, then this is subclass coupling to the polymorphic structure in question.

Specifically, the last line says that "if a client type knows specifics about the subtypes that exist...".  In .NET, if I use the WebRequest.Create("ftp://..."); then I know that an FtpWebRequest will be returned, and that I can change properties that are specific to the FtpWebRequest subclass, such as the UseBinary property.  I wouldn't be able to do that unless I had specific knowledge about the subtype of WebRequest, so in my mind, this is a case of subclass coupling and is bad design.
I struggle to believe that this is bad design on behalf of the .NET framework developers, and instead imagine that my understanding of the above is a little off.  Would someone be able to explain why the example I have provided in .NET is not an example of subclass coupling?

A: I would say that it depends. A lot of the time you don't want to work on the conrete types, like your FtpWebRequest, since this makes you coupled to that type. If you instead work against an interface called IRequest or IWebRequest you will not be as coupled to the concrete implementation of those interfacet which means that it will be easier to test your code, most of the time, and you will have less pain to going from ftp to some other protocol as long as they conform to the interface you are using. But if you are doing something really simple there might be no need to put in the extra abstraction layers that the interfaces create.
Simple example:
public interface IDoSomething { void DoSomething(); }
public class DoSomethingA { public void DoSomething(); }
public interface DoSomethingB { public void DoSomething(); }

public class UseDoSomething
{
    public UseDoSomething(IDoSomething do) { do.DoSomething(); }
}

If you in the class UseDoSomething took in one of the concrete types; DoSomethingA or DoSomethingB, you would have tighter coupling towards that implementation. With the example I provided you are free to use any implementation of IDoSomething as input to UseDoSomething which is great for the future and also makes it easier to test. As you might realise everything depends on you requirements etc. Maybe you must use the concrete type since you need to access that specific thing of the type, then it might be fine to do so.
Do I make myself clear?


text:
Q: zone delegation in Bind I have a lot of zones defined in my DNS server. I need to delegate one particular zone to a foreign DNS server and I don't have access to my domain-registrar control panel, currently.
Is there a way in Bind to delegate the resolution of a whole zone to another DNS server?
I thought it was possible to just name the foreign server ns1.delegatenameserver.com in the zone file but it's not working.
$TTL 3600
@               IN SOA ns1.delegatednameserver.com. hostmaster.ariel.org. (
                        2013120904      ;serial
                        3600            ;refresh
                        360             ;retry
                        86400           ;expire
                        3600            ;minimum
                )

                IN NS           ns1.delegatednameserver.com.

A: It's not entirely clear from your question how far along you are, but to delegate a subdomain you have to have control over its parent domain.
So, if you control example.com and want to delegate sub.example.com to another DNS, you have to do:
In example.com's zone file
## this is the "glue" record
sub.example.com. IN NS ns1.sub.example.com.
ns1.sub.example.com. IN A 123.123.123.123 ;; IP address of the foreign DNS server to which you're delegating

In the foreign DNS server:
## you must have configured the sub.example.com zone
@           IN SOA ns1.sub.example.com. hostmaster.sub.example.com. (
                    2016060700      ;serial
                    3600            ;refresh
                    360             ;retry
                    86400           ;expire
                    3600            ;minimum
            )

                     IN NS  ns1.sub.example.com.
ns1.sub.example.com. IN A   123.123.123.123

www                  IN A   121.121.121.121
;; etc

Note that you can only properly delegate a subdomain, and to achieve it you must control its upper-level domain.
If you don't have control over the upper-level domain, you can still transfer load/responsibility over a domain by other means.
Let's say you control example.com at ns1.example.com (delegator) and want to delegate to ns3.example.com (delegatee).
1. add extra NS records to the zone file in ns1.example.com and set up a master/slave relationship
Your delegator nameserver will still get requests, but some clients will hit the delegatee.
You must set up example.com as a slave zone in ns3.example.com with master ns1.example.com for this to work. You will still have control of example.com in your delegator nameserver.
2. forward the zone to ns3.example.com
You can forward every request you receive to example.com by configuring:
zone "example.com" IN { type forward; forwarders { 122.122.122.122; }; }; // ns3.example.com

You will still receive every request for example.com on your delegator nameserver, which will then send the request forward but control of the zone contents will be entirely under control of the delegatee ns3.example.com.
In the delegated nameserver, example.com must be configured as a master zone.
3. ns1.example.com as slave
You can set up example.com as a slave zone in ns1.example.com with master ns3.example.com.
This is similar to option 2 above, with the difference that ns3.example.com won't be receiving any DNS requests from the world, only zone transfer requests from ns1.example.com.
ns1.example.com also keeps a cached copy of the zone and will still answer queries if ns3.example.com goes down.

A: The address of the name server is missing in this zone declaration.
Add the following to your declaration file.
ns1  IN A  ip.of.delgated.server


text:
Q: Translation for TYPO3 Backend Content Elements How can I get a translation string in TYPO3 Backend?
In language overview in Backend, I have my custom Content Elements displayed.
If there is no link title set, the button has a language specific default value:

*

*EN: Read more

*DE: Mehr erfahren

In Frontend, we have <f:translate, but in Backend this does not work?
Version: TYPO3 V10 LTS

A: depending on where your label is. the string is defined in TCA (Table Configuration Array) or Flexform. in both cases you use an LLL reference instead of the label
usually somthing like this:
LLL:EXT:my_ext/Resources/Private/Language/backend.xlf:my_label_name
let me pick explain the diffrent parts:
LLL: proccess this aht Local Language resource (similar to http: in an URL)
EXT: this is an Extension Path chheck prefixes like typo3conf/ext/ or typo3/sysext
my_ext/Resources/Private/Language/backend.xlf the path to the file
:my_label_name the label inside the file

A: <f:translate> does work in the backend as well.
The language file should at least look like:
<?xml version="1.0" encoding="utf-8" standalone="yes" ?>
<xliff version="1.0">
    <file source-language="en" datatype="plaintext" original="messages" date="2013-08-22T11:22:55Z" product-name="efemtpy">
        <header/>
        <body>
            <trans-unit id="title">
                <source>Title</source>
            </trans-unit>
        </body>
    </file>
</xliff>

Maybe you forgot the <source>-Tag like I did before.


text:
Q: How to draw a diagonal border with multiple lines? i'm trying to draw a table with the first cell splitted by a diagonal border. But since my headings have 2 lines, the other cells also have 2 lines, and then the borders are incomplete, generating "gaps" over the table, as well the cells are not centered at the middle of the cell, becoming an ugly format.
I'm using slashbox package, and compiling with Overleaf.
Can someone help?
Thanks!!
Eduardo.
\usepackage{slashbox}
\begin{document}
\begin{table}[H]
\begin{center}
\caption{Classificação de Marchal: as estruturas de mercado diferenciadas também por fatores associados ao comportamento dos agentes a natureza dos produtos.}
\label{table:rossetti}
\begin{tabular}{|l||*{3}{c|}}\hline
\backslashbox{\textbf{Procura}}{\textbf{Oferta}}
& \textbf{Um so vendedor} & \begin{tabular}[c]{@{}c@{}}\textbf{Pequeno numero}\\ \textbf{de vendedores}\end{tabular} & \begin{tabular}[c]{@{}c@{}}\textbf{Grande numero}\\ \textbf{de vendedores}\end{tabular} \\ \hline
Um só comprador\\ &Monopolio bilateral & Quase monopsonio & Monopsonio\\\hline
Pequeno numero de\\compradores &Quase monopolio &Oligopolio bilateral &Oligopsonio\\\hline
Grande numero de\\compradores &Monopolio &Oligopolio &Concorrencia perfeita\\ \hline
\end{tabular}
\end{center}
\end{table}
\end{document}

A: I propose this solution with diagbox and makecell.  To make the table fit text width, I suggest loading the geometry package. I also loaded  caption to  have a more decent spacing between caption and table. Note that you shouldn't use the center environment within table, as it adds unwanted vertical spacing – use \centering instead.
\documentclass{article}
\usepackage{geometry}
\usepackage{diagbox}
\usepackage{caption, makecell}

\begin{document}

\begin{table}[!h]
\renewcommand{\theadfont}{\normalsize\bfseries}
\centering
\caption{Classificação de Marchal: as estruturas de mercado diferenciadas também por fatores associados ao comportamento dos agentes a natureza dos produtos.}
\label{table:rossetti-1}
\begin{tabular}{|l||*{3}{c|}}\hline
\diagbox[height=30pt, width=90pt]{\textbf{Procura}}{\textbf{Oferta}}
& \thead{Um so vendedor} & \thead{Pequeno numero \\ de vendedores} & \thead{Grande numero\\ de vendedores} \\ \hline
\Gape[6pt]{Um só comprador} & Monopolio bilateral & Quase monopsonio & Monopsonio\\\hline
\makecell[l]{Pequeno numero \\ de compradores} & Quase monopolio &Oligopolio bilateral &Oligopsonio\\\hline
\makecell[l]{Grande numero \\ de compradores} &Monopolio &Oligopolio &Concorrencia perfeita\\ \hline
\end{tabular}
\end{table}

\end{document}

A: With {NiceTabular} of nicematrix, which has a built-in command \diagbox.
\documentclass{article}
\usepackage{geometry}
\usepackage{caption}
\usepackage{nicematrix}

\begin{document}

\begin{table}[!h]
\centering
\caption{Classificação de Marchal: as estruturas de mercado diferenciadas também por fatores associados ao comportamento dos agentes a natureza dos produtos.}
\label{table:rossetti-1}
\begin{NiceTabular}{|l||*{3}{c|}}\hline
\RowStyle{\bfseries}
\diagbox{\bfseries Procura}{\bfseries Oferta\;}
& Um so vendedor & \Block{}{Pequeno numero \\ de vendedores} & \Block{}{Grande numero\\ de vendedores} \\ \hline
\RowStyle[cell-space-limits=6pt]{}
Um só comprador & Monopolio bilateral & Quase monopsonio & Monopsonio\\\hline
\Block{}{Pequeno numero \\ de compradores} & Quase monopolio &Oligopolio bilateral &Oligopsonio\\\hline
\Block{}{Grande numero \\ de compradores} &Monopolio &Oligopolio &Concorrencia perfeita\\ \hline
\end{NiceTabular}
\end{table}

\end{document}


text:
Q: Why doesn't the __unicode__ return value show up in Django admin? I made something like this :
models.py
from django.db import models
from django.utils.encoding import smart_text
class SignUp(models.Model):
    first_name=models.CharField(max_length=100,null=True,blank=True)
    second_name=models.CharField(max_length=100,null=True,blank=True)
    email=models.EmailField(max_length=100)
    casPridania=models.DateTimeField(auto_now_add=True,auto_now=False)
    casAktualizacie=models.DateTimeField(auto_now_add=False,auto_now=True)

    def __unicode__(self):
        return smart_text(self.first_name)

admin.py
from django.contrib import admin
from .models import SignUp
class prihlasenieAdmin (admin.ModelAdmin):
    class Meta:
        model=SignUp

admin.site.register(SignUp,prihlasenieAdmin)

It looks fine, but when I log on my page with /admin and make a new sign up, it doesn't return first name, it returns "Sign up object". I tried to return email and now first_name, but nothing worked.
//Solved by using __str__ instead of __unicode__ in module.py

A: def __str__(self):
    return self.first_name


text:
Q: Linux pipes and select There is a shell script
#!/bin/bash

while :
do
    echo "++stdout..";
    echo "++stderr.." >> /dev/stderr;
    sleep 1
done

and c prog
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <signal.h>
#include <time.h>
#include <fcntl.h>
#include <string.h>

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

  int pipefd[2];
  int pipe_stderr[2];

  char parametr[32];

   if(argc != 2)
   {
        fprintf(stderr,"Niepoprawna liczba argumetnow procesu P \n");
        exit(EXIT_FAILURE);
   }

  /* pipe
      pipe0 - write
      pipe1 - read
  */
  if(pipe(pipefd) == -1)
   {
    perror("pipe");
    exit(EXIT_FAILURE);
   }

  if(pipe(pipe_stderr) == -1)
   {
    perror("pipe");
    exit(EXIT_FAILURE);
   }

  sprintf(parametr,"%d",pipefd[0]); //convert - we want to use exec

   pid = fork() ;
   if(pid < 0)
   {
    perror("fork!");
   }
   else if(pid == 0)
   {
        puts("child");
        dup2(pipefd[1],STDOUT_FILENO); // write
        dup2(pipe_stderr[1],STDERR_FILENO); // write

        close(pipefd[0]);
        close(pipe_stderr[0]);
        execv(argv[1],&argv[1]);
   }
   else{
        puts("parent");
        fd_set set;
        struct timeval timeout;
        int sel;
        char buf;

        close(pipefd[1]) ;
        close(pipe_stderr[1]) ;

        fcntl(pipefd[0],F_SETFL,O_NONBLOCK);
        fcntl(pipe_stderr[0],F_SETFL,O_NONBLOCK);

        FD_ZERO(&set);
        FD_SET(pipefd[0], &set); // READ
        FD_SET(pipe_stderr[0], &set); // READ

        timeout.tv_sec = 17;
        timeout.tv_usec = 0;

        while(1){
            puts("Select");
            sel = select(FD_SETSIZE,&set,NULL,NULL,&timeout);
            if(sel < 0 )
            {
                perror("Select");
            }
            else if(sel == 0)
            {
                printf("No communicate \n");
            }
            else{
                if(FD_ISSET(pipefd[0], &set)){
                    puts("PARENT_READ_STDOUT:");
                    while(1){
                        ssize_t ret = read(pipefd[0], &buf,1);
                        if(ret > 0){
                            write(STDOUT_FILENO, &buf,1);
                        }else{
                            break;
                        }
                    }
                }

                if(FD_ISSET(pipe_stderr[0], &set)){
                    puts("PARENT_READ_STDERR:");
                    while(1){
                        ssize_t ret = read(pipe_stderr[0], &buf,1);
                        if(ret > 0){
                            write(STDERR_FILENO, &buf,1);
                        }else{
                            break;
                        }
                    }
                }
            }
        }
   }
}

the output of
./main ./test.sh

is
parent
Select
child
PARENT_READ_STDOUT:
++stdout..
Select
PARENT_READ_STDOUT:
++stdout..
Select
PARENT_READ_STDOUT:
++stdout..
Select
PARENT_READ_STDOUT:
++stdout..
Select
PARENT_READ_STDOUT:
++stdout..
Select
PARENT_READ_STDOUT:
++stdout..
Select

where did the stderr output go??

A:     timeout.tv_sec = 17;
    timeout.tv_usec = 0;

    while(1){

    FD_ZERO(&set);
    FD_SET(pipefd[0], &set); // READ
    FD_SET(pipe_stderr[0], &set); // READ


text:
Q: Use package.json script without yarn/npm command Is there a possibility to run scripts commands inside package.json file without having to type yarn or npm before? I mean I have something like:
 "scripts": {
    "get": "node index.js"
  }

so to run it I have to type yarn get [arguments]. Is there any way to type only get [arguments] and it will also work?

A: I believe these scripts are run off on npm / yarn shell-scripts, so you do need to call npm / yarn for it to know what to run.
Alternatively, you could extract these scripts out to a bash (.sh) file and execute the bash file. In your package.json, you can also link the script to just run the bash file.

A: if you are not on windows this wont work but i am so im not sure how to do on any other os
In windows you can just create a .cmd file called eg. "get.cmd" then in command prompt run
what it does is just run the file named "get" and it asks for the args then runs the file; it does not need the extension so its just "get"
"get" and it will run the content inside the file
package.json:
"scripts": {
   "get": "node index.js"
}

get.cmd: (this is windows batch)
# just to make it cleaner (you dont get it showing what was ran it just runs)
@echo off
# this is to get the args
set /p args="args: "
# then it runs the yarn with %args% because args was defined with the set /p
yarn get %args%

index.js: (this is just for example put your real file)
console.log("you ran index!)

In command prompt:
C:\users\*user*\*folder*> get
args: 123
you ran index!


text:
Q: How to split list of points from picture to contiguous blocks I have three hundreds of photos. All of them were made around one object, but it was done manually, so it needs to be adjusted. That one object should be in the same position, as i'm going to make timelapse video from these photos. And this one object should be exactly in the same place. Shifts between photos can be up to 300-500px, so it's too big. I found one red sign on that main object, and it exists on each photo, so it's my start point.
So, i have implemented small .Net application that:

*

*Load each image.

*Scans for pixels in the main area of photo

*For each pixel it tries to compare current pixel with needed. Needed
pixel saved as HSL numbers. All photos are a bit different in
brightness, so it tries to search not specific color, but range of
colors similar to needed one. So, i have acceptable deltas for each H,S and L values

*It searches minimal X and Y coordinates for these pixels that satisfy color range

*Then I have coordinates where that main object should be

*Then I make new delta between minimal X and Y values and my hard coded center coordinates

*Then I save photo as new one with these delta, so that red sign is on the same place on all photos.

Basically I have List<Point> for each image that satisfy color range.
But I have one problems - because of different brightness and big color range, on some photos it finds a couple of pixels that also satisfy needed color range. And if they above sign, then delta for saving is incorrect.
How can I ignore these false alarms pixels?
My current idea is group pixels by location with some delta. So group of pixels near by will be grouped as one block.
Steps for that:

*

*I have list of Point with needed colors. Some of them can be false alarm pixel

*then I group them by distance between them with 50px delta.

*If some pixels are near by, then I count them as one block

*Then i filter all blocks that has less then 40 pixels, that should be enough for my case. Currently there are just 5-20 false alarm pixels.

My current code to filter them:
Dictionary<Rectangle, List<Point>> blocks = new Dictionary<Rectangle, List<Point>>();
const int blockDelta = 50; // pixels delta
foreach (var point in points
{
    bool added = false;

    foreach (var rectangle in blocks.Keys)
    {
        if (point.X >= rectangle.Left && point.X <= rectangle.Right &&
            point.Y >= rectangle.Top && point.Y <= rectangle.Bottom)
        {
            blocks[rectangle].Add(point);
            added = true;
            break;
        }
    }

    if (added)
        continue;

    Rectangle newRect = new Rectangle(point.X - blockDelta,
            point.Y - blockDelta, blockDelta*2, blockDelta*2);

    blocks.Add(newRect, new List<Point>());
    blocks[newRect].Add(point);
}

But problem with that code is that if my sign has 130px width, then it will divide it to 3 blocks instead of one. And I can't increase delta, as then false alarm pixels will be also included into that block, and I want to avoid it.
Are there any better solutions for it? Or maybe you can give me some idea how to calculate such continuous blocks?
Thank you for any ideas.
UPDATE1:
Here is part of that image:

I'm searching for these red signs covered by orange lines. And I use top of these signs to center image. But because of chromatic aberration on some parts of stone outlines there are a couple of red pixels, that broke logic.

A: 1.the false alarm pixels is bright or dark pixels, vary a lot from the red pixels, so I suggest  using rgb instead.
2.after using threshold choosing the "wanted" pixels ,you can try dilatation to get the missed "wanted" pixels back , since there is only four big stars in each image,you can select the top four pixel group according to the number of pixels it contains
http://docs.opencv.org/doc/tutorials/imgproc/erosion_dilatation/erosion_dilatation.html


text:
Q: HttpListener transfer to location without redirect I'm using HttpListener behind a Nginx as proxy, and using Nginx to serve static files.
I want to redirect a request to a resource inside the code without disclosing the resulting location or perform a redirection, something similar to Server.Transfer in ASP.net.
Thank in advance.


text:
Q: How to use map inside subscribe rxjs6 I have a service which returns an Observable, after getting the response I map the response and assign result to the array.
  this.dataService.fetchData().subscribe(response =>{
    [...this.DataMappingField ]=  response.map(({ ID: id, Name: name }) => ({ id, name }));
  });

With spread operators inside subscribe I am getting the error below.
Error: Property 'map' does not exist on type 'Modelclass'.
Response from service
[
  {ID: 6197, Name: 'A', desc: null,catergory:'lap'},
  {ID: 6198, Name: 'B', desc: null,catergory:'lap'}
]

In service, fetchData method:
fetchData(): Observable<Modelclass> {
  return this.http
    .get<Modelclass>(REQUEST_URL)
    .pipe(
      tap(response => response)
    );
}

Model class:
export class Modelclass {
  ID: any;
  Name: string;
}

But the below code is working fine when call with method:
this.dataService.fetchData().subscribe(this.fetchResponse);

private fetchResponse(response): void => {
  [...this.DataMappingField ]= response.map(({ ID: id, Name: name }) => ({ id, name }));
}

A: I think the problem is incorrect response typing. The definition of fetchData method should be like this:
fetchData(): Observable<Modelclass[]> {
  return this.http
    .get<Modelclass[]>(REQUEST_URL)
    .pipe(
      tap(response => response)
    );
}

Note I am using Modelclass[] as a response type.


text:
Q: What a good text editor with RTL (right-to-left) support? gvim doesn't seem to support it out of the box on my Ubuntu lucid.

A: Since you mention Gvim specifically I assume that its the editor your prefer.  Gvim/vim does support right-to-left text.
Use the option :set rl or the long form :set rightleft to enable it.  You can add this to your .vimrc if you want to always use it.
vim will need to be compiled with the +rightleft option.  I'm not 100% sure if Ubuntu does this, but CentOS does.  To check I did vim --version | grep +rightleft since vim can display what options it was compiled with.

A: Since starting to study Arabic and also having to process it in scripts, etc., I keep trying out new text editors as I encounter them. However, and I'm clearly very opinionated here, Gedit beats them all. Hands-down. With most text editors something isn't just quite right, but with Gedit everything just works the way you'd expect it to. One small gripe is the new auto-disappearing scrollbar, which of course covers the first one or two Arabic letters in line of text starting on the right. On the command line, I use vim alternating between :set rl/:set norl as described above.

A: Yudit is an editor specifically designed to cope well with "exotic" language and language combinations. This includes advanced support for bidirectional text. On the minus side, it's otherwise rather primitive for an editor.
Emacs's development branch (what is currently known as Emacs 24.0.50.x and will eventually be Emacs 24.1) supports bidirectional text. On Ubuntu, try the emacs-snapshot Install emacs-snapshot http://bit.ly/software-small package (as this is a development snapshot, you may be better off recompiling a more recent version).

A: I found out that JetBrains Editors have good RTL support.
I personally use their IntelliJ IDEA
They can be run on various platforms.

A: RTL support in Linux is actually pretty good. As far as I can tell, anything that could be considered a "good text editor" also has RTL support.
I would pick your favorite editor based on other criteria, then if it's not obvious ask how to enable RTL support. If your primary system language is set to a RTL region most things seem to default to it pretty well.


text:
Q: Using blowfish encryption with Android? I'm trying to use a blowfish cipher inside an Android application.
It appears that the Android platform supports blowfish (it appears to be in the source code), but when I try to get a cipher using:
Cipher.getInstance("blowfish");

I get a "java.security.NoSuchAlgorithmException"

A: Based on a quick Google search, try a capital B in "Blowfish", and see if that helps.


text:
Q: What math/stats knowledge does learning Bayesian probability require? I study undergraduate "pure" math and philosophy. I know that a number of philosophers use Bayesian probability to augment their epistemic logic. My school teaches Bayesian probability as a brief part of a fourth year class. Enrolling in it requires completing a series of stats classes that are outside of my path. However, for a few reasons, I suspect that those prerequisites exist to prepare students to learn the other elements of the class that includes the lessons on BP, and that learning BP doesn't require a three year trek through non-Bayesian probability theory. That said, I really don't know. Perhaps I'm wrong.
What math/stats knowledge does learning Bayesian probability require?

A: You need working knowledge of calculus, like being able to take integrals, and not like knowing Weierstrass theorem. For instance, if you can take this integral without looking at any references with a pen and a paper, you're probably equipped to take the course:
$\int_{-\infty}^{\infty}\frac{1}{\sqrt{2\pi}}e^{-\frac{x^2}{2}}|x^3|dx$
Knowing linear algebra helps too, but you can pick it up on the way. I'm not talking about anything crazy, it's simple matrix manipulations, pretty much within what's described in Algebra.B section of Madelung's Die Mathematischen Hilfsmittel des Physikers book. It's available online here, and is an awesome little book on applied math. For instance, if you can solve this equation, you're good to go:
$\det\left|\begin{matrix}1-\lambda& 2\\2 &1-\lambda\end{matrix}\right|=0$
You don't need measure theory and real analysis, but it helps to know them. The key is not to enroll in courses taught at math dept for math majors. Take a course specifically designed for applied folks, maybe for psychologists or other math-challenged constituents. Courses taught for physicists could be a good compromise: they have enough math to actually gain useful skills, but they don't bother with proofs and other crazy stuff mathematicians are obsessed about.

A: I was in a similar boat, having been a Math/CS double major but needing to learn a lot of Bayesian probability for work. What I'd recommend:

*

*Practical ability to do and understand integrals

*An understanding of numerical methods for approximating integrals (sampling, Monte Carlo method)

*Knowing the R programming language is very useful - most texts I've come across do the examples in R.

*General understanding of model evaluation - you would certainly get this in stats, but you can get it in other fields (psychology, biology, machine learning) as well.

*There are lots of general modeling "tricks" that I didn't see studying pure math that would have been nice to know before jumping into Bayesian probability, such as regularization and parameter selection.
Since you are a math major, you probably will see real analysis anyway, but I did not really find it that helpful for this. I did not find my background in measure theory helpful either. It very well might be that the class offered at your school is built with the assumed stats background - in which case, I recommend getting a book about Bayesian statistics/probability (I found this one useful) and working through it yourself.


text:
Q: JS - how to get a string of outerHTML textContent? question in JavaScript -
I defined an element using tagName, and I want to get the string of it's full define (like "

let elem = elementsArr[i].outerHTML.textContent;

it returns me undefined.
I'd like some help :)
Just want to know why my code doesn't work

A:
Just want to know why my code doesn't work

Because .outerHTML haven't method .textContent, so it returns undefined.
If you want to get the content of the element you can use .innerHTML.
Or if you want only the text, you can use .textContent on the element.
See example :

d = document.getElementById("d");
console.log(d.outerHTML);
console.log(d.innerHTML);
console.log(d.textContent);

Content

Further Elaborated

A: .outerHTML returns a string, and String has no method textContent as it is all text content;
You can clear out the HTML with a RegEx or with a function - see below:
This returns all the text with none of the tags :)

function strip(html) {
  var doc = new DOMParser().parseFromString(html, 'text/html');
  return doc.body.textContent || "";
}

demo = document.getElementById("demo");

console.log(strip(demo.outerHTML));

console.log(demo.outerHTML.replace(/<(?:.|\n)*?>/gm, '')); // even simpler

Some

text here

reference: Strip HTML from Text JavaScript
EDIT: You can also just use element.textContent and it will return exactly what you want


text:
Q: Garbage collecting in a ThreadPool? I need to handle http requests and the best way I found was using a ThreadPool. Please dont recommend using a finished library, because when I try to do something similar, there will be the same problem(s)!
When try a DDOS-Tool on my own webserver the cpu usage gets high and the memory increases incredible fast!
When I stop the tool the memory usage still increases (see screenshot)!
I want the program to decrease its memory usage after the DDOS-Tool has been stopped.
But unfortunately it does not!
Here is my code: You can try it. It does not need any libraries!
using System;
using System.Collections.Generic;
using System.IO;
using System.Net.Sockets;
using System.Threading;

namespace Webserver
{
  class Program
  {
    static void Main(string[] args)
    {
      TcpListener tcpListener = new TcpListener(81);
      tcpListener.Start();
      while (true)
        ThreadPool.QueueUserWorkItem(DoWork, tcpListener.AcceptTcpClient());
    }

    static void DoWork(object arg)
    {
      try
      {
        using (TcpClient tcpClient = (TcpClient)arg)
        {
          tcpClient.ReceiveTimeout = 500;
          tcpClient.SendTimeout = 500;

          using (NetworkStream networkStream = tcpClient.GetStream())
          {
            networkStream.ReadTimeout = 500;
            networkStream.WriteTimeout = 500;

            List<string> headers = new List<string>();

            using (StreamReader streamReader = new StreamReader(networkStream))
            using (StreamWriter streamWriter = new StreamWriter(networkStream))
            {
              while (true)
              {
                string line = streamReader.ReadLine();

                if (line == "") break;
                else headers.Add(line);
              }

              Console.WriteLine(headers[0]);

              streamWriter.WriteLine("HTTP/1.0 200 OK");
              streamWriter.WriteLine("Server: Webserver");
              streamWriter.WriteLine("Content-Type: text/html; charset=UTF-8");
              streamWriter.WriteLine("");
              streamWriter.WriteLine("Hello World!");
            }
          }
        }
      }
      catch (Exception ex)
      {
        Console.ForegroundColor = ConsoleColor.Red;
        Console.WriteLine(ex.Message);
        Console.ResetColor();
      }
    }
  }
}

The red lines mark the timestamps when I started and stopped the ddos-Tool. As you can see, the memory still increases after the tool has been stopped.
I want my program to get down back to 17 MB memory usage as it was at the beginning.

A: This similar question has some good advice.
Your code is currently already pretty efficient as it is. The using statements automatically disposes the objects when finished so you don´t need to worry about them. As for using garbage collection anywhere is always a tricky business especially in a multy threading environment.
To use the garbage collection just type:
// for a full garbage collection:
GC.Collect();
// for a first generation garbage collection:
GC.Collect(0);

this forces the Garbage collector to 'Collect' the garbage. Garbage collection is thread safe and it blocks all other threads. Since other threads are blocked it might result in some latency. I'm not sure if it will improve your performance, but by all means try.
For more information on how it works you can read this article


text:
Q: Can't debug through onReceive() in boot completed receiver Thanks a ton to this site, I have made significant progress with my first Android project.
I'm trying to get the execution suspend in the onReceive() method of a boot completed receiver. Below are my manifest and receiver code.
Android 2.3.3
API - 10
IDE - Eclipse
Running on emulator
Manifest:
<?xml version="1.0" encoding="utf-8"?>
  <manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.android.demo.notepad3" >

<uses-sdk android:minSdkVersion="10" />

<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />

<application android:icon="@drawable/icon" >
    <activity
        android:label="@string/app_name"
        android:name=".ProjectTrackerHomeActivity" >
        <intent-filter >
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity android:name=".ProjectTrackerEditActivity" />

    <receiver android:name=".ProjectTrackerNotification" />

    <receiver
        android:name=".ProjectTrackerOnBootReceiver" >
        <intent-filter >
            <action android:name="android.intent.action.BOOT_COMPLETED" />
        </intent-filter>
    </receiver>
</application>

</manifest>

Receiver:
public class ProjectTrackerOnBootReceiver extends BroadcastReceiver {
private ProjectTrackerDBAdapter mDbHelper;

@Override
public void onReceive(Context context, Intent intent) {
    Debug.waitForDebugger();
    AlarmManager
              mgr=(AlarmManager)context.getSystemService(Context.ALARM_SERVICE);

              //I place the break point at line 2, the alarm manager line

             // Further code, irrelevant
    }

My observations -1. When I run this application in debug mode on eclipse, the break point is not even hit.2. When I run some other application in debug mode, this break point is hit momentarily! But before I can proceed with a step by step execution, the execution resumes. It doesn't stop there.
My reasoning for this behavior is that -1. When I run some other application, since this above app is already installed, it catches the boot complete broadcast and so the breakpoint is hit. (But why doesn't the execution halt at the breakpoint?)2. When I run only this app, it gets installed first and in the time it takes for installation, it misses the boot complete broadcast.
May I please get some assistance with the below queries -1. How can I make the execution halt at the breakpoint without it resuming further?2. Can I somehow run an already installed version of this app on the emulator in debug mode "without having it to get freshly installed" on the emulator every time I run it?
3. Is there anything else I'm doing wrong or missing something?
Kindly let me know since I really need to debug through onReceive() to catch further application logic bugs. Thanks a lot, folks.

A: Another method which I prefer as it means you do not need to keep restarting the device(boring, gradle takes long enough to load as it is), is to simply run the app in debug mode and then simulate an action which will call your Broadcast receiver using the following command in your terminal.
adb shell am broadcast -a android.intent.action.BOOT_COMPLETED -p com.example.package_name

The above creates a broadcast with action "BOOT_COMPLETE" and now you can debug without restarting.

A: Use the below line before the code where you want the debugger to stop:
android.os.Debug.waitForDebugger();

A: Not sure why this question is asked so many times and it was so hard to find the answer but this works like a champ for me.

*

*In your receiver class within the onReceive() override add the below call for waitForDebugger() as the first call.

*Deploy to the device by running the app.

*Once the updated apk is on the device, reboot the device.

*While device is rebooting return to your IDE (In this example Android Studio 1.4) and go to "Run" menu > "Attach debugger to Android Process".

*Check "Show all processes".

*Wait... Once the waitForDebugger() line is hit, your app/package will appear in this list. In my case, it took at least 2 minutes AFTER the device rebooted.

*Click "OK", wait a moment and your breakpoint will be hit.

You can now step through your code like normal. Have fun!
@Override
public void onReceive(Context context, Intent intent) {

    // Add this at beginning of method
    android.os.Debug.waitForDebugger();

    // Place breakpoint below
    String myVariable = "Some Value";

}

A: You need to shutdown the phone and start it up to ever see onReceive get called from bootcompleted. To debug this, just add a Log statement in onReceive instead of setting a breakpoint. Otherwise, you'll have to add some action to the receiver in the manifest and then manually sendBroadcast(new Intent("someName")) with the name you specified in the receiver element in the manifest.


text:
Q: show GKGameCenterViewController in SKScene I struggling with the following Problem:
I've made a game with SpriteKit. I implemented the GameCenter to my game. It works. Player logs in automatically and the highscore will be added to the default Leaderboard. But for example in the "EndScreen" I want to show the GameCenterLeaderboard.
Appledocumentation tells me that I should use the following code:
- (void) showGameCenter

{

GKGameCenterViewController *gameCenterController = [[GKGameCenterViewController alloc] init];

if (gameCenterController != nil)

{

gameCenterController.gameCenterDelegate = self;

[self presentViewController: gameCenterController animated: YES completion:nil];

}

}

But presentViewController does not work. Is there any way to switch from a SKScene to my standard ViewController. Or how can I show up the GameCenterleaderboard with a button touched?
To be honest I'm pretty new to programming so this issue here might not a big problem to solve for you guys.
Big big thanks for the help.

A: yes there is a way, you can call this code directly from -(void)showGameCenter:
  UIViewController *vc = self.view.window.rootViewController;
  [vc presentViewController: gameCenterController animated:YES completion:Nil];

A: You can use notification to tell ViewController to show a leaderboard.
ViewController.m:
@implementation GameSceneViewController

- (void)awakeFromNib {
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(showGameCenter)
                                                 name:@"ShowLeaderboard"
                                               object:nil];
}

- (void) dealloc
{
    // If you don't remove yourself as an observer, the Notification Center
    // will continue to try and send notification objects to the deallocated
    // object.
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

.....

SKScene.m:
- (void)showLeaderboard {
        [[NSNotificationCenter defaultCenter]
             postNotificationName:@"ShowLeaderboard"
                           object:nil
                         userInfo:nil];
}


text:
Q: which identifiers are available to lambda in constructor initializer list more to the point, what's wrong with this code:
#include <assert.h>
#include <functional>
using namespace std;

    template< class BaseObjectId >
    class Check
    {
    protected:
        Check( function<bool()> const f ) { assert( f() ); }
    };

    template< int tpMinValue, int tpMaxValue >
    class IntegerSubrange
        : private Check< IntegerSubrange< tpMinValue, tpMaxValue > >
    {
    private:
        int     value_;

    public:
        enum :int { minValue = tpMinValue, maxValue = tpMaxValue };

        static bool rangeContains( int const x )
        {
            return (minValue <= x && x <= maxValue);
        }

        operator int() const
        {
            return value_;
        }

        void operator/=( int const rhs )
        {
            value_ /= rhs;
            assert( rangeContains( value_ ) );
        }

        explicit IntegerSubrange( int const value )
            : Check< IntegerSubrange< tpMinValue, tpMaxValue > >(
                [=]() -> bool { return rangeContains( value ); }
                )
            , value_( value )
        {}
    };

int main() {}

Visual C++ reports a syntax error:

foo.cpp
foo.cpp(41) : error C2059: syntax error : ')'
        foo.cpp(44) : see reference to class template instantiation 'IntegerSubrange' being compiled
foo.cpp(42) : error C2059: syntax error : ','
foo.cpp(43) : error C2334: unexpected token(s) preceding '{'; skipping apparent function body

A: To summarize the comments: The questioner's code is valid. Apparently some compilers older than GCC 4.4 or Visual C++ 2011 will reject it, due to those compilers' incomplete support for C++11-style lambdas. But modern compilers (and certainly any compiler that claims to support the new C++11 standard) should handle it just fine.
To answer your question literally: In a ctor-initializer-list, the same identifiers are available (and refer to the same things) as they would refer to if you moved them inside the curly braces of the constructor function itself. In particular, this means that you can do
class C {
    const char *p_ = "foo";
    char c_;
    C(int): p_(__func__) { }      // referring to "__func__"
    C(double): c_(*this->p_) { }  // referring to "this"
};

Here's what the Standard has to say on the subject:

Names in the expression-list or braced-init-list of a mem-initializer
  are evaluated in the scope of the constructor for which the
  mem-initializer is specified. ... [Note: Because the mem-initializer
  are [sic] evaluated in the scope of the constructor, the this pointer can be
  used in the expression-list of a mem-initializer to refer to the
  object being initialized. —end note]    (N3337 §12.6.2 #12)