text:
Q: Fixed positioned element does not adapt to the width of the window/viewport I'm trying to make a fixed positioned navigation bar for my site with css. The problem occurs when I'm resizing the browser. The elements inside my navigation bar go out of the viewport when I resized my the browser window size.
It's a similar problem with this site. When you scroll down a bit, you should see that "Products" element with a fixed positioned. Now try resize the browser window width until you can't see that "Job Listings", "Company Pages", "Candidate Search" links. Your browser should give you a scroll bar to scroll within the pages. When you scroll to the right, the pages content will get scrolled to, but this scrolling doesn't affect that "Products" element.
#header {
top:0px;
left:0px;
position:fixed;
height:50px;
width:100%;
z-index:100;
background:rgb(0, 0, 0);
background:rgba(0, 0, 0, 0.8);
padding-top:10px;
}

#nav_bar {
color:#FFFFFF;
width:894px;
margin:0 auto;
background:rgb(255, 255, 255);
background:rgba(255, 255, 255, 0.3);
-webkit-border-radius:10px;
-moz-border-radius:10px;
border-radius:10px;
padding:3px;
font-weight:bold;
}

a{
color:#FFFFFF;
text-decoration:none;
color:#F9BF3B;
background:rgb(137, 196, 244);
background:rgba(137, 196, 244, 0.5);
text-decoration:none;
}

#navlink {
text-decoration:none;
display:inline-block;
padding-top:10px;
padding-bottom:10px;
width:100px;
-webkit-border-radius:10px;
-moz-border-radius:10px;
border-radius:10px;
text-align:center;
}

Any idea to solve this? Thanks. Btw this is my code

A: The main answer to your question is:
You can't scroll the whole page (with the navbar included) because you use position: fixed.
http://quirksmode.org/css/css2/position.html

An element with position: fixed is taken out of the normal flow of the
  page and positioned at the desired coordinates relative to the browser
  window. It remains at that position regardless of scrolling.

In your case, if you want to keep your navbar position:fixed, AND make all the navigation links accessible when you resize your window, I have a better suggestion:, change the width values that you've set in pixels into percentages and your elements will be fluid. Never use pixel width values if you want your layout to be fluid.
Here's the updated code: http://jsfiddle.net/httg1e2w/3/
PS: Important: you are using "navlink" multiple times in your HTML. IDs are supposed to be Unique. Use classes instead. This may create you headaches in older browsers.
link


text:
Q: background-size min() min(); works in chrome but doesn't in firefox or Edge I just started developing a new site and already ran into trouble with different browsers.
I have these lines of css to set the background image:
body
{
    background-image: url("../Images/Background.jpg");
    background-repeat: no-repeat;
    background-size: max(100vw, 1920px) max(100vh, 876px);

}

This works fine in Chrome, but doesn't apply the background size in Firefox or Edge.
In the Firefox inspector it says 'invalid property value'.
Do you have any work around? I want the image to stretch to the window size, but maintain its size at its resolution if the window is smaller. I can't use min-height as that would stretch the window even if there is no content.
Thanks!

A: You can simulate this using pseudo element:

html:before {
  content: "";
  position:fixed;
  left:50%;
  top:50%;
  transform:translate(-50%,-50%);
  background: url("https://i.picsum.photos/id/1074/800/800.jpg") center/cover no-repeat;
  min-width:800px;
  min-height:800px;
  width:100vw;
  height:100vh;
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: App crash when button clicked I tried to give the action on the button, but after the click arises error like this.
In which section the error of my code?

public class SyncDataFragment extends Fragment {
    View view;
    Activity act;
    public static final String TAG = SyncDataFragment.class.getSimpleName();

    private Button btnUpload;

    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                    Bundle savedInstanceState) {

            view = inflater.inflate(R.layout.layout_sync_server, null);

            btnUpload = (Button) view.findViewById(R.id.btnSyncToServer);

            btnUpload.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                            submitData();
                    }
            });

            return view;

    }

    public void submitData() {

            final String urlPath = "http://www.mylink.co.id/insert";
            HashMap<String, String> params = new HashMap<String, String>();
            params.put("nama", "Bertho");
            params.put("alamat", "Palmerah");
            params.put("tanggal", "2015-03-18 11:34:00");

            JsonObjectRequest req = new JsonObjectRequest(urlPath, new JSONObject(params),
                   new Response.Listener<JSONObject>() {
                       @Override
                       public void onResponse(JSONObject response) {
                           try {
                               VolleyLog.v("Response:%n %s", response.toString(4));
                               Toast.makeText(act, response.toString(4), Toast.LENGTH_LONG).show();
                           } catch (JSONException e) {
                               e.printStackTrace();
                               Toast.makeText(act, "Error...Masuk catch", Toast.LENGTH_LONG).show();
                           }
                       }
                   }, new Response.ErrorListener() {
                       @Override
                       public void onErrorResponse(VolleyError error) {
                           VolleyLog.e("Error: ", error.getMessage());
                           Toast.makeText(act, error.getMessage(), Toast.LENGTH_LONG).show();
                       }
                   });

            // add the request object to the queue to be executed
            AppController.getInstance().addToRequestQueue(req);
            }
    }


text:
Q: Finding likeness between one row and many rows Disclaimer: I'm very new to MySQL, doing this as an experiment to learn more.
Essentially, I have a table where one row is the 'master' row. I want to compare this row against a handful of other rows. From that handful, I want to select the one that is the most 'correct' or similar to the master row and store it to a variable. If none of the handful rows are similar enough to the master, I'd just want to cancel the operation.
I can think of a way to do this with iteration, but I keep reading that iteration is very inefficient/bad practice with SQL and want to see if there's another way.
With this example, I'd want to select submission 2, and reject submissions 1 and 3.
Type, Answer 1, Answer 2, Answer 3
Master, 100, 200, 300
Submission 1, 100, 400, 300
Submission 2, 100, 200, 300
Submission 3, 200, 100, 300

However, in the following example, I'd want to select submission 1, despite the two not being exactly alike.
Type, Answer 1, Answer 2, Answer 3
Master, 100, 200, 300
Submission 1, 100, 400, 300
Submission 2 , 100, 500, 500
Submission 3, 200, 100, 300

Finally, here I'd want to select Submission 1, as it occurs before Submission 3, despite the two being the same degree of correct.
Type, Answer 1, Answer 2, Answer 3
Master, 100, 200, 300
Submission 1, 100, 400, 300
Submission 2 , 100, 500, 500
Submission 3, 500, 200, 300

A: Try the following query.  It computes the number of answers which the Master row has in common with each other row.  And in the case of tie by number of right answers, it uses the numerical difference from each wrong answer to choose the closest match.
SELECT t.Type, t.Answer1, t.Answer2, t.Answer3,
       (t.a1 + t.a2 + t.a3) AS numRight,
       (t.d1 + t.d2 + t.d3) AS numOff
FROM
(
    SELECT t2.Type, t2.Answer1, t2.Answer2, t2.Answer3,
           CASE WHEN t1.Answer1 = t2.Answer1 THEN 1 ELSE 0 END AS a1,
           CASE WHEN t1.Answer2 = t2.Answer2 THEN 1 ELSE 0 END AS a2,
           CASE WHEN t1.Answer3 = t2.Answer3 THEN 1 ELSE 0 END AS a3,
           ABS(t1.Answer1 - t2.Answer1) ASd1,
           ABS(t1.Answer2 - t2.Answer2) AS d2,
           ABS(t1.Answer3 - t2.Answer3) AS d3
    FROM yourTable t1 INNER JOIN yourTable t2
        ON t1.Type = 'Master' AND t2.Type <> 'Master'
) t
ORDER BY numRight DESC, numOff

If you just want one row, you can add LIMIT 1 to the end of the query.
Demo here:
SQLFiddle


text:
Q: Firebase orderby() with equalTo() returns zero items I have this rule in my firebase database
"Item":{
    "$userId": {
    ".write": "auth != null && $userId === auth.uid"
    }
}

I have this data
Item
 nXQw4a2jlMg34567811glaTD0bE2
   -KNJLSxfR_S8AeLj0v7d
     height:20
     id:-KNJLSxfR_S8AeLj0v7d

When i write the below query, everything is ok.
mDataBase = FirebaseDatabase.getInstance().getReference(FirebaseConstants.ITEM);
  query = mDataBase.orderByChild("userId/height").limitToLast(2);

But the below query returns zero
public void getItems(String key){
//key is -KNJLSxfR_S8AeLj0v7d
DatabaseReference reference = FirebaseDatabase.getInstance().getReference(FirebaseConstants.ITEM);
reference.orderByChild("userId/id").equalTo(key).addValueEventListener(new MyEventListener());

}

My listener
 private class MyEventListener implements ValueEventListener{

@Override
public void onDataChange(DataSnapshot dataSnapshot) {
  if(dataSnapshot != null){

   Log.d("size is "+dataSnapshot.getChildrenCount()) // returns 0
   for(DataSnapShot entry: dataSnapshot){
     Item item = entry.getValue(Item.class);
     Log.d("height is "+ item.getHeight())
   }

  }

}

@Override
public void onCancelled(DatabaseError databaseError) {

}

}

Why is it returning zero and already i have data in my firebase Db?

A: There are a few small problems with your code:

*

*There is no child userId, that you are trying to order/filter on: orderByChild("userId/height"). So that means the result will be empty.

*You cannot loop over a snapshot (I'm surprised that even compiles). Instead you should loop over its children: for(DataSnapShot entry: dataSnapshot.getChildren()) {...

*You're using a query, but your code would be more efficient and a lot more scalable if you'd simply look up the item by their key: reference.child(key).addValueEventListener(...


text:
Q: div height in percentage does not work even with 100perc html and body I'd like to set the div height using percentages that do not depend on items in it.
I got a fixed header on the top of the screen and a centered div. But set height in percentages does not work. It enlarges only if I add some items in there.
Please help.
I have this code:
<!DOCTYPE html>

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

header

main info

And this CSS.
html{
    width: 100%;
    height: 100%;
}
body{
    overflow: hidden;
    margin: 0;
    width: 100%;
    height: 100%;
}

header{
    position: fixed;
    top: 0px;
    width: 100%;
    height: 10%;
    border: solid red 1px;
}

#main{
    display: block;
    width: 65%;
    height: 80%;
    border: solid green 1px;
    margin: 8% auto 0 auto;
}

A: You forgot to make it's parent 100% height too.
#conteiner has automatic height by default because its div block. And default height is height of its children. If parent's height isn't set manually, children height in percents are ignoring by browser
#conteiner {
    height: 100%;
}

A: at your style file you have to write style for container div code like
#container{
     height:100%;
}


text:
Q: android soft keyboard whill be covered by input filed in cordova when I text input field, the input field is covered by the softkeyboard in android phone. I build my app with cordova  / angular 6
I have tried the solution:
<preference name="Fullscreen" value="false" />
<edit-config file="AndroidManifest.xml" mode="merge" target="/manifest/application/activity[@android:name='MainActivity']">
    <activity android:windowSoftInputMode="adjustResize" />
</edit-config>

but still not working...
Is any other possible way to set by cordova, not use input focus scroll? thank you :)

A: We solved using two functions in JS and the plugin ionic-plugin-keyboard.
First, catch up the event in your main function:
window.addEventListener('native.keyboardshow', keyboardShowHandler);
window.addEventListener('native.keyboardhide', keyboardHideHandler);

Then, use functions to move your fields up/down (here is our code managing our custom login form as an example to modify):
function keyboardShowHandler(e) {
$("#login .content a.reset-password").slideUp("slow", function () {});
$("#login .content a.sign-up").slideUp("slow", function () {});
$("#login .content a.credits").slideUp("slow", function () {});
$("#login .content a.tutorial").slideUp("slow", function () {});
}

function keyboardHideHandler(e) {
$("#login .content a.reset-password").slideDown("slow", function () {});
$("#login .content a.sign-up").slideDown("slow", function () {});
$("#login .content a.credits").slideDown("slow", function () {});
$("#login .content a.tutorial").slideDown("slow", function () {});
}


text:
Q: Flutter cloud firestore range base query What I'm trying to do:
I have a collection called "Users" where each user(document) has its own latitude and longitude saved inside of that file. With that, I'm trying to do a query which will look something like this.
_firestore
        .collection('Users')
        .where('lat', isGreaterThanOrEqualTo: docLat)
        .where('lat', isLessThanOrEqualTo: maxLat)
        .where('lon', isGreaterThanOrEqualTo: docLon)
        .where('lon', isLessThanOrEqualTo: maxLon)

Error:

PlatformException (PlatformException(error, All where filters other
  than whereEqualTo() must be on the same field. But you have filters on
  'lat' and 'lon', null))

Problems:

*

*I can not use GeoPoint as type in my document. Why? Because if I will search base on that, something like this:

_firestore
        .collection('Users')
        .where('geopoint', isGreaterThanOrEqualTo: myGeopoint)
        .where('geopoint', isLessThanOrEqualTo: limitGeopoint)
is not going to work because it will comper just the Latitude of my GeoPoint, and the Longitude is going to be ignored.

*I can not use Geohash. If will compare them in the same way as I did with GeoPoints it will fail to show me all the results because the way how geohash works.

*I know about some packages like firestore_helpers or geoflutterfire. But the problem with those is that I CAN NOT limit the result set. I etcher get all of them or not. Or if have any idea how can I limit them let me know (no, I don't want to limit the collection result, before the data is going to be sent to one of those packages, check my last question)

What I've tried to do:
I head about Composite Index used in firebase and I've made them like this.

But the query is still not working and I wasn't able to find any example with composite index yet used in flutter (or at least dart) for my case.
So far as I understood I need to use the Compose Index something like this.
 _firestore
        .collection('Users')
        .where('lat_lon', isGreaterThanOrEqualTo: userData.geopoint.latitude.toString() + "_0.0")
        .where('lat_lon', isLessThanOrEqualTo: maxLimit.latitude.toString() + "_0.0")
        .where('lat_lon', isGreaterThanOrEqualTo:  "0.0_" + userData.geopoint.longitude.toString())
        .where('lat_lon', isLessThanOrEqualTo: "0.0_" +maxLimit.longitude.toString())

But is not working either. Do you have any solution for me? I really need to find a way to fix this.


text:
Q: Run time Complexity I believe that the following code is big theta of n^3, is this correct?
for (int i = 0; i < n; i ++)
{  // A is an array of integers
   if (A[i] == 0) {
      for (int j = 0; j <= i; j++) {
          if (A[i] == 0) {
             for (int k = 0; k <= j; k++) {
                 A[i] = 1;
             }
          }
      }
   }
}

And that the following is big theta of nlog(n)
for (int i = 1; i < n; i *= 2)
{
   func(i);
}

void func(int x) {
  if (x <= 1) return;
  func(x-1);
}

because the for loop would run log(n) times, and func runs at most n recursive calls.
Thanks for the help!

A: Your intuition looks correct. Note that for the first bit if the input contains non-zero elements the time complexity drops down to big-theta(n). If you remove the checks it would definitely be big-theta(n^3).

A: You are correct about the second snippet, however the first is not Big-Theta(n^3). It is not even O(n^3)! The key observation is: for each i, the innermost loop will execute at most once.
Obviously, the worst-case is when the array contains only zeros. However, A[i] will be set to 1 in the first pass of the inner-most loop, and all subsequent checks of if (A[i] == 0) for the same i will be evaluated to false and the innermost loop will not be executed anymore until i increments. Therefore, there are total of 1 + 2 + 3 + .. + n = n * (n + 1) / 2 iterations, so the time complexity of the first snippet is O(n^2).
Hope this helps!


text:
Q: Jquery not disabled the parent Input tag not disabled.This is my code.Please help me.
var input = $('input[value="' + $(this).val() + '"]');
input.prop('disabled', true);
input.parent('li').addClass('disabled');

A: You should use filter() to find the input with value instead of using Attribute value selector.

Reduce the set of matched elements to those that match the selector or pass the function's test.

Also you can use closest() to traverse up to desired parent.
Script
var value = $(this).val();
var input = $('input').filter(function(){
    return value == $(this).val();
}).prop('disabled', true);
input.closest('li').addClass('disabled');


text:
Q: Stopping setinterval function in Jquery after loading required page I'm using this code below to load external pages into a div. One of the pages has a setinterval function for 1 second. when i navigate back to the page the setinterval code runs twice and i only want it to run once. how do i stop the interval when i navigate out of that page?
$(document).ready(function() {
    $('.content').html("");
    $('.content').load($('.john:first').attr('href'));
    $('.john').click(function() {
        var href = $(this).attr('href');
        $('.content').html("");
        $('.content').load(href).fadeIn('1000');
        return false;
    });
});

the setinterval function in that page looks like this.
function loadingstaff (){
    var ids = "";
    $.post("loadfast.php",{id: ids},
    function (data){
        $(".getposta").html(data);
    });
}
var refreshIntervalId = setInterval(loadingstaff, 1000);

A: $('.john').click(function(event) {
    event.stopImmediatePropagation()
    var href = $(this).attr('href');
    $('.content').html("");
    $('.content').load(href).fadeIn('1000');
    return false;
});

A: Use setTimeout insted of setInterval. The setInterval do the task after the given time recursively, and you need just one time, so the setTimeout is best for your purpose.
function loadingstaff (){
   var ids = "";
   $.post("loadfast.php",{id: ids},
   function (data){
       $(".getposta").html(data);
   });
 }
var refreshIntervalId = setTimeout(loadingstaff, 1000);


text:
Q: How to show one JSON Object per ViewPager in Android? I am working on a short news app. It's parsed JSON from a URL. I want to show one news per view pager.on swipe on next ViewPager, I want to show next news like the list. How can I can do that with ViewPager?

A: Set JSON data to PagerAdapter as we set to Base Adapter or other adapters & create custom layout for adapter.

view_pager_layout.xml

<RelativeLayout
        android:id="@+id/loutPager"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center">

        <android.support.v4.view.ViewPager
            android:id="@+id/viewPager"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_above="@+id/loutCirIndicator"
            android:background="@android:color/transparent"
            android:padding="5dp"/>

        <LinearLayout
            android:id="@+id/loutCirIndicator"
            android:layout_width="match_parent"
            android:layout_height="20dp"
            android:layout_alignParentBottom="true"
            android:background="@android:color/transparent"
            android:gravity="center_vertical"
            android:orientation="horizontal">

            <me.relex.circleindicator.CircleIndicator
                android:id="@+id/indicator"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_gravity="center"
                android:gravity="center"
                app:ci_drawable="@drawable/bg_selected_indicator"
                app:ci_drawable_unselected="@drawable/bg_unselected_indicator" />
        </LinearLayout>

    </RelativeLayout>

row_pager_item.xml

<LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center"
        android:orientation="vertical">

        <ImageView
            android:id="@+id/imageView"
            android:layout_width="match_parent"
            android:layout_height="200dp"
            android:adjustViewBounds="true"
            android:clickable="false"
            android:scaleType="centerInside" />

        <TextView
            android:id="@+id/textView"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:text="abc" />

    </LinearLayout>

ViewPager Adapter

public class SamplePagerAdapter extends PagerAdapter {
    Activity activity;
    List<Response_Model> Arr_ResultList;
    ImageView imageView;
    TextView textView;

    public SamplePagerAdapter(final Activity activity,final  List<Response_Model> Arr_ResultList) {
        this.activity = activity;
        this.Arr_ResultList = Arr_ResultList;
    }

    @Override
    public int getCount() {
        return Arr_ResultList.size();
    }

    @Override
    public boolean isViewFromObject(View view, Object object) {
        return view == object;
    }

    @Override
    public Object instantiateItem(ViewGroup container, int position) {

        final int pos = position;

        View view = LayoutInflater.from(container.getContext()).inflate(R.layout.row_pager_item, container, false);
        imageView = (ImageView) view.findViewById(R.id.imageView);
        textView = (TextView) view.findViewById(R.id.textView);

            Glide.with(activity).load(Arr_ResultList.get(pos).getImage())
                    .thumbnail(0.5f)
                    .crossFade()
                    .diskCacheStrategy(DiskCacheStrategy.ALL)
                    .into(imageView);

            textView.setText(Arr_ResultList.get(pos).getName());

        container.addView(view);

        return view;

    }

    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
        container.removeView((LinearLayout) object);
    }
}

Set Pager Adapter to ViewPager

SamplePagerAdapter pagerAdapter = new SamplePagerAdapter(MainActivity.this, Arr_Result_List);
viewPager.setAdapter(pagerAdapter);
indicator.setViewPager(viewPager);

A: You can use PagerAdapter for ViewPager and create your custom xml layout and
set your view on cell by position. Pass your list into pager adapter in adapter constructor.
You can refer this link it will be help you.

*

*https://www.journaldev.com/10096/android-viewpager-example-tutorial


text:
Q: Get folder path in ASP.NET page I am working on an app to extract data and store into database. I create a windows service and start it from asp.net page. The thing I want to do now is to select folder path from my machine and then my windows service can extract data from the files in that folder.
suppose the folder path on my machine is C:\test\data.txt, and in code behind, I get this path through asp.net FileUpload contrl, it may look like the following:
string filePath = FileUploadControl.filePath(); //filePath is exactly C:\test\data.txt

I did research online, it looks like that I cannot make it by FileUpload control. So I am wondering that if I can walk around this limit? Thanks in advance.

A: You can't read client files 'just like that' on a server. Those are two separate systems and security makes it undesirable to make this possible.


text:
Q: Setting up a React application and NodeJS backend in Kubernetes? I am trying to setup a sample React application wired to a NodeJS backend as two pods in Kubernetes. This is the (mostly) the default CRA and NodeJS application with Express i.e. npx create-react-app my_app.
Both application runs fine locally through yarn start and npm app.js respectively. The React application uses a proxy defined in package.json to communicate with the NodeJS back-end.
React package.json
...
  "proxy": "http://localhost:3001/"
...

React Dockerfile
FROM node:10
WORKDIR /usr/src/app
COPY package*.json ./
RUN yarn
COPY . .
CMD [ "yarn", "start" ]

NodeJS Dockerfile
FROM node:10
WORKDIR /usr/src/app
COPY package*.json ./
RUN npm install
COPY . .
EXPOSE 3001
CMD [ "node", "app.js" ]

ui-deployment
apiVersion: extensions/v1beta1
kind: Deployment
metadata:
    name: sample-ui
    namespace: my_namespace
spec:
  replicas: 1
  selector:
    matchLabels:
      app: my_namespace
      component: sample-ui
  template:
    metadata:
      labels:
        app: my_namespace
        component: sample-ui
    spec:
      containers:
      -
        name: sample-ui
        image: xxx
        imagePullPolicy: IfNotPresent
        ports:
        - containerPort: 3000
          name: http
          protocol: TCP
        resources:
          limits:
            cpu: 100m
            memory: 128Mi
          requests:
            cpu: 100m
            memory: 128Mi

server-deployment
apiVersion: extensions/v1beta1
kind: Deployment
metadata:
    name: sample-server
    namespace: my_namespace
spec:
  replicas: 1
  selector:
    matchLabels:
      app: my_namespace
      component: sample-server
  template:
    metadata:
      labels:
        app: my_namespace
        component: sample-server
    spec:
      containers:
      -
        name: sample-server
        image: xxx
        imagePullPolicy: IfNotPresent
        ports:
        - containerPort: 3001
          name: http
          protocol: TCP
        resources:
          limits:
            cpu: 100m
            memory: 128Mi
          requests:
            cpu: 100m
            memory: 128Mi

ui-service
apiVersion: v1
kind: Service
metadata:
  name: sample-ui
  namespace: my_namespace
  labels: {app: sample-ui}
spec:
  type: LoadBalancer
  selector:
    component: sample-ui
  ports:
  - name: listen
    protocol: TCP
    port: 3000

server-service
apiVersion: v1
kind: Service
metadata:
  name: sample-server
  namespace: my_namespace
  labels: {app: sample-server}
spec:
  selector:
    component: sample-server
  ports:
  - name: listen
    protocol: TCP
    port: 3001

Both services run fine on my system.
get svc
sample-server            ClusterIP      10.19.255.171   <none>           3001/TCP                     26m
sample-ui                LoadBalancer   10.19.242.42    34.82.235.125    3000:31074/TCP               26m

However, my deployment for the CRA crashes multiple time despite indicating it is still running.
get pods
sample-server-598776c5fc-55jsz                     1/1     Running     0          42m
sample-ui-c75ccb746-qppk2                          1/1     Running     4          2m38s

I suspect that my React Dockerfile is improperly configured but I'm not sure how to write it to work with a NodeJS backend in kubernetes.
a) How can I setup my Dockerfile for my CRA such that it will run in a pod?
b) How can I setup my docker services and pods such that they communicate?

A: You will have to use come API gateway in front of your server or you can use ambassador from kubernetes.
Then you can get your client connected to server.

A:
a) How can I setup my Dockerfile for my CRA such that it will run in a
pod?

React docker file is looking good you need to check why container of pod is failing.
Using kubectl describe pod <POD name> or debug more logs using the command kubectl logs <pod name>

How can I setup my docker services and pods such that they
communicate?

For this, you are on right track, how server and frontend will communicate in Kubernetes using the service name.
This might weird at first level but Kubernetes DNS takes care of it.
How if you have two service frontend (sample-ui) and backend (sample-server)
sample-ui will send the request to sample-server so they get connected that way.
You can also try this by going inside the sample-ui POD(container)
kubect exec -it sample-ui-c75ccb746-qppk2 -- /bin/bash

now you are inside of sample-ui container let's send request to sample-server from here
if curl not exist you can install it using the apk install curl or apt-get install curl or yum install curl
curl http://sample-server:3001

Magic you might see response from server.
So your while flow goes like
user coming to frontend load balancer service > calling sample-ui service > internally inside kubernetes cluster now your sample-ui calling the sample-server
All the service that you create inside the K8s will be accesible by it's name.


text:
Q: how to write Python script that ingests this JSON data and transforms it into a data table `Python script that ingests this JSON data and transforms it into a data table
`Below is the JSON data
{"inappproduct": [{"packageName": "game",
  "sku": "game_product1",
  "status": "active",
  "purchaseType": "managedUser",
  "defaultPrice": {"priceMicros": "69990000", "currency": "CAD"},
  "prices": {"DZ": {"priceMicros": "6325000000", "currency": "DZD"},
   "AU": {"priceMicros": "79990000", "currency": "AUD"},
   "CA": {"priceMicros": "69990000", "currency": "CAD"},
   "IT": {"priceMicros": "54990000", "currency": "EUR"},
   "JP": {"priceMicros": "6000000000", "currency": "JPY"},
   "RU": {"priceMicros": "3790000000", "currency": "RUB"},
   "SG": {"priceMicros": "68980000", "currency": "SGD"},
   "KR": {"priceMicros": "65000000000", "currency": "KRW"},
   "GB": {"priceMicros": "48990000", "currency": "GBP"},
   "US": {"priceMicros": "49990000", "currency": "USD"},
  "listings": {"en-US": {"title": "currency_1",
    "description": "In-game currency"}},
  "defaultLanguage": "en-US"}},
 {"packageName": "game",
  "sku": "game_bundle1",
  "status": "active",
  "purchaseType": "managedUser",
  "defaultPrice": {"priceMicros": "139990000", "currency": "CAD"},
  "prices": {"DZ": {"priceMicros": "12750000000", "currency": "DZD"},
   "AU": {"priceMicros": "159990000", "currency": "AUD"},
   "CA": {"priceMicros": "139990000", "currency": "CAD"},
   "IT": {"priceMicros": "109990000", "currency": "EUR"},
   "JP": {"priceMicros": "11800000000", "currency": "JPY"},
   "RU": {"priceMicros": "7490000000", "currency": "RUB"},
   "SG": {"priceMicros": "148980000", "currency": "SGD"},
   "KR": {"priceMicros": "130000000000", "currency": "KRW"},
   "GB": {"priceMicros": "99990000", "currency": "GBP"},
   "US": {"priceMicros": "99990000", "currency": "USD"},
  "listings": {"en-US": {"title": "bundle",
    "description": "In-game bundle"}},
  "defaultLanguage": "en-US"}}]}

The following are some considerations:
 ● The column packageName can be found from the JSON key "packageName"
   ● The column sku can be found from the JSON key "sku"
 ● The column countryCode can be found from the JSON keys that contain two-
   letter country codes nested within the JSON key "prices"
 ● The column currency can be found from the JSON key "currency"
   ` ● The column price can be found from the JSON key "priceMicros". The price
       is equal to "priceMicros" divided by 1,000,000.
`the result should look like below

packageName         sku          countryCode    currency   price
game            game_product1     CA            CAD        69.99
game            game_product1     US            USD        48.99
. . . . .
. . . . .
. . . . .
game            game_bundle1      GB            GBP        99.99

A: I'd use pandas and a list comprehension, so install pandas package
if you don't have installed yet.
I'll give a name to your "JSON data".
my_json = {

"inappproduct": [{"packageName": "game",
  "sku": "game_product1",
  "status": "active",
  "purchaseType": "managedUser",
  "defaultPrice": {"priceMicros": "69990000", "currency": "CAD"},
  "prices": {"DZ": {"priceMicros": "6325000000", "currency": "DZD"},
   "AU": {"priceMicros": "79990000", "currency": "AUD"},
   "CA": {"priceMicros": "69990000", "currency": "CAD"},
   "IT": {"priceMicros": "54990000", "currency": "EUR"},
   "JP": {"priceMicros": "6000000000", "currency": "JPY"},
   "RU": {"priceMicros": "3790000000", "currency": "RUB"},
   "SG": {"priceMicros": "68980000", "currency": "SGD"},
   "KR": {"priceMicros": "65000000000", "currency": "KRW"},
   "GB": {"priceMicros": "48990000", "currency": "GBP"},
   "US": {"priceMicros": "49990000", "currency": "USD"},
  "listings": {"en-US": {"title": "currency_1",
    "description": "In-game currency"}},
  "defaultLanguage": "en-US"}},
 {"packageName": "game",
  "sku": "game_bundle1",
  "status": "active",
  "purchaseType": "managedUser",
  "defaultPrice": {"priceMicros": "139990000", "currency": "CAD"},
  "prices": {"DZ": {"priceMicros": "12750000000", "currency": "DZD"},
   "AU": {"priceMicros": "159990000", "currency": "AUD"},
   "CA": {"priceMicros": "139990000", "currency": "CAD"},
   "IT": {"priceMicros": "109990000", "currency": "EUR"},
   "JP": {"priceMicros": "11800000000", "currency": "JPY"},
   "RU": {"priceMicros": "7490000000", "currency": "RUB"},
   "SG": {"priceMicros": "148980000", "currency": "SGD"},
   "KR": {"priceMicros": "130000000000", "currency": "KRW"},
   "GB": {"priceMicros": "99990000", "currency": "GBP"},
   "US": {"priceMicros": "99990000", "currency": "USD"},
  "listings": {"en-US": {"title": "bundle",
    "description": "In-game bundle"}},
  "defaultLanguage": "en-US"}}]}

And then:
>>> import pandas as pd
>>> records = [
...     {
...         "packageName": x["packageName"],
...         "sku": x["sku"],
...         "countryCode": k,
...         "currency": v["currency"],
...         "price": str(float(v["priceMicros"])/1e6)
...     }
...     for x in my_json["inappproduct"]
...     for k, v in x["prices"].items()
...     if isinstance(v, dict) and v.get("currency") is not None
... ]
>>> app_df = pd.DataFrame(records)
>>> app_df = app_df.reindex(columns=["packageName", "sku", "countryCode", "currency", "price"])
>>> app_df
   packageName            sku countryCode currency     price
0         game  game_product1          CA      CAD     69.99
1         game  game_product1          JP      JPY    6000.0
2         game  game_product1          IT      EUR     54.99
3         game  game_product1          DZ      DZD    6325.0
4         game  game_product1          GB      GBP     48.99
5         game  game_product1          RU      RUB    3790.0
6         game  game_product1          US      USD     49.99
7         game  game_product1          KR      KRW   65000.0
8         game  game_product1          AU      AUD     79.99
9         game  game_product1          SG      SGD     68.98
10        game   game_bundle1          CA      CAD    139.99
11        game   game_bundle1          JP      JPY   11800.0
12        game   game_bundle1          IT      EUR    109.99
13        game   game_bundle1          DZ      DZD   12750.0
14        game   game_bundle1          GB      GBP     99.99
15        game   game_bundle1          RU      RUB    7490.0
16        game   game_bundle1          US      USD     99.99
17        game   game_bundle1          KR      KRW  130000.0
18        game   game_bundle1          AU      AUD    159.99
19        game   game_bundle1          SG      SGD    148.98


text:
Q: JAVA - Trying to use a variable from inside an actionperformed outside the class I am trying to access the (double) percentage variable outside my actionPerformed while retaining the changes that it goes through.
it is a drop down menu, and an ok button you press. once you press it, it calculates a value for percentage, which then i want to use later on in the program.
Here is a snippet of the code:
btn.addActionListener(
new ActionListener(){
    public void actionPerformed(ActionEvent e){

    String currentCountry = (String)cb.getSelectedItem();
    double percentage = 0.00;

        if(currentCountry.equals("Brazil") || currentCountry.equals("Argentina")) {
            cb2.removeAllItems();
            for(int i = 0; i < choicesSouthAmerica.length; i++) {
                cb2.addItem(choicesSouthAmerica[i]);
            }
        }

        else {

            cb2.removeAllItems();
            for(int i = 0; i < choicesEurope.length; i++) {
                cb2.addItem(choicesEurope[i]);
            }
        }

    btn.setEnabled(false);
    btn2.setEnabled(true);

        if(currentCountry.equals("Brazil") || currentCountry.equals("Argentina")){
                percentage = 1/5;
                System.out.println(percentage);
            }
        else{
                percentage = 1/8;
                System.out.println(percentage);
            }
        }
    }

);

Thank you kindly

A: you could use the putClientProperty(Object,Object) and getClientProperty(Object) functions as follow :
JButton btn = new JButton("Ok");
    btn.putClientProperty("percentage",1.0);//or whatever initial value
    btn.addActionListener(arg0 -> {
        JButton source = (JButton) arg0.getSource();
        double per = (double)source.getClientProperty("percentage");
        per = (double)10/8;
        source.putClientProperty("percentage",per);
    });
    double percentage = (double)btn.getClientProperty("percentage");//or use it in any other object that has access to the btn object

A: Sadly Java doesn't support closures, so you can not modify variables outside the scope of an anonymous class. But you can access final variables, so in principle you can do something like this:
class Percentage {
    double p;
}
final Percentage p = new Percentage();

btn.addActionListener(
    new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            // [...]
            p.p = 1/5;
            // [...]
        }
    }
);

Then you can access the updated percentage via p.p outside of your anonymous class. (Btw. is it really a "percentage" or in fact a ratio?)
But this doesn't seem very idiomatic for Java, so the clean solution is probably just to make a proper class with a private instance variable and a getter and use this instead of the anonymous class.

A: I think what you actually need is just a static field (it can have whatever access modifiers you want). So something like this I think should work:
public class Test {

        static double d = 0;

        public static void main(String[] args) {
            JButton b = new JButton("ASDF");
            b.addActionListener(new ActionListener(){
                @Override
                public void actionPerformed(ActionEvent arg0) {
                    d = 5;
                }

            });
        }
    }


text:
Q: Vector of strings with a counter C++ I am inputting a file of characters and each word gets its own spot in a vector. I then need to keep track of each word and find out how many times each unique word appeared such that:
There are three trees trees trees
should output:
There 1
are 1
three 1
trees 3
I was wondering how to use a vector of strings to keep tract of each word.
Would I do a vector of strings with each string having a vector of a single int?

A: Don't drive a nail with a screwdriver. A std::vector, isn't particularly useful for this task at its most-basic form  : simple frequency calculation. Arbitrary input from standard input would best utilize an associative container, where the key is the input string, and the value is an accumulated frequency.
Unordered Frequency Calculation
A unordered mapping class, std::unordered_map, keying on std::string and mapping to a frequency counter for that string, can be used to track basic frequency. For example:
#include <iostream>
#include <vector>
#include <string>
#include <unordered_map>

int main()
{
    std::unordered_map<std::string, unsigned> m;
    std::string word;
    while (std::cin >> word)
        ++m[word]; // increment the count for this word

    for (auto const& pr : m)
        std::cout << pr.first << ':' << pr.second << '\n';
}

Lexicographical Ordered Frequency
Note: there is no specific order to using the associative container std::unordered_map (hence the name). If you desired lexicographical ordering, you could simply use a regular std::map. such as:
#include <iostream>
#include <vector>
#include <string>
#include <map>

int main()
{
    std::map<std::string, unsigned> m;
    std::string word;
    while (std::cin >> word)
        ++m[word];

    for (auto const& pr : m)
        std::cout << pr.first << ':' << pr.second << '\n';
}

Positional Retention Frequency Calculation
Maintaining where, within the input stream, a word appears while calculating the frequency counter is also possible, and takes only a little more code. Choose either the unordered or ordered associative container as we did before, but rather than mapping to unsigned, we map to std::vector<unsigned>, where we accumulate a word counter as we consume input words. The overall size of each vector still retains the frequency counter but the vector itself retains the position within the input stream the associated word appears. For example:
#include <iostream>
#include <vector>
#include <string>
#include <map>

int main()
{
    std::map<std::string, std::vector<unsigned int>> m;
    std::string word;
    unsigned ctr = 0;
    while (std::cin >> word)
        m[word].push_back(++ctr);

    for (auto const& pr : m)
    {
        std::cout << pr.first << ':' << pr.second.size() << " { ";
        for (auto pos : pr.second)
            std::cout << pos << ' ';
        std::cout << "}\n";
    }
}

This will produce output of the form:
word : frequency { n1 n2 n3... }

where word is a distinct word, frequency is the overall frequency in the input stream, and n1,n2,n3,... are the positions (starting at 1) where the word appeared during processing.
Hopefully, one of these methods is useful.

A: You can use the multiset class from c++ which will keep track of how many times you added each word to the set. Also keep in mind you can read complete words from in streams in c++ and it will automatically skip any space characters.
I will read from stdin for this example (note, I did not compile this, it's just to show the idea).
#include <set>
using namespace std;

int main(){
  string word;
  multiset<string> ocurrences;
  while(cin >> word){
    ocurrences.insert(word);
  }
  for(string w : ocurrences){  // Iterate over all words in the set
    cout<<w<<" "<<counts.count(w)<<" ";
  }
}

As mentioned in the comments, if you want to print the words in the order of first ocurrence, just keep a vector<string> and add each word you read if it's not already in the set, then iterate over this vector instead of the set.
#include <set>
using namespace std;

int main(){
  string word;
  vector<string> words;
  multiset<string> ocurrences;
  while(cin >> word){
    if(ocurrences.count(word) == 0) //Is this the first time we see this word?
      words.push_back(word);
    ocurrences.insert(word);
  }
  for(string w : words){ //Iterate over the words in the order
                         //they appeared in the input.
    cout<<w<<" "<<ocurrences.count(w)<<" ";
  }
}

Another thing, even though a multiset is better suited to fix this specific problem, what you are asking about in your question is called a map, a data structure which associates a key to a value (possibly of different types). C++ already has a map implementation. In this case you would need a map<string, int> to associate each word to the times it occurs.

A: Here's a way you can do this by accumulating your dictionary over a stream of words and using C++17 structured bindings:
int main()
{
    std::istringstream words( "There are three trees trees trees" );

    auto dic = std::accumulate(
        std::istream_iterator< std::string >( words ) ,
        std::istream_iterator< std::string >( ) ,
        std::unordered_map< std::string , int >( ) ,
        []( auto && map , auto && word ) -> decltype( auto )
        {
            auto [ it , success ] = map.try_emplace(
                std::forward< decltype( word ) >( word ) , 0 );

            ++ it->second;

            return std::forward< decltype( map ) >( map );
        } );

    for ( const auto & [ key , value ] : dic )
    {
        std::cout << key << ": " << value << std::endl;
    }
}

Live at Coliru (with some warnings though)
> trees: 3
> three: 1
> There: 1
> are: 1


text:
Q: How do you swap the commands for two symbols? I find that I much prefer \varphi to \phi and generally would rather use the \varphi than the \phi. But it's three more characters to type \varphi instead of \phi, which is most troublesome. So I would like to swap the two commands. I tried a couple of things on my own, but one resulted in an infinite loop in compilation and the other led to \varphi taking over all of the \phi commands I made. What would be the correct way to do this?

A: The usual way to exchange two values is to use a temporary command name to store one of them while swapping, but if, for no particular reason, you want to avoid the extra command name then:
\documentclass{article}

\begin{document}

$\phi\varphi$

\expandafter\mathchardef\expandafter\varphi\number\expandafter\phi\expandafter\relax
\expandafter\mathchardef\expandafter\phi\number\varphi

$\phi\varphi$

\end{document}

A: Try the following:
$\phi\varphi$
\let\temp\phi
\let\phi\varphi
\let\varphi\temp
$\phi\varphi$

A: For non-complex macros, using an interim macro to swap definitions is sufficient. However, if the macros (say, funcA and funcB) takes optional arguments, you need to use a different approach via letltxmacro's macro \LetLtxMacro{<new macro>}{<old macro>}:
\usepackage{letltxmacro}% http://ctan.org/pkg/letltxmacro
%...
\LetLtxMacro{\temp}{\funcA}
\LetLtxMacro{\funcA}{\funcB}
\LetLtxMacro{\funcB}{\temp}


text:
Q: How to delay expensive calculation in postgres until final steps I have a simple postgres 9.1 query that contains a very expensive calculation:
SELECT a, b, sum(c), very_expensive_calculation(f)
FROM my_table
GROUP BY a, b, f

The function very_expensive_calculation() is a custom function of mine (non-aggregate) that runs a recursive summation of values behind the scenes, and because of this it takes a while. The problem occurs because there are many duplicates in my_table because it's very de-normalized so it runs once for each row when it should only run on distinct values. I tried the following to run the function on the pre-grouped values:
SELECT a, b, c_sum, very_expensive_calculation(f)
FROM (
  SELECT a, b, sum(c) c_sum, f
  FROM my_table
  GROUP BY a, b, f
) pre_group

This cuts down on the number of runs for very_expensive_calculations() because if the original query contained 100 rows but the grouped contained only 10, then I have a 90% reduction in executions. However, this is hacky and is coming with other problems (there's a lot more criteria and columns w/ custom logic that I'm not showing, and they're suffering from this hack).
Can I run the first query but delay very_expensive_calculation() to run on the already grouped values for f, possibly by declaring very_expensive_function() as an aggregate?
EDIT (@gordon linoff): Would the following behave the same as the answer mentioned below?
WITH fvec AS (
 select f, very_expensive_calculation(f) as vec
 from (select distinct f from my_table) mt
)
Select a, b, sum(c), fvec.vec
from my_table agg inner join fvec on agg.f = fvec.f
group by a, b, fvec.vec

Our auto-generated code can do WITH clauses easily but I'm not sure if this behaves the same as the join solution below.

A: Given your original query, I think this might be the cheapest way would be to do the calculation only one time for each f and join the results back in:
select agg.*, fvec.fec
from (SELECT a, b, sum(c) as sumc
      FROM my_table
      GROUP BY a, b, f
     ) agg join
     (select f, very_expensive_calculation(f) as vec
      from (select distinct f from my_table) mt
     ) fvec
     on agg.f = fvec.f;

I don't see how writing a custom-aggregation function would help unless the aggregation function stashed already computed values.  The aggregation function is going to be called for each row in the original table, not each row in the post-aggregated results.


text:
Q: How to access to appsettings from service class in .net core 7 application using minimal api? I'm working on a .net core 7 application. I have to implement a minimal api using a service class.
In this service class, i've to access to appsettings.
In the program.cs file, i have the following lines :
var builder = WebApplication.CreateBuilder(args);
builder.Configuration.AddJsonFile("appsettings.Local.json", true);
builder.Configuration["groupParameterOne:ParameterA"];

I need to access to appsettings from a service class but i don't know how to inject the builder in my service class.
I can implement a static class to set and access my settings but i don't think it's the right way to do that.
Thanks in advance for your help.


text:
Q: The difference in these two queries (EXISTS with NOT LIKE and NOT EXISTS with LIKE) I have a really hard time to understand the difference between these two queries. The don't give the same output, just a slightly difference in the results. Isn't these two queries the same, but just inverted? You can see the difference in the last subquery.
SELECT *
FROM[dbo].[MNO International AB$Item] t1
WHERE
    t1.[Item Type] = 0
    AND (
            NOT EXISTS(SELECT * FROM [dbo].[MNO International AB$Item Cross Reference] t2 WHERE t2.[Item No_] = t1.No_ AND t2.[Cross-Reference Type No_] = 'EAN13' AND t2.[Cross-Reference No_] <> '' AND t2.[Cross-Reference Type] = 3)
            OR t1.[Statistics Group] = 0
        ) --Result: 2178

    AND NOT EXISTS
                (SELECT * FROM [dbo].[MNO International AB$Master] t2
                 WHERE t1.[Master No_] = t2.No_
                 AND t2.[Collection No_] LIKE 'NEW-NOS'
                 )

The other Query
SELECT *
FROM[dbo].[MNO International AB$Item] t1
WHERE
    t1.[Item Type] = 0
    AND (
            NOT EXISTS(SELECT * FROM [dbo].[MNO International AB$Item Cross Reference] t2 WHERE t2.[Item No_] = t1.No_ AND t2.[Cross-Reference Type No_] = 'EAN13' AND t2.[Cross-Reference No_] <> '' AND t2.[Cross-Reference Type] = 3)
            OR t1.[Statistics Group] = 0
        ) --Result: 2178

    AND EXISTS
                (SELECT * FROM [dbo].[MNO International AB$Master] t2
                 WHERE t1.[Master No_] = t2.No_
                 AND t2.[Collection No_] NOT LIKE 'NEW-NOS'
                 )

A: I think results will give not same. Because:
NOT(A = B AND C <> D)
= NOT(A = B) OR NOT(C <> D)
= A <> B OR C = D

Return your query:
NOT EXISTS (t1.[Master No_] = t2.No_ AND t2.[Collection No_] NOT LIKE 'NEW-NOS')
= EXISTS (t1.[Master No_] <> t2.No_ OR t2.[Collection No_] LIKE 'NEW-NOS')


text:
Q: snprintf and Visual Studio 2010 I'm unfortunate enough to be stuck using VS 2010 for a project, and noticed the following code still doesn't build using the non-standards compliant compiler:
#include <stdio.h>
#include <stdlib.h>

int main (void)
{
    char buffer[512];

    snprintf(buffer, sizeof(buffer), "SomeString");

    return 0;
}

(fails compilation with the error: C3861: 'snprintf': identifier not found)
I remember this being the case way back with VS 2005 and am shocked to see it still hasn't been fixed.
Does any one know if Microsoft has any plans to move their standard C libraries into the year 2010?

A: Short story: Microsoft has finally implemented snprintf in Visual Studio 2015. On earlier versions you can simulate it as below.

Long version:
Here is the expected behavior for snprintf:
int snprintf( char* buffer, std::size_t buf_size, const char* format, ... );

Writes at most buf_size - 1 characters to a buffer. The resulting
  character string will be terminated with a null character, unless
  buf_size is zero. If buf_size is zero, nothing is written and
  buffer may be a null pointer. The return value is the number of
  characters that would have been written assuming unlimited buf_size,
  not counting the terminating null character.

Releases prior to Visual Studio 2015 didn't have a conformant implementation. There are instead non-standard extensions such as _snprintf() (which doesn't write null-terminator on overflow) and _snprintf_s() (which can enforce null-termination, but returns -1 on overflow instead of the number of characters that would have been written).
Suggested fallback for VS 2005 and up:
#if defined(_MSC_VER) && _MSC_VER < 1900

#define snprintf c99_snprintf
#define vsnprintf c99_vsnprintf

__inline int c99_vsnprintf(char *outBuf, size_t size, const char *format, va_list ap)
{
    int count = -1;

    if (size != 0)
        count = _vsnprintf_s(outBuf, size, _TRUNCATE, format, ap);
    if (count == -1)
        count = _vscprintf(format, ap);

    return count;
}

__inline int c99_snprintf(char *outBuf, size_t size, const char *format, ...)
{
    int count;
    va_list ap;

    va_start(ap, format);
    count = c99_vsnprintf(outBuf, size, format, ap);
    va_end(ap);

    return count;
}

#endif

A: If you don't need the return value, you could also just define snprintf as _snprintf_s
#define snprintf(buf,len, format,...) _snprintf_s(buf, len,len, format, __VA_ARGS__)

A: snprintf is not part of C89. It's standard only in C99. Microsoft has no plan supporting C99.
(But it's also standard in C++0x...!)
See other answers below for a workaround.

A: I believe the Windows equivalent is sprintf_s

A: Another safe replacement of snprintf() and vsnprintf() is provided by ffmpeg. You can checkout the source here (suggested).

A: I tried @Valentin Milea's code but I've got access violation errors. The only thing that worked for me was Insane Coding's implementation: http://asprintf.insanecoding.org/
Specifically, I was working with VC++2008 legacy code. From Insane Coding's implementation (can be downloaded from the link above), I used three files: asprintf.c, asprintf.h and vasprintf-msvc.c. Other files were for other versions of MSVC.
[EDIT] For completeness, their contents are as follows:
asprintf.h:
#ifndef INSANE_ASPRINTF_H
#define INSANE_ASPRINTF_H

#ifndef __cplusplus
#include <stdarg.h>
#else
#include <cstdarg>
extern "C"
{
#endif

#define insane_free(ptr) { free(ptr); ptr = 0; }

int vasprintf(char **strp, const char *fmt, va_list ap);
int asprintf(char **strp, const char *fmt, ...);

#ifdef __cplusplus
}
#endif

#endif

asprintf.c:
#include "asprintf.h"

int asprintf(char **strp, const char *fmt, ...)
{
  int r;
  va_list ap;
  va_start(ap, fmt);
  r = vasprintf(strp, fmt, ap);
  va_end(ap);
  return(r);
}

vasprintf-msvc.c:
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#include "asprintf.h"

int vasprintf(char **strp, const char *fmt, va_list ap)
{
  int r = -1, size = _vscprintf(fmt, ap);

  if ((size >= 0) && (size < INT_MAX))
  {
    *strp = (char *)malloc(size+1); //+1 for null
    if (*strp)
    {
      r = vsnprintf(*strp, size+1, fmt, ap);  //+1 for null
      if ((r < 0) || (r > size))
      {
        insane_free(*strp);
        r = -1;
      }
    }
  }
  else { *strp = 0; }

  return(r);
}

Usage (part of test.c provided by Insane Coding):
#include <stdio.h>
#include <stdlib.h>
#include "asprintf.h"

int main()
{
  char *s;
  if (asprintf(&s, "Hello, %d in hex padded to 8 digits is: %08x\n", 15, 15) != -1)
  {
    puts(s);
    insane_free(s);
  }
}


text: Q: Are there branches of mathematics that are unique to String Theory? I have read that String Theory has developed "new" math but the sources do not specifically identify the math. My question: are there branches of mathematics that are unique to String Theory? By unique I mean not used in fundamental theories such as: classical field theory, relativity and quantum mechanics.


text:
Q: How to link Interface Builder views I'm trying to figure out how to link all the views I've made in interface builder with a navigation controller but I'm finding the concept a little tricky to grasp.
All the example code I have looked at shows how to do this with arrays that store all your controllers and i'm finding it difficult to adapt to my project as my views have been completely built in IB and not in xCode.
thanks in advance.

A: Generally speaking a navigation controller maintains a stack of viewControllers that you push and pop onto. If you are using IB when you drag a Navigation Controller from the library into you application window it will actually add a number of objects including a UIViewController that will act as the Root View Controller. Change the class of that root view controller to be the class of your first view controller.
You can create additional view controllers (I would put these other view controllers in separate NIB files) which you then push onto the view controller stack when you want to make them visible. You don't need to link them to the navigation controller in IB.
So for example to push a new view controller onto the stack you would have some code something like this (the view controller is loaded from DetailView.xib:
DetailViewController *viewController = [[DetailViewController alloc]
            initWithNibName:@"DetailView" bundle:nil];

viewController.someAttribute = someValue;

[[self navigationController] pushViewController:viewController animated:YES];
[viewController release];

If you are using UITableViewControllers you might put this code in the didSelectRowAtIndexPath:indexPath method so that the new view controller appears when the user selects a row in the table.
The navigation controller will take care of popping the top view controller when the user taps the back button or you can pop it yourself by calling popViewControllerAnimated:
[[self navigationController] popViewControllerAnimated:YES]


text:
Q: Geometric Mean: is there a built-in? I tried to find a built-in for geometric mean but couldn't.
(Obviously a built-in isn't going to save me any time while working in the shell, nor do I suspect there's any difference in accuracy; for scripts I try to use built-ins as often as possible, where the (cumulative) performance gain is often noticeable.
In case there isn't one (which I doubt is the case) here's mine.
gm_mean = function(a){prod(a)^(1/length(a))}

A: No, but there are a few people who have written one, such as here.
Another possibility is to use this:
exp(mean(log(x)))

A: Here is a vectorized, zero- and NA-tolerant function for calculating geometric mean in R. The verbose mean calculation involving length(x) is necessary for the cases where x contains non-positive values.
gm_mean = function(x, na.rm=TRUE){
  exp(sum(log(x[x > 0]), na.rm=na.rm) / length(x))
}

Thanks to @ben-bolker for noting the na.rm pass-through and @Gregor for making sure it works correctly.
I think some of the comments are related to a false-equivalency of NA values in the data and zeros. In the application I had in mind they are the same, but of course this is not generally true. Thus, if you want to include optional propagation of zeros, and treat the length(x) differently in the case of NA removal, the following is a slightly longer alternative to the function above.
gm_mean = function(x, na.rm=TRUE, zero.propagate = FALSE){
  if(any(x < 0, na.rm = TRUE)){
    return(NaN)
  }
  if(zero.propagate){
    if(any(x == 0, na.rm = TRUE)){
      return(0)
    }
    exp(mean(log(x), na.rm = na.rm))
  } else {
    exp(sum(log(x[x > 0]), na.rm=na.rm) / length(x))
  }
}

Note that it also checks for any negative values, and returns a more informative and appropriate NaN respecting that geometric mean is not defined for negative values (but is for zeros). Thanks to commenters who stayed on my case about this.

A: I use exactly what Mark says. This way, even with tapply, you can use the built-in mean function, no need to define yours! For example, to compute per-group geometric means of data$value:
exp(tapply(log(data$value), data$group, mean))

A: The EnvStats package has a function for geoMean and geoSd.

A: In case there is missing values in your data, this is not a rare case.
you need to add one more argument.
You may try following code:
exp(mean(log(i[ is.finite(log(i)) ]), na.rm = TRUE))

A: This version provides more options than the other answers.

*

*It allows the user to distinguish between results that are not (real) numbers and those that are not available. If negative numbers are present, then the answer won't be a real number, so NaN is returned. If it's all NA values then the function will return NA_real_ instead to reflect that a real value is literally not available. This is a subtle difference, but one that might yield (slightly) more robust results.

*The first optional parameter zero.rm is intended to allow the user to have zeros affect the output without making it zero. If zero.rm is set to FALSE and eta is set to NA_real_ (its default value), zeros have the effect of shrinking the result towards one. I don't have any theoretical justification for this - it just seems to make more sense to not ignore the zeros but to "do something" that doesn't involve automatically making the result zero.

*eta is a way of handling zeros that was inspired by the following discussion: https://support.bioconductor.org/p/64014/
geomean <- function(x,
                    zero.rm = TRUE,
                    na.rm = TRUE,
                    nan.rm = TRUE,
                    eta = NA_real_) {
    nan.count <- sum(is.nan(x))
     na.count <- sum(is.na(x))
  value.count <- if(zero.rm) sum(x[!is.na(x)] > 0) else sum(!is.na(x))

  #Handle cases when there are negative values, all values are missing, or
  #missing values are not tolerated.
  if ((nan.count > 0 & !nan.rm) | any(x < 0, na.rm = TRUE)) {
    return(NaN)
  }
  if ((na.count > 0 & !na.rm) | value.count == 0) {
    return(NA_real_)
  }

  #Handle cases when non-missing values are either all positive or all zero.
  #In these cases the eta parameter is irrelevant and therefore ignored.
  if (all(x > 0, na.rm = TRUE)) {
    return(exp(mean(log(x), na.rm = TRUE)))
  }
  if (all(x == 0, na.rm = TRUE)) {
    return(0)
  }

  #All remaining cases are cases when there are a mix of positive and zero
  #values.
  #By default, we do not use an artificial constant or propagate zeros.
  if (is.na(eta)) {
    return(exp(sum(log(x[x > 0]), na.rm = TRUE) / value.count))
  }
  if (eta > 0) {
    return(exp(mean(log(x + eta), na.rm = TRUE)) - eta)
  }
  return(0) #only propagate zeroes when eta is set to 0 (or less than 0)
}

A: We can use psych package and call geometric.mean function.

A: The
exp(mean(log(x)))

will work unless there is a 0 in x. If so, the log will produce -Inf (-Infinite) which always results in a geometric mean of 0.
One solution is to remove the -Inf value before calculating the mean:
geo_mean <- function(data) {
    log_data <- log(data)
    gm <- exp(mean(log_data[is.finite(log_data)]))
    return(gm)
}

You can use a one-liner to do this but it means calculating the log twice which is inefficient.
exp(mean(log(i[is.finite(log(i))])))

A: exp(mean(log(x1))) == prod(x1)^(1/length(x1))


text:
Q: Security issue with controller I have my Banks Controller
class Api::V1::BanksController < ApplicationController
  before_action :authenticate_user!
  respond_to :json

  # PUT /api/v1/banks/:id.json
  def update
    @bank = UserBank.find_by!(uuid: params[:id])

    if @bank.update_attributes bank_params
      render json: @bank
    else
      render json: @bank.errors, status: :unprocessable_entity
    end
  end

  private

  def bank_params
     params.require(:bank).permit(:iban, :bic)
  end
end

I'm using devise for the authentication. My problem comes from the fact that any users can update another user's bank object just by getting the access-token from the login response.
Is there a clean/secure/automatic way of preventing a user to interact with somebody else's details ?
or should I just make sure that the bank object I'm updating belongs to the logged-in user ?
thanks a lot

A: Your mixing up authentication and authorization.
Authentication is concerned with the identity of the user.
Authorization is a set of rules for who is allowed to do what in your application.
Devise provides authentication, you can either create your own authorization system or use a library (recommended) such as Pundit or CanCanCan.
A hacky home rolled authorization check would look like:
class AuthorizationError < StandardError; end

class ApplicationController
  rescue_from AuthorizationError, with: :deny_access

  def deny_access
    head :unauthorized and return
  end
end

class Api::V1::BanksController < ApplicationController
  before_action :authenticate_user!
  before_action :set_bank!
  before_action :authorize!
  respond_to :json

  # PUT /api/v1/banks/:id.json
  def update
    @bank = UserBank.find_by!(uuid: params[:id])
    respond_with @bank.update(bank_params)
  end

  private
  def set_bank!
    @bank = UserBank.find_by!(uuid: params[:id])
  end

  def authorize!
    # this is the authorization rule.
    unless @bank.user == current_user
      raise AuthorizationError
    end
  end

  def bank_params
     params.require(:bank).permit(:iban, :bic)
  end
end


text:
Q: Makefile, rule for all rule patterns Context
I am using the pattern rule
%.png: %.tex
    compile.sh $<

to generate png files from all available (changed) tex files.
Problem
What I do not get right is that I want to use make all to do that for all of them at once.
all: *.tex
    compile.sh $^

However, $^ seems to be always replaced by all tex files and not only the changed ones (obviously, the Makefile does not really know about the connection to the png files).
Not working alternative
Using
all: *.png
    compile.sh $^

does not make sense when the png files do not exist yet, right?

A: Is there really some specific reason that you have to do them all with a single command?  Why can't you just have all depend on all the .png files?
%.png: %.tex
        compile.sh $<

TEXFILES := $(wildcard *.tex)
all: $(TEXFILES:.tex=.png)


text:
Q: Structuring a log file based on key words I'd like to ask for help.
I need to know how can i structure a big log file from a device.
This is the problem. I am currently working for a company and i have some machines (like ATM/Coffe machine/Drinks/Ciggaretes ...) which devices generate big log files and i want to cut the text in order to find some particular errors during process. I know the option with find but the point is to seperate specific event which has a beginning and ending and something in between. Bthw log files are stored in Notepad, but if there's a solution in Word and Excel it's accepted as well.
Thank you!

A: It would ultimately depend on the structure of the log file in question.
For example, you may be able to import the log file into a DBMS such as MS Access or SQL Server and then run queries to return events which occur within a given time, return a specific error code/description, or match some other criteria of your choice.

A: If you're just parsing a text file to find specific words/phrases then you should be able to use grep (on Linux), Select-String (powershell) or FINDSTR (using Windows cmd).
All of these work by checking lines of text for a pattern match, in this case the error message that you're looking for.
So you'd want something along the lines of:
grep <your error message> <the files to search>

And then maybe redirect that to a file so that it's easier for you to read through afterwards.


text:
Q: Terminal's bin/bash not responding I have Googled through several instances of this issue but cannot get Terminal to open up with bash. I restarted the program, the computer and even logged in through another Administrator account but this did not solve the issue. (Note: I'm the only user. I created the alternate for this purpose just in case it would respond). I assume it might have something to do with the fact that the bash executable is zero bytes in size and was accessed today. I don't know how but perhaps I altered it?
Here is a screenshot with the relevant windows:

The bash file exists where it should, the Terminal startup settings are set to open with /bin/bash, and the text on what "used to be" my Terminal is as follows:
[Command not found: /bin/bash]

[Could not create a new process and open a pseudo-tty.]

Any help would be greatly appreciated!


text:
Q: Funcion de factorización recursiva Javascript Me encuentro tratando de realizar una función recursiva en la que obtengamos los mínimos denominadores en un array de un numero pasado por parámetro, por ejemplo factoreo(8) debería devolver [2,2,2] ya que 2x2x2 es 8, el problema que tengo es que no se me ocurre bien como encarar la función, por el momento tengo hecho esto
 function factores(num) {
  if(num % 2 != 0){
      return num
  } else {

  };
};

A: Si no entiendo mal, los comunes denominadores pueden ser varios por lo tanto se deberia colectar una lista de arrays con los minimos denominadores posibles
function factores(num, denominadores, collect) {
  const resultado = denominadores.reduce((a, b) => a * b, 1);

  if(resultado === num) {
    collect.push(denominadores)
  } else if(resultado < num) {
    for(let i = 2; i < num; i++) {
      factores(num, [...denominadores, i], collect);
    }
  }
};

const denominadoresColectados = [];
factores(12, [], denominadoresColectados);

console.log(denominadoresColectados);

Este ejemplo retornaria esta matriz
[
  [ 2, 2, 3 ],
  [ 2, 3, 2 ],
  [ 2, 6 ],
  [ 3, 2, 2 ],
  [ 3, 4 ],
  [ 4, 3 ],
  [ 6, 2 ]
]

Aquí el numero 1 debe ser descartado ya que de lo contraria generaría infinitos denominadores con 1, por eso el bucle comienza desde 2
Espero te sirva


text:
Q: Use local variables in (click) event without two way binding I read out an array of user objects with *ngFor. I want to remove objects with a "remove" checkbox and set button (next to each row in a table). How can I pass the state of the checkbox to the setUser function.
<ion-row class="userList" *ngFor="let user of users">
    <ion-col col-5 class="userName">
        {{user.firstname}} {{user.lastname}}
    </ion-col>
    <ion-col>
        <ion-checkbox></ion-checkbox> Remove
    </ion-col>
    <ion-col>

        <button ion-button color="primary" (click)="setUser(user._id,???)">Set</button>
    </ion-col>
</ion-row>

A: You need to have a boolean variable with the user Object to bind the state of the user. say
Active .
<ion-checkbox [(ngModel)]="user.Active"></ion-checkbox>

and you can pass or use the Active variable in your setUser function then,
<button ion-button color="primary" (click)="setUser(user._id,user.Active)">Set</button>

A: Try this.
Set template reference variable of your checkbox "userCheckbox" in this example.
<ion-checkbox #userCheckbox></ion-checkbox>

Then pass that variable of checkbox value, it will be true/false.
<button ion-button color="primary" (click)="setUser(user._id,userCheckbox.value)">Set</button>

A: If you don't want [(ngModel)] to be used at all:
Create an array say checkedUsers (size equal to number of users) and initialize them as false
<ion-row class="userList" *ngFor="let user of users; let i = index"> // add index)
<ion-checkbox [checked]="checkedUsers[index]"></ion-checkbox> // or [value]
(click)="setUser(user._id, index)"
setUser(userid, index){
   this.checkedUsers[index] = true;
}

This approach isn't the recommened way, you can continue with Sajeetharan way


text:
Q: Parallax scroll-Text from previous page showing up on top of next page I'm trying to create a parallax scroll effect not just for the background image but also for the text on my page. I managed to get it to work for the background image and tried using z-index for the various text but that hasn't worked either.
Is there a way to do this similar to what I've tried using just CSS or am I going down the complete wrong avenue/need to use JavaScript?
The HTML I've written is:
<!DOCTYPE html>

        <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" rel="stylesheet">
        <link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.0/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">
        <link href="styles.css" rel="stylesheet">

HOME

CV

SYNTHETIC CHEMISTRY

SOFTWARE DEVELOPMENT

                            MY NAME

                            Interactive resume

Profile

                            Synthetic chemist with a strong interest in software engineering

About me

                                Since graduating in 2018 I have worked in the materials science industry specialising in organic synthetic chemistry and polymerisations. Specifically I work in the synthesis of fluorescent polymer nanoparticles for use in cancer diagnosis and general histopathology. I also have a keen interest in software development and

Details

And the relevant CSS code is:
.about_me_background{
  background-image: url(https://imgur.com/G8Bk9xu);
  background-size: cover;
  width: 100%;
  min-height: 100vh;
  background-repeat: no-repeat;
  background-attachment: fixed;
  background-position: center;
}

.background_white{
  background: #FFFFFF;
  background-size: cover;
  width: 100%;
  min-height: 100vh;
  background-repeat: no-repeat;
  background-attachment: fixed;
  background-position: center;
}

.centered{
  position: fixed;
  top: 40%;
  left: 50%;
  transform: translate(-50%, -50%);
  -webkit-transform: translate(-50%, -50%);
  -moz-transform: translate(-50%, -50%);
  -o-transform: translate(-50%, -50%);
  -ms-transform: translate(-50%, -50%);
}

.ambroise_text{
  text-align: center;
  font-family: ambroise-std, serif;
  font-style: normal;
  line-height: 1.2em;
  text-transform: none;
  letter-spacing: 6px;
  font-weight: 300;
  color: #fff;
}

.bottom_border{
  padding-bottom: 15px;
  border-bottom: 0.5px solid #FFFFFF;
  border-bottom-width: 1px;
  border-bottom-style: solid;
}

Also apologies I tried adding the URL of the first background image but it didn't work. Heres the imgur url if you want to download it.
https://imgur.com/G8Bk9xu

A: Don't know if this is what you are looking for, but try to add z-index to the centered class:
.centered{
  position: fixed;
  top: 40%;
  left: 50%;
  transform: translate(-50%, -50%);
  -webkit-transform: translate(-50%, -50%);
  -moz-transform: translate(-50%, -50%);
  -o-transform: translate(-50%, -50%);
  -ms-transform: translate(-50%, -50%);
/* add z-index */
  z-index : -1;
}


text:
Q: Is it possible to set voice routing policy for multiple users? I am trying to create a Powershell script that will iterate through a CSV file and apply voice routing policy that will assign international dialling for all users in the CSV.
Connect-MicrosoftTeams
$list = Import-Csv "C:\file path"
foreach($entry in $list) {
    Get-CsonlineUser -Identity $entry | FL SipAddress, OnlineVoiceRoutingPolicy
    Grant-CsOnlineVoiceRoutingPolicy $entry -Policyname VRP_GB_International
    Get-CSOnlineUser -Identity $entry | FL SipAddress, OnlineVoiceRoutingPolicy
}
Write-Host $entry has been granted International Dialling on Teams. Please allow upto 8 hours for the change to take effect.

I note the Write-Host won't be able to access the $entry variable as this is local to the foreach. Still I'm hoping it gives an idea of what I'm trying to achieve.
The most pressing issue is that when I run this I get a lot of blood on the shell, The error seems to suggest it doesn't recognise the cmdlet Get-CsOnlineUser.
Is it possible to assign this policy to multiple users from a CSV?


text:
Q: How to iterate through an xml path string (table rows -- tr[1], tr[2], tr[3]...) using Python? I have this html xml path:
"//*[@id="example"]/tbody/tr[2]/td[1]"

It has to be processed as a string by my find_element() algorithm
but I need to iterate up at tr[2] (eg, tr[2], tr[3], tr[4]...) so that my webscraping algorithm can expand a clickable button in a html table.
What are some strategies / implementations to accomplish this?
(I'm using the Selenium python library for the webscraper)

A: If you wan to loop through it then ,
Just make your xpath dynamic like this :
I am assuming you have 5 rows.
for i in range(5):
 driver.find_element_by_xpath("//*[@id="example"]/tbody/tr['"+i+"']/td[1]").click()

Or using WebDriverWait, it would be :
wait = WebDriverWait(driver,30)

for i in range(5):
  wait.until(EC.element_to_be_clickable((By.XPATH, "//*[@id="example"]/tbody/tr['"+i+"']/td[1]"))).click()

Note that, in case you will have to imports these :
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

A: You can get collection of all desired elements (rows) using below code:
driver.find_elements_by_xpath("//*[@id="example"]/tbody//tr/td[1]");

Then you can iterate over collection of elements and do the desired operation.


text:
Q: Is there an easy way to suppress footnotes and citations? I'm looking to perform a word count on a long PDF that contains many footnotes and citations. Is there an easy way to prevent basically anything that would appear as a footnote, including auto-citations in BibLaTeX, from being printed?
MWE (compiles with XeLaTeX):
\documentclass[a4paper,11pt]{memoir}

\usepackage{polyglossia}
\setmainlanguage[variant=usmax]{english}
\usepackage[backend=biber]{biblatex-chicago}
\usepackage{filecontents}

\begin{filecontents}{lib.bib}
@book{foobar,
title = {Foo},
author = {John Bar},
location = {Footown},
publisher = {Bar},
date = {2005},
}
\end{filecontents}
\bibliography{lib.bib}

\begin{document}

Some text that I want to be in the word count.\autocite[Prenote][Postnote]{foobar} Some more text.\footnote{A footnote}

\end{document}

A: If you redefine the footnote command to do exactly nothing, no footnote will be printed in your document.
\renewcommand\footnote[1]{}


text:
Q: Disappearing UIBarButtonItems in iOS 4 I've been developing on an iOS 5 device, and it's been working fine. Now I've been testing it with different versions of the iOS simulator, and in 4.0 I'm getting some strange behaviour with my custom UIBarButtonItems. On the main screen of the app both of the bar buttons show throughout the lifetime of the app. Those two buttons bring up modal view controllers, each with a 'close' button. This is an object description of the 'close' button on one of the modal view controllers (I set a breakpoint in the 'viewWillAppear' method):
(gdb) po [[[self navigationItem] rightBarButtonItem] customView]
<UIButton: 0x72766e0; frame = (264 6; 51 31); opaque = NO; layer = <CALayer: 0x7276d70>>

Those both show up when the each modal view controller is opened. But then one of the modal view controllers has a button that pushes another view controller on top, and the view controller's base class automatically makes a custom back button and puts it on the leftBarButtonItem of the view. However, this doesn't show up. Here's the object description of the button that doesn't show up (again, in 'viewWillAppear'):
(gdb) po [[[self navigationItem] leftBarButtonItem] customView]
<UIButton: 0x766be00; frame = (0 0; 43 31); opaque = NO; layer = <CALayer: 0x766be90>>

...which doesn't look like anything is wrong. I then press where the back button should be, and the view controller pops off, revealing the first modal view controller, but with no 'close' button. Again, I broke in viewWillAppear and this is what I got:
(gdb) po [[[self navigationItem] rightBarButtonItem] customView]
<UIButton: 0x72766e0; frame = (264 6; 51 31); alpha = 0; opaque = NO; layer = <CALayer: 0x7276d70>>

This is strange, since I don't set the alpha value of  a UIBarButtonItem anywhere in my own code. Also, it works fine on  iOS 5. The way I implement the custom UIBarButtonItems is using some static methods I put in a category called UIBarButtonItem+Utils.h that returns UIBarButtonItems initialised with a custom UIButton as the custom view. If you need me to post the code for that method I can, but the main point is that it doesn't ever change the button's alpha value. Has anyone else experienced anything like this?


text:
Q: How to control the type of value bound using ngModel (number gets distorted to string)? I asked a question and got it working. However, I notice that although the data provided consists of objects declared like this:
export interface GisPoint { e: number; n: number; }

when the user enters a value, the original contents being { e: 12, n: 34 } become string'ish, i.e. { e: "123", n: 34 }. I understand that the result from the input will be assumed a string so I'll have to convert it. However, as the binding goes through ngModel, I actually don't react explicitly to keyUp or blur.
Do I have to explicitly do that? If so, there's really no point using  ngModel. It would be quite nifty to be able to keep the type when the edited value gets entered.

A: Given this HTML markup:
<input type="number" [(ngModel)]="data.age">

You will get the desired number in your model. Angular will not convert it to a string. One "side effect" is that browser will add these number spinners.
The easiest way to hide them is to use a small css rule:
/* Chrome, Safari, Edge, Opera */
input::-webkit-outer-spin-button,
input::-webkit-inner-spin-button {
  -webkit-appearance: none;
  margin: 0;
}

/* Firefox */
input[type=number] {
  -moz-appearance:textfield;
}

More info on css here and here.
Check this working stackblitz.

A: You can implement the ControlValueAccessor interface for the Component, so that you specify which value represents the model.
Here's a couple good articles to start from:

*

*https://medium.com/@majdasab/implementing-control-value-accessor-in-angular-1b89f2f84ebf

*https://alligator.io/angular/custom-form-control/


text:
Q: Android app Crashed on setContentView I am brand new to android development and the code crashes at the setContentView(R.layout.main).  I don't know why.  I have tried the standard clean and build and restarting eclipse.
Main Code:
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

}

Main.xml Code:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="fill_parent"
    android:layout_height="fill_parent">

    <TabHost xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@android:id/tabhost" android:layout_width="fill_parent"
        android:layout_height="fill_parent">
        <LinearLayout android:orientation="vertical"
            android:layout_width="fill_parent" android:layout_height="fill_parent">
            <View android:layout_width="fill_parent" android:layout_height="0.5dip"
                android:background="#000" />
            <TabWidget android:id="@android:id/tabs"
                android:layout_width="fill_parent" android:layout_height="wrap_content"
                android:layout_marginLeft="0dip" android:layout_marginRight="0dip" />
            <View android:layout_width="fill_parent" android:layout_height="2dip"
                android:background="#696969" />
            <View android:layout_width="fill_parent" android:layout_height="2dip"
                android:background="#000" />
            <FrameLayout android:id="@android:id/tabcontent"
                android:layout_width="fill_parent" android:layout_height="fill_parent" />
        </LinearLayout>
    </TabHost>

</LinearLayout>

A: Remove xmlns from TabHost. There should only be one xmlns in layout xml file.
<TabHost
    android:id="@android:id/tabhost" android:layout_width="fill_parent"
    android:layout_height="fill_parent">


text:
Q: insert an sd card before using the camera android emulator When i open camera in my Android emulator. I get message insert an sd card before using the camera android emulator

Here is my configuration of emulator

My android studio version is

Android Studio 2.3.3 Build #AI-162.4069837, built on June 6, 2017 JRE:
  1.8.0_92-b14 amd64 JVM: Java HotSpot(TM) 64-Bit Server VM by Oracle Corporation

Any idea how to solve this?


text:
Q: web.config redirect to https with 301 status code I'm trying to force redirect all http traffic to https while returning 301 status code.
So I have this in my Web.Release.config file.
<rewrite>
  <rules>
    <rule name="Redirect to https" xdt:Transform="Insert">
      <match url="(.*)"/>
      <conditions>
        <add input="{HTTPS}" pattern="Off"/>
        <add input="{REQUEST_METHOD}" pattern="^get$|^head$" />
      </conditions>
      <action type="Redirect" url="https://{HTTP_HOST}/{R:1}" statusCode="301" redirectType="Permanent" />
    </rule>
  </rules>
</rewrite>

and I keep getting 307 instead of 301. How can I force it to return 301 status code?

A:
<action type="Redirect" url="https://{HTTP_HOST}/{R:1}" statusCode="301" redirectType="Permanent" />

According to your code, we could find that you specify redirectType="Permanent", it should return 301 status code. I try to reproduce the issue on my side, here is my config files.
Web.config
<?xml version="1.0" encoding="utf-8"?>
<!--
  For more information on how to configure your ASP.NET application, please visit http://go.microsoft.com/fwlink/?LinkId=169433-->
<configuration>
 <system.web>
    <compilation debug="true" targetFramework="4.5"/>        <httpRuntime targetFramework="4.5"/>
  </system.web>
  <system.codedom>
    <compilers>

      <compiler language="c#;cs;csharp" extension=".cs"
    type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
    warningLevel="4" compilerOptions="/langversion:6 /nowarn:1659;1699;1701"/>
      <compiler language="vb;vbs;visualbasic;vbscript" extension=".vb"
    type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
    warningLevel="4" compilerOptions="/langversion:14 /nowarn:41008 /define:_MYTYPE=\"Web\" /optionInfer+"/>
    </compilers>
  </system.codedom>
</configuration>

Web.Release.config
<?xml version="1.0" encoding="utf-8"?>

<!-- For more information on using web.config transformation visit http://go.microsoft.com/fwlink/?LinkId=125889 -->

<configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform">
  <!--In the example below, the "SetAttributes" transform will change the value of "connectionString" to use "ReleaseSQLServer" only when the "Match" locator finds an attribute "name" that has a value of "MyDB".

    <connectionStrings>
      <add name="MyDB" connectionString="Data Source=ReleaseSQLServer;Initial Catalog=MyReleaseDB;Integrated Security=True"
    xdt:Transform="SetAttributes" xdt:Locator="Match(name)"/>
    </connectionStrings>-->
  <system.web>
    <compilation xdt:Transform="RemoveAttributes(debug)" />
    <!--In the example below, the "Replace" transform will replace the entire
      <customErrors> section of your web.config file.
      Note that because there is only one customErrors section under the
      <system.web> node, there is no need to use the "xdt:Locator" attribute.

      <customErrors defaultRedirect="GenericError.htm" mode="RemoteOnly" xdt:Transform="Replace">
        <error statusCode="500" redirect="InternalError.htm"/>
      </customErrors>-->
  </system.web>
  <system.webServer xdt:Transform="Insert">
    <rewrite>
      <rules>
        <rule name="Redirect to https">
          <match url="(.*)"/>
          <conditions>
            <add input="{HTTPS}" pattern="Off"/>
            <add input="{REQUEST_METHOD}" pattern="^get$|^head$" />
          </conditions>
          <action type="Redirect" url="https://{HTTP_HOST}/{R:1}" redirectType="Permanent" />
        </rule>
      </rules>
    </rewrite>
  </system.webServer>
</configuration>

I could see 301 status code in Network tool when I visit my website.

I keep getting 307 instead of 301. How can I force it to return 301 status code?

You could check your Web.config file and make sure whether you define other URL Rewrite Rules that change status code.


text:
Q: The set of Locales is a subset of the set of Toposes. Given an ordered set $(Z, \leq)$, we can consider the category $C_Z$ with $Ob(C)=Z$ and for each $r,e\in Z$, $\hom_{C_Z}(r,e)$ is a singleton if $r\leq e$ and is $\emptyset$ if $\neg(r\leq e)$. The idea is that ordered sets are special kinds of categories (with no more than one morphism between any two objects).
An ordered set is called a frame if it admits arbitrary joins and binary meets and binary meets distribute over joins. A morphisms between frames is a monotone function preserving arbitrary joins and binary meets. A Grothendieck topos is a category satisfying the so-called Giraud axioms, which are very similar to the axioms of a frame (binary limits; arbitary small colimits, which are stable under pullbacks).

*

*Is $Z\mapsto C_Z$ a fully faithful functor from the category of frames to the category of Grothendieck toposes (with geometric morphisms)?

*If yes, why is it more common to embed frames into Grothendieck toposes via $Z\mapsto Sh(Z)=$ topos of sheaves on $Z$? Is this embedding somehow related to the functor $Z\mapsto C_Z$?

*Does 1. imply that the category of frames is equivalent to the category of Grothendieck toposes of the form $C_Z$ for some ordered set?

*Why are frames required to be ordered sets, i.e., such that $\leq$ is antisymmetric: if $r\leq e\leq r$, then $r=e$ and not merely preordered sets? Because for Grothendieck toposes we don't require them that isomorphic objects are equal (which is the categorical analogue).

A: No, for a frame $Z$, the category $C_Z$ is never a Grothendieck topos (unless it has only one object).
In terms of Giraud's axioms, $C_Z$ fails the axiom that coproducts should be disjoint. In a frame, $1+1=1$, while in a topos, $1+1=1$ implies $0=1$, which implies that the topos is trivial.


text:
Q: Django escape only certain HTML tags Is it possible to escape all html tags except for the  tag somehow?
I am sending a user entered string from a view to an html template where I have manually added  tags to the string in the view. I would like to allow for that to be shown, but of course omit all html tags entered by the user.

A: The short answer to your question is that you could write your own filter to do this.
A better solution IMHO would be to remove any tags from your user input, then add whatever tags you want, and then use the "safe" filter to display your modified text.


text:
Q: Proof of a sequence $\{S_n\}$ converging to $0$ First, the question asks

Prove that $1+\frac12+\frac13+\cdots+\frac1n<2\sqrt n$

At first glance, I see that this is a proof involving induction, and I arrived at an inequality as shown below where I complete my proof:

$$\frac1{\sqrt{k+1}-\sqrt k}<2k+2$$

Then, the question asks further

Let $S_n=\frac{1}{n}+\frac{1}{2n}+\frac1{3n}+\cdots+\frac1{n^2}$ for each $n\in\Bbb N$. Prove that $\{S_n\}$ converges to $0.$

The second part of the question is where I am stuck. I don't know how I can make use of the first part of the question to answer the latter part.

A: \begin{align}S_n&=\frac1n+\frac1{2n}+\frac1{3n}+\cdots+\frac1{n^2}\\[10pt]
&=\frac1n\left(1+\frac12+\frac13+\cdots+\frac1n\right)\\[10pt]
&\leqslant\frac{2\sqrt n}n\\[10pt]
&=\frac2{\sqrt n}.\end{align}

A:
The second part of the question is where I am stuck at. I don't know how I can make use of the first part of the question to answer the latter part.

Hint
Note that (use of the first part in blue):
$$S_n = \frac{1}{n}\left( \color{blue}{1+\frac{1}{2}+\frac{1}{3}+...+\frac{1}{n}}\right) \color{blue}{\le} \frac{1}{n}\cdot \color{blue}{2\sqrt{n}} = \ldots$$

A: Using the first part of the question:
$$S_n=\sum_{k=1}^n\frac1{kn}=\frac1n\sum_{k=1}^n\frac1n$$
$$<\frac1n\cdot2\sqrt n=\frac2{\sqrt n}$$
Since $S_n$ is bounded below by 0 and  bounded above by $\frac2{\sqrt n}$, whose limit as $n\to\infty$ is also 0, $S_n$ converges to 0.


text:
Q: 'Cloth shop' and 'Clothes shop' My understanding of noun + noun as an English learner would always believe that the first noun of the construction I've mentioned above (noun + noun) is singular. So, I'd believe that Cloth shop is correct and Clothes shop is incorrect.
However, Swan's book: Advanced Oxford Grammar Course has changed my view that the first noun could be plural, though, I've never been familiar with it. I'll just copy what the book says regarding singular and plural as reference.

[1] The first noun is often like an object (of a verb or preposition).
It is normally singular, even if it has a plural meaning.

*

*a shoe shop = 'a shop that sells shoes'

*a toothbrush = 'a brush for teeth'

*a war film = 'a film about war'

[2] In a few noun + noun combinations, the first noun is
plural.

*

*antiques dealer

*sports car

*drugs problem
This is especially the case when the first noun is mainly or only used
in the plural, or has a different meaning in the singular.

*

*accounts department

*customs officer

*clothes shop

*glasses case

*savings account

*arms trade

I'm pretty sure I've seen noun + noun (a cloth store) somewhere, even though the second noun is different from the example above i.e. (store and shop). My question regarding this problem, if my suspicion is correct that it's possibly possible to say cloth shop, what's the difference between that noun + noun and clothes shop?

A: It is grammatically possible to say "cloth shop" but no one would ever actually say that.
A shop which sells garments that are meant to be worn is a "clothes shop" and that is the only form you will ever see for that meaning.
A shop which sells the material with which to make garments could be called a "cloth shop" and it would sell cloths, not clothes. But no-one calls that kind of store a "cloth shop." Instead it is called a "fabric shop."

Your baseline problem may be that you think the word cloth is the singular form of the word clothes. That is not correct. A cloth is a piece of fabric; cloths are multiple pieces of fabric. Clothes are garments, and it is always a plural noun; in order to refer to a single "clothe" you must use a construction like an article of clothing.


text: Q: Can I create a web server with dart/flutter available from anywhere in the world I want to create a web server with flutter/dart, something similar to how the following app works on android https://github.com/mvbasov/lWS. I have searched but I don't see how the server can be deployed on mobile devices. And the truth is that the server is going to be the base of my app, the main functions will be others that depend on the server. thanks in advance.


text:
Q: The "Impedance" Equation
In "Right the first time" by Lee W. Ritchey, he says "The impedance will be the same whether
the frequency of the EM energy is 1 MHz or 1 GHz. This holds true so long as none of the three variables changes with
frequency."
But clearly that equation has a dependence on \$ \omega \$ ? What's going on here?

A: The book is downloadable from here: Right First Time and the relevant section of the book is pages 119 to 122.
In this book the author is specifically talking about PCB design and is making the reasonable assumption that \$ R_0 \$ and \$ G_0 \$ and negligible in comparison with the inductive and capacitive effects for frequencies of a few 100kHz and above.
This fits with my personal experience of PCB design and several authors have made the same assumption.
The statement \$ Z = \sqrt{\dfrac{R_0 + \text{j} \omega L_0}{G_0 + \text{j} \omega C_0}}\$ is false but at these frequencies the impedance varies very little with frequency and \$ Z = \sqrt{\dfrac{L_0}{C_0}}\$ is a very close approximation.

A: Take a look at fairly standard cable used for telephones. It has a characteristic impedance that varies quite a lot in the audio range: -

And, this effect is as a direct result of the standard characteristic impedance equation for a transmission line. As frequency drops into the audio range, R starts to dominate over jwl and the impedance becomes: -
\$\sqrt{\dfrac{R}{j\omega C}}\$
As frequency lowers more the impedance tends to become: -
\$\sqrt{\dfrac{R}{G}}\$
And, at much higher frequencies, the characteristic impedance is the standard formula used by RF guys: -
\$\sqrt{\dfrac{L}{C}}\$
It's also noteworthy that many sources refer to a transmission line as "distortionless" if the ratio R to G is the same as L to C. When this happens, the impedance is constant from DC to any frequency.


text:
Q: Convert the mysql date format to dd-mmm-yyyy in mysql I have maintained a table with start_date as "date" datatype and now I wanted to display the date in dd-mmm-yyyy format.
public static BusObjectIterator<com.timesheetmd.weeksView> weeksOfYear(int year)
{
    String queryText = "SELECT `id`, `year`, CONCAT(CAST(`start_date` AS CHAR), ' to ', CAST(`end_date` AS CHAR)) AS 'week' FROM `weeks` WHERE `weeks`.`year` = :year AND end_date <= CURRENT_DATE ORDER BY start_date DESC";
QueryObject query = new QueryObject(queryText);
query.addParameter("year", "weeks.year ", QueryObject.PARAM_INT,year);//NOPMD
query.setResultClass(weeksView.class);
return query.getObjects();
}

As I want to return the result in the form of BusObjectIterator. Is it possible to change the format of the date in the query itself?

A: You  need DATE_FORMAT(start_date,'%d-%b-%Y') instead of your CAST(...AS CHAR).
Here's the DATE_FORMAT() writeup.