text:
Q: Airflow Helm Chart Worker Node Error - CrashLoopBackOff I am using official Helm chart for airflow. Every Pod works properly except Worker node.
Even in that worker node, 2 of the containers (git-sync and worker-log-groomer) works fine.
The error happened in the 3rd container (worker) with CrashLoopBackOff. Exit code status as 137 OOMkilled.
In my openshift, memory usage is showing to be at 70%.
Although this error comes because of memory leak. This doesn't happen to be the case for this one. Please help, I have been going on in this one for a week now.
Kubectl describe pod airflow-worker-0 ->
worker:
    Container ID:  <>
    Image:         <>
    Image ID:     <>
    Port:          <>
    Host Port:     <>
    Args:
      bash
      -c
      exec \
      airflow celery worker
    State:          Running
      Started:      <>
    Last State:     Terminated
      Reason:       OOMKilled
      Exit Code:    137
      Started:      <>
      Finished:     <>
    Ready:          True
    Restart Count:  3
    Limits:
      ephemeral-storage:  30G
      memory:             1Gi
    Requests:
      cpu:                50m
      ephemeral-storage:  100M
      memory:             409Mi
    Environment:
      DUMB_INIT_SETSID:                        0
      AIRFLOW__CORE__FERNET_KEY:               <>                     Optional: false
    Mounts:
      <>
  git-sync:
    Container ID:   <>
    Image:          <>
    Image ID:       <>
    Port:           <none>
    Host Port:      <none>
    State:          Running
      Started:      <>
    Ready:          True
    Restart Count:  0
    Limits:
      ephemeral-storage:  30G
      memory:             1Gi
    Requests:
      cpu:                50m
      ephemeral-storage:  100M
      memory:             409Mi
    Environment:
      GIT_SYNC_REV:                HEAD
    Mounts:
      <>
  worker-log-groomer:
    Container ID:  <>
    Image:         <>
    Image ID:      <>
    Port:          <none>
    Host Port:     <none>
    Args:
      bash
      /clean-logs
    State:          Running
      Started:      <>
    Ready:          True
    Restart Count:  0
    Limits:
      ephemeral-storage:  30G
      memory:             1Gi
    Requests:
      cpu:                50m
      ephemeral-storage:  100M
      memory:             409Mi
    Environment:
      AIRFLOW__LOG_RETENTION_DAYS:  5
    Mounts:
      <>

I am pretty much sure you know the answer. Read all your articles on airflow. Thank you :)
https://stackoverflow.com/users/1376561/marc-lamberti

A: The issues occurs due to placing a limit in "resources" under helm chart - values.yaml in any of the pods.
By default it is -
resources: {}

but this causes an issue as pods can access unlimited memory as required.
By changing it to -
resources:
   limits:
    cpu: 200m
    memory: 2Gi
   requests:
    cpu: 100m
    memory: 512Mi

It makes the pod clear on how much it can access and request.
This solved my issue.


text:
Q: Html optional box selected issue I've a html list of select item. There is a value name: other, which if selected, I want to show a text input.
The following is my code. If the user selects any option except other, the text input should hide. How do I show this text field when the user selects other from the select.

    Interest *

    <select name="interest" id="travel_arriveVia" onchange="showfield(this.options[this.selectedIndex].value)">
        <option value="art" <?php if ($g_interest=="art" ) echo 'selected = "selected"'; ?>>Art</option>
        <option value="litteratures" <?php if ($g_interest=="litteratures" ) echo 'selected = "selected"'; ?>>Litteratures</option>
        <option value="business" <?php if($g_interest=="business" ) echo 'selected = "selected"'; ?>>Business</option>
        <option value="internet" <?php if($g_interest=="internet" ) echo 'selected = "selected"'; ?>>Internet</option>
        <option value="other_interest" <?php if($g_interest=="internet" ) echo 'selected = "selected"'; ?>>Other</option>
    </select>

Thanks.

A: Instead of your div1 you can do the following :
<select name="interest" id="travel_arriveVia" onchange="showfield(this.options[this.selectedIndex].value)">
        <option value="art" <?php if ($g_interest=="art" ) echo 'selected = "selected"'; ?>>Art</option>
        <option value="litteratures" <?php if ($g_interest=="litteratures" ) echo 'selected = "selected"'; ?>>Litteratures</option>
        <option value="business" <?php if($g_interest=="business" ) echo 'selected = "selected"'; ?>>Business</option>
        <option value="internet" <?php if($g_interest=="internet" ) echo 'selected = "selected"'; ?>>Internet</option>
        <option value="other_interest" <?php if($g_interest=="internet" ) echo 'selected = "selected"'; ?>>Other</option>
</select>

<input type="text" name="other_interest" id="txtOther" class="trother" style="display: none;" />

A: Keep the text input there but just show and hide it when the select is changed.
<select name="interest" id="travel_arriveVia" onchange="showfield(this.options[this.selectedIndex].value)">
    <option value="art" <?php if ($g_interest=="art" ) echo 'selected = "selected"'; ?>>Art</option>
    <option value="litteratures" <?php if ($g_interest=="litteratures" ) echo 'selected = "selected"'; ?>>Litteratures</option>
    <option value="business" <?php if($g_interest=="business" ) echo 'selected = "selected"'; ?>>Business</option>
    <option value="internet" <?php if($g_interest=="internet" ) echo 'selected = "selected"'; ?>>Internet</option>
    <option value="other_interest" <?php if($g_interest=="other_interest" ) echo 'selected = "selected"'; ?>>Other</option>
</select>

<input type="text" id="other_interest" name="other_interest" class="trother" style="<?php if($g_interest != 'other_interest') echo 'display:none;'; ?>" />

redpajama_set_name: RedPajamaStackExchange


text:
Q: Removing "Chapter" from chapter headings, change font and spacing, and center I'm using the book style in LaTeX. I want my chapter headings to look like this:
      1
 Great Chapter

It should be in the sans-serif and bold font, centered, and I want to be able to customize the spacing before and after the heading, and also customize the spacing between the "1" and the "Great Chapter." How can I do this in LaTeX?

A: The titlesec package can facilitate all of this.

From the titlesec package
 \titlespacing{command}{left spacing}{before spacing}{after spacing}[right]

How to read {12pt plus 4pt minus 2pt}

*

*12pt is what we would like the spacing to be

*plus 4pt means that TeX can stretch it by at most 4pt

*minus 2pt means that TeX can shrink it by at most 2pt
This is one example of the concept of, 'glue', in TeX; it may seem strange to use the word 'glue' for a stretchable space, but to quote Knuth (The TeXbook)

But whenever the author has suggested changing TeX's terminology,
  numerous people have said that they like the word "glue" in spite of
  its inappropriateness; so the original name has stuck.

\documentclass{book}
\usepackage{lipsum}
\usepackage[explicit]{titlesec}

% custom chapter
\titleformat{\chapter}[display]
{\filcenter\LARGE\bfseries\sffamily}
{\thechapter\\[2cm]% spacing between number and Great chapter
#1}
{1pc}
{\Huge}
% From the titlesec package
% \titlespacing{command}{left spacing}{before spacing}{after spacing}[right]
% spacing: how to read {12pt plus 4pt minus 2pt}
%           12pt is what we would like the spacing to be
%           plus 4pt means that TeX can stretch it by at most 4pt
%           minus 2pt means that TeX can shrink it by at most 2pt
%       This is one example of the concept of, 'glue', in TeX
\titlespacing{\chapter}{0pt}{*4}{-0.1cm}
\begin{document}

\chapter{Great chapter}
\lipsum
\end{document}


text:
Q: Best practice for drawable(density) I wrote a small class, which can be used to create custom drawables. For the most part everything works as expected, but when it comes to display the drawables nearly "pixel-perfect", I really have no idea how get a proper solution. A proper solution would be to get an 100% centred character/text on the underlying shape. Any advice is welcome. Thanks in advance.
Here is the class:
public class DrawableSquareLetter extends Drawable {

    private final Paint paint;
    private Paint textPaint;
    private final Builder builder;

    public DrawableSquareLetter(Builder builder) {
        this.builder = builder;
        paint = new Paint();
        paint.setAntiAlias(true);
        paint.setStyle(Paint.Style.FILL);
        paint.setColor(builder.color);

        if (builder.applySurfaceShadow) {
            paint.setShadowLayer(
                    DeviceUtils.dp2px(4),
                    DeviceUtils.dp2px(2),
                    DeviceUtils.dp2px(2),
                    Color.parseColor(MaterialColor.GREY_900));
        }

        textPaint = new Paint();
        textPaint.setColor(builder.textColor);
        textPaint.setAntiAlias(true);
        textPaint.setFakeBoldText(builder.isBold);
        textPaint.setStyle(Paint.Style.FILL);
        textPaint.setTypeface(builder.typeface);
        textPaint.setTextAlign(Paint.Align.CENTER);

        if (builder.applyTextShadow) {
            textPaint.setShadowLayer(
                    DeviceUtils.dp2px(2),
                    DeviceUtils.dp2px(1),
                    DeviceUtils.dp2px(1),
                    Color.parseColor(MaterialColor.GREY_800));
        }

    }

    @Override
    public void draw(Canvas canvas) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            canvas.drawRoundRect(0, 0, builder.size, builder.size, builder.rounded, builder.rounded, paint);
        } else canvas.drawRect(0, 0, builder.size, builder.size, paint);

        if (builder.textSize == -1) {
            textPaint.setTextSize(builder.size * .80f);
        } else textPaint.setTextSize(builder.textSize);

        float width = builder.size;
        float height = builder.size;

        String text = builder.isUpperCase ? builder.text.toUpperCase() : builder.text;
        canvas.drawText(text, width / 2f, height / 2f - (((textPaint.descent() + textPaint.ascent())) / 2f), textPaint);
    }

    @Override
    public void setAlpha(int alpha) {
        paint.setAlpha(alpha);
    }

    @Override
    public void setColorFilter(ColorFilter colorFilter) {
        paint.setColorFilter(colorFilter);
    }

    @Override
    public int getOpacity() {
        return PixelFormat.TRANSLUCENT;
    }

    public static class Builder {

        private final float size;
        private final int color;
        private String tag = "";
        private float rounded;
        private final String text;
        private int textColor = Color.BLACK;
        private float textSize = -1;
        private Typeface typeface = Typeface.DEFAULT;

        private boolean isUpperCase = true;
        private boolean isBold = true;
        private boolean applyTextShadow = true;
        private boolean applySurfaceShadow = true;

        public Builder(int sizeDp, int color, String text) {
            this.text = text;
            this.size = DeviceUtils.dp2px(sizeDp);
            this.color = color;
        }

        public Builder(int sizeDp, String color, String text) {
            this.text = text;
            this.size = DeviceUtils.dp2px(sizeDp);
            this.color = Color.parseColor(color);
        }

        public Builder textSize(float textSize) {
            this.textSize = DeviceUtils.sp2px(textSize);
            return this;
        }

        public Builder rounded(int radiusDp) {
            this.rounded = DeviceUtils.dp2px(radiusDp);
            return this;
        }

        public Builder textColor(int textColor) {
            this.textColor = textColor;
            return this;
        }

        public Builder textColor(String textColor) {
            this.textColor = Color.parseColor(textColor);
            return this;
        }

        public Builder typeface(Typeface typeface) {
            this.typeface = typeface;
            return this;
        }

        public Builder disableUpperCase() {
            this.isUpperCase = false;
            return this;
        }

        public Builder disableBold() {
            this.isBold = false;
            return this;
        }

        public Builder disableShadowOnSurface() {
            this.applySurfaceShadow = false;
            return this;
        }

        public Builder disableShadowOnText() {
            this.applyTextShadow = false;
            return this;
        }

        public Builder setTag(String tag) {
            this.tag = tag;
            return this;
        }

        public DrawableSquareLetter build() {
            return new DrawableSquareLetter(this);
        }

        public void show(ImageView imageView) {
            imageView.setImageDrawable(this.build());
        }
    }

    public String getTag() { return builder.tag; }

}

A: If you want to center the text in the underlying shape, you need to draw the text in the right place and for that you need to use Paint.getTextBounds (String text, int start, int end, Rect bounds)

public void getTextBounds (String text, int start, int end, Rect
  bounds)
Return in bounds (allocated by the caller) the smallest rectangle that
  encloses all of the characters, with an implied origin at (0,0).

Once you execute this method, you will have information in the bounds. All you need to do is write a logic in the draw method of your Drawable, where you calculate the x/y coordinates to perform drawText() (based on this bounds rect).


text:
Q: Importing Libraries to an Android project I have imported a project from a book on Android development and I am currently getting warnings icons appearing next to a number of imports at the start of my project. When I hover over the warning icon the message that appears is as follows...
"The import java.io.IOException is never used"
I received these warning before on another project and when I imported a the necessary library the warning icons disappeared. My problem is that I do not know which library to import to resolve the warning symbol next to the following statements in my .java file...
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.text.ParseException;
import java.util.GregorianCalendar;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

A: I assume you're using Eclipse. Go to Source -> Organize Imports. The unnecessary imports should automatically be removed and only the ones really needed should remain.

A: Remove
import java.io.IOException;

A: this is not a problem and you don''t need to import any library to fix this.
All you need to do is "organize imports"
Option 1: right click in the editor ->Source->Organize Imports
Option 2: press [Ctrl]+[Shift]+o

A: "The import java.io.IOException is never used"
This warning means that you have imported a class java.io.IOException that you are not using in your code. This is not a compiling error so you don't have to fix it in order to run correctly your project.
Anyway if you wanna make the warning vanish there are many ways.The fastest one is to just eliminate this line. If you are using Eclipse and you have many warnings like this then the fastest fix is to put the mouse cursor over the yellow underlined text and wait the open of the quick-fix panel of Eclipse. In this panel you can chose both "remove unused import" or "Organize import". Both this system will remove all your unused import. There is also a third option: "@Suppress warnings". In this case you shouldn't use this option because it will only hide the warning not solving the problem.
Eclipse quick-fix is a powerful feature, using it will fast your code writing a lot so you should start practice it ^^
This kind of error are quiet often in project because many programmers doesn't care a lot for the "unused import warnings" and through the code change they forget to remove useless import


text:
Q: Updating records with SQL statement that are in 2 diff. tables not working This is my SQL statement:
UPDATE sysdba.CONTACT, sysdba.ADDRESS
SET sysdba.ADDRESS.Address1 = '123 Tech Parway'
WHERE sysdba.CONTACT.AddressID = sysdba.ADDRESS.AddressID
AND sysdba.CONTACT.contactID = 'CRBD'

What is wrong here?

A: TSQL solution
UPDATE sysdba.ADDRESS
SET Address1 = '123 Tech Parway'
FROM sysdba.ADDRESS
INNER JOIN sysdba.CONTACT
    ON sysdba.CONTACT.AddressID = sysdba.ADDRESS.AddressID
WHERE sysdba.CONTACT.contactID = 'CRBD'

A: I can't see any problem with this syntax according to MySQL UPDATE command reference. Maybe you're getting errors from MSSQLServer? Could you supply the errors for further investigation?


text:
Q: VFIO: PCI-stub GPU passthrough only audio device I'm in desperate need of help as I have tried everything I can imagine.
I'm trying to setup GPU passthrough. It works perfect on Nouveau drivers and both my GPU and Audio gets stubbed.
However I'm forced to use NVIDIA drivers due to having a GTX1050 card as 'main' card (using a gTX980 as passthrough).
On Nouveau drivers only 1 screen works on a very small resolution and I'm unable to fix this.
But the main problem is, is that only 1 device, the audio gets stubbed:
# dmesg | grep stub
[    2.015410] pci-stub: add 10DE:13C0 sub=FFFFFFFF:FFFFFFFF
cls=00000000/00000000
[    2.015413] pci-stub: add 10DE:0FBB sub=FFFFFFFF:FFFFFFFF
cls=00000000/00000000
[    2.015420] pci-stub 0000:02:00.1: claimed by stub

So as far as I get it, NVIDIA claims the device before PCI-stub gets the chance.
I don't know how to fix it. Is anyone able to help me out?
Using Kubuntu 17.04 on a GTX1050, trying to passthrough a GTX980 with NVIDIA 381.22 drivers.
Let me know if any further information is required, thank you!


text:
Q: Remove key from known_hosts I built several virtual machines during the last few weeks. The problem is, the .ssh/known_hosts gives me the Man in the middle warning. This happens because another fingerprint is associated with the virtual machine IP.
In the .ssh/known_hosts file, however, I don't find the record related to the IP, only two bizarre, key-like strings and "ssh-rsa".
Does anyone have any ideas about how to remove the old key from known_hosts?

A: You need to run the following command to get rid of this problem. Open the terminal and type the following command:
For all examples below just replace the value after -R:
ssh-keygen -R server-name
ssh-keygen -R server.ip.addre.ss
ssh-keygen -R 202.54.1.5
ssh-keygen -R server1.example.com

A: All answers are good, but for real SSH pro we have missing information how to remove ssh signature with (non-standard) port number.

*

*Simple SSH host signature remove command:
  ssh-keygen -R example.com

*Complex ssh key remove, e.g. you connect to ssh on non standard port 222:
  ssh example.com -p 222

and you get warning, and to remove this, you need to use square brackets colon port number:
    ssh-keygen -R [example.com]:222

Note, that probably there will be IP record for the same host, so you will need to remove that one also.
Hope this helps for non-standard configuration users.

A: The simplest solution is:
rm -f .ssh/known_hosts

ssh will recreate the file again, but you lose key checking for other hosts!
Or, you can use:
ssh-keygen -R "hostname"

Or the ssh "man-in-the-middle" message should indicate which line of the known_hosts file has the offending fingerprint.  Edit the file, jump to that line and delete it.

A: There is an ssh-keygen switch (-R) for this.
man ssh-keygen reads:

-R hostname
Removes all keys belonging to hostname from a known_hosts file.  This
               option is useful to delete hashed hosts (see the -H option above).

A: The warning will tell you the exact line in the known hosts file.
Here's an example:
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@       WARNING: POSSIBLE DNS SPOOFING DETECTED!          @
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
The RSA host key for foo-bar.net has changed,
and the key for the corresponding IP address 127.0.0.1
is unchanged. This could either mean that
DNS SPOOFING is happening or the IP address for the host
and its host key have changed at the same time.
Offending key for IP in /home/user/.ssh/known_hosts:6
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@    WARNING: REMOTE HOST IDENTIFICATION HAS CHANGED!     @
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
IT IS POSSIBLE THAT SOMEONE IS DOING SOMETHING NASTY!

See the /home/user/.ssh/known_hosts:6 part? It specifies the file and line number.

A: Here is a method using Ex editor:
ex +6d -scwq ~/.ssh/known_hosts

where 6th is your line number mentioned in the warning message. Such as this one:

Offending key for IP in /home/user/.ssh/known_hosts:6 <== LINE NUMBER

In general, it's advised to use ex to edit the files non-interactively, instead of sed, which is more a Stream EDitor and its -i parameter which is a non-standard FreeBSD extension.

A: sed -i '6d' ~/.ssh/known_hosts

Will modify the file ~/.ssh/known_hosts:6 , removing the 6th line.
In my opinion, using ssh-keygen -R is a better solution for an openssh power user, while your regular Linux admin would do better to keep his/her sed skills fresh by using the above method.

A: You can also instruct ssh to not check the known_hosts file using the UserKnownHostsFile and StrictHostKeyChecking flags.
For instance:
ssh -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no user@example.com

For ease of use you can alias this:
alias boldssh='ssh -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no'

Now you can just boldssh whenever you are sure you trust the server's certificate.

A: The entry for the host name or ip should be in the first column.  The warning should also list a line number where the offending key lies.

A: It is a text file.  You can easily edit with vi(m) and simply delete the line in question (dd), and save the file (wq). But if there is a specific command to remove a host, that's probably the safest method.

A: You can also remove a single line from known hosts with e.g. rmknownhost 111 (111 is the line to remove):
#! /usr/bin/env ruby
line = ARGV[0] || raise("gimme line to remove")
hosts = File.expand_path("~/.ssh/known_hosts")
content = File.readlines(hosts)
removed = content.delete_at line.to_i - 1
puts "Removed:\n#{removed}"
File.open(hosts, 'w'){|f| f.write content * ""}

Save this as rmknownhost in a folder from your PATH.


text:
Q: Reverse color order of colorbar (not colormap) (Matplotlib) I have a pandas dataframe of 350 rows × 16 columns of just 0 and 1.
I create a correlation matrix
dummy.corr(method ='kendall')

I'm plotting a correlogram:
f = plt.figure(figsize=(19, 15))
plt.matshow(dummy.corr(), fignum=f.number)
plt.xticks(range(dummy.select_dtypes(['number']).shape[1]), dummy.select_dtypes(['number']).columns, fontsize=14, rotation=45)
plt.yticks(range(dummy.select_dtypes(['number']).shape[1]), dummy.select_dtypes(['number']).columns, fontsize=14)
cb = plt.colorbar()

cb.ax.tick_params(labelsize=14)

plt.grid(b=None)

I'd like to reverse the order of the colors. Most answers I've found out deal with colormap but I'm just using colorbar.
How can i do it?

A: The default colormap used when you call matshow is viridis. If you use the reverse viridis colormap (viridis_r) in your matshow, you will automatically get the reverse colorbar. See below:
import matplotlib.pyplot as plt
import numpy as np

fig=plt.figure(figsize=(10,5))
c=np.random.choice(10,size=(10,10))

#Not reversed
ax1=plt.subplot(121)
ax1.set_title('Not reversed')
dat1=ax1.matshow(c)
cb1=plt.colorbar(dat1)

#reversed
ax2=plt.subplot(122)
ax2.set_title('Reversed')
dat2=ax2.matshow(c,cmap='viridis_r')
cb2=plt.colorbar(dat2)

plt.show()

See result below:


text:
Q: How can I calculate the base current of a transistor to get a specific emitter-collector voltage? For this circuit I am asked to calculate how much base current I need to supply to the transistor to get a Vce = 220.745 mV. The thing that has me stuck in this is that the problem does not provide me with a (betha) value.
Is there a way to calculate the base current without (betha)?
If not I will use (betha) as 100, since the problem tells me to use a Vce I calculated in a previous problem using (betha forward) as 100 and (betha reverse) as 0.01. As you can see I already calculated the collector current (Ic) using KVL. Since the collector-emitter saturation voltage is approximately 0.2 V, I assume that my transistor is in saturation.
When the transistor is in saturation, does Ic = (betha)(Ib) still apply?
I would really thank your reply :)

A: There exists a method for determining the saturation voltage \$v_{CESAT}\$ for a given current \$i_B\$.  With a few assumptions for the forward and reverse current gain \$\beta_F\$ and \$\beta_R\$ , we can determine the current \$i_B\$ from the saturation voltage \$v_{CE}\$.
I've referenced chapter 5 page 233 in Microelectronic Circuit Design by Jaeger and Blalock ISBN 978-0-07-319163-8
Assume that both junctions are forward biased. (This is required to approximate \$i_B\$ and \$i_C\$ in order to arrive at this equation).
\$v_{CESAT} = V_Tln(
\frac{1}{\alpha_R}
\frac{1+\frac{i_C}{(\beta_R+1)i_B}}
     {1-\frac{i_C}{\beta_Fi_B}})     \$ for \$i_B > \frac{i_C}{\beta_F}\$
This equation is only valid in the condition condition that \$i_B > \frac{i_C}{\beta_F}\$

This equation is important and highly useful in the design of saturated digital switching circuits.  For a given value of collector current, [this] can be used to determine the base current required to achieve a desired value of \$v_{CESAT}\$.

With \$V_{CE} < 0.7V\$, it can be assumed operation is in the forward saturation region. For your situation with \$V_{CE} = 220.745mV\$, we can simplify to
\$6835 = \frac{1}{\alpha_R}
\frac{1+\frac{i_C}{(\beta_R+1)i_B}}
     {1-\frac{i_C}{\beta_Fi_B}}\$
But, we still need to know \$\beta_R, \beta_F,\$ and \$\alpha_R = \frac{1}{\beta_R+1}\$
Choosing arbitrarily, and within reason, \$\beta_F = 50\$ and \$\beta_R = 1\$ we can solve for
 \$i_B = 0.39414mA\$ with \$i_B > \frac{i_C}{\beta_F} = 0.39116mA\$
And with a similarly reasonable \$\beta_F = 100\$ we find
\$i_B = 0.19850mA\$ with \$i_B > \frac{i_C}{\beta_F} = 0.19558mA\$
That is great and all, but how do we know these results make sense? If you are computing \$V_{CESAT}\$, you expect a small value close to zero, even \$0.06V\$ is sensible. Plugging the currents back into the original equation in both cases it yeilds \$0.220745V\$
Some methods to check the work cannot be used without a value for \$I_S\$.  Also note that the above equation is independent of \$I_S\$.
Final note, the above work was done assuming npn transistor, but pnp can be computed as well.


text:
Q: How to do mapping with the entityclass from Dto class and also using repository to do this,but I am not getting it This is my dto class and I try to map the field of entity becuse I want to use that in the service layer.

Blockquote

package com.prolifics.dto;

import java.util.Map;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonInclude.Include;

@JsonIgnoreProperties(ignoreUnknown = true)
@JsonInclude(Include.NON_NULL)
public class FacilityDTO {
    private Integer id;

    private String city;

    private String name;

    private String pin;

    private String state;

    private String status;
    private float lattitude;

    private float longitude;

    private Map<String,Integer> vaccineStock;

    public Map<String, Integer> getVaccineStock() {
        return vaccineStock;
    }

    public void setVaccineStock(Map<String, Integer> vaccineStock) {
        this.vaccineStock = vaccineStock;
    }

    public float getLattitude() {
        return lattitude;
    }

    public void setLattitude(float lattitude) {
        this.lattitude = lattitude;
    }

    public float getLongitude() {
        return longitude;
    }

    public void setLongitude(float longitude) {
        this.longitude = longitude;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getCity() {
        return city;
    }

    public void setCity(String city) {
        this.city = city;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getPin() {
        return pin;
    }

    public void setPin(String pin) {
        this.pin = pin;
    }

    public String getState() {
        return state;
    }

    public void setState(String state) {
        this.state = state;
    }

    public String getStatus() {
        return status;
    }

    public void setStatus(String status) {
        this.status = status;
    }

}

In my facilityVaccineEntity there is a stock variable of int type  and I want to map that field in my dto class as it does not contain stock field so that I can access it from service class. how to do this?
@Repository
public interface FacilityVaccineRepository extends CrudRepository<FacilityVaccine,Integer>{

    public FacilityVaccine stock(int stock);

}


text:
Q: If $x^y + y^x = 84$ and $x>3$, find the value of $x$ and $y$. How do we go about this questions?
I see that taking log on both sides is not an option since the LHS consists of a sum and not a product.
I tried differentiating it but without any boundary conditions I fail to see any possible solutions.
Can someone guide me on how to tackle this question?

A: Hint:  There aren't many choices for $y$.  It can only be $1,2,$ or $3,$ because if it is $4$ or greater $x^y \gt 84$  So try each of them in turn and see what you find.

A: Note if $y=1$ then $f(x,1) = x+1$ so let $x = 83$.

A: (1,83) and (83,1) seem to be the only answers.
In [1]: for x in range(1,84):
   ...:     for y in range(1,84):
   ...:         if x**y + y**x == 84:
   ...:             print (x,y)
   ...:
(1, 83)
(83, 1)

(Don't know whether python scripts are allowed to prove things on MSE, though)


text:
Q: Minecraft validate on mojang i have a problem with a minecraft premium validate account on mojang,
skin not load in picturebox, is the most important part of the program, please help !!!!!
wikipedia: http://wiki.vg/Authentication
my code:
If CheckBox1.Checked = True Then
            Dim site As String = "https://authserver.mojang.com/validate"
            Dim username As String = Form2.TextBox1.Text
            Dim password As String = Form2.TextBox2.Text
            Dim usernamenick2 As String
            Dim result As String
            Dim appData As String = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData)

            If My.Computer.FileSystem.FileExists(appData & "\.xerosfiles\launcher files\lastlogin.json") = True Then

                Dim result2 As String = My.Computer.FileSystem.ReadAllText(appData & "\.xerosfiles\launcher files\lastlogin.json")

                Dim fileReader As String

                fileReader = My.Computer.FileSystem.ReadAllText(appData & "\.xerosfiles\launcher files\lastlogin.json")
                Dim json2 As JObject = JObject.Parse(fileReader)
                UpdateTextBox(fileReader)
                Dim items2 As String() = fileReader.Split(New Char() {":"c})

                Dim at As String = json2.SelectToken("accessToken")
                Dim ct As String = json2.SelectToken("clientToken")

                Dim message As String = "{""accessToken"": """ & at & """clientToken"": """ & ct & """}"

                Dim request As WebRequest
                request = WebRequest.Create(site)
                Dim response As WebResponse
                Dim postData As String = message
                Dim data As Byte() = Encoding.UTF8.GetBytes(postData)

                request.Method = "POST"
                request.ContentLength = data.Length
                Dim stream As Stream = request.GetRequestStream()
                Try
                    stream.Write(data, 0, data.Length)
                    stream.Close()
                Catch
                End Try

                Try
                    response = request.GetResponse()
                    Dim sr As New StreamReader(response.GetResponseStream())
                    result = (sr.ReadToEnd)

                    If result = "" Then
                        Form2.hiddencb.Checked = True
                        Dim json As JObject = JObject.Parse(result2)

                        usernamenick2 = json.SelectToken("selectedProfile").SelectToken("name")
                        PictureBox2.Load("https://minotar.net/body/" & usernamenick2 & "/150.png")
                    Else

                    End If
                    Form2.hiddencb.Checked = True
                Catch ex As Exception
                    Form2.hiddencb.Checked = False

                    If My.Settings.cb1 = "true" Then
                        MsgBox("Wylogowano z konta, proszę się zalogować!")
                    End If
                End Try

            End If
        End If


text:
Q: Feature Test in Laravel 8 uses withHeader to set Host invalid? Since my project has deployed multiple domain names, the API interface that needs to be tested is using the api.example.test domain name as the entrance.
Using $this->get('/v1/ping') in Feature Test will request to www.example.test, I hope to set up $this->withHeader('Host', config('domain.api_domain')) uniformly in setUp in ApiFeatureBaseTestCase to automatically request API related tests to api.example.test Go in.
However, in practice, I found that this is invalid. By tracing the code, I found two codes that may cause the invalid Host setting:
First place (Laravel):
Code in Laravel Framework src/Illuminate/Foundation/Testing/Concerns/MakesHttpRequests.php:503, pass the parameter $uri ='/v1/ping' into $this->prepareUrlForRequest($uri) and get a complete Url with the default Host, the return value is http://www.example.test/v1/ping.
Second place  (Symfony):
In the code of Symfony HttpFoundation Component Request.php:355, the parsing in $uri will be used first The coming out host is overwritten in the Header as the default Host.
The above two codes eventually caused the Host I set by withHeader to fail. Obviously, in this code logic, Symfony HttpFoundation Component's choice of Host in conflict cannot be considered wrong, but I submitted this question issue was closed when it was given to Laravel Framework.

I don't know if this issue is a bug or feature?

Finally, I am sorry that my question has interrupted everyone's time, but if there is a conclusion on this question, please tell me what should be more appropriate?
My current approach is $this->get($this->api_base_url . '/v1/ping'), but I don't think this is elegant
3Q!!1
Code example
// File: config/domain.php
return [
    'api_domain' => 'api.example.test',
    'web_domain' => 'www.example.test',
];

// File: routes/demo.php
Route::domain(config('domain.api_domain'))
     ->middleware(['auth:api', 'api.sign.check'])
     ->namespace($this->namespace)
     ->group(function () {
         Route::get('/v1/ping', function () {
             return 'This Api v1';
         });
     });

Route::domain(config('domain.web_domain'))
     ->middleware('web')
     ->namespace($this->namespace)
     ->group(base_path('routes/web.php'));

// File: tests/ApiFeatureBaseTestCase.php
namespace Tests;

class ApiFeatureBaseTestCase extends TestCase
{
    protected function setUp(): void
    {
        parent::setUp();

        $this->withHeader('Host', config('domain.api_domain'));
    }
}

// File: tests/Feature/ApiPingTest.php
namespace Tests\Feature;

use Tests\ApiFeatureBaseTestCase;

class ApiPingTest extends ApiFeatureBaseTestCase
{
    public function testPing()
    {
       $this->get('/v1/ping');
    }
}

A: Can you create a wrapper method on your ApiFeatureBaseTestCase class?
public function get($uri, array $headers = [])
{
    return parent::get(config('domain.api_domain') . $uri, $headers);
}

Then in your ApiPingTest class:
public function testPing()
{
    $this->get('/v1/ping');
}


text:
Q: WP_Query on custom field and order results I have the following WP_Query:
$custom_query_args = array(
    'post_type'         => 'mcg_event',
    'posts_per_page'    => -1,
    'meta_query'        => array(
        'relation'  => 'AND',
        array(
            'key'   => 'event_status',
            'value' => 'archived',
        ),
        array(
            'key'       => 'event_start_date',
            'orderby'   => 'meta_value_num',
            'order'     => 'ASC',
        )
    ),
);

I'm looking to do 2 things:

*

*only fetch events that have an event_status of archived

*order the results by event_start_date
I can do either of these queries separately with no problem but when I put them together as above the order makes no difference.
What am I missing?

A: For the ordering you should use the orderby argument of the query. So it would go something like this:
$custom_query_args = array(
    'post_type'     => 'mcg_event',
    'posts_per_page'=> -1,
    'meta_key'      => 'event_start_date',
    'orderby'       => 'meta_value_num',
    'order'         => 'ASC',
    'meta_query'    => array(
        array(
            'key'   => 'event_status',
            'value' => 'archived',
        ),
    )
);

A: Change your code with this and might help you with what you are looking for. The issue here is that we cannot include key, order and orderby in meta_query. But if you want to order you result posts based on key than you can pass the query arguments as below:
$custom_query_args = array(
    'post_type'         => 'mcg_event',
    'posts_per_page'    => -1,
    'order'             => 'ASC',
    'meta_key'          => 'event_start_date',
    'orderby'           => 'meta_value_num',
    'meta_query'        => array(
        array(
            'key'   => 'event_status',
            'value' => 'archived',
        ),
    )
);


text:
Q: Can there particles which do not interact with matter at all? Weakly interacting massive particles (WIMPs) are hypothetical particles that are one of the proposed candidates for dark matter. They are proposed to have very weak interaction with ordinary matter particles, which got me thinking that can there be other particles that have no interaction with matter at all (not even gravitational). Also is it possible that these particles have their own set of interactions, completely different from known four kinds of interactions between ordinary matter particles?

A: The question whether or not non-interacting particles exists is not part of physics. As long as these particles have no interaction what-so-ever we have no way to measure them. Hence, there is no consequence of their existence. Personally it follows that this is therefore a non fruitful question.
I know that the Pauli exclusion principle is not based on an interaction, but a principle about symmetries. Hence, the above is only true if we assume that there are no symmetry principles involved with the non-interacting particles as well.


text:
Q: Dynamically Resizing Controls on Windows Forms I have a winform which can be resized.  I have 4 chart control in the form and sit side by side. When the form is in maximum size, the layout of each chart control is run out. I try to set the anchor style but I got no luck.  How I can make each control equally use the form width?
Normal size winform. The chart control sits side by side.

Maximum size form, the chart control is not in equal size and not sit side by side

How can I set the Anchor and make each control in the right position?

A: That's what a SplitContainer is for.
It has two panels splitted horizontally or vertically (property Orientation)
The user has then the ability to resize both panels.
Insert a SplitContainer and dock it fully in the parent form. (Dock = DockStyle.Fill)
Insert another two SplitContainers in each panel of the top SplitContianer.
Place your charts into the child SplitContainers.
You will find many examples in the web...


text:
Q: Find an ideal of $R = \mathbf{Z}/12\mathbf{Z} = \{0,1,2,\dots,11\}$ with two elements Let $R = \mathbf{Z}/12\mathbf{Z} = \{0,1,2,\dots,11\}$.

Find an ideal $I$ of $R$ which consists of two elements.
How many elements does $R/I$ have?

I thought the ideals would be $\{0\}$, $\{0,6,2\}$, and $\{0,4,3\}$.
Do the ideals not need the element $0$?

A: First you should know that $I$ has the property such that if you take an element $x \in R$ and $y \in I$ then $xr$ and $rx$ both belong to $I$
That's why you need $[0] \in I$ because $0 \times x = 0$ for any $x \in R$
Think about it , if you take $I = \{0,1 \}$ then you get that $2 \times 1 = 2 \not \in I$ and so $I \neq \{0,1\}$
Try $I = \{0,2 \}$ then you will get that $3 \times 2 = 6 \not \in I$ and so it can't be possible
Try $I = \{0,3 \}$ then you will get that $ 2 \times 3 = 6 \not \in I$ and so it can't be possible
Try $I = \{0,4 \}$ then you will get that $ 2 \times 4 = 8 \not \in I$ and so it can't be possible
Try $I = \{0,5 \}$ then you will get that $ 2 \times 5 = 10 \not \in I$ and so it can't be possible
Try $I = \{0,7 \}$ then you will get that $ 2 \times 7 = 14 = 2 \not \in I$ and so it can't be possible
Try $I = \{0,8 \}$ then you will get that $ 2 \times 8 = 16 = 4 \not \in I$ and so it can't be possible
Try $I = \{0,9 \}$ then you will get that $ 2 \times 9 = 18 = 6 \not \in I$ and so it can't be possible
Try $I = \{0,10 \}$ then you will get that $ 2 \times 10 = 20= 8 \not \in I$ and so it can't be possible
Try $I = \{0,11 \}$ then you will get that $ 2 \times 11 = 22= 10 \not \in I$ and so it can't be possible
Now you are only left with one possibility
Try $I = \{0,6 \}$ then you will get that $ 2 \times 6 = 12=  0  \in I$ and $3 \times 6 = 18 = 6  \in I$ and $4 \times 6 = 2 \times 2 \times 6 = 2 \times 0 = 0 \in I$ and so on, you will see that this is the only possible ideal as you said
You can see that $6$ worked because $6$ is a zero divisor


text:
Q: good use of action cable I'm starting with rails 6 and action cable, I've been creating channels for the use of action cable and updating the values in one view when they change or are modified in another. But I have one question, is it harmful to create too many channels? I'm creating my commercial application and I have about 25 sections on my page, each section is a CRUD of a different model. To apply action cable to them I must create 25 channels for each model? or would it be affecting the performance of my application by creating so many channels?

A: ActionCable channels are just keys in redis backend, they all use the same websocket (if you set it up the recommended way). So this shouldn't affect your apps performance.
But 25 models means 25 stream_from calls and 25 subscriptions.create calls. This would hurt the productivity of the programmer. I don't know the details of your requirements but I would seek to generalize the updates that gets sent over websockets just to simplify the mental model.


text:
Q: keyup event in CKEditor I'm using CKEditor and have an initEditor function that bootstraps all the event handler function of the editor instance like this:
btw, I'm using CoffeeScript
editor.on 'change', => ...
editor.on 'blur', => ...
editor.on 'key', => ...

and soon I found that the keyevent is actually keydown, I wonder there is a keyup event API, because this doesn't seem to work in my code:
editor.on 'keyup', => ...

and I got an error:

TypeError: editor.onKeyup is not a function

in:
editor.onKeyup((e) => {...})

A: Editor doesn't have a keyup event. If you want to catch it you should bind it to editors dom.
editor.document.on('keyup',function(){alert('kek')});


text:
Q: Is my understanding of parallel operations in Spark correct? I am newbie to Spark and trying to understand the Spark concept with Python. While using Python to develop applications for Spark, I get a bit confused with the way to get my data processed in parallel style.
1. Everyone says that I don't need to worry about which node and how many nodes will be invloved in processing my data encapsulated in RDD variables. Therefore, based on my best understanding, I believe what a Spark cluster would do to the code below:
a = sc.textFile(filename)
b = a.filter(lambda x: len(x) > 0 and x.split("\t").count("9999-12-31") == 0)
c = b.collect()

could be described as the following steps:
(1) Variable a will be saved as an RDD variable containing the    expected txt file content (2) Different chunks of RDD a will be broadcasted to different nodes in the cluster and filter method will be conducted for each chunk in different node (3) when the collection action is invoked, the results will be returned to the master from different nodes and saved as a local variable, c.
Is my description right? If not, what exactly will the procedure be? If I am right, what is the point to have parallelize method? Does the following code experience the same thing as that listed above?
a = sc.textFile(filename).collect()
b = sc.parallelize(a).filter(lambda x: len(x)>0 and x.split("\t").count("9999-12-31"))
c = b.collect()

2. For the following code, would the SQL query syntax be processed in parallel by dividing the defined table into many partitions?
a = sc.textFile(filename)
b = a.filter(lambda x: len(x) > 0 and x.split("\t").count("9999-12-31") == 0)
parts = b.map(lambda x: x.split("\t"))
records = parts.map(Row(r0 = str(x[0]), r1 = x[1], r2 = x[2]))
rTable = sqlContext.createDataFrame(records)
rTable.registerTempTable("rTable")
result = sqlContext.sql("select substr(r0,1,2), case when r1=1 then r1*100 else r1*10 end, r2 from rTable").collect()

A: Your first step description is true. But there is something more about second and third steps.
Second Step:
According to Spark documentation:

def textFile(path: String, minPartitions: Int = defaultMinPartitions): RDD[String]
The textFile method also takes an optional second argument for controlling the number of partitions of the file. By default, Spark creates one partition for each block of the file (blocks being 64MB by default in HDFS), but you can also ask for a higher number of partitions by passing a larger value.

If you put your file in HDFS and pass its path as textFile parameter, partitions of RDD a are created based on the HDFS blocks. So in this case the amount of palatalization  depend on number of HDFS blocks. Also data has already partitioned and moved to cluster machines via HDFS.
If you use path on the local file system (available on all nodes) and do not specify minPartitions the default parallelism (that depends on number of cores in your cluster) is chosen. In this case you have to copy your file on every worker or put it into a shared storage which is available to every worker.
In each of the cases, Spark avoid broadcasting any data and instead tries to use existing blocks in each machines. So your second step is not totally true.
Third Step
According to Spark documentation:

collect(): Array[T]
  Return an array that contains all of the elements in this RDD

In this step your RDD b is shuffled/collected into your driver program/node.


text: Q: ArcMap Mosaic Dataset function chain result to NetCDF I've been working on a mosaic dataset and added some changes by using the function chain options. This works fine in ArcMap and I can create a time varying result out of this. Since I want a 3D result as well using ArcScene and ArcScene can't handle mosaic datasets, I tried to convert the Mosaic Dataset to NetCDF. Unfortunately it seems that ArcMap doesn't convert the final result from the function chain. How can I get this to work, so I can get my function chain result visualized in ArcScene?


text:
Q: Populated Dropdown with autoComplete textbox I am new in angular js . I want to make a page with two dropdowns .One for country and other for cities .I want to make filter dropdown 2 according to the country selected.And i want to autocomplete my textbox by place depending on the selection of dropdown 2 (i mean city  dropdown).
can anyone help me please???

A: Well, you need to select country and based on selected country you need to display cities list in other dropdown right? Here is my code.
Html template code

CitiCountry

        <select class="form-control" ng-model="searchcountry" ng-  options="co.country for co in countryList |orderBy:'country'">
          <option value="">Select Country</option>
        </select>

        <select class="form-control" ng-model="searchCity" ng-options="ci.city for ci in citiesList | filter:searchcountry | orderBy:'city'">
         <option value="">Select City</option>
        </select>

JS code
function CitiCountry($scope) {
$scope.countryList=[{"country":"Pakistan"},{"country":"India"}]
    $scope.citiesList=[{"city":"mumbai","country":"India"},
                       {"city":"banglore","country":"India"},
                       {"city":"Islamabad","country":"Pakistan"},
                       {"city":"Delhi","country":"India"}];
    $scope.$watch('searchcountry', function() {
        $scope.searchState = null;
    });
    $scope.$watch('searchState', function() {
        $scope.searchCity = null;

    });
}

Here is fiddle Demo


text:
Q: Add Virtual Host for Localhost Ampps <VirtualHost *:80>
    DocumentRoot "C:/Program Files (x86)/Ampps/www"
    ServerName localhost
</VirtualHost>

<VirtualHost *:80>
    DocumentRoot "C:/Program Files (x86)/Ampps/www/proj"
    ServerName proj.local
</VirtualHost>

How do I bind a specific "domain" (virtual host domain) to one location?  Above points proj.local to localhost as well.

A: As you said you are using AMPPS, I suppose you are adding this instructions to the folder:
AMPPS/apache/conf/extra/httpd-vhosts.conf

With that in mind I'll show an example of configuration.
<VirtualHost project.local:80>
    <Directory "/Users/you/yourproject">
        Options FollowSymLinks Indexes
        AllowOverride All
        Order deny,allow
        allow from All
    </Directory>
    ServerName project.local
    ServerAlias project.local 127.0.0.1
    ScriptAlias /cgi-bin/ "/Users/you/yourproject/cgi-bin/"
    DocumentRoot "/Users/you/yourproject"
    ErrorLog "/Applications/AMPPS/apache/logs/project.error_log"
    CustomLog "/Applications/AMPPS/apache/logs/project.access.log" combined
</VirtualHost>

All right. After doing that, you will have to add to your hosts file. In Mac they are located in:
/etc/hosts

If you are using a Windows environment you will find the hosts file in:
c:\windows\system32\drivers\etc\hosts

Attention: You may have to type your password again or allow the program you're using to edit the file to use administrator privileges.
Then you'll add your local IP and the hostname to it. Just like this:
127.0.0.1      project.local

If you don't add the URL to the hosts file that won't work.

A: Have you tried with <VirtualHOst proj.local:80>? You should be able to find more examples here: http://httpd.apache.org/docs/2.2/vhosts/examples.html

A: <VirtualHost 127.0.0.1:80>
DocumentRoot "C:\xampp\htdocs"
ServerName xampp.local
ServerAlias www.xampp.local
</VirtualHost>

after adding it at the end of your httpd-vhosts.conf file restart your xampp and also add following lines to your hosts file available at C:\Windows\System32\Drivers\etc\hosts
127.0.0.1      xampp.local


text:
Q: Открыть новое окно в kivy python Подскажите как мне при нажатии кнопки "Aply" открывать новое окно класса SecondWind ??
from kivy.app import App

from kivy.uix.widget import Widget
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.textinput import TextInput
from kivy.uix.button import Button
from kivy.uix.anchorlayout import AnchorLayout
from kivy.properties import ObjectProperty

from kivy.config import Config
Config.set('graphics', 'resizable', 0)
Config.set('graphics', 'height', 400)
Config.set('graphics', 'width', 300)

class SecondWind(Widget):
    def wind(self):
        bl = BoxLayout(orientation = 'horizontal', spacing = 2)

        bl.add_widget(Button(text = '1'))
        bl.add_widget(Button(text = '2'))
        bl.add_widget(Button(text = '3'))

        return bl

class TrainApp(App):
    dic = {}
    sw = SecondWind()

    def build(self):
        al = AnchorLayout()
        bl = BoxLayout(orientation = 'vertical',spacing = 5, size_hint = (.8,.8 ))

        self.key = TextInput( background_color = [1,0.3,0.5,1],multiline = False)
        self.value = TextInput(text = '2nd Name', background_color = [1,0.3,0.5,1],multiline = False )

        bl.add_widget(self.key)
        bl.add_widget(self.value)
        bl.add_widget(Button(text = 'Aply', on_press = self.aply))

        al.add_widget(bl)

        return al

    def aply(self, instance):
        if self.key.text != '':
            self.dic[self.key.text] = self.value.text
        else:
            self.dic['Name'] = self.value.text
        print(self.dic)

if __name__ == '__main__':
    TrainApp().run()


text:
Q: Can I get all the studio's detail from Mindbody to my application through the MindBody API? I am working on an app where I need to integrate the MindBody API, and I have accessed it successfully, but the problem is that I am not sure whether I can get only my studio related data or all the studio related data which are available on MindBody Website.
I have registered on MindBody website and got login credential for developer like:
username: Siteowner
password: abc
I have also downloaded sample iOS code from https://github.com/arrak-rukkharat/API-Integration-iOS and inserted my credential and it's working well.
But the main thing is I want all the studio's data not only mine. So is it possible? Can I get all the studio's data through this API call?
Please provide me any sources related to this confusion.
thanks

A: Everything depends on which exactly data you what to request using API.
You should be able to get limited information of any studio using your dev credentials only, sending them as SourceCredentials in your API requests.
You need to be granted access by the studios to get all information (available with API) for any studio, sending also UserCredentials in you API requests - these are either your developer credentials (but username is with underscore in the beggining) or the studio's staff/owner user credentials.
More information about authentication (how to be granted access),  SourceCredentials and UserCredentials is available in : Mindbodyonline documentation
The other useful source is a list of API methods that provides an overview of each method. Normally a method that requires UserCredentials is marked with a line 'This requires a staff credentials' or similar. For example take a look at   ClassService.UpdateClientVisits()  documentation. Methods that aren't marked with such line should provide you information for any studio without any additional authentication except your dev credentials (SourceCredentials).


text:
Q: Difference between unlink and rm on unix Whats the real different between these two commands? Why is the system call to delete a file called unlink instead of delete?

A: You need to understand a bit about the original Unix file system to understand this very important question.
Unlike other operating systems of its era (late 60s, early 70s) Unix did not store the file name together with the actual directory information (of where the file was stored on the disks.)  Instead, Unix created a separate "Inode table" to contain the directory information, and identify the actual file, and then allowed separate text files to be directories of names and inodes.  Originally, directory files were meant to be manipulated like all other files as straight text files, using the same tools (cat, cut, sed, etc.) that shell programmers are familiar with to this day.
One important consequence of this architectural decision was that a single file could have more than one name!  Each occurrence of the inode in a particular directory file was essentially linking to the inode, and so it was known.  To connect a file name to the file's inode (the "actual" file,) you "linked" it, and when you deleted the name from a directory you "unlinked" it.
Of course, unlinking a file name did not automatically mean that you were deleting / removing the file from the disk, because the file might still be known by other names in other directories.  The Inode table also includes a link count to keep track of how many names an inode (a file) was known by; linking a name to a file adds one to the link count, and unlinking it removes one.  When the link count drops down to zero, then the file is no longer referred to in any directory, presumed to be "unwanted," and only then can it be deleted.
For this reason the "deletion" of a file by name unlinks it - hence the name of the system call - and there is also the very important ln command to create an additional link to a file (really, the file's inode,) and let it be known another way.
Other, newer operating systems and their file systems have to emulate / respect this behavior in order to comply with the Posix standard.


text:
Q: Defining Indexes in SqlAlchemy with Alembic I completely agree that this is a pretty basic question and may be it has its answer somewhere, but I somehow can not find it out. (also I am not very proficient with SqlAlchemy)
I have this code --
from sqlalchemy import Column, Integer, Text, String, TIMESTAMP, Boolean, \
    UnicodeText
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import scoped_session, sessionmaker
from sqlalchemy.schema import Sequence, ForeignKey, Index
from zope.sqlalchemy import ZopeTransactionExtension
import datetime

DBSession = scoped_session(sessionmaker(extension=ZopeTransactionExtension()))
Base = declarative_base()

class Users(Base):
    __tablename__ = "user_table"

    id = Column(Integer, Sequence('idseq'), primary_key = True)
    email = Column(String, unique=True)
    ip_addr = Column(String)
    created_date = Column(TIMESTAMP(timezone=True), default=datetime.datetime.utcnow)
    modified_date = Column(TIMESTAMP(timezone=True), default=datetime.datetime.utcnow)
    #Index('user_index',Users.c.email)

How can I

*

*Define a Single Column Index (say on email) on this? (Probaby
index=True will do this. And if so, then it is mostly the next point
where I am lost)

*How can I define a Multi Column Index on this (say, for an example, on email and ip_addr. I am using alembic for Migration and when I define something like - Index('user_index',Users.c.email) [commented line] After the column definitions in the class it does give me an error that "NameError: name 'Users' is not defined" )

In the alembic's env.py, apart from all the normal and default lines, I have these two lines
from tutorial.models import Base
.
.
.
target_metadata = Base.metadata

My app name is tutorial. And if somehow it is needed I am using Pyramid as the framework. and postgres as the db.
I am telling again that, it may be a very basic question, but just I can not figure it out right now and so any help will be great.
Thanks.

A: For I, Yes, use index=True on your field definition.
For II, just put the Index declaration outside the class definition:
class Users(Base):
    __tablename__ = "user_table"

    id = Column(Integer, Sequence('idseq'), primary_key=True)
    email = Column(String, unique=True)
    ip_addr = Column(String)
    created_date = Column(TIMESTAMP(timezone=True), default=datetime.datetime.utcnow)
    modified_date = Column(TIMESTAMP(timezone=True), default=datetime.datetime.utcnow)

Index('user_index', Users.c.email, Users.c.ip_addr)


text:
Q: How to skip text at the beginning of a json file in python I have a json object file and at the beginning of this file a header of text, date, time, IP address.
I've tried f.readlines()[5:] to no avail.
I've tried next(f)
I wish to skip 5 or 6 lines of text and go directly into the json data.
Here is an example.
import jsonlines
import json

data_file = input("Enter a file to parse: ")
with jsonlines.open(data_file) as file:
    for obj in file:
        try:
            jsonparse = json.loads(obj)
        except Exception as e:
            pass
        print(obj)

Error:
jsonlines.jsonlines.InvalidLineError: line contains invalid json: Expecting value: line 1 column 1 (char 0) (line 1)

Top of json file:
Start:  07/02/2019 14:59:40.686
Connected To:
192.168.11.203
Here is the full long error:
Enter a file to parse: Play.raw
Traceback (most recent call last):
  File "C:\Users\sdickey\AppData\Local\Programs\Python\Python37\lib\site-packages\jsonlines\jsonlines.py", line 159, in read
    value = self._loads(line)
  File "C:\Users\sdickey\AppData\Local\Programs\Python\Python37\lib\json\__init__.py", line 348, in loads
    return _default_decoder.decode(s)
  File "C:\Users\sdickey\AppData\Local\Programs\Python\Python37\lib\json\decoder.py", line 337, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "C:\Users\sdickey\AppData\Local\Programs\Python\Python37\lib\json\decoder.py", line 355, in raw_decode
    raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "C:/Users/sdickey/PycharmProjects/Python Testing/Actall Data/testing.py", line 6, in <module>
    for obj in file:
  File "C:\Users\sdickey\AppData\Local\Programs\Python\Python37\lib\site-packages\jsonlines\jsonlines.py", line 204, in iter
    skip_empty=skip_empty)
  File "C:\Users\sdickey\AppData\Local\Programs\Python\Python37\lib\site-packages\jsonlines\jsonlines.py", line 164, in read
    six.raise_from(exc, orig_exc)
  File "<string>", line 3, in raise_from
jsonlines.jsonlines.InvalidLineError: line contains invalid json: Expecting value: line 1 column 1 (char 0) (line 1)

Process finished with exit code 1

A: I think you are trying to convert to json line by line. You need to join all lines by \n igoring the first 5 lines and then load it:
import json
with open("test.txt") as f:
  json_obj = "\n".join(f.readlines()[5:])
  jsonparse = json.loads(json_obj)
  print(jsonparse)

A: It is always preferable not to read the whole file in memory but one line at a time.
Assuming your input file contains:
first line
second line
third line
fourth line
fifth line
{ "k1": "val1", "k2": "val2" }
{ "k3": "val3", "k4": "val4" }

if you just want to skip 5 lines, you could do it brutally as:
import json

with open("test.txt") as f:
    for _ in range(5):
        next(f)
    for line in f:
        obj = json.loads(line)
        print(obj)

or using enumerate:
import json

with open("test.txt") as f:
    for i, line in enumerate(f):
        if i<5:
            continue
        obj = json.loads(line)
        print(obj)

or use itertools' dropwhile:
import itertools as it
import json

with open("test.txt") as f:
    for i, line in it.dropwhile(lambda i: i[0]<5, enumerate(f)):
        obj = json.loads(line)
        print(obj)


text:
Q: Migrate Horde database I have been using Horde Webmail edition with Postgresql for the longest time. I'm in the process of migrating servers and considering dropping Postgresql in favor of MySQL. (I'm very happy with Postgresql but unfortunately there are too many applications that will only work with MySQL and I try to avoid running/maintaining both.)
What would be an elegant way to migrate the Horde database (users, calendars, etc) from Postgresql to MySQL? Is there anything better than dumping the database, fixing the syntax and importing again?


text:
Q: Make HTTPHandler (ashx) to place session cookie in ASP.NET How can I make a HTTPHandler in an ashx file PLACE a SessionCookie managed by ASP.NET? It seems, that the call of an ashx-File does not place a cookie, so no session can be maintained.
Background: I am about to write HTTP based web service wrapper. Different clients call the URL I provide them with the given parameters. I check the credentials, call the 3rd party web service and deliver the changed result back to the client. The 3rd party web service provider demands by contract a SessionID for every different client calling.
Solution: An HTTPHandler seems to be the best choice. So I created a Web Site Project. Unfortunately a direct call of a ashx-File seems not to add a session cookie to the response, so a new SessionID is being created for every call from the same client.
I did the following relevant:

*

*Implemented markup interfaces IRequiresSessionState or/and
IReadOnlySessionState

*Added <sessionState mode="InProc" cookieless="false" timeout="20" />
to the web.config

*Save something in the session state in the Global.asax File in the
Session_Start-Method HttpContext.Current.Session("init") = 0

Different attempts which work, but should be avoided:

*

*Before calling the ashx-File a call of the Default.aspx File places a session cookie, so the session is being maintained.

*Implement an "own" Session with a database and a timestamp.

Version: IIS 6.0

A: IRequireSessionState and IRequireReadOnlySessionState are mutually exclusive. You should only be implementing the former if you intend to update session state in any way.


text:
Q: Is every closed set (in R) countable? I am trying to prove something and was wondering if one can assume that any closed set in the real numbers is countable. Im not finding any info so Im wondering if that statement is too vague.

A: No, one cannot assume that any closed set is countable. For example, consider [0,1]. This set is closed but it has uncountably many numbers.

A: Actually, in any topology of $\mathbb{R}$ there are a uncountable closed sets: take $\mathbb{R}$


text:
Q: Building Shape Model I am trying to build Statistical Shape Model(I want to start with Statistical Shape Model and then I will try to build Active Shape Model and Active Appearance Model).
So I implemented two classes, first for Generalized Procrustes Analysis(Python code sample which I translated to C# code) and second for Principal Component Analysis(C# code sample).
I have one more sample which has function which can build shape model, but I can't use it because it is very difficult to understand. That function also uses GPA and PCA but returns different result.
So my questions:

*

*Why results are different(given that my code gives the same results as in the samples)?

*How I can connect(if I may say so) these two classes and what else I need to do to build shape model?

Any help would be useful! Thanks!


text:
Q: Cloud Dataflow Job failed Our Cloud dataflow job has failed this morning with the following error:

Jul 20, 2015, 7:02:57 AM (41114dff4e115290): Workflow failed. Causes:
  (ba1dfdda2b6af333): Map task completion for Step
  "Clicks_07_2015-BQ-Read+Clicks_07_2015-ParDoDFP-transform+Clicks_07_2015-BQ-Write"
  failed. Causes: (3bcd8d4fd3828211): No exported files
  "gs://path/to/file/*.json"
  found after export of table "Clicks_07_2015" in dataset
  "--dataset--" in project "{--project--id--}".

This Job has been running successfully for the past few days without any code changes and has failed this morning. We can see that there is a json file in this cloud storage folder so i'm not sure why this could have failed. Is this a bug?
Job Id: 2015-07-19_14_01_42-8050965853069761045

A: When tables are exported from BigQuery to Cloud Storage, they are subject to the eventual consistency properties of that system.  In this case, it appears that the index was still stale after repeated retries, at which point Dataflow failed the job.  We'll work on handling this particular case better, thank you for your patience.
This should a rare occurrence, but you may find it useful to run the CLI in a retry loop to work around this scenario.
https://cloud.google.com/dataflow/pipelines/dataflow-command-line-intf


text:
Q: samba4 not building in Arch cp bin/tdbtool bin/tdbdump bin/tdbbackup /tmp/yaourt-tmp-root/aur-samba4/pkg//opt/samba4/samba/bin
cp ./include/tdb.h /tmp/yaourt-tmp-root/aur-samba4/pkg//opt/samba4/samba/include
cp tdb.pc /tmp/yaourt-tmp-root/aur-samba4/pkg//opt/samba4/samba/lib/pkgconfig
cp libtdb.a libtdb.so.1.2.4 /tmp/yaourt-tmp-root/aur-samba4/pkg//opt/samba4/samba/lib
rm -f /tmp/yaourt-tmp-root/aur-samba4/pkg//opt/samba4/samba/lib/libtdb.so
ln -s libtdb.so.1.2.4 /tmp/yaourt-tmp-root/aur-samba4/pkg//opt/samba4/samba/lib/libtdb.so
rm -f /tmp/yaourt-tmp-root/aur-samba4/pkg//opt/samba4/samba/lib/libtdb.so.1
ln -s libtdb.so.1.2.4 /tmp/yaourt-tmp-root/aur-samba4/pkg//opt/samba4/samba/lib/libtdb.so.1
mkdir -p /tmp/yaourt-tmp-root/aur-samba4/pkg/`/tmp/yaourt-tmp-root/aur-samba4/src/bin/python -c "import distutils.sysconfig; print distutils.sysconfig.get_python_lib(1, prefix='/opt/samba4/samba')"`
cp tdb.so /tmp/yaourt-tmp-root/aur-samba4/pkg/`/tmp/yaourt-tmp-root/aur-samba4/src/bin/python -c "import distutils.sysconfig; print distutils.sysconfig.get_python_lib(1, prefix='/opt/samba4/samba')"`
/bin/install -c -d /tmp/yaourt-tmp-root/aur-samba4/pkg//opt/samba4/samba/share/man/man8
for I in manpages/*.8; do \
                /bin/install -c -m 644 $I /tmp/yaourt-tmp-root/aur-samba4/pkg//opt/samba4/samba/share/man/man8; \
        done
/bin/install: cannot stat `manpages/*.8': No such file or directory
make: *** [installdocs] Error 1
    Aborting...
==> ERROR: Makepkg was unable to build samba4.
==> Restart building samba4 ? [y/N]
==> -------------------------------
==>c

Any ideas as what is causing my build to fail? I assume it's an issue with manpages I can't figure out exactly what package it is looking for that I don't have.

A: Try updating your version of libtdb then recompile.

A: Looks like the section 8 manpage doesn't exist...you could just try touch manpages/forgetthis.8

A: Have you tried posting a comment on the AUR page?  The maintainer is usually able to help with those sorts of things.
The thing that usually gets me into trouble is not having an updated system.  You've -Syued today?


text:
Q: Rails Activestorage + DirectUpload javascript progress bar not showing when using "remote:true" I have been using Rails ActiveStorage DirectUpload in my Rails app. And here is the code of the form:

Select Files To Upload

<%= form_for @uploader, url: uploaders_file_path(@uploader), :html => {:multipart => true} do |f| %>
  <%= f.file_field :file, direct_upload: true,  class: "form-control" %>

  <%= f.button type: "submit", id: "submit-uploader", class: "btn btn-primary btn-md", data: {disable_with: "Uploading..."} do %>
    Upload
  <% end %>
<% end %>

Everything works alright and the progress bar is also showing when i upload the file:

But, when I try to make the form to be submitted as js, the progress bar is not showing even though the file upload is successful. I just added "remote: true" to make the form to be submitted as js. But now the progress bar is no longer showing.
Here is the new code of the form:
<%= form_for @uploader, url: uploaders_file_path(@uploader), remote: true, :html => {:multipart => true} do |f| %>
  <%= f.file_field :file, direct_upload: true,  class: "form-control" %>

  <%= f.button type: "submit", id: "submit-uploader", class: "btn btn-primary btn-md", data: {disable_with: "Uploading..."} do %>
    Upload
  <% end %>
<% end %>

And here is direct_uploads.js code:
addEventListener("direct-upload:initialize", event => {
  const { target, detail } = event
  const { id, file } = detail
  target.insertAdjacentHTML("beforebegin", `

      ${file.name}

  `)
})

addEventListener("direct-upload:start", event => {
  const { id } = event.detail
  const element = document.getElementById(`direct-upload-${id}`)
  element.classList.remove("direct-upload--pending")
})

addEventListener("direct-upload:progress", event => {
  const { id, progress } = event.detail
  const progressElement = document.getElementById(`direct-upload-progress-${id}`)
  progressElement.style.width = `${progress}%`
})

addEventListener("direct-upload:error", event => {
  event.preventDefault()
  const { id, error } = event.detail
  const element = document.getElementById(`direct-upload-${id}`)
  element.classList.add("direct-upload--error")
  element.setAttribute("title", error)
})

addEventListener("direct-upload:end", event => {
  const { id } = event.detail
  const element = document.getElementById(`direct-upload-${id}`)
  element.classList.add("direct-upload--complete")
})

The above code is taken from: https://guides.rubyonrails.org/active_storage_overview.html#direct-uploads

A: Try this DirectUpload guide section.
Working with the DirectUpload class directly let you submit with remote: true.

*

*Catch the submit (event.preventDefault())

*Upload file using DirectUpload class. Which provides events to show progress bar and all stuff.

*Submit your form by js.

Means more code but its an option.


text:
Q: Deep Learning with many categories Do deep learning algorithms run into trouble when tasked with classifying high dimensional input into one of many categories? By many I mean thousands or millions. If it does, how could one deal with this problem? Any references?

A:
If it does, how could one deal with this problem? Any references?

You can use hierarchical softmax, importance sampling, noise
contrastive estimation, or negative sampling: they are commonly used in language modeling, for example.
FYI:

*

*Why is hierarchical softmax better for infrequent words, while negative sampling is better for frequent words? (The answer gives a brief overview of what hierarchical softmax and negative sampling are)

*http://www.deeplearningbook.org/ section "12.4.3 High-Dimensional Outputs": presents hierarchical softmax, importance sampling, noise contrastive estimation, and negative sampling.

*Dyer, Chris. "Notes on Noise Contrastive Estimation and Negative Sampling." arXiv preprint arXiv:1410.8251 (2014).  https://arxiv.org/abs/1410.8251


text:
Q: Get content of a mail IMAPCLIENT I am using the IMAPclient to get the content of emails, so i made this piece of code :
messages = server.search(['FROM', user['email']], charset='UTF-8')
if len(messages) > 0:
    for mail_id, data in server.fetch(messages, ['ENVELOPE']).items():
        envelope = data[b'ENVELOPE']

How can I have the content of the emails?

A: Don't know if you found the answer elsewhere... try:
   messages = server.search(['FROM', user['email']], charset='UTF-8')
   if len(messages) > 0:
       for mail_id, data in server.fetch(messages,['ENVELOPE','BODY[TEXT]']).items():
           envelope = data[b'ENVELOPE']
           body = data[b'BODY[TEXT]']

The email content is in body.


text:
Q: Is it possible to plot the data from this webpage using Dygraphs? I am trying to create a chart from historical stock information, retrieved from Yahoo Finance, using Dygraphs.
The url I am trying to use as source of data is:
http://ichart.finance.yahoo.com/table.csv?s=UL.PA&a=08&b=7&c=1984&d=01&e=24&f=2014&g=d&ignore=.csv
When I include the code below in my HTML file, I do not get any error message with Firebug. Yet the chart is empty.
Could anyone help me explain what I am doing wrong?

LC

A: You're running into the same-origin policy for XmlHttpRequest.
When I run your code in jsfiddle, I see this error in the Chrome Developer Console:
XMLHttpRequest cannot load http://ichart.finance.yahoo.com/table.csv?s=UL.PA&a=08&b=7&c=1984&d=01&e=24&f=2014&g=d&ignore=.csv.
No 'Access-Control-Allow-Origin' header is present on the requested resource.
Origin 'http://fiddle.jshell.net' is therefore not allowed access.

You'll have to do the request server-side, rather than client-side.


text:
Q: How to determine layout that yields maximum number of squares inside a larger grid I am trying to determine what algorithm to use to determine the layout that yields the maximum number of 2x2 square grids that can fit inside a larger non-uniform grid.
The image below shows an example of a non-uniform grid (black lines) with a maximum of 12 fitted 2x2 square grids (blue boxes). Is there a systematic approach to determine the layout that yields maximum capacity? As can be seen in the image below the 2x2 square grids do not need to be horizontally or vertically aligned. Thanks!

A: I'd try an integer program solver, (e.g., OR-Tools).
The formulation I have in mind is pretty standard. Let's suppose we have a grid with labeled squares like
  ab
cdefgh
ijklmn

For each square that can be the the upper left corner of a 2x2 (a, c, d, e, f, g), we have a 0-1 variable that will be 1 if that square is chosen and 0 otherwise. For every square, we have a constraint that the sum of variables of 2x2s overlapping that square is at most 1.
a ≤ 1            (a)
a ≤ 1            (b)
c ≤ 1            (c)
c + d ≤ 1        (d)
a + d + e ≤ 1    (e)
a + e + f ≤ 1    (f)
f + g ≤ 1        (g)
g ≤ 1            (h)
c ≤ 1            (i)
c + d ≤ 1        (j)
d + e ≤ 1        (k)
e + f ≤ 1        (l)
f + g ≤ 1        (m)
g ≤ 1            (n)

And naturally we want to maximize the sum of the variables:
max a + c + d + e + f + g


text:
Q: SyntaxError: Unexpected token v in JSON at position 0 at JSON.parse () at XMLHttpRequest.onLoad I'm new to Angular.I have some problems regarding the passing data between back-end and front-end.I have  a system which passes booking data to the back-end to be saved in the database.Here is my code,
bookings.ts file
export class Bookings{
    departure:number;
    arrival:string;
    departd:string;
    returnd:string;
    classtype:string;
    adults:number;
    children:number;
    infants:number;
}

booking.component.ts
export class BookingComponent implements OnInit {

  booking:Bookings =new Bookings();

  message:Observable<Object>;

  constructor(private flightService:FlightService, private router: Router) { }

  ngOnInit(): void {
  }

  save() {
    this.flightService.search(this.booking).subscribe(data => console.log(data), error => console.log(error));
    // this.flightService.search(this.booking)

    this.booking = new Bookings();
    this.bookingData();
  }

  onSubmit() {
    this.save();
  }

  bookingData() {
    this.router.navigate(['/bookings']);
  }

}

flight.service.ts
export class FlightService {

  private baseUrl='http://localhost:8080/flight/destinations';

  constructor(private http: HttpClient) { }

  getDestinations(): Observable<Destination[]>{
    // return  this.http.get(`${this.baseUrl}`);
    return  this.http.get<Destination[]>(this.baseUrl);
  }

  search(booking: Object): Observable<any> {
   return this.http.post(`${this.baseUrl}`, booking);
  }

}

FlightData Controller class
@CrossOrigin(origins = "http://localhost:4200")
@RestController
@RequestMapping("/flight")
public class FligthtDataController {

@Autowired
private FligthtDataServices flightDataServices;

    @GetMapping("/destinations")
    public List<Destinations> getdestinationData() {
        List<Destinations> ds=flightDataServices.getDestinations();
        return ds;
    }

    @PostMapping("/destinations")
    public String  serchBooking(@RequestBody Booking booking) {
    System.out.println("Departure:"+booking.getDeparture());
    System.out.println("Arrival:"+booking.getArrival());
    System.out.println("Depart Date:"+booking.getDepartd());
    System.out.println("Return Date:"+booking.getReturnd());
    System.out.println("Class:"+booking.getClasstype());
    System.out.println("Adults"+booking.getAdults());
    System.out.println("Children"+booking.getChildren());
    System.out.println("Infants"+booking.getInfants());

        return "Successfuly saved the data";
    }

}

The problem with me is when I return a String  from the back-end in the Post method  as shown above the data from the front-end comes to the post method as expected but it gives a error in the console as follows

But when I return a number as below it doesn't show any error the value also printed on the console
  @PostMapping("/destinations")
    public int  serchBooking(@RequestBody Booking booking) {
    System.out.println("Departure:"+booking.getDeparture());
    System.out.println("Arrival:"+booking.getArrival());
    System.out.println("Depart Date:"+booking.getDepartd());
    System.out.println("Return Date:"+booking.getReturnd());
    System.out.println("Class:"+booking.getClasstype());
    System.out.println("Adults"+booking.getAdults());
    System.out.println("Children"+booking.getChildren());
    System.out.println("Infants"+booking.getInfants());

        return 123;
    }

No error in console as shown below the number also printed.

please help me to understand this. and help me to resolve this issue.Thank you

A: A string is not valid JSON that can be ran through JSON.parse, but a number is.
You can see examples here:

// valid, will return 123
console.log(JSON.parse(123));

// invalid, will error
try {
 console.log(JSON.parse("Sucessfully saved the data"));
} catch(e) {
  console.log("Error", e)
}
// proper JSON "object" from the server
console.log(JSON.parse(`{"message": "Sucessfully saved the data"}`));

You need to return a proper JSON string from your server, like the one in the example, then read the message property from that response.

A: just to add to @cjd82187 answer... you don't have to return JSON. My API happens to return a string, in which case I've added the following to options:
responseType: 'text'

This, however, resulted in another issue: "type text is not assignable to type json". The solution to this is the following:
responseType: 'text' as 'json'

an example:
this.httpClient.post<any>(
    this.statusApiEndpoint,
    jobId,
    {
        headers: headers,
        responseType: 'text' as 'json'
    }).map(r => {
           console.log(r)
           return r;
          });


text:
Q: Exercise with string I have a problem with an exercise I found here exercise 3. I report it here.
#include <iostream>
#include <cstring>
using namespace std;

class Animal
{
    protected:
     int age;
     char name[10];
    public:
     void set_data (int a, char b[10]) // the set data is inherited by here to the two classes Zebra and Dolphin
     {
        age = a;
        strcpy(b,name);

     }
};

class Zebra:public Animal
{
    public:

    void message_zebra() {
        cout<< "The zebra named "<< name <<" is "<< age << " years old. The zebra comes from Africa. \n";
        }
};

class Dolphin: public Animal
{
    public:

    void message_dolphin() {
        cout<< "The dolphin named "<< name << " is "<<age << " years old. The dolphin comes from New Zeland.\n";
        }
};

int main ()
{
    Zebra zeb;
    Dolphin dol;
    char n1[10] = "Max";
    char n2[10] = "John";

    zeb.set_data (5,n1);
    dol.set_data (2,n2);

    zeb.message_zebra() ;
    dol.message_dolphin() ;

    return 0;
}

In principle, I have two base classes that inherit the proprieties of the class Animal but when I run it in the main, I can't be able to display the correct name of the two animals.

A: Regardless of your specific bug (strcpy() argument order as commenters suggest), there are some issues both with the problem definition and your solution.

Exercise 3
Write a probram with a mother class animal. Inside it define a name and an age variables, and set_value() function. Then create two bases variables Zebra and Dolphin which write a message telling the age, the name and giving some extra information (e.g. place of origin).

The first thing we notice about this problem is that the wording is vague and unclear. What are "bases variables" anyway? Are you asked to subclass Animal? Who knows. As for the place of origin - is it the specific instance' origin, or the entire class'? And - is it the Animal class or the inheriting subclass? who knows.
Also, a set_value() member function is really quite an awful thing to have. Even if your members aren't public, you would still have a separate setter method for each field, e.g. void setName(const std::string& name). Of course, it would be nicer to use a reference or a proxy for setting and getting a field, e.g. std::string& name() and const std::string& name() const.
Now, about your own code, note that the Zebra and Dolphin class don't really have a different behavior; and their "message" members print the same thing, except for the class name and the place of origin, which are different data. So why even bother with a subclass?
Also, it's not a good idea to use char arrays - use std::string unless there's a good reason not to. That way, you won't have an artificial limitation on the name length.


text:
Q: How to control the behaviour of QGridLayout Using PyQT6
I am trying to create and app that adds a new frame (stack1) whenever the check box is clicked. It all works well until the app hides the stack when you untick the checkbox.

Clearly what I'd like is for the app to return to the initial shape when I hide the stack. I am aware that since I have added a column to the QTGrid,the window has likely reshaped taking into account the extra space. I am getting the same behaviour using deleteLater. So  my question is how can I avoid that? Is there a way to reset the gridLayout to go back to just 1 column?
Here is a reproducible example:
import sys
from PyQt6.QtCore import *
from PyQt6.QtGui import *
from PyQt6.QtWidgets import *

from PyQt6.QtWidgets import QWidget, QApplication, QVBoxLayout, QStackedWidget,
QLabel, QPushButton
import sys
from PyQt6.QtGui import QIcon
from PyQt6 import QtGui

class Window(QDialog):

    def __init__(self):
        super().__init__()
        self.setWindowTitle("Anticoagulant Dose calculator")
        self.buttons = {'metrics': ['Age?', 'Height in cm?', 'Serum Creatinine?', 'Weight in kg?', 'Sex?'],
     'anticoagulant': ['DOAC', 'warfarin, \nacenocumarol'],
      'indication': ['VTE',  'Atrial Fibrilation', 'Mechanical Heart valve'],
       'VTE': ['single VTE > 12 months', 'VTE 3-12 months or  \n multiple, large volume PE or \n active cancer', 'VTE < 3 months \n or known antithrombin deficiency or \n antiphospholipid syndrome'],
        'af': ['No',"Yes, within the past 12 months","Yes, within the past 3 months"],
         'Mech': 'mech',
         'sexo': ['Male', 'Female']}

        self.dialogLayout = QVBoxLayout()
        self.anticoagLayout = QVBoxLayout()
        self.rejillaLayout = QGridLayout()
        self.anticoagButtongroup = QButtonGroup()
        self.indicationButtongroup = QButtonGroup()

        self.UIcomponents()
        self.setLayout(self.rejillaLayout)

        self.stack1 = QWidget()
        self.stack1UI()

    def stack1UI(self):
        for a in self.buttons['anticoagulant']:
            self.anticoag_rb = QRadioButton(a)
            self.anticoagButtongroup.addButton(self.anticoag_rb)
            self.dialogLayout.addWidget(self.anticoag_rb)

        for i in self.buttons['indication']:
            self.indication_rb = QRadioButton(i)
            self.indicationButtongroup.addButton(self.indication_rb)
            self.dialogLayout.addWidget(self.indication_rb)
        self.stack1.setLayout(self.dialogLayout)

    def cb_onclicked(self):
        self.cbox = self.bridgingCheckBox.sender()
        try:
            if self.cbox.isChecked():
                print('Puenteando')
                self.rejillaLayout.addWidget(self.stack1, 0, 2)
                self.stack1.show()
            else:
                self.stack1.deleteLater()
                print('No puenteando')
        except RuntimeError:
            pass

    def UIcomponents(self):
        self.entries = {}
        formas = QFormLayout()
        for m in self.buttons['metrics']:
            if m != 'Sex?':
                self.ent = QLineEdit()
                formas.addRow(m, self.ent)

            else:
                print('Sexo?')
                self.sComboBox = QComboBox()
                self.sComboBox.addItems(self.buttons['sexo'])
                sLabel = QLabel('Sex:?')
                sLabel.setBuddy(self.sComboBox)
                formas.addRow(sLabel, self.sComboBox)

        self.entries[m] = self.ent
        self.bridgingCheckBox = QCheckBox("Bridging dose")
        self.bridgingCheckBox.toggled.connect(self.cb_onclicked)
        formas.addRow(self.bridgingCheckBox, None)
        self.rejillaLayout.addLayout(formas, 0, 0)

if __name__ == '__main__':

    app = QApplication([])
    window = Window()
    window.setGeometry(50, 50, 300, 160)
    window.show()
    sys.exit(app.exec())

Many thanks in advance.

A: Thanks yo @ekhumoro for the answer:
gridding the stack at the init stage then hiding it, and then adding the code to the checkbox connector does it.
def cb_onclicked(self):
    self.cbox = self.bridgingCheckBox.sender()
    self.stack1.setVisible(self.bridgingCheckBox.isChecked())
    self.adjustSize()


text:
Q: How to suppress script errors in Visual Studio's embedded browser I'm using the embedded webbrowser in Visual Studio to look up API documentation while I work on my program that targets said API.
Unfortunately, there are multiple script errors on the website that I use. So whenever I navigate to a page, multiple warnings pop.
In my internet options, I've set the following preferences:

[x] Disable script debugging (Internet Explorer)
[x] Disable script debugging (Other)
[ ] Display a notification about every script error

But no matter what I do, I can't get rid of these f@#{[^@| popups

I'm about to lose my mind over this. Please help.
edit
To clarify: this isn't an ASP project. I'm simply viewing a remote website in the embedded browser.

View | Other Windows | Web Browser (CTRL + Alt + R)

This is the browser that opens when you follow a hyperlink in a file.

A: Was having the same problem, this single line of code did the trick.
webBrowser1.ScriptErrorsSuppressed = true;


text:
Q: MongoDB search a document and find value using PHP I have the following json data:
{
"name" : "Template1",
"data" : {
    "columns" : [
        {
            "name" : "Brand Size",
            "record" : [
                {
                    "fname" : "column_search",
                    "fields" : [
                        {
                            "name" : "column_search_form_search",
                            "value" : "332"
                        },

                    ],
                    "rules" : [
                        {
                            "rules_info_cond" : "if",
                        }
                    ]
                },
        {
            "name" : "vendorArticleName",
            "record" : [
                {
                    "fname" : "column_search",

                    "rules" : [
                        {
                            "rules_info_cond" : "if",
                        }
                    ]
                },
        {
            "name" : "Remarks",
            "record" : [
                {
                    "fname" : "column_information_show",

                    "rules" : [
                        [
                        ]
                    ]
},

}
I would like to get data->columns->name which have fname = 'column_information_show'
I was able to find using MongoDB but not able to find with PHP. Help me please!

A: $array = json_decode($jsonData, true);

foreach($array['data']['columns'] as $value) {
    if($value['record']['fname'] == 'column_information_show'){
        return $value;
    }
}

This will loop through your json data and return the first column where the fname is equal to column_information_show. If there are multiple columns that you want to return you could add them to an array and then return it later.


text:
Q: onClick of background of RemoteView unecpected behaviour I want my widget to show a list with a clickable button and clickable background on the ListItem that contains the button. I created a service, that distinguishes between the different events, but the click on the background is never registered, if the onClickFillIntent is set on the button.
(I already tried setting multiple onClickFillIntents on other things, like a TextView and a button, this works flawlessly. Everything but the background works.)
TLDR;
why does intent1 work, but intent2 doesnt?
There is no error in logcat.
widget.kt
class Widget() : AppWidgetProvider() {

override fun onUpdate(context: Context, appWidgetManager: AppWidgetManager, Ids: IntArray) {
    for (i in Ids.indices) {
        val views = RemoteViews(context.getPackageName(), R.layout.classificationwidget)
        views.setRemoteAdapter(R.id.widget_list, context.intentFor<WidgetService>())
            views.setPendingIntentTemplate(R.id.widget_list, PendingIntent.getService(context,0,context.intentFor<DataCollectorService>("someAction"), PendingIntent.FLAG_CANCEL_CURRENT))
            appWidgetManager.updateAppWidget(Ids[i], views)
        }
    }
}

class WidgetService : RemoteViewsService() {
    override fun onGetViewFactory(intent: Intent): RemoteViewsFactory {
        return WidgetViews(this.applicationContext)
    }
}

class WidgetViews(private val context: Context) : RemoteViewsService.RemoteViewsFactory {

    override fun getViewAt(position: Int): RemoteViews? {
        val views = RemoteViews(context.packageName, R.layout.widgetlistitem)
        val intent1 = context.intentFor<MyService>(ACTION to "1")
        views.setOnClickFillInIntent(R.id.widget_button, intent1)
        val intent2 = context.intentFor<MyService>(ACTION to "2")
        views.setOnClickFillInIntent(R.id.widget_item_background, intent2)
        return views
    }
    ... (rest of the methods)
}

widgetlistitem.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/widget_item_background"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="2dp"
android:background="@drawable/card"
android:clickable="true"
android:focusable="true">

<Button
    android:id="@+id/widget_button"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentEnd="true"
    android:layout_alignParentTop="true"
    android:layout_margin="8dp"
    android:text="Jetzt" />
</RelativeLayout>

widget_list.xml
<?xml version="1.0" encoding="utf-8"?>
<ListView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/widget_list"
android:layout_width="match_parent"
android:layout_height="wrap_content"
tools:listitem="@layout/widgetlistitem">
</ListView>