text:
Q: XAML designer does not work when using a WCF service I just began doing my first steps with WCF services and made up a little WPF application that displays data retrieved from a WCF service. I split the application into two projects: a project containing the (WPF) UI and a second project containing the WCF service client.
After copying the endpoint definition from the app.config of the second project to the app.config of the first project (which is, of course, the StartUp project) the application is running now.
But since I began using the WCF service client, the XAML designer does not work anymore. It always shows the exception:
Could not find default endpoint element that references contract 'MyContract' in the ServiceModel client configuration section. This might be because no configuration file was found for your application, or because no endpoint element matching this contract could be found in the client element.
This is exactly the same exception that I got before copying the endpoint definition to the other app.config file. So I guess the XAML designer doesn't use this configuration. Is it possible to fix this weird behavior? It would be okay for me if the XAML designer won't use the WCF at all (which it shouldn't do anyway IMHO) and just use some default data.
I already thought about stubbing the WCF service client in the DesignerMode case using RhinoMocks, but stubbing the asynchronous WCF calls isn't the easiest thing to do.
Any ideas?

A: I found out how to avoid the problem: It seems that the XAML designer doesn't work if I call anything on my business object which does the WCF communication from the ViewModel's constructor (which is defined as DataContext in the main window's XAML file).
A simple
if (DesignerProperties.GetIsInDesignMode(new DependencyObject()))
{
    return;
}

before accessing the business object makes the XAML designer work again.

A: Also - the converse works; ie, by moving the service reference stuff to the 'main' app.config it can be found by the 'child' project.

A: Had the same problem.
My solution was to move view model assignment from xaml to .cs code file.
Step 1: remove in your xaml:
<Window.DataContext>
    <viewModel:MainViewModel/>
</Window.DataContext>

Step 2: add to your window constructor in .cs code file:
DataContext = new MainViewModel();


text:
Q: Wordpress navigation style like Android Market WEBSITE I'm pretty new to wordpress, html, css, and javascript and would love your help if possible:
I'm trying to get the wp_nav_menu for my site to resemble the tabs from https://market.android.com/books.  The tabs are layered, change color on hover, and load the contents of the tab without navigating away from the page (I DO NOT NEED THIS FUNCTION).
Any help would be much appreciated.

A: You would do well to download Firebug or use Chrome developer tools to inspect the CSS and markup of the page. It's the best way to find out exactly how someone is getting a specific effect.
That being said, there are a couple things in play here.
The actual shape of the tabs is being created with a neat trick that uses borders to create shapes. In this case, the markup for the tabs is just an unordered list with spans for the tab text. Using border-bottom and border-right, the shape of the tabs is created:
border-bottom: 24px solid #3D3D3D;
border-right: 24px solid transparent;

The tabs are then given a negative right margin to cause them to overlap with each other:
margin-right: -12px;

Finally, all tabs except for the selected tab are given an opacity of 0.35, which causes the transparency you see:
opacity: 0.35;

EDIT: Wow, I somehow completely overlooked the fact that you are using WordPress. I'm not familiar with WP, but assuming that the nav can be output as an unordered list with spans containing the text, you should be just fine. This is a pretty standard way to do navigation, so all you really need is the CSS.

redpajama_set_name: RedPajamaStackExchange


text:
Q: TWRP breaks data partition (couldn't boot into ubuntu touch) I followed this guide: https://forums.ubports.com/topic/4964/fairphone-3-fp3
downloaded stable GITLAB CI
I flashed boot.img and system.img, also used TWRP, stuck at android bootloader start screen
flashed boot.img and system.img again, stuck at start again
I also tried an older one but - nothing
Now I need a step-by-step guide from YOU and much help
thank you for help!!!
The Problem was that twrp broke the data partition and the recovery repaired it so when ubuntu-touch doesn't boot, you have to try this.

A: It works if you start recovery one time!!!!
Just wait a bit and when screen color changes you win

A: The port of Ubuntu Touch for the Fairphone 3 is not yet daily driver ready, it's still pretty much under developement, as you can see on the UBports forum page for the Halium 10 based port, some pretty relevant stuff like the ability to play media (video and audio) is still not working. The page also has instructions for flashing, and people discussing issue they had while doing it.


text:
Q: How do you inflate an XML layout in android? I'm writing an android application which starts of as a listview, for which I've written a class that extends ArrayAdapter, populating each row from a database. When an Item in the list is clicked, it fires an intent to another class which I want to list the details of the item clicked, so I can inflate the view with the item details. For now I just want to inflate one TextView as follows.
<TextView
    android:id="@+id/name"
    android:textColor="#FFFFFF"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
/>

How would I go about writing the class for a details page which only establishes itself after receiving an intent? Do I need to extend something to override the getView method?

A: For inflating you can use
public View myView()
{
    View v;
    LayoutInflater inflater = (LayoutInflater) getBaseContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    v = inflater.inflate(R.layout.prob3_layout, null);
    return v;
}

A: You need to create Custom Adapter to show your Values in List View.
Check out this Custom List in Android
Let me know if you find any difficulty.

A: Generally what you want to do is write another Activity (a details Activity). You will have a corresponding view (XML) to go with this activity. You pass the id of the item clicked through a Bundle. Here is another question which shows hows to pass data to another Activity (through an Intent).
So you would build a new view to show the details. In your new DetailsActivity.java that extends Activity, in your onCreate you would call setContent(R.layout.detailsView) - where R.layout.detailsView corresponds to an xml you created.


text:
Q: auth::attempt method not defined Auth seems to have no method called attempt, here is my code, im using codeception unit test with cest:
use Illuminate\Support\Facades\Session;
use Illuminate\Support\Facades\Auth;
use Illuminate\Routing\Controller;

class ReportCest
{
    protected $valid_email = 'email@gmail.com';
    protected $valid_password = 'pass';

    public function _before(UnitTester $I)
    {
        Auth::attempt([
               'email' => $this->valid_email,
               'password' => $this->valid_password
        ]);
    }
}

In the Illuminate\Foundation\Auth\AuthenticatesAndRegistersUsers.php used:
$this->auth->attempt($credentials, $request->has('remember')
i wonder how could i implement it like this

A: after these lines
use Illuminate\Support\Facades\Session;
use Illuminate\Support\Facades\Auth;
use Illuminate\Routing\Controller;

type this
use Auth;

or try this way
\Auth::attempt(.....

A: Try this, define Auth before the class definition
use Auth;


text:
Q: How does a crystal radio headset act as a lowpass filter to remove the carrier wave.? I saw a similar question " How can a diode act as a detector in a crystal receiver"  but one of the comments said "after the diode splits the wave form to the top half ...the carrier must still be removed from the signal". The implication was that the headset did this.
I though a kind person would take me through the steps again just beginning in front of the diode so I don't miss anything.  Thank you much

A:
web specs
Impedance: 20K ohm
Resistance: 20M ohm
Capacitance: 15,000 pf
Sensitivity: 57db at 1KHz
Frequency Range: 200 - 8,000Hz
Operation Temperature: -20 to 60 degree Celsius
Wire: 42-inch Molded twisted Wire
Connector: Tinned Leads for DIY Connections

So it is the large wafer ceramic crystal capacitance that filters out the carrier after rectification.
The 20k impedance is the average vibration load impedance while at DC it is 20 MOhm.
Here's a poor response from a lousy diode.

When I was 10, my Dad made me a radio in the early 60's.  It was wound on a glass pickle jar, a crystal diode and a crystal earbud, with an antenna wire across the street to a tree to pick up AM radio a 100 miles away. Fortunately, no lightning and no batteries needed. It was my 2nd electronic inspiration. The 1st was picking up Texas TV on hot summer day in Flin Flon Mb, when I was 8 and the RCMP radio on the useless B/W TV with the VHF tuner.  XJG22

A: For a crystal radio, there is no real need for a low pass filter for carrier removal.
You can't hear the carrier, and the headphone can't react to it, so it is effectively ignored. Perhaps just consider that the audio channel to the headphone IS a low pass filter.
In some circuits you will find a capacitor after the diode rectifier and this charge storage effectively removes the carrier.
Here's one WITH a capacitor:

...and one WITHOUT a capacitor:

You would not hear any difference in the audio outputs.
Both from here with a dozen variations on the theme.

A: The crystal acts as half-wave rectifier.  Amplitude modulated signal after going through the crystal is severely distorted - the negative half cycles of the signal are replaced by zero voltage, but positive half cycles become through with only a little attenuated.
Half-wave rectified AM radio signal, when Fourier-analyzed, contains several frequency components summed:

*

*DC-component

*original audio signal which was inputted to the AM radio transmitter

*Hig frequency components at the transmitter's operating frequency Fx and its harmonics at 2Fx, 3Fx, 4Fx...(etc)

The DC component isn't hearable, it only pulls a little dimple to the diapraghms of the headphones, so small that it cannot be detected by watching.
The original audio signal is hearable. It can be considered as the variation of the rectified DC when the amplitude of the radio signal varies along the audio signal
High frequency distortion products of the rectification are well beyond the operating frequency range of the headphones. They are unhearable.


text:
Q: How to have only one tab open in wxribbon bar in wxpython? I am building a GUI and I am using wxribbon for wxpython. I want to have only one tab(ribbon page) in when user starts my app, from where user can dynamically add more pages or can add panels and buttons to a page. I am able to achieve all the dynamic parts of ribbon. The only problem I have is that I am unable to start with only one ribbon page. When I define only one page, I don't see the ribbon bar(tab bar), what I see is only the page. Now, when I define two page in the beginning, then I see the bar. Can someone tell me what I code have to change in wxribbon so that I am able to have a tab bar visible with only one page in it. Any help would be great. Thanks!. The sample code I am using to add a page is as follows :
import wxRibbon as RB
self._ribbon = RB.RibbonBar(self, id = wx.ID_ANY)
page_1 = RB.RibbonPage(self._ribbon, WORKPIECE, "Workpiece", Bitmap("eye.xpm"))
page_2 = RB.RibbonPage(self._ribbon, wx.ID_ANY, "New Tab", Bitmap("empty.xpm"))

A: You need the flag RIBBON_BAR_ALWAYS_SHOW_TABS
try this:
self._ribbon = RB.RibbonBar(self, wx.ID_ANY, agwStyle = RB.RIBBON_BAR_DEFAULT_STYLE | RB.RIBBON_BAR_ALWAYS_SHOW_TABS)


text:
Q: Using usb to connect Android to Pixhawk I am looking for a way to connect my pixhawk to an android device using the USB(OTG) cable.
After doing some research i figured there is two possible ways to do that. Either using the micro usb port on the pixhawk or just using a USB FTDI cable to use the telemetry port.
What i am asking if it would be possible to use dronekit android with either of those options ?
If yes which one would you recommend.
Thanks

A: I consider you wanna make a "flying Android"?
Android device is not a good onboard device because of its poor IO ports.But Android is a good device to be a ground station.
You can only use a USB FTDI to connect each other.The micro-usb on pixhawk is used to debug,your vehicle while not fly if pixhawk's micro-usb is in use.


text:
Q: Animation only happens one time public static Animator zoomInImage(ImageView smallImage, ImageView largeImage, long duration) {
    Rect startBounds    = new Rect();
    Rect endBounds      = new Rect();
    Point globalOffset  = new Point();

    smallImage.getGlobalVisibleRect(startBounds);
    largeImage.getGlobalVisibleRect(endBounds, globalOffset);

    startBounds.offset(-globalOffset.x, -globalOffset.y);
    endBounds.offset(-globalOffset.x, -globalOffset.y);

    float startScale;
    if ((float) endBounds.width() / endBounds.height()
            > (float) startBounds.width() / startBounds.height()) {
        // Extend start bounds horizontally
        startScale = (float) startBounds.height() / endBounds.height();
        float startWidth = startScale * endBounds.width();
        float deltaWidth = (startWidth - startBounds.width()) / 2;
        startBounds.left -= deltaWidth;
        startBounds.right += deltaWidth;
    } else {
        // Extend start bounds vertically
        startScale = (float) startBounds.width() / endBounds.width();
        float startHeight = startScale * endBounds.height();
        float deltaHeight = (startHeight - startBounds.height()) / 2;
        startBounds.top -= deltaHeight;
        startBounds.bottom += deltaHeight;
    }

    smallImage.setAlpha(0f);

    largeImage.setPivotX(0f);
    largeImage.setPivotY(0f);

    AnimatorSet animatorSet = new AnimatorSet();

    animatorSet
            .play(ObjectAnimator.ofFloat(largeImage, View.X, startBounds.left, endBounds.left))
            .with(ObjectAnimator.ofFloat(largeImage, View.Y, startBounds.top, endBounds.top))
            .with(ObjectAnimator.ofFloat(largeImage, View.SCALE_X, startScale, 1f))
            .with(ObjectAnimator.ofFloat(largeImage, View.SCALE_Y, startScale, 1f));

    animatorSet.setDuration(duration);
    animatorSet.setInterpolator(new DecelerateInterpolator());
    animatorSet.start();
    largeImage.setVisibility(View.VISIBLE);
    return animatorSet;

}

public static Animator zoomOutImage(final ImageView smallImage, final ImageView largeImage, long duration) {
    Rect startBounds    = new Rect();
    Rect endBounds      = new Rect();
    Point globalOffset  = new Point();

    smallImage.getGlobalVisibleRect(startBounds);
    largeImage.getGlobalVisibleRect(endBounds, globalOffset);

    startBounds.offset(-globalOffset.x, -globalOffset.y);
    endBounds.offset(-globalOffset.x, -globalOffset.y);

    float startScale;
    if ((float) endBounds.width() / endBounds.height()
            > (float) startBounds.width() / startBounds.height()) {
        // Extend start bounds horizontally
        startScale = (float) startBounds.height() / endBounds.height();
        float startWidth = startScale * endBounds.width();
        float deltaWidth = (startWidth - startBounds.width()) / 2;
        startBounds.left -= deltaWidth;
        startBounds.right += deltaWidth;
    } else {
        // Extend start bounds vertically
        startScale = (float) startBounds.width() / endBounds.width();
        float startHeight = startScale * endBounds.height();
        float deltaHeight = (startHeight - startBounds.height()) / 2;
        startBounds.top -= deltaHeight;
        startBounds.bottom += deltaHeight;
    }

    largeImage.setPivotX(0f);
    largeImage.setPivotY(0f);

    AnimatorSet animatorSet = new AnimatorSet();

    animatorSet
            .play(ObjectAnimator.ofFloat(largeImage, View.X, startBounds.left))
            .with(ObjectAnimator.ofFloat(largeImage, View.Y, startBounds.top))
            .with(ObjectAnimator.ofFloat(largeImage, View.SCALE_X, startScale))
            .with(ObjectAnimator.ofFloat(largeImage, View.SCALE_Y, startScale));

    animatorSet.setDuration(duration);
    animatorSet.setInterpolator(new DecelerateInterpolator());
    animatorSet.addListener(new AnimatorListenerAdapter() {
        @Override
        public void onAnimationEnd(Animator animation) {
            smallImage.setAlpha(1f);
            largeImage.setVisibility(View.INVISIBLE);
        }

        @Override
        public void onAnimationCancel(Animator animation) {
            smallImage.setAlpha(1f);
            largeImage.setVisibility(View.INVISIBLE);
        }
    });
    animatorSet.start();

    return animatorSet;
}

The above two function is for animating zoomIn and zoomOut of image. The problem with above code is the zoomIn animation is happening one once that is at the beginning but not on later time. While zoomOut is working. The zoomIn and zoomOut function is being called on click action on image.
The behaviour is like on click of small image animation to zoom is correct and on click of large image animation to zoom out is also correct but when small image is clicked again the large image appears suddenly.
I am calling it like this
lImageView.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        if (currentAnim != null) currentAnim.cancel();
        currentAnim = ZoomAnimator.zoomOutImage(sImageView, lImageView, getResources().getInteger(
                android.R.integer.config_shortAnimTime));
    }
});

sImageView.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        if (currentAnim != null) currentAnim.cancel();
        currentAnim = ZoomAnimator.zoomInImage(sImageView, lImageView, getResources().getInteger(
                android.R.integer.config_shortAnimTime));
    }
});

A: I think your implementation is too complicated. Try to use Transition API from androidx (support) package, animations with it are much easier. Call TransitionManager.beginDelayedTransition then change view scale. There is default ChangeTransform transition which handle scale changes.
import androidx.transition.ChangeTransform;
import androidx.transition.Transition;
import androidx.transition.TransitionManager;

private void onClick() {
    View imageView = findViewById(R.id.imageView);
    ViewGroup parent = findViewById(R.id.parent);

    Transition transition = new ChangeTransform();
    transition.setDuration(600);
    transition.addTarget(R.id.imageView);

    TransitionManager.beginDelayedTransition(parent, transition);
    float scale = zoom ? 1 : 0.5f;
    imageView.setScaleX(scale);
    imageView.setScaleY(scale);
}

R.id.parent is parent ViewGroup of ImageView. Here is result:

Cool thing is that you can click on image in the middle of previous animation. TransitionManager will start new animation from current view scale values.


text:
Q: Orthogonal projection theorem in case of incomplete space Prove that every incomplete inner product space $H$ has a closed vector subspace $H_0$ such that $H≠H_0⊕H_0^\perp$.
I can't come up with a universal construction of such a subspace for any incomplete inner product space. Maybe we can somehow use here fact that there a Coushy sequense that doesn't converge to the element of this space?

A: Suppose that $H$ is not complete, and let $\hat{H}$ be the completion of $H$. Choose $\hat{x}\in \hat{H}\setminus H$. Let $H_0=\{ x \in H : \langle x,\hat{x}\rangle_{\hat{H}} = 0 \}$. $H_0$ is closed in $H$ and $H_0 \ne H$ because $H$ is dense in $\hat{H}$ and $\hat{x}\ne 0$. Furthermore,
$          H_0^{\perp_{H}}=\{ x \in H : x\perp H_0 \} = \{0\}.
$
So $H_0 \oplus H_0^{\perp_{H}} =H_0\oplus\{0\}\ne H$.


text:
Q: Using knockoutjs data-bind on nested ul I tried to use a foreach data-bind on buttons. The button I tried to generate for each record have its own list of options thanks to the foundation split button.
The problem is that the inner ul doesn't access the correct item binded.
I wrote a little example program to show the problem:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Try</title>
    <link rel="stylesheet" href="css/foundation.css" />

persons

Remove

When clicking on the button itself the person object is the correct one, clicking on the arrow and choosing remove will result in always removing the last object and not the chosen one.

A: The remove menu item appears to be shared among the buttons, so the way to tell it which one it is affecting is to remember the last clicked.
var lastClicked;

self.removePerson = function () {
    self.persons.remove(lastClicked);
};

self.presentPerson = function () {
    var person = this;
    window.alert(person.name + " " + person.age);
    lastClicked = person;
};

Fiddle here.

A: In order to avoid sharing one menu between all buttons, you need to have unique id's for them. In Knockout, we usually do that using $index.
In order for the DOM items to all be present in time for foundation's initialization, I moved the foundation call to after ko.applyBindings. It would probably be a good idea to make a custom binding handler that applies foundation to DOM items that get updated or whatever, but this was sufficient for this exercise.

// This is a simple *viewmodel* - Java0Script that defines the data and behavior of your UI
function AppViewModel() {
    var self = this;

    self.persons = ko.observableArray([{
        name: 'Bert',
        age: 30,
        hobbies: ["music", "computers"]
    }, {
        name: 'Charles',
        age: 31,
        hobbies: ["sports"]
    }, {
        name: 'Denise',
        age: 32,
        hobbies: ["art", "fashion", "games"]
    }]);

    self.removePerson = function (data) {
        console.debug("Remove", data, this);
        self.persons.remove(this);
    };

    self.presentPerson = function () {
        var person = this;
        window.alert(person.name + " " + person.age);
    };
}

// Activates knockout.js
ko.applyBindings(new AppViewModel());
// Init foundation
$(document).foundation();

<link href="//cdnjs.cloudflare.com/ajax/libs/foundation/5.5.3/css/foundation.min.css" rel="stylesheet"/>

persons

Remove


text:
Q: Generate points which lie on linestring in geopandas Lets say that I have the following geodataframe:
import geopandas as gpd
from shapely.geometry import LineString

line = LineString([(2.2, 4.2), (7.2, -25.1), (9.26, -2.456)])
gdf = gpd.GeoDataFrame(index=[0], crs='epsg:4326', geometry=[line])

Now what I want to achieve is to generate, lets say, 100 points that randomly lie on this linestring given in gdf. And then create another geodataframe which only includes these points.
Is it possible?
Best

A: *

*clearly a LineString has multiple straight line segments

*generate points on each segment that are linearly spaced

*randomly select some of the points generated along each segment

*have visualised to make it clear using folium
import geopandas as gpd
from shapely.geometry import LineString, Point
import numpy as np

line = LineString([(2.2, 4.2), (7.2, -25.1), (9.26, -2.456)])
gdf = gpd.GeoDataFrame(index=[0], crs="epsg:4326", geometry=[line])

N_POINTS = 20
POINTS_PER_SEGMENT = 100
# generate points per segment and randomly select N of them
gdf2 = gpd.GeoDataFrame(
    geometry=np.random.choice(
        [
            Point(x, y)
            for p1, p2 in zip(line.coords, line.coords[1:]) # iterate through line segments
            for x, y in zip(
                np.linspace(p1[0], p2[0], POINTS_PER_SEGMENT),
                np.linspace(p1[1], p2[1], POINTS_PER_SEGMENT),
            )
        ],
        N_POINTS,
    ),
    crs="epsg:4386",
)

m = gdf.explore(color="red", height=300, width=500)
gdf2.explore(m=m)


text:
Q: Shapes from different sources are offset I am looking for a reliable shapefile of the Seoul Capital Area (SCA), comprising Seoul, Incheon and Gyeonggi-do provinces. One common source is GADM. However, the coastline is not up-to-date so I have found another source in Korea's NSDI (in Korean) which includes a more up-to-date coastline. (I attach the files, as they are not accessible outside Korea.)
However, I find that the datasets are substantially non-aligned, so I wonder if I have made a mistake or whether the problem lies in one of the sources. As can be seen on the map below, the GADM regions (black outline) display a significant shift to the south of the NSDI regions (red outline). The shift appears to increase in the eastward direction, westernmost Incheon being well aligned, which makes me suspect that this is a projection issue. Perhaps, the wrong CRS is being applied somewhere.

Here's my code:
library(sf)

#***1 GADM data processing***

#Load GADM shapefile
sca_gadm <- readRDS("gadm36_KOR_1_sf.rds") #class "sf" "data.frame"

#Subset SCA
sca_gadm <- sca_gadm[sca_gadm$NAME_1 %in% c("Seoul", "Incheon", "Gyeonggi-do"),]

#Flatten coordinate system
sca_gadm <- st_transform(sca_gadm, 5179)

#Remove Incheon outlying polygon error (courtesy of https://gis.stackexchange.com/a/359722/88704)

#Inspect coordinates of bounding box
(bb <- st_bbox(sca_gadm)) #class "bbox"
#xmin      ymin      xmax      ymax
#844186.2 1677674.0 1141187.7 2024763.7

#Add 50000 to ymin to make sure outlying area is outside coordinates
bb[2] <- bb[2] + 50000

#Crop SCA with bb polygon
sca_gadm <- st_intersection(sca_gadm, st_as_sfc(bb))

#***2 NSDI data processing***

#Dissolve NSDI sub-regions for comparison with GADM (courtesy of https://gis.stackexchange.com/a/361510/88704)

#Load, buffer, dissolve, reverse buffer: Seoul
sel_nsdi <- cbind(st_read("LARD_ADM_SECT_SGG_11.shp"), Name="Seoul")
sel_nsdi <- st_buffer(sel_nsdi, 35)
sel_nsdi$geometry <- st_union(sel_nsdi$geometry)
sel_nsdi <- st_buffer(sel_nsdi, -35)

#Load, buffer, dissolve, reverse buffer: Incheon
inc_nsdi <- cbind(st_read("LARD_ADM_SECT_SGG_28.shp"), Name="Incheon")
inc_nsdi <- st_buffer(inc_nsdi, 25)
inc_nsdi$geometry <- st_union(inc_nsdi$geometry)
inc_nsdi <- st_buffer(inc_nsdi, -25)

#Load, buffer, dissolve, reverse buffer: Gyeonggi-do
ggd_nsdi <- cbind(st_read("LARD_ADM_SECT_SGG_41.shp"), Name="Gyeonggi-do")
ggd_nsdi <- st_buffer(ggd_nsdi, 50)
ggd_nsdi$geometry <- st_union(ggd_nsdi$geometry)
ggd_nsdi <- st_buffer(ggd_nsdi, -50)

#Combine sub-regions into SCA
sca_nsdi <- rbind(sel_nsdi, inc_nsdi, ggd_nsdi)

#***3 Overlay GADM and NSDI regions***

#Both datasets share same EPSG:5179
st_crs(sca_nsdi, parameters=T)$epsg==st_crs(sca_gadm, parameters=T)$epsg

#Plot Overlaying regions
plot(sca_nsdi$geometry, border="red")
plot(sca_gadm$geometry, add=T)


text:
Q: SOAP over HTTP Web Services and timeouts I have a few specific questions about web services (SOAP over HTTP):

*

*A client calls a web service. If, in the middle of the call, the client terminates it's own connection, is the server aware that the connection was terminated?

*This is more of a HTTP question. Is is possible for a client to call a web service and be forced to wait for some amount of time before the processing actually occurs? For example, if I have a web service generated on a server, is it possible for the call to get stuck before it hits my implementation code? Perhaps the thread pool for the servlets are too busy? I equate this to when a website gets slammed from traffic (i.e. the Slashdot effect).

Thanks a lot!

A: 1) Yes, when thinking of HTTP (which in nearly all cases is over Tcp), a client close() will trigger a close of communication and server connection will be released (see also Tcp protocol).
2) For most server implementations, there is a maximum size of parallel workers (e.g. thread-pool size). That is why long running server execution time can be bad, because it is blocking incoming request if all threads are busy (and clients hitting reload all over again, which makes it even more severe). The way to deal with this is setting timeouts (both on client and server side). Finding the right timeout is not trivial, it highly depends on your use-case.


text:
Q: C# How to spawn Enemies and move them? I am trying to spawn enemies and move them from left to right with a timer how can i do this?
Example:
int count;
timer (every 1 sec)
{
    Enemy somename+count = new Enemy();
    count++;
}

timer (every 0.001 sec)
{
    somename+count.x++;
}

A: If this is an assignment, and to get it up and running. Just use the Timer class.
You will not get as high resolution as 1000hz (1ms) as you wished for the movement though.
Documentation: Timer class
        var timerCreate = new Timer {Interval = 1000};
        timerCreate.Tick += delegate(object o, EventArgs args)
        {
            // create them
        };

        var timerAction = new Timer {Interval = 50};
        timerAction.Tick += delegate(object o, EventArgs args)
        {
            // move them
        };

A: As you are creating, the enemies inside a local scope, you cannot access them, once you get out of the loop. Instead, have a list and add your newly spawned enemies to this list.
Maintain two threads for doing your two tasks.
1) Thread - 1 will add spawn enemies add adds enemies to our list.
2) Thread -2 will move the enemies in our spawned list.
But, as out list is a shared resource between both the threads, always access the list using 'locks'.

A: Your fundamental problem seems to be lacking a way to store references to all of your enemies.  Generics and collections provide a solution to this type of problem.  I'll use a List<T>, which is the most basic such collection.  There are many others, however, that each have their own useful properties.
Consider :
private class Enemy
{
    public int position;
}

private List<Enemy> enemyList = new List<Enemy>();

private void timer1_Tick(object sender, EventArgs e)
{
    enemyList.Add(new Enemy());
}

private void timer2_Tick(object sender, EventArgs e)
{
    foreach(Enemy enemy in enemyList)
    {
        enemy.position++;
    }
}

Also consider that updating a large list of visual objects every 0.001 second is useless and wasteful.  One millisecond updates correspond to 1000fps.  No video device will update that fast and no human being can see that fast.  Generally, for real-time updates you should aim to update between 30-60fps.  That corresponds to no more frequently than about 0.016s (16ms).


text:
Q: Subscribe to log4net messages From what I can tell, all of the existing log4net appenders are designed to push messages. I have an application with multiple services, and I want to make it easy for devs to subscribe to log messages on-demand.
There are a couple of benefits to this approach:

*

*Low overhead when no one is subscribed

*No need to open up firewall ports on the subscriber side

*No need to turn appenders on/off at runtime

One thought I have is to use UDP to push all of the messages to a central location, and have that server set up to allow SignalR clients to subscribe.
I'm hoping there are existing solutions. This seems like a common scenario.

A: I'm not aware of any exciting solution using UDP to push the logs. However log4net appenders are really easy to write.
To comment on your benefits:
•Low overhead when no one is subscribed
This is not really true, you still have to do all appender logic in the log4net application. Your program is not aware of if someone is subscribed.
•No need to open up firewall ports on the subscriber side
Messages are leaking on your network, anyone can get them. You have to recheck all logging on security information.
•No need to turn appenders on/off at runtime
Appenders are running all the time, so they will have a performance impact on your application. Log4net is light wait, but the more you log and push even debug information, it will not improve your performance.

A: I couldn't find an existing solution, so I created my own:
log4stuff.com


text:
Q: Optimizing a nested for-loop which uses the indices of an array for function Let's imagine an empty NumPy array of 3x4 where you've got the coordinate of the top-left corner and the step size in horizontal and vertical direction.
Now I would like to know the coordinates for the middle of each cell for the whole array. Like this:

For this I implemented a nested for-loop.
In [12]:
import numpy as np
# extent(topleft_x, stepsize_x, 0, topleft_y, 0, stepsize_y (negative since it's top-left)
extent = (5530000.0, 5000.0, 0.0, 807000.0, 0.0, -5000.0)

array = np.zeros([3,4],object)
cols = array.shape[0]
rows = array.shape[1]

# function to apply to each cell
def f(x,y):
return x*extent[1]+extent[0]+extent[1]/2, y*extent[5]+extent[3]+extent[5]/2

# nested for-loop
def nestloop(cols,rows):
    for col in range(cols):
        for row in range(rows):
            array[col,row] = f(col,row)

In [13]:
%timeit nestloop(cols,rows)
100000 loops, best of 3: 17.4 µs per loop

In [14]:
array.T
Out[14]:
array([[(5532500.0, 804500.0), (5537500.0, 804500.0), (5542500.0, 804500.0)],
       [(5532500.0, 799500.0), (5537500.0, 799500.0), (5542500.0, 799500.0)],
       [(5532500.0, 794500.0), (5537500.0, 794500.0), (5542500.0, 794500.0)],
       [(5532500.0, 789500.0), (5537500.0, 789500.0), (5542500.0, 789500.0)]], dtype=object)

But eager to learn, how can I optimize this? I was thinking of vectorizing or using lambda. I tried to vectorize it as follow:
array[:,:] = np.vectorize(check)(cols,rows)
ValueError: could not broadcast input array from shape (2) into shape (3,4)

But, than I got a broadcasting error. Currently the array is 3 by 4, but this also can become 3000 by 4000.

A: Surely the way you are computing the x and y coordinates is highly inefficient because it's not vectorized at all. You can do:
In [1]: import numpy as np

In [2]: extent = (5530000.0, 5000.0, 0.0, 807000.0, 0.0, -5000.0)
   ...: x_steps = np.array([0,1,2]) * extent[1]
   ...: y_steps = np.array([0,1,2,3]) * extent[-1]
   ...:

In [3]: x_coords = extent[0] + x_steps + extent[1]/2
   ...: y_coords = extent[3] + y_steps + extent[-1]/2
   ...:

In [4]: x_coords
Out[4]: array([ 5532500.,  5537500.,  5542500.])

In [5]: y_coords
Out[5]: array([ 804500.,  799500.,  794500.,  789500.])

At this point the coordinates of the points are given by the cartesian product() of these two arrays:
In [5]: list(it.product(x_coords, y_coords))
Out[5]: [(5532500.0, 804500.0), (5532500.0, 799500.0), (5532500.0, 794500.0), (5532500.0, 789500.0), (5537500.0, 804500.0), (5537500.0, 799500.0), (5537500.0, 794500.0), (5537500.0, 789500.0), (5542500.0, 804500.0), (5542500.0, 799500.0), (5542500.0, 794500.0), (5542500.0, 789500.0)]

You just have to group them 4 by 4.
To obtain the product with numpy you can do (based on this answer):
In [6]: np.transpose([np.tile(x_coords, len(y_coords)), np.repeat(y_coords, len(x_coords))])
Out[6]:
array([[ 5532500.,   804500.],
       [ 5537500.,   804500.],
       [ 5542500.,   804500.],
       [ 5532500.,   799500.],
       [ 5537500.,   799500.],
       [ 5542500.,   799500.],
       [ 5532500.,   794500.],
       [ 5537500.,   794500.],
       [ 5542500.,   794500.],
       [ 5532500.,   789500.],
       [ 5537500.,   789500.],
       [ 5542500.,   789500.]])

Which can be reshaped:
In [8]: product.reshape((3,4,2))   # product is the result of the above
Out[8]:
array([[[ 5532500.,   804500.],
        [ 5537500.,   804500.],
        [ 5542500.,   804500.],
        [ 5532500.,   799500.]],

       [[ 5537500.,   799500.],
        [ 5542500.,   799500.],
        [ 5532500.,   794500.],
        [ 5537500.,   794500.]],

       [[ 5542500.,   794500.],
        [ 5532500.,   789500.],
        [ 5537500.,   789500.],
        [ 5542500.,   789500.]]])

If this is not the order you want you can do something like:
In [9]: ar = np.zeros((3,4,2), float)
    ...: ar[0] = product[::3]
    ...: ar[1] = product[1::3]
    ...: ar[2] = product[2::3]
    ...:

In [10]: ar
Out[10]:
array([[[ 5532500.,   804500.],
        [ 5532500.,   799500.],
        [ 5532500.,   794500.],
        [ 5532500.,   789500.]],

       [[ 5537500.,   804500.],
        [ 5537500.,   799500.],
        [ 5537500.,   794500.],
        [ 5537500.,   789500.]],

       [[ 5542500.,   804500.],
        [ 5542500.,   799500.],
        [ 5542500.,   794500.],
        [ 5542500.,   789500.]]])

I believe there are better ways to do this last reshaping, but I'm not a numpy expert.
Note that using object as dtype it's a huge performance penalty, since numpy cannot optimize anything (and is sometimes slower than using normal lists). I have used a (3,4,2) array instead which allows faster operations.


text:
Q: gzip_http_version 1.1; in Nginx, when using HTTP/2 In an Nginx server block of a site aimed to work with HTTP/2, I've seen this:
gzip_http_version 1.1;

Can this make some conflict with some packets sent in HTTP/2?
I don't understand this Gzip directive hence I can't say if HTTP/2 packets could be affected by it.

A: gzip_http_version is the minimum version of the HTTP protocol of the request (coming from client) needed to compress the response from server. It defaults to 1.1.
So, any user agent that is sending request using protocol version 1.0, won't get the response compressed from server; the response would go as-is. Note that, setting the value to 1.1 would probably hurt very very tiny subset of crowd (probably someone with Win XP, which is unsupported now BTW), if any.
To answer your question:

Can this make some conflict with some packets sent in HTTP/2?

No, as nginx would handle requests differently based on the value of $server_protocol variable (one of HTTP/1.0, HTTP/1.1, HTTP/2.0).

As a side note, as Transfer-Encoding header is not supported in HTTP/1.0 you should not set gzip_http_version to 1.0. Otherwise, you would not get keepalives as Content-Length header is not set when gzip_http_version is used; HTTP/1.1 tackles this using Transfer-Encoding: chunked header.


text:
Q: ¿Como saber si el primer caracter de un String es un int? Mi problema como el título lo indica deseo saber si el primer caracter de un String es un número 9. Tengo el siguiente código pero quiero saber si se puede optimizar:
String palabra = "9394";
if(palabra != null && palabra.contains("9")){
    int index = palabra.indexOf("9");
    if(index == 0){
         System.out.println("9 es la primera letra");
    }
}

A: Puedes utilizar string.charAt(0) que te permite obtener el primer carácter del string.
if (string.charAt(0) = '9') {
// Tu codigo
}

.charAt(index) Recordar que devuelve un tipo char.

Información Adicional: si quieres saber si el primer carácter es un dígito, no importa cual (no solo 0 a 9, todos los del unicode):
Character.isDigit(string.charAt(0))

A: Hay varias formas de hacer lo que quieres. Quizá lo más sencillo sea usar substring, pues al parecer no interesa una conversión de tipos, sino solamente verificar que el primer carácter es 9 o no.
Te muestro un ejemplo, usando también un operador ternario, el cual puede ser muy útil para estos casos, ayudando a simplificar código.
    String palabra = "9394";
    String laPrimera=palabra.substring(0, 1);
    String esNueve=(palabra != null && laPrimera.equals("9")) ? "Es nueve: " : "No es nueve, es: ";
    System.out.println(esNueve+laPrimera);

Salida:
Es nueve: 9

Si probásemos por ejemplo con este valor: "1394", la salida sería:
No es nueve, es: 1


text:
Q: One Function for all DB Queries PHP i'm working with PHP for some weeks now and with the time i am asking myself, if it is possible to handle all database-queries (SELECT, UPDATE, INSERT, DELETE) with a single function.
At the moment i have round about 30x of these "try-catch" PDO's to communicate with my database:
//DB connection info already set...

    try {

        $exc = $this->dbh->prepare("SELECT uid FROM users WHERE email = :mail");

        $exc->bindParam(':mail', $mail, PDO::PARAM_STR);

        $exc->execute();
        $exc->setFetchMode(PDO::FETCH_ASSOC);

        while ($row = $exc->fetch()) {
            // do something with $row['uid']
        }

        $this->dbh = null;
        $exc = null;

    } catch (PDOException $e) {
        echo $e;
        $this->dbh = null;
        $exc = null;
    }

Is there a way to minify this code by using a single function and do i or the server get any profit of this ?
Thank you, Louis

A: Like I said in my comment, your code is already quite good, but there are a couple places where you could reduce the amount of boilerplate you're writing.
// You can set the default fetch mode in the constructor
$this->dbh = new PDO($cstr, $user, $pass, [PDO::DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC]);

try {
    $exc = $this->dbh->prepare("SELECT uid FROM users WHERE email = :mail");

    // you don't have to explicitly bind your parameters
    // and you can feed them directly to execute()
    $exc->execute([':mail' => $mail]);

    while ($row = $exc->fetch()) {
        // do something with $row['uid']
    }
} catch (PDOException $e) {
    echo $e;
} finally {
    // 'finally' blocks are always executed
    $this->dbh = null;
    $exc = null;
}

However:

*

*I'm not sure why you're setting $this->dbh and $exc to null at the end.

*

*$exc will be dereferenced when it goes out of scope, eg: at the end of the enclosing function, and then garbage-collected later.

*The same goes for $this->dbh when its containing object goes out of scope, and what if you want/need to use it elsewhere in the class? Please don't tell me that you reinitialize it repeatedly.

*Unless you're ludicrously low on RAM and need to immediately recover the literal handful of bytes from these objects there's no reason to explicitly unset them.

*Don't catch an Exception that you're not doing anything with.

*

*By only echoing the error message and letting execution continue in a broken/unexpected state you're setting yourself up for more trouble down the line.

*Let the Exception bubble up to higher, more general layer, or just don't catch it at all and let it cause execution to halt. You can use set_exception_handler() to define how your app deals with uncaught exceptions, eg: safely logging the details and/or showing a user-friendly error message.


text:
Q: passing quoted arguments from batch file to `powershell start` - self-elevation on demand I am writing a Windows batch file that automatically escalates itself to administrative permissions, provided the user clicks "Yes" on the User Access Control dialog that appears.
I am using a technique I learned here to detect whether we already have admin rights and another from here to escalate. When appropriate, the following script, let's call it foo.bat, re-launches itself via a powershell-mediated call to runas:
@echo off
net session >NUL 2>NUL
if %ERRORLEVEL% NEQ 0 (
powershell start -wait -verb runas "%~dpfx0" -ArgumentList '%*'
goto :eof
)

echo Now we are running with admin rights
echo First argument is "%~1"
echo Second argument is "%~2"
pause

My problem is with escaping quotes in the -ArgumentList.  The code above works fine if I call foo.bat one two from the command prompt, but not if one of the arguments contains a space, for example as in foo.bat one "two three" (where the second argument should be two words, "two three").
If I could even just get the appropriate behavior when I replace %* with static arguments:
powershell start -wait -verb runas "%~dpfx0" -ArgumentList 'one "two three"'

then I could add some lines in foo.bat that compose an appropriately-escaped substitute for %*.   However, even on that static example, every escape pattern I have tried so far has either failed (I see Second argument is "two" rather than Second argument is "two three") or caused an error (typically Start-Process: A positional parameter cannot be found that accepts argument 'two').  Drawing on the docs for powershell's Start-Process I have tried all manner of ridiculous combinations of quotes, carets, doubled and tripled quotes, backticks, and commas, but there's some unholy interaction going on between batch-file quoting and powershell quoting, and nothing has worked.
Is this even possible?

A: This is my batch for that purpose:
::ElevateMe.cmd::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
@echo off & setlocal EnableExtensions DisableDelayedExpansion
Set "Args=%*"
net file 1>nul 2>&1 || (powershell -ex unrestricted -Command ^
  Start-Process -Verb RunAs -FilePath '%comspec%' -ArgumentList '/c %~f0 %Args:"=\""%'
  goto :eof)
:: Put code here that needs elevation
Echo:%*
Echo:%1
Echo:%2
Pause

Sample output:
one "two three"
one
"two three"
Drücken Sie eine beliebige Taste . . .

If you want the elevated cmd to stay open, use -ArgumentList '/k %~f0 %Args:"=\""%

A: *

*You've run into a perfect storm of two quoting hells (cmd and PowerShell), garnished with a PowerShell bug (as of PowerShell Core 6.2.0).

*To work around the bug, the batch file cannot be reinvoked directly and must instead be reinvoked via cmd /c.

*LotPings' helpful answer, which takes that into account, typically works, but not in the following edge cases:

*

*If the batch file's full path contains spaces (e.g., c:\path\to\my batch file.cmd)

*If the arguments happen to contain any of the following cmd metacharacters (even inside "..."): & | < > ^; e.g., one "two & three"

*If the reinvoked-with-admin-privileges batch file relies on executing in the same working directory it was originally called from.

The following solution addresses all these edge cases. While it is far from trivial, it should be reusable as-is:
@echo off
setlocal

:: Test whether this invocation is elevated (`net session` only works with elevation).
:: If already running elevated (as admin), continue below.
net session >NUL 2>NUL && goto :elevated

:: If not, reinvoke with elevation.
set args=%*
if defined args set args=%args:^=^^%
if defined args set args=%args:<=^<%
if defined args set args=%args:>=^>%
if defined args set args=%args:&=^&%
if defined args set args=%args:|=^|%
if defined args set "args=%args:"=\"\"%"
powershell -NoProfile -ExecutionPolicy Bypass -Command ^
  " Start-Process -Wait -Verb RunAs -FilePath cmd -ArgumentList \"/c \"\" cd /d \"\"%CD%\"\" ^&^& \"\"%~f0\"\" %args% \"\" \" "
exit /b

:elevated

:: =====================================================
:: Now we are running elevated, in the same working dir., with args passed through.
:: YOUR CODE GOES HERE.

echo First argument is "%~1"
echo Second argument is "%~2"

pause

A: The only approved way to elevate is to use a manifest. This emulates Unix's SUDO.EXE.
To run a command and stay elevated
RunAsAdminconsole <Command to run>

To elevate current cmd window or create a new elevated one
RunAsAdminconsole

From https://pastebin.com/KYUgEKQv

REM Three files follow
REM RunAsAdminConsole.bat
REM This file compiles RunAsAdminconsole.vb to RunAsAdminconsole.exe using the system VB.NET compiler.
REM Runs a command elevated using a manifest
C:\Windows\Microsoft.NET\Framework\v4.0.30319\vbc "%~dp0\RunAsAdminconsole.vb" /win32manifest:"%~dp0\RunAsAdmin.manifest" /out:"%~dp0\RunAsAdminConsole.exe" /target:exe
REM To use
rem RunAsAdminconsole <Command to run>
pause

RunAsAdmin.manifest

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0">
<assemblyIdentity
    version="1.0.0.0"
    processorArchitecture="*"
    name="Color Management"
    type="win32"
/>
<description>Serenity's Editor</description>
<trustInfo xmlns="urn:schemas-microsoft-com:asm.v2">
<security>
    <requestedPrivileges>
        <requestedExecutionLevel level="requireAdministrator" uiAccess="false"/>
    </requestedPrivileges>
</security>
</trustInfo>
</assembly>

'RunAsAdminConsole.vb
'Change cmd /k to cmd /c to elevate and run command then exit elevation
imports System.Runtime.InteropServices
Public Module MyApplication

    Public Sub Main ()
        Dim wshshell as object
        WshShell = CreateObject("WScript.Shell")
        Shell("cmd /k " & Command())
    End Sub

End Module

----------------------------------------


text:
Q: SQL Server Windows authentication using other people's credential I'm trying to connect to a SQL Server database (where only Windows authentication is allowed) via Python. the Python part serves as a web API and the permission control is under AD group on the SQL server. Thus, instead of using my own identity, I need to use other's ones (provided their Windows username and password)
Assuming I'm user A and I try to log in to the server on behalf of user B. (Of course I know his Windows login). Firstly I'm using Python-ldap to get the authencation.
# This step runs successfully
conn_ladp = ldap.initialize("ldap://ladp_address:389")
login_str = 'userB@domain.com'
password = 'userB_pw'
handle = conn_ladp.simple_bind_s(login_str ,password)

Then I try to connect to the server
conn_sql = pyodbc.connect('DRIVER={ODBC Driver 13 for SQL Server};SERVER=server_name;Trusted_Connection=yes;')
cursor = conn_sql.cursor()
# I checked the permision, it's still using user A's identity.
cursor.execute('some query')

However it's still under my current identity (user A). Seems that there is some 'miscommunication' between the ldap and pyodbc. Could anyone help me figure out how to connect them and fix the problem? Thanks.


text:
Q: Equality regarding the square of the sample mean Given that $X_1,...,X_n$ is an i.i.d sample and its sample mean is $\overline X_n$, I have to prove the following equation:
\begin{equation*}
        \frac{n-1}{n} \sum_{i=1}^n(\overline{X}_{n-1,i}^2  - \overline{X}_n^2)^2 - \frac{\hat{\alpha}_2^2}{n^2(n-1)} = \frac{4 \overline X_n^2 \hat \alpha_2}{n}
-  \frac{4 \overline X_n \hat \alpha_3}{n(n-1)} + \frac{\hat \alpha_4}{n(n-1)^2}- \frac{\hat{\alpha}_2^2}{n^2(n-1)},
\end{equation*}
where $\overline X_{n-1,i} = \frac{1}{n-1} \sum_{j\neq i}^{n} X_j$, $\overline{X}_n^2$ is the square of the sample mean, and $\hat \alpha_k = \frac{1}{n-1} \sum_{i=1}^n (X_i - \overline X_n)^k$.
Can you help me proving this?
Thanks


text:
Q: make up with vs make up to vs make it up to Is there any difference in meaning between "to make up with someone" and " to make up to someone"?
I've also heard " I'll make it up to him." in an American TV show.
What role does that "it" play in that sentence? Does it mean the same as " I'll make up with(or to) him" ?

A: These are two different idiomatic expressions.
To "make up (with)" someone is to reconcile after a disagreement:

The couple was fighting all night but they made up before morning.
The estranged son made up with his father after his mother's death.

To "make it up to (someone)" means to offer redress for a wrong you have committed against them, or a favor they did for you.

Tom was late for his date, so he offered to make it up to her by taking her to a really nice restaurant the following week.
If you can babysit my son this evening, I promise to make it up to you sometime.

A: "Make up to someone" is incorrect. The other two are similar, but differ slightly.
"Make up with someone" is about resolution of a mutual disagreement or conflict. Perhaps both parties in a dispute, argument, or fight continue to harbor emotional negativity toward one another; one or both later decide to resolve the lingering issues, and one approaches the other for resolution. One person alone cannot fix a two-party issue, nor can one person alleviate both parties' negative feelings. As such, the "making up" (resolution) is a group activity, something you do together, hence the use of "with".
"Make it up to someone" is about a single person being wronged to some degree, often times to a second person's benefit. For example,

Hey man, can you cover my shift at work tomorrow? I have a friend in town and I'd like to meet up with him for a bit. I promise I'll make it up to you!

This request would inconvenience the person being asked, because they lose a day off should they agree to take the shift at work. But the requester is promising to "make it up to them" at a point in the future, perhaps by taking one of their shifts or with gifts or other favors. The requester exclusively benefited and the requestee was inconvenienced. Therefore the "making up" is not a group activity and thus we use "to" and not "with".

A: To "make up with someone" generally refers to an act of mutual forgiveness or sorting out of differences, like when a couple has a fight but they talk it through and as a result get back together.
To "make it up to someone" refers to an act of kindness or a favor done for someone because you have wronged them in the past. For example, if someone missed a friend's birthday they would "make it up to them" later by buying them lunch. "It" in that context refers to the bad deed that needs to be amended.

A: Actually, "make up to someone" is an informal expression used to describe someone who acts friendly or helpful in order to get some personal benefit. It is used to express disapproval.
For example, one might refer to a student who makes up to his or her professor to get better grades, or to an employee who makes it up to the boss to get on a fast line for promotion. (see: https://www.merriam-webster.com/dictionary/make%20up%20to%20(someone) OR https://www.macmillandictionary.com/dictionary/british/make-up-to)
To "make up with" generally means to reconcile one's differences with someone who one has fought with or had some sort of disagreement with. For example, after fighting for years, she made up with her mother and they now have a much healthier relationship.
However, I have also heard it used idiomatically for making plans, as in "I made up with Bill to see a movie tonight."
"Make it up to someone" means to do something nice to someone because they're upset (or you've upset them), or sometimes just because you feel that you've done something wrong as in: "I came late to Kate's party, so I made it up to Kate by staying after the party was over to help her clean up."


text:
Q: Laplace Smoothing for Bernoulli model for naive bayes classifier I have to implement a naive bayes classifier for classifying a document to a class. So, in getting the conditional probability for a term belonging to class, along with laplace smoothing, we have:
prob(t | c) = Num(Word occurences in the docs of the class c) + 1 / Num(documents in class c) + |V|
Its a bernoulli model, which will have either 1 or 0 and the vocabulary is really large, like perhaps 20000 words and so on. So, won't the laplace smoothing give really small values due to the large size of the vocabulary or am I doing something wrong.
According to the psuedo code from this link: http://nlp.stanford.edu/IR-book/html/htmledition/the-bernoulli-model-1.html, for the bernoulli model we just add 2 instead of |V|. Why so?

A: Consider the case of multinomial naive Bayes. The smoothing you defined above is such that you can never get a zero probability.
With the multivariate/Bernoulli case, there is an additional constraint: probabilities of exactly 1 are not allowed either. This is because when some t from the known vocabulary is not present in the document d, a probability of 1 - prob(t | c) is multiplied to the document probability. If prob(t | c) is 1, then once again this is going to produce a posterior probability of 0.
(Likewise, when using logs instead, log(1 - prob(t | c)) is undefined when the probability is 1)
So in the Bernoulli equation (Nct + 1) / (Nc + 2), both cases are protected against. If Nct == Nc, then the probability will be 1/2 rather than 1. This also has the consequence of producing a likelihood of 1/2 regardless of whether t exists (P(t | c) == 1/2) or not (1 - P(t | c) == 1/2)


text:
Q: Observables and the Web API So now that Angular 2 is in beta I have been using observables on the client side and I have been using ASP.NET Core Web API on the server side.  My question is if I want to display a value on my website as that value changes I understand how to do it on the client side with Observables, but how do I use Observables with a Web API service on the server?
Thanks for your time....

A: If I understand your question correcly, you can use Refit , to generate the implementation of an interface that returns an IObservable from a REST API.
For the example below, an interface is declared for the /users/{user} REST API. The return type is an IObservable and when you compile this, Refit generates the implementation.
public interface IRestAPI
{
    // Returns the raw response, as an IObservable that can be used with the
    // Reactive Extensions
    [Get("/users/{user}")]
    IObservable<HttpResponseMessage> GetUser(string user);
}

To initialize it, you do something like this:
 var api = RestService.For<IRestAPI>("http://api.example.com/users");


text:
Q: Symbolic links lost after restart I have been working on setting up some symbolic links so that I can easily access directories and files on another internal hard drive. When I create the links they work well, but every time that I restart the links are lost. Is there a better way to use links or refresh them?
I am currently creating links like this
ln -s /media/UserName/DiskName

I am running ubuntu 15.04 64-bit

A: The reason is quite clear. You did not set mounting rules for this disk in /etc/fstab/.
When system starts, the disk is not mounted.
Just add a line to /etc/fstab for a permanent rule and the problem will be solved.
This is a guide.


text:
Q: Why dont c++ strings work with scanf and printf string a;
scanf("%s",&a);

gives me an error "unhandled exception :Access violation writing location 0x000EEFFEE" when i run the program and enter the string for expression.
whereas
char a[20];
scanf("%s",a);

works fine.
Is it only because scanf and printf are inherited from C.
What methods can I use to fix the error.
Is it possible at all to make printf scanf work with c++ strings.

A: The reasons std::string can't be used with printf is that std::string is not a sequence of characters.
The printf function expects a sequence of characters terminated by '\0'.
For all we know the std::string class could be implemented as:
class string
{
  unsigned int capacity;
  unsigned int size;
  char *       p_char_sequence;
};

As you can see, the first two items are not characters.
Also, there are not printf format specifiers for std::string.
In summary, there is no guarantee that the first items in memory of a std::string are the characters; it could be a class or structure.
There is a mitigation, the std::string::c_str() method.  This method returns a pointer to a C-Style string equivalent of the std::string contents.
Edit 1: scanf
The scanf function is more interesting.  The scanf function requires a pointer to an array of characters.  There is no guarantee that the first memory address in a std::string is a sequence of characters.  See printf explanation above.
Also, there is no guarantee that the pointer returned by std::string::c_str() is valid for receiving characters.  It could be a temporary area in memory, used only for output.  Thus it can't be used for scanf.
The scanf function will write characters to the array locations until the input is terminated.  This means that if you allocate space for 3 characters and the User inputs 20 characters, the scanf function will start overwriting the array and write to whatever follows it.  This could trigger a system error (such as writing outside your program's area) or write to hardware addresses.  This is why most references say to use fscanf where a limit or capacity can be specified.

A: You need to use c-strings with scanf not c++ strings.  Redeclare expression as char expression[N]; where N is a large enough number of characters to store the entire word.  Also you would not need the & infront of it when you pass it to scanf since arrays are converted to pointers automatically.
An even better approach would be to replace scanf with cin >> expression;  And replace printf with cout << expression;  that is the way to do it in c++.


text:
Q: Python Casting a sorted list to dictionary, difference in Google Colab and Pycharm chars = dict(sorted(crops.items(),key=lambda kv: kv[1].size, reverse=True)[:4])

I am creating a dictionary, chars, that maps count variables (any integer vals) to my four largest crop values from a previous dictionary, crops.
I am running the above  line in both Google Colab and Pycharms and it gives me a different dictionary in each. In Colab, it gives me what I want, from the list seen below (Note: lots of lines were taken out of the list). It retains the order of the list { (6, crop1), (7,crop2) , (2, crop3) , (3, crop4) } .
However, in pycharms the output is { (2, crop3) , (3, crop4), (6, crop1), (7,crop2)} , where it is still getting the largest four crops, but by casting it to dict() it seems to reorder my list in the dictionary by the count variables.
Chars list:
[(6, array([[78, 76, 77, 78, 73, 81, 80, 81, 79, 72, 77, 78, 71, 73, 78, 81,
        82, 79, 76, 74, 75, 85, 86, 78, 76, 84, 85, 80, 78, 73, 76],
      ..., (7, array([[89, 90, 87, 83, 82, 83, 77, 76, 75, 74, 71, 73, 74, 77, 77, 80,
        77, 75..., (3, array([[ 79,  77,  81,  74,  80,  85,  83,  79,  74,  77,  74,  76,  78,
        ...]

I am not sure what is causing this and could definitely use some help. Maybe an issue is also for PyCharms the code is running realtime in a Gazebo simulation, so maybe that changes how dict() is casting my list?

A: Dictionaries are an inheritently unordered data structure - period.
Dictionaries in python (*) are insert sorted - the first item put into it is also the first printed.
(*) holds for python 3.7 and above - below 3.7 dicts may be randomly sorted or (implementation detail) be insert sorted as well.
If you get different sortings you either insert in a different order OR run wildly different versions of python.
How do I detect the Python version at runtime?
In case you use an earlier version of python >= 3.1 you can use collections.ordereddict


text: Q: ¿Como podria reutilizar mi tabla foto en base de datos? tengo una tabla tema, la cual puede tener varias fotos,y también tengo mi tabla publicación y también puede tener fotos,como podría reutilizar mi tabla fotos,para usarla en la tabla publicación?.gracias de antemano


text:
Q: What is the distribution of the sample variance of the Skellam distribution? I want to estimate the parameter  $\mu$ using the difference between two Poisson distributions with the same parameter, i.e. a Skellam distribution with $\mu_1=\mu_2 = \mu$.
I can calculate the variance of the Skellam distribution as the average variance over multiple samples, however, depending on sample size and some good/bad luck, I have quite a bit of error in my estimate (red crosses in the figure below); the variance should be $2\mu$. If I knew what distribution I was looking for, I could fit that instead to hopefully get a more robust estimate.
Why am I doing this if I appear to know $\mu$? In my application, I only know $\hat{\mu}=\beta_1\mu+\beta_0$, so I need a second estimate of $\mu$ to find out the betas.

A: Some of the comments have pointed out that there may be better ways to solve your problem that do not involve finding the distribution of the sample variance of the Skellam distribution.  Here I will answer the title question irrespective of those other issues.

The exact distribution of the sample variance from a Skellam distribution is complicated, since it is a quadratic function of Poisson random variables.  Using the large-sample approximation with the chi-squared distribution (see e.g., O'Neill 2004) you can get the approximate distribution:
$$S_n^2 \sim 2 \mu \cdot \frac{\text{Chi-Sq}(DF_n)}{DF_n} \quad \quad \quad DF_n = \frac{2n \mu^2}{3 \mu^2 + (n-3) / (n-1)}.$$
This should get you a reasonable approximation to the distribution of the sample variance, so long as $n$ is not too small.

A: I'm not sure what the problem is: sample variance is a random variable. I would guess it is distributed as a (re-scaled) Chi-square for this distribution. For a fixed number of samples, the standard error of the variance statistic will be proportional to the population variance you are trying to estimate. Thus I would expect these histograms to get 'wider' as the population variance increases.


text:
Q: Why does Google Apps Script's UrlFetchApp return HTML instead of csv file (requesting Facebook API)? Background
UrlFetchApp responds with an html file instead of a csv file when I'm requesting a report via the facebook insights API. From the Facebook documentation- bottom of the page:

Export Reports
We provide a convenience endpoint for exporting  to a localized human-readable format.
   to a localized human-readable format.

curl -G \
  -d 'report_run_id=<AD_REPORT_RUN_ID>' \
  -d 'name=myreport' \
  -d 'format=csv' \
'https://www.facebook.com/ads/ads_insights/export_report/'

I have already ran the report and therefore have got an adReportId and authentication is no issue as I'm using a valid access_token.
In fact, when I visit the url manually the download of the correct csv file starts immediately.
The Problem
When parsing the csv response Google Apps Script throws the following error:

Could not parse text. (line 219, file)

Lines 215-219:
function getReportData(reportId) {
  const id = reportId || CacheService.getScriptCache().get('campaign-report-id');
  const facebookUrl = buildFacebookReportUrl(id);
  //facebookUrl:https://www.facebook.com/ads/ads_insights/export_report?report_run_id=<REPORT_ID>&format=csv&access_token=<ACCESS_TOKEN>
  var fetchRequest = UrlFetchApp.fetch(facebookUrl);
  var response = fetchRequest.getContentText();
  Logger.log(response);
  return Utilities.parseCsv(fetchRequest)
    };

function buildFacebookReportUrl(reportId) {
  const baseUrl = `https://www.facebook.com/ads/ads_insights/export_report?`;
  const paramString = `report_run_id=${reportId}&format=csv&access_token=${
    fbConfig.TOKEN}`;
  const requestUrl = `${baseUrl}${paramString}`;
  return encodeURI(requestUrl);
}

The log shows the following data for response (truncated):
<!DOCTYPE html>
<html lang="en" id="facebook" class="no_js">

<head>
    <meta charset="utf-8" />
    <meta name="referrer" content="default" id="meta_referrer" />
    <script>
        window._cstart = +new Date();
    </script>
    <script>
        function envFlush(a) {
            function b(b) {
                for (var c in a) b[c] = a[c]
            }
            window.requireLazy ? window.requireLazy(["Env"], b) : (window.Env = window.Env || {}, b(window.Env))
        }
        envFlush({
            "ajaxpipe_token": "AXjyFTuniyv5Ka6j",
            "timeslice_heartbeat_config": {
                "pollIntervalMs": 33,
                "idleGapThresholdMs": 60,
                "ignoredTimesliceNames": {
                    "requestAnimationFrame": true,
                    "Event listenHandler mousemove": true,
                    "Event listenHandler mouseover": true,
                    "Event listenHandler mouseout": true,
                    "Event listenHandler scroll": true
                },
                "isHeartbeatEnabled": true,
                "isArtilleryOn": false
            },
            "shouldLogCounters": true,
            "timeslice_categories": {
                "react_render": true,
                "reflow": true
            },
            "sample_continuation_stacktraces": true,
            "dom_mutation_flag": true,
            "stack_trace_limit": 30,
            "deferred_stack_trace_rate": 1000,
            "timesliceBufferSize": 5000,
            "show_invariant_decoder": false,
            "compat_iframe_token": "AQ7vXO7c6UeVAX4i",
            "isCQuick": false
        });
    </script>
    <style></style>
    <script>
        __DEV__ = 0;
        CavalryLogger = window.CavalryLogger || function(a) {
            this.lid = a, this.transition = !1, this.metric_collected = !1, this.is_detailed_profiler = !1, this.instrumentation_started = !1, this.pagelet_metrics = {}, this.events = {}, this.ongoing_watch = {}, this.values = {
                t_cstart: window._cstart
            }, this.piggy_values = {}, this.bootloader_metrics = {}, this.resource_to_pagelet_mapping = {}, this.initializeInstrumentation && this.initializeInstrumentation()
        }, CavalryLogger.prototype.setIsDetailedProfiler = function(a) {
            this.is_detailed_profiler = a;
            return this
        }, CavalryLogger.prototype.setTTIEvent = function(a) {
            this.tti_event = a;
            return this
        }, CavalryLogger.prototype.setValue = function(a, b, c, d) {
            d = d ? this.piggy_values : this.values;
            (typeof d[a] === "undefined" || c) && (d[a] = b);
            return this
        }, CavalryLogger.prototype.getLastTtiValue = function() {
            return this.lastTtiValue
        }, CavalryLogger.prototype.setTimeStamp = CavalryLogger.prototype.setTimeStamp || function(a, b, c, d) {
            this.mark(a);
            var e = this.values.t_cstart || this.values.t_start;
            e = d ? e + d : CavalryLogger.now();
            this.setValue(a, e, b, c);
            this.tti_event && a == this.tti_event && (this.lastTtiValue = e, this.setTimeStamp("t_tti", b));
            return this
        }, CavalryLogger.prototype.mark = typeof console === "object" && console.timeStamp ? function(a) {
            console.timeStamp(a)
        } : function() {}, CavalryLogger.prototype.addPiggyback = function(a, b) {
            this.piggy_values[a] = b;
            return this
        }, CavalryLogger.instances = {}, CavalryLogger.id = 0, CavalryLogger.disableArtilleryOnUntilOffLogging = !1, CavalryLogger.getInstance = function(a) {
            typeof a === "undefined" && (a = CavalryLogger.id);
            CavalryLogger.instances[a] || (CavalryLogger.instances[a] = new CavalryLogger(a));
            return CavalryLogger.instances[a]
        }, CavalryLogger.setPageID = function(a) {
            if (CavalryLogger.id === 0) {
                var b = CavalryLogger.getInstance();
                CavalryLogger.instances[a] = b;
                CavalryLogger.instances[a].lid = a;
                delete CavalryLogger.instances[0]
            }
            CavalryLogger.id = a
        }, CavalryLogger.now = function() {
            return window.performance && performance.timing && performance.timing.navigationStart && performance.now ? performance.now() + performance.timing.navigationStart : new Date().getTime()
        }, CavalryLogger.prototype.measureResources = function() {}, CavalryLogger.prototype.profileEarlyResources = function() {}, CavalryLogger.getBootloaderMetricsFromAllLoggers = function() {}, CavalryLogger.start_js = function() {}, CavalryLogger.done_js = function() {};
        CavalryLogger.getInstance().setTTIEvent("t_domcontent");
        CavalryLogger.prototype.measureResources = function(a, b) {
            if (!this.log_resources) return;
            var c = "bootload/" + a.name;
            if (this.bootloader_metrics[c] !== void 0 || this.ongoing_watch[c] !== void 0) return;
            var d = CavalryLogger.now();
            this.ongoing_watch[c] = d;
            "start_" + c in this.bootloader_metrics || (this.bootloader_metrics["start_" + c] = d);
            b && !("tag_" + c in this.bootloader_metrics) && (this.bootloader_metrics["tag_" + c] = b);
            if (a.type === "js") {
                c = "js_exec/" + a.name;
                this.ongoing_watch[c] = d
            }
        }, CavalryLogger.prototype.stopWatch = function(a) {
            if (this.ongoing_watch[a]) {
                var b = CavalryLogger.now(),
                    c = b - this.ongoing_watch[a];
                this.bootloader_metrics[a] = c;
                var d = this.piggy_values;
                a.indexOf("bootload") === 0 && (d.t_resource_download || (d.t_resource_download = 0), d.resources_downloaded || (d.resources_downloaded = 0), d.t_resource_download += c, d.resources_downloaded += 1, d["tag_" + a] == "_EF_" && (d.t_pagelet_cssload_early_resources = b));
                delete this.ongoing_watch[a]
            }
            return this
        }, CavalryLogger.getBootloaderMetricsFromAllLoggers = function() {
            var a = {};
            Object.values(window.CavalryLogger.instances).forEach(function(b) {
                b.bootloader_metrics && Object.assign(a, b.bootloader_metrics)
            });
            return a
        }, CavalryLogger.start_js = function(a) {
            for (var b = 0; b < a.length; ++b) CavalryLogger.getInstance().stopWatch("js_exec/" + a[b])
        }, CavalryLogger.done_js = function(a) {
            for (var b = 0; b < a.length; ++b) CavalryLogger.getInstance().stopWatch("bootload/" + a[b])
        }, CavalryLogger.prototype.profileEarlyResources = function(a) {
            for (var b = 0; b < a.length; b++) this.measureResources({
                name: a[b][0],
                type: a[b][1] ? "js" : ""
            }, "_EF_")
        };
        CavalryLogger.getInstance().log_resources = true;
        CavalryLogger.getInstance().setIsDetailedProfiler(true);
        window.CavalryLogger && CavalryLogger.getInstance().setTimeStamp("t_start");
    </script>
    <title id="pageTitle">Facebook</title>
    <link rel="shortcut icon" href="https://static.xx.fbcdn.net/rsrc.php/yz/r/KFyVIAWzntM.ico" />
    <link type="text/css" rel="stylesheet" href="https://static.xx.fbcdn.net/rsrc.php/v3/y2/l/0,cross/3kNz1uzYvN2.css?_nc_x=Ij3Wp8lg5Kz" data-bootloader-hash="SUv1J" />
    <link type="text/css" rel="stylesheet" href="https://static.xx.fbcdn.net/rsrc.php/v3/yW/l/0,cross/9NGO1GuacRK.css?_nc_x=Ij3Wp8lg5Kz" data-bootloader-hash="nOHzA" />
    <link type="text/css" rel="stylesheet" href="https://static.xx.fbcdn.net/rsrc.php/v3/yA/l/0,cross/rvNB4fphdT0.css?_nc_x=Ij3Wp8lg5Kz" data-bootloader-hash="T1Fcr" />
    <link type="text/css" rel="stylesheet" href="https://static.xx.fbcdn.net/rsrc.php/v3/yJ/l/0,cross/kDxV0y2UotM.css?_nc_x=Ij3Wp8lg5Kz" data-bootloader-hash="cNDmN" />
    <script src="https://static.xx.fbcdn.net/rsrc.php/v3/yh/r/53ZB62AZOTo.js?_nc_x=Ij3Wp8lg5Kz" data-bootloader-hash="QPWJc"></script>
    <script>
        requireLazy(["gkx"], function(gkx) {
            gkx.add({
                "676837": {
                    "result": false,
                    "hash": "AT5qgm2lluu0ObEm"
                },
                "676920": {
                    "result": false,
                    "hash": "AT4fRx_5a-x5BCKq"
                },
                "676921": {
                    "result": false,
                    "hash": "AT7L2NIsWs1k6mzF"
                },
                "676922": {
                    "result": false,
                    "hash": "AT434PRa2zIf0VNU"
                },
                "676940": {
                    "result": false,
                    "hash": "AT75c1NCKpiznkoK"
                },
                "946894": {
                    "result": false,
                    "hash": "AT4KxZoaFuONM6jW"
                },
                "996939": {
                    "result": false,
                    "hash": "AT7CXDiWhrCd8u4n"
                },
                "996940": {
                    "result": false,
                    "hash": "AT4S6r3cOh4ebic8"
                },
                "1073500": {
                    "result": false,
                    "hash": "AT6ny6L_AsBsjSUH"
                },
                "1113247": {
                    "result": false,
                    "hash": "AT6aSDBxHRQgvz2h"
                },
                "1263340": {
                    "result": false,
                    "hash": "AT4j6MH_K-2kudmO"
                },
                "1167394": {
                    "result": false,
                    "hash": "AT7tg1d7ZhRzO_3p"
                }
            });
        });
        requireLazy(["qex"], function(qex) {
            qex.add({
                "1211266": {
                    "r": null
                }
            });
        });
        require("TimeSliceImpl").guard(function() {
                    (require("ServerJSDefine")).handleDefines([
                                ["cr:696703", [], {
                                    "__rc": [null, "Aa2d-W5-1nWg1sVgO19izjYy_tqPH8dlVHuIPPgy4FLx3zt-Nw63rJWoc0DdN3TfViSyYfbhpyQGjKQRzfCxl1I"]
                                }, -1],
                                ["cr:708886", ["EventProfilerImpl"], {
                                    "__rc": ["EventProfilerImpl", "Aa2d-W5-1nWg1sVgO19izjYy_tqPH8dlVHuIPPgy4FLx3zt-Nw63rJWoc0DdN3TfViSyYfbhpyQGjKQRzfCxl1I"]
                                }, -1],
                                ["cr:717822", ["TimeSliceImpl"], {
                                    "__rc": ["TimeSliceImpl", "Aa2d-W5-1nWg1sVgO19izjYy_tqPH8dlVHuIPPgy4FLx3zt-Nw63rJWoc0DdN3TfViSyYfbhpyQGjKQRzfCxl1I"]
                                }, -1],
                                ["cr:806696", ["clearTimeoutBlue"], {
                                    "__rc": ["clearTimeoutBlue", "Aa2d-W5-1nWg1sVgO19izjYy_tqPH8dlVHuIPPgy4FLx3zt-Nw63rJWoc0DdN3TfViSyYfbhpyQGjKQRzfCxl1I"]
                                }, -1],
                                ["cr:807042", ["setTimeoutBlue"], {
                                    "__rc": ["setTimeoutBlue", "Aa2d-W5-1nWg1sVgO19izjYy_tqPH8dlVHuIPPgy4FLx3zt-Nw63rJWoc0DdN3TfViSyYfbhpyQGjKQRzfCxl1I"]
                                }, -1],
                                ["cr:896462", ["setIntervalAcrossTransitionsBlue"], {
                                    "__rc": ["setIntervalAcrossTransitionsBlue", "Aa2d-W5-1nWg1sVgO19izjYy_tqPH8dlVHuIPPgy4FLx3zt-Nw63rJWoc0DdN3TfViSyYfbhpyQGjKQRzfCxl1I"]
                                }, -1],
                                ["cr:986633", ["setTimeoutAcrossTransitionsBlue"], {
                                    "__rc": ["setTimeoutAcrossTransitionsBlue", "Aa2d-W5-1nWg1sVgO19izjYy_tqPH8dlVHuIPPgy4FLx3zt-Nw63rJWoc0DdN3TfViSyYfbhpyQGjKQRzfCxl1I"]
                                }, -1],
                                ["cr:1003267", ["clearIntervalBlue"], {
                                    "__rc": ["clearIntervalBlue", "Aa2d-W5-1nWg1sVgO19izjYy_tqPH8dlVHuIPPgy4FLx3zt-Nw63rJWoc0DdN3TfViSyYfbhpyQGjKQRzfCxl1I"]
                                }, -1],
                                ["cr:1100101", ["requestAni [20 - 01 - 28 15: 24: 04: 186 CET] < !DOCTYPE html >
                                        < html lang = "en"
                                        id = "facebook"
                                        class = "no_js" >
                                        < head > < meta charset = "utf-8" / > < meta name = "referrer"
                                        content = "default"
                                        id = "meta_referrer" / > < script > window._cstart = +new Date();
    </script>
    <script>
        function envFlush(a) {
            function b(b) {
                for (var c in a) b[c] = a[c]
            }
            window.requireLazy ? window.requireLazy(["Env"], b) : (window.Env = window.Env || {}, b(window.Env))
        }
        envFlush({
            "ajaxpipe_token": "AXjyFTuniyv5Ka6j",
            "timeslice_heartbeat_config": {
                "pollIntervalMs": 33,
                "idleGapThresholdMs": 60,
                "ignoredTimesliceNames": {
                    "requestAnimationFrame": true,
                    "Event listenHandler mousemove": true,
                    "Event listenHandler mouseover": true,
                    "Event listenHandler mouseout": true,
                    "Event listenHandler scroll": true
                },
                "isHeartbeatEnabled": true,
                "isArtilleryOn": false
            },
            "shouldLogCounters": true,
            "timeslice_categories": {
                "react_render": true,
                "reflow": true
            },
            "sample_continuation_stacktraces": true,
            "dom_mutation_flag": true,
            "stack_trace_limit": 30,
            "deferred_stack_trace_rate": 1000,
            "timesliceBufferSize": 5000,
            "show_invariant_decoder": false,
            "compat_iframe_token": "AQ7vXO7c6UeVAX4i",
            "isCQuick": false
        });
    </script>
    <style></style>
    <script>
        __DEV__ = 0;
        CavalryLogger = window.CavalryLogger || function(a) {
            this.lid = a, this.transition = !1, this.metric_collected = !1, this.is_detailed_profiler = !1, this.instrumentation_started = !1, this.pagelet_metrics = {}, this.events = {}, this.ongoing_watch = {}, this.values = {
                t_cstart: window._cstart
            }, this.piggy_values = {}, this.bootloader_metrics = {}, this.resource_to_pagelet_mapping = {}, this.initializeInstrumentation && this.initializeInstrumentation()
        }, CavalryLogger.prototype.setIsDetailedProfiler = function(a) {
            this.is_detailed_profiler = a;
            return this
        }, CavalryLogger.prototype.setTTIEvent = function(a) {
            this.tti_event = a;
            return this
        }, CavalryLogger.prototype.setValue = function(a, b, c, d) {
            d = d ? this.piggy_values : this.values;
            (typeof d[a] === "undefined" || c) && (d[a] = b);
            return this
        }, CavalryLogger.prototype.getLastTtiValue = function() {
            return this.lastTtiValue
        }, CavalryLogger.prototype.setTimeStamp = CavalryLogger.prototype.setTimeStamp || function(a, b, c, d) {
            this.mark(a);
            var e = this.values.t_cstart || this.values.t_start;
            e = d ? e + d : CavalryLogger.now();
            this.setValue(a, e, b, c);
            this.tti_event && a == this.tti_event && (this.lastTtiValue = e, this.setTimeStamp("t_tti", b));
            return this
        }, CavalryLogger.prototype.mark = typeof console === "object" && console.timeStamp ? function(a) {
            console.timeStamp(a)
        } : function() {}, CavalryLogger.prototype.addPiggyback = function(a, b) {
            this.piggy_values[a] = b;
            return this
        }, CavalryLogger.instances = {}, CavalryLogger.id = 0, CavalryLogger.disableArtilleryOnUntilOffLogging = !1, CavalryLogger.getInstance = function(a) {
            typeof a === "undefined" && (a = CavalryLogger.id);
            CavalryLogger.instances[a] || (CavalryLogger.instances[a] = new CavalryLogger(a));
            return CavalryLogger.instances[a]
        }, CavalryLogger.setPageID = function(a) {
            if (CavalryLogger.id === 0) {
                var b = CavalryLogger.getInstance();
                CavalryLogger.instances[a] = b;
                CavalryLogger.instances[a].lid = a;
                delete CavalryLogger.instances[0]
            }
            CavalryLogger.id = a
        }, CavalryLogger.now = function() {
            return window.performance && performance.timing && performance.timing.navigationStart && performance.now ? performance.now() + performance.timing.navigationStart : new Date().getTime()
        }, CavalryLogger.prototype.measureResources = function() {}, CavalryLogger.prototype.profileEarlyResources = function() {}, CavalryLogger.getBootloaderMetricsFromAllLoggers = function() {}, CavalryLogger.start_js = function() {}, CavalryLogger.done_js = function() {};
        CavalryLogger.getInstance().setTTIEvent("t_domcontent");
        CavalryLogger.prototype.measureResources = function(a, b) {
            if (!this.log_resources) return;
            var c = "bootload/" + a.name;
            if (this.bootloader_metrics[c] !== void 0 || this.ongoing_watch[c] !== void 0) return;
            var d = CavalryLogger.now();
            this.ongoing_watch[c] = d;
            "start_" + c in this.bootloader_metrics || (this.bootloader_metrics["start_" + c] = d);
            b && !("tag_" + c in this.bootloader_metrics) && (this.bootloader_metrics["tag_" + c] = b);
            if (a.type === "js") {
                c = "js_exec/" + a.name;
                this.ongoing_watch[c] = d
            }
        }, CavalryLogger.prototype.stopWatch = function(a) {
            if (this.ongoing_watch[a]) {
                var b = CavalryLogger.now(),
                    c = b - this.ongoing_watch[a];
                this.bootloader_metrics[a] = c;
                var d = this.piggy_values;
                a.indexOf("bootload") === 0 && (d.t_resource_download || (d.t_resource_download = 0), d.resources_downloaded || (d.resources_downloaded = 0), d.t_resource_download += c, d.resources_downloaded += 1, d["tag_" + a] == "_EF_" && (d.t_pagelet_cssload_early_resources = b));
                delete this.ongoing_watch[a]
            }
            return this
        }, CavalryLogger.getBootloaderMetricsFromAllLoggers = function() {
            var a = {};
            Object.values(window.CavalryLogger.instances).forEach(function(b) {
                b.bootloader_metrics && Object.assign(a, b.bootloader_metrics)
            });
            return a
        }, CavalryLogger.start_js = function(a) {
            for (var b = 0; b < a.length; ++b) CavalryLogger.getInstance().stopWatch("js_exec/" + a[b])
        }, CavalryLogger.done_js = function(a) {
            for (var b = 0; b < a.length; ++b) CavalryLogger.getInstance().stopWatch("bootload/" + a[b])
        }, CavalryLogger.prototype.profileEarlyResources = function(a) {
            for (var b = 0; b < a.length; b++) this.measureResources({
                name: a[b][0],
                type: a[b][1] ? "js" : ""
            }, "_EF_")
        };
        CavalryLogger.getInstance().log_resources = true;
        CavalryLogger.getInstance().setIsDetailedProfiler(true);
        window.CavalryLogger && CavalryLogger.getInstance().setTimeStamp("t_start");
    </script>
    <title id="pageTitle">Facebook</title>
    <link rel="shortcut icon" href="https://static.xx.fbcdn.net/rsrc.php/yz/r/KFyVIAWzntM.ico" />
    <link type="text/css" rel="stylesheet" href="https://static.xx.fbcdn.net/rsrc.php/v3/y2/l/0,cross/3kNz1uzYvN2.css?_nc_x=Ij3Wp8lg5Kz" data-bootloader-hash="SUv1J" />
    <link type="text/css" rel="stylesheet" href="https://static.xx.fbcdn.net/rsrc.php/v3/yW/l/0,cross/9NGO1GuacRK.css?_nc_x=Ij3Wp8lg5Kz" data-bootloader-hash="nOHzA" />
    <link type="text/css" rel="stylesheet" href="https://static.xx.fbcdn.net/rsrc.php/v3/yA/l/0,cross/rvNB4fphdT0.css?_nc_x=Ij3Wp8lg5Kz" data-bootloader-hash="T1Fcr" />
    <link type="text/css" rel="stylesheet" href="https://static.xx.fbcdn.net/rsrc.php/v3/yJ/l/0,cross/kDxV0y2UotM.css?_nc_x=Ij3Wp8lg5Kz" data-bootloader-hash="cNDmN" />
    <script src="https://static.xx.fbcdn.net/rsrc.php/v3/yh/r/53ZB62AZOTo.js?_nc_x=Ij3Wp8lg5Kz" data-bootloader-hash="QPWJc"></script>
    <script>
        requireLazy(["gkx"], function(gkx) {
            gkx.add({
                "676837": {
                    "result": false,
                    "hash": "AT5qgm2lluu0ObEm"
                },
                "676920": {
                    "result": false,
                    "hash": "AT4fRx_5a-x5BCKq"
                },
                "676921": {
                    "result": false,
                    "hash": "AT7L2NIsWs1k6mzF"
                },
                "676922": {
                    "result": false,
                    "hash": "AT434PRa2zIf0VNU"
                },
                "676940": {
                    "result": false,
                    "hash": "AT75c1NCKpiznkoK"
                },
                "946894": {
                    "result": false,
                    "hash": "AT4KxZoaFuONM6jW"
                },
                "996939": {
                    "result": false,
                    "hash": "AT7CXDiWhrCd8u4n"
                },
                "996940": {
                    "result": false,
                    "hash": "AT4S6r3cOh4ebic8"
                },
                "1073500": {
                    "result": false,
                    "hash": "AT6ny6L_AsBsjSUH"
                },
                "1113247": {
                    "result": false,
                    "hash": "AT6aSDBxHRQgvz2h"
                },
                "1263340": {
                    "result": false,
                    "hash": "AT4j6MH_K-2kudmO"
                },
                "1167394": {
                    "result": false,
                    "hash": "AT7tg1d7ZhRzO_3p"
                }
            });
        });
        requireLazy(["qex"], function(qex) {
            qex.add({
                "1211266": {
                    "r": null
                }
            });
        });
        require("TimeSliceImpl").guard(function() {
                    (require("ServerJSDefine")).handleDefines([
                                ["cr:696703", [], {
                                    "__rc": [null, "Aa2d-W5-1nWg1sVgO19izjYy_tqPH8dlVHuIPPgy4FLx3zt-Nw63rJWoc0DdN3TfViSyYfbhpyQGjKQRzfCxl1I"]
                                }, -1],
                                ["cr:708886", ["EventProfilerImpl"], {
                                    "__rc": ["EventProfilerImpl", "Aa2d-W5-1nWg1sVgO19izjYy_tqPH8dlVHuIPPgy4FLx3zt-Nw63rJWoc0DdN3TfViSyYfbhpyQGjKQRzfCxl1I"]
                                }, -1],
                                ["cr:717822", ["TimeSliceImpl"], {
                                    "__rc": ["TimeSliceImpl", "Aa2d-W5-1nWg1sVgO19izjYy_tqPH8dlVHuIPPgy4FLx3zt-Nw63rJWoc0DdN3TfViSyYfbhpyQGjKQRzfCxl1I"]
                                }, -1],
                                ["cr:806696", ["clearTimeoutBlue"], {
                                    "__rc": ["clearTimeoutBlue", "Aa2d-W5-1nWg1sVgO19izjYy_tqPH8dlVHuIPPgy4FLx3zt-Nw63rJWoc0DdN3TfViSyYfbhpyQGjKQRzfCxl1I"]
                                }, -1],
                                ["cr:807042", ["setTimeoutBlue"], {
                                    "__rc": ["setTimeoutBlue", "Aa2d-W5-1nWg1sVgO19izjYy_tqPH8dlVHuIPPgy4FLx3zt-Nw63rJWoc0DdN3TfViSyYfbhpyQGjKQRzfCxl1I"]
                                }, -1],
                                ["cr:896462", ["setIntervalAcrossTransitionsBlue"], {
                                    "__rc": ["setIntervalAcrossTransitionsBlue", "Aa2d-W5-1nWg1sVgO19izjYy_tqPH8dlVHuIPPgy4FLx3zt-Nw63rJWoc0DdN3TfViSyYfbhpyQGjKQRzfCxl1I"]
                                }, -1],
                                ["cr:986633", ["setTimeoutAcrossTransitionsBlue"], {
                                    "__rc": ["setTimeoutAcrossTransitionsBlue", "Aa2d-W5-1nWg1sVgO19izjYy_tqPH8dlVHuIPPgy4FLx3zt-Nw63rJWoc0DdN3TfViSyYfbhpyQGjKQRzfCxl1I"]
                                }, -1],
                                ["cr:1003267", ["clearIntervalBlue"], {
                                    "__rc": ["clearIntervalBlue", "Aa2d-W5-1nWg1sVgO19izjYy_tqPH8dlVHuIPPgy4FLx3zt-Nw63rJWoc0DdN3TfViSyYfbhpyQGjKQRzfCxl1I"]
                                }, -1],
                                ["cr:1100101", ["requestAni

What I've tried (other stackoverflow solutions)

*

*This question claims that a similar urlFetch request yielded the csv content, however I don't understand the additional options he puts in (I don't think I need it as authentication is no issue and it works when manually visiting the url)

*This questions has the same issue but the only response is towards authentication issues which I can exclude in my case.

*I have tried this implementation (getting the blob) as well resulting in a Google Apps Script error when trying to unzip the blob.

*This question made me check the csv file for any possible malformation, however after inspection and manual importing into google sheets everything looked fine:

*Thanks to @TheMaster who pointed out encoding I've also added above the buildFacebookReportUrl() function and have also tried encodeURIComponent() for the token and reportId -- without success though:

function buildFacebookReportUrl(reportId) {
  const baseUrl = `https://www.facebook.com/ads/ads_insights/export_report?`;
  const paramString = `report_run_id=${encodeURIComponent(reportId)}&format=csv&access_token=${encodeURIComponent(
    fbConfig.TOKEN
  )}`;
  const requestUrl = `${baseUrl}${paramString}`;
  return encodeURI(requestUrl);
}

How to reproduce

*

*Facebook Insights API Quickstart

*Send a POST request to /insights endpoint, which responds with the id of an Ad Report Run.

*Export Report like in the Example above

I hope someone can reproduce this error or spots immediately what's wrong with my request.
Let me know if you need more context! (Don't have a lot of experience but tried my best giving context)

A: Posting an answer as I finally found out what was wrong.
The problem is that I made an asynchronous request to create the report and wanted to download it before the job was completed.
From Facebook documentation:

*

*Send a POST request to <AD_OBJECT>/insights endpoint, which responds with the  id of an Ad Report Run.

*Ad Report Runs contain information about this asynchronous job, such as  async_status. Poll this field until async_status is Job
  Completed and  async_percent_completion is 100.

*Then you can query <AD_REPORT_RUN_ID>/insights edge to fetch the final result.

I tried to do 3. before conditions in step 2 were fulfilled.
The Solution
I have added a while loop polling the async_status field as recommended.
function fetchReportAndSaveToSheet() {
  const reportId = createReportAndReturnId();
  //THE FOLLOWING CODE HAS SOLVED MY ISSUE
  let jobIsCompleted = false;
  const runReportAdsUrl = `https://graph.facebook.com/v5.0/${reportId}?access_token=${fbConfig.TOKEN}`;
  while (!jobIsCompleted) {
    const fetchRequest = UrlFetchApp.fetch(runReportAdsUrl));
    const runReportAds = JSON.parse(fetchRequest.getContentText());
    jobIsCompleted= runReportAds.async_status === 'Job Completed';
    if (runReportAds.async_status === 'Job Failed') {
      Logger.log((runReportAds.async_status))
      break
    }
  //END OF CODE MODIFICATION
  }
  cacheId(reportId);
  const data = getReportData(reportId);
  clearData();
  pushReportToSheet(data);
}
}


text:
Q: QR Code generator only generate the QR code for the first input I am new to stackoverflow and i wanted to create a QR code generator that translate the 2 inputs into a QR code, however the code only translate the first input into a QR code and does not include the information for the second input.
I also try using querySelectorAll but it doesnt change anything I hope good sirs would be so kind to teach me where I'm wrong at.
here is the code for HTML
  <!DOCTYPE html>

    <meta charset="UTF-8">
    <title>PracticeQRProgram</title>
    <link rel="stylesheet" href="style.css">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

QR CODE GENERATOR

              <input class="form" type="text" spellcheck="false" placeholder="Enter Full Name">
              <input class="form" type="text" spellcheck="false" placeholder="Enter ID no.">
            <button>Submit</button>

here is the code for javascript
var wrapper = document.querySelector(".wrapper"),
qrInput = wrapper.querySelector(".form input");
generateBtn = wrapper.querySelector(".form button");
qrImg = wrapper.querySelector(".qr-code img");
let preValue;
generateBtn.addEventListener("click", () => {
    let qrValue = qrInput.value.trim();
    if(!qrValue || preValue === qrValue) return;
    preValue = qrValue;
    generateBtn.innerText = "Submitting...";
    qrImg.src = `https://api.qrserver.com/v1/create-qr-code/?size=200x200&data=${qrValue}`;
    qrImg.addEventListener("load", () => {
        wrapper.classList.add("active");
        generateBtn.innerText = "QR Code";
    });
});
qrInput.addEventListener("keyup", () => {
    if(!qrInput.value.trim()) {
        wrapper.classList.remove("active");
        preValue = "";
    }
});

and here is for the style.css
@import url('https://fonts.googleapis.com/css2?family=Poppins:wght@400;500;600;700&display=swap');
*{
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  font-family: 'Poppins', sans-serif;
}
body{
  display: flex;
  padding: 0 10px;
  min-height: 100vh;
  align-items: center;
  background-image: url("ICpEP.jpg");
  background-color: #cccccc;
  justify-content: center;
}
.wrapper{
  height: 650px;
  max-width: 410px;
  background: #fff;
  border-radius: 7px;
  padding: 20px 25px 0;
  transition: height 0.2s ease;
  box-shadow: 0 10px 30px rgba(0,0,0,0.1);
}
.wrapper.active{
  height: 650px;
}
header h1{
  font-size: 21px;
  font-weight: 500;
}
header p{
  margin-top: 5px;
  color: #575757;
  font-size: 16px;
}
.wrapper .form{
  margin: 20px 0 25px;
}
.form :where(input, button){
  width: 100%;
  height: 55px;
  border: none;
  outline: none;
  border-radius: 5px;
  transition: 0.1s ease;
}
.form input{
  font-size: 18px;
  padding: 0 17px;
  border: 1px solid #999;
}
.form input :focus{
  box-shadow: 0 3px 6px rgba(0,0,0,0.13);
}
.form input::placeholder{
  color: #999;
}
 .form button{
  color: #fff;
  cursor: pointer;
  margin-top: 20px;
  font-size: 17px;
  background: #3498DB;
}
.qr-code{
  opacity: 0;
  display: flex;
  padding: 33px 0;
  border-radius: 5px;
  align-items: center;
  pointer-events: none;
  justify-content: center;
  border: 1px solid #ccc;
}
.wrapper.active .qr-code{
  opacity: 1;
  pointer-events: auto;
  transition: opacity 0.5s 0.05s ease;
}
.qr-code img{
  width: 170px;
}
@media (max-width: 430px){
  .wrapper{
    height: 650px;
    padding: 16px 20px;
  }
  .wrapper.active{
    height: 650px;
  }
  header p{
    color: #696969;
  }
  .form :where(input, button){
    height: 52px;
  }
  .qr-code img{
    width: 160px;
  }

}

A: In this line:
qrImg.src = `https://api.qrserver.com/v1/create-qr-code/?size=200x200&data=${qrValue}`;

You are only sending the qrValue to the api.  You will have to read and send both the id and name info to the api if you want both encoded.
That being said I would adjust the code a bit to make it easier to reason about.
Firstly I would add unique id's to each of the input elements eg:
<input id="name-input" class="form" type="text" spellcheck="false" placeholder="Enter Full Name">
<input id="id-input" class="form" type="text" spellcheck="false" placeholder="Enter ID no.">

Next I would select these elements directly using:
var qrNameInput = document.getElementById("name-input");
var qrIdInput = document.getElementById("id-input");

Then in your event listener I would read these values:
var name = qrNameInput.value.trim();
var id = qrIdInput.value.trim();

And finally send both of these information on to the api:
qrImg.src = `https://api.qrserver.com/v1/create-qr-code/?size=200x200&data="name:${name},id:${id}"`;

A: querySelectorAll() is the way to do this !
but you have to change some of your code, because it returns a NodeList, so you'll have to iterate on the result to find your values, like this :

const qrInputs = wrapper.querySelectorAll('.form input');

generateBtn.addEventListener('click', () => {
  let qrValue = getQrValue();
  //[...]
}

function getQrValue() {
  //To use array function, you have to cast the NodeList to an Array
  const inputsArray = Array.from(qrInputs)
  //getting an array of values from inputs
  const values = inputsArray.map((input) => input.value);
  // return a signle string with all values separated with '_'
  return values.join('_');
}

And with qrInput.addEventListener("keyup", [...]) you can just set the listener on the form instead (events are bubbling up)