text:
Q: Does CSRF defense also defend against clickjacking? Suppose my web app is protected against a CSRF attack with a CSRF token, and, in addition, it uses SSL and is protected against XSS attacks. Also, for the purposes of this question, suppose it's used only from recent browsers and that they have no bugs. I can protect against frame-based clickjacking with an X-Frame-Options:Deny header, but I don't see what additional protection it would be providing, as any frame-based form submission would be lacking the CSRF token. (And the same-origin policy prevents the CSRF token from being discovered by the attacker's JavaScript.) Questions:

*

*Is there some other kind of clickjacking that's not frame based? (I.e., is an X-Frame-Options:Deny not a complete clickjacking defense?)

*In the absence of an X-Frame-Options:Deny header, is it still possible for a clickjacking attack to succeed given the above assumptions?
(I'm asking this not because I want to prevent frame-based clickjacking, because I do include the X-Frame-Options:Deny header. Rather, I'm trying to understand how the scope of clickjacking attacks.)

A: Doing some more research, I think I have answered my own question: The overlaid, transparent iframe holds the site to be attacked, accessed normally. For example, it might be a page with a button to delete photos, emails, etc. The visible page, from the attacker's site, is something else entirely, perhaps for entering a contest, with a button positioned exactly where the iframe button is. So, this is not a case of CSRF, because the form submitted is not a forgery; it's real in every way, and hasn't been altered.
The solution is to disallow the site from being loaded into a frame, which is what X-Frame-Options:Deny does.


text:
Q: How fix File 'xxx' specified for property 'signingConfig.storeFile' does not exist I'm new in android studio, when I want export the apk it give me error. This:
Error:A problem was found with the configuration of task ':app:packageRelease'.

File 'sistemasmas' specified for property 'signingConfig.storeFile' does not exist.

How do I fix this error?
This is my build.gradle:
 apply plugin: 'com.android.application'

android {
    compileSdkVersion 22
    buildToolsVersion "22.0.1"

defaultConfig {
    applicationId "com.sistemasmas.escribiramanowhatsapp"
    minSdkVersion 15
    targetSdkVersion 22
    versionCode 1
    versionName "1.0"
}

buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'

    }
}
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'com.android.support:appcompat-v7:22.1.1'
    compile 'com.google.android.gms:play-services:7.0.0'
}

A: Add the signing configuration to the build file for the app module
android {
    ...
    defaultConfig { ... }
    signingConfigs {
        release {
            storeFile file("myreleasekey.keystore")
            storePassword "password"
            keyAlias "MyReleaseKey"
            keyPassword "password"
        }
    }
    buildTypes {
        release {
            ...
            signingConfig signingConfigs.release
        }
    }
}

It will solve your problem. It helped me.

A: you can use the 'Generate Signed Apk' tool.
See your Android Studio's  Build ->  Generate Signed APK menu.
Otherwise,if you want package the project with command.You need define these in your release part.
 release {
    minifyEnabled false
    proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'

    android.signingConfigs.release.storeFile = file('C://your-release-key.keystore')
    android.signingConfigs.release.storePassword = "yourstorePassword"
    android.signingConfigs.release.keyAlias = "yourkeyAlias"
    android.signingConfigs.release.keyPassword = "yourkeyPassword"
}

However,It's not safe to put your pass directly in build.gradle.

A: It didn't work for me in the release{ section, but the following did
android {
signingConfigs {
    Signature {
        keyAlias 'yourfilealias'
        keyPassword 'yourkeypassword'
        storeFile file('keystore.jks')
        storePassword 'yourstorepassword.'
    }

} ...

Note: keystore.jks will probably need your path preceding it.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Load CustomView and its logic at Runtime I'm creating a custom component for an Android App (exactly a volume fader for an audio mixer). It works fine.
What I want is to load several instances of this component at Run-Time.
I tried with this:
LinearLayout layout = (LinearLayout)findViewById(R.id.mixerContainer) //This layout
for(int i=0;i<8;i++){
  LayoutInflater l = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
  View v = l.inflate(R.Layout.MyVolumeFader, null);
  layout.add(v);
}

This adds the view correctly, but doesn't attach all the logic of my component (that is contained in MyVolumeFader class).
How can I solve this problem?
--
The code looks like:
MyVolumeFader.java
public class MyVolumeFader extends RelativeLayout{
 [...]

 private VerticalSeekBar volumeBar;

 [...]

 ->volumeBar handling<-
}

MyVolumeFader.xml
<RelativeLayout...
Some TextViews, Buttons and a VerticalSeekBar are here...

Thank you.

A: You may consider using windowmanager and its' addview method to solve your provlem like this.
mWindowManager.addView(new ChartTools(this, a, list, "业务统计").getChart(),
        ParamTools.getChartParams());


text:
Q: Chart.js - Multiple bar Charts - Only Show Last Chart Chart.js - Multiple Bar Charts - Only Show Last Chart.Basically data comes from django and is rendered in the template.Data is proper but only one of 2 charts are being rendered.
I also tried changing ctx but it did not worked
HTML Code

    <canvas id="indiacanvas"></canvas>

    <canvas id="usacanvas"></canvas>

Basically data comes from django and is rendered in the template.Data is proper but only one of 2 charts are being rendered.
I also tried changing ctx but it did not worked
Script.js
//BAR CHART USD
    var barChartData = {
      labels: [{% for item in listyear1 %}'{{item| date:"Y"}}', {% endfor %}],
    datasets: [
      {
        label: "Total amount",
        backgroundColor: "lightblue",
        borderColor: "blue",
        borderWidth: 1,
        data: [{% for inr in USATOTAL %}'{{inr}}', {% endfor %}],
        },
    {
      label: "Amount Recieved",
      backgroundColor: "lightgreen",
      borderColor: "green",
      borderWidth: 1,
      data: [{% for rinr in RUSDS %} '{{rinr}}', {% endfor %}],
        },
    {
      label: "Amount Left",
        backgroundColor: "pink",
          borderColor: "red",
            borderWidth: 1,
              data: [{% for linr in LUSDS %} '{{linr}}', {% endfor %}],
        },
      ],
    };
    var chartOptions = {
      responsive: true,
      legend: {
        position: "top",
      },
      title: {
        display: true,
        text: "YearWise Summary USD",
      },
      scales: {
        yAxes: [
          {
            ticks: {
              beginAtZero: true,
            },
          },
        ],
      },
    };

    window.onload = function () {
      var ctx = document.getElementById("usacanvas").getContext("2d");
      window.myBar = new Chart(ctx, {
        type: "bar",
        data: barChartData,
        options: chartOptions,
      });
    };

// Bar Chart India
var barChartData = {
      labels: [{% for item in listyear %}'{{item| date:"Y"}}', {% endfor %}],
    datasets: [
      {
        label: "Total amount",
        backgroundColor: "lightblue",
        borderColor: "blue",
        borderWidth: 1,
        data: [{% for inr in INDIATOTAL %}'{{inr}}', {% endfor %}],
        },
    {
      label: "Amount Recieved",
        backgroundColor: "lightgreen",
          borderColor: "green",
            borderWidth: 1,
              data: [{% for rinr in RINR %} '{{rinr}}', {% endfor %}],
        },
    {
      label: "Amount Left",
        backgroundColor: "pink",
          borderColor: "red",
            borderWidth: 1,
              data: [{% for linr in LINR %} '{{linr}}', {% endfor %}],
        },
      ],
    };

    var chartOptions = {
      responsive: true,
      legend: {
        position: "top",
      },
      title: {
        display: true,
        text: "YearWise Summary INR",
      },
      scales: {
        yAxes: [
          {
            ticks: {
              beginAtZero: true,
            },
          },
        ],
      },
    };

    window.onload = function () {
      var ctx = document.getElementById("indiacanvas").getContext("2d");
      window.myBar = new Chart(ctx, {
        type: "bar",
        data: barChartData,
        options: chartOptions,
      });
    };

A: Due to JavaScripts async nature, ctx might get reassigned. Try using ctx2 as variable name for the second chart.


text:
Q: plot ellipse in a seaborn scatter plot I have a data frame in pandas format (pd.DataFrame) with columns = [z1,z2,Digit], and I did a scatter plot in seaborn:
dataframe = dataFrame.apply(pd.to_numeric, errors='coerce')
sns.lmplot("z1", "z2", data=dataframe, hue='Digit', fit_reg=False, size=10)
plt.show()

What I want to is plot an ellipse around each of these points. But I can't seem to plot an ellipse in the same figure.
I know the normal way to plot an ellipse is like:
import matplotlib.pyplot as plt
from matplotlib.patches import Ellipse

elps = Ellipse((0, 0), 4, 2,edgecolor='b',facecolor='none')
a = plt.subplot(111, aspect='equal')
a.add_artist(elps)
plt.xlim(-4, 4)
plt.ylim(-4, 4)
plt.show()

But because I have to do "a = plt.subplot(111, aspect='equal')", the plot will be on a different figure. And I also can't do:
a = sns.lmplot("z1", "z2", data=rect, hue='Digit', fit_reg=False, size=10)
a.add_artist(elps)

because the 'a' returned by sns.lmplot() is of "seaborn.axisgrid.FacetGrid" object. Any solutions? Is there anyway I can plot an ellipse without having to something like a.set_artist()?

A: Seaborn's lmplot() used a FacetGrid object to do the plot, and therefore your variable a = lm.lmplot(...) is a reference to that FacetGrid object.
To add your elipse, you need a refence to the Axes object. The problem is that a FacetGrid can contain multiple axes depending on how you split your data. Thankfully there is a function FacetGrid.facet_axis(row_i, col_j) which can return a reference to a specific Axes object.
In your case, you would do:
a = sns.lmplot("z1", "z2", data=rect, hue='Digit', fit_reg=False, size=10)
ax = a.facet_axis(0,0)
ax.add_artist(elps)


text:
Q: Nextcloud with Replicas on Azure Kubernetes - Failing to Mount Azure Files ReadWriteMany Volume I'm trying to deploy Nextcloud w/HPA (replicas - horizontal scaling) on Azure Kubernetes with the official Nextcloud Helm chart and a ReadWriteMany volume created following these official instructions, but the volume never mounts, get this (or some version thereof) error:
kind: Event
apiVersion: v1
metadata:
  name: nextcloud-6bc9b947bf-z6rlh.16bf7711bc2827a5
  namespace: nextcloud
  uid: c3c5619b-19da-4070-afbb-24bce111ddbe
  resourceVersion: '55858'
  creationTimestamp: '2021-12-10T18:08:27Z'
  managedFields:
    - manager: kubelet
      operation: Update
      apiVersion: v1
      time: '2021-12-10T18:08:27Z'
      fieldsType: FieldsV1
      fieldsV1:
        f:count: {}
        f:firstTimestamp: {}
        f:involvedObject: {}
        f:lastTimestamp: {}
        f:message: {}
        f:reason: {}
        f:source:
          f:component: {}
          f:host: {}
        f:type: {}
involvedObject:
  kind: Pod
  namespace: nextcloud
  name: nextcloud-6bc9b947bf-z6rlh
  uid: 6106d13f-7033-4a4e-a6e9-a8e3947c52a4
  apiVersion: v1
  resourceVersion: '55764'
reason: FailedMount
message: >
  MountVolume.MountDevice failed for volume "nextcloud-rwx" : rpc error: code =
  Internal desc = volume(#azure-secret#aksshare#) mount
  "//nextcloudcluster.file.core.windows.net/aksshare" on
  "/var/lib/kubelet/plugins/kubernetes.io/csi/pv/nextcloud-rwx/globalmount"
  failed with mount failed: exit status 32

  Mounting command: mount

  Mounting arguments: -t cifs -o
  dir_mode=0777,file_mode=0777,gid=33,mfsymlinks,actimeo=30,<masked>
  //nextcloudcluster.file.core.windows.net/aksshare
  /var/lib/kubelet/plugins/kubernetes.io/csi/pv/nextcloud-rwx/globalmount

  Output: mount error(13): Permission denied

  Refer to the mount.cifs(8) manual page (e.g. man mount.cifs) and kernel log
  messages (dmesg)
source:
  component: kubelet
  host: aks-agentpool-16596208-vmss000002
firstTimestamp: '2021-12-10T18:08:27Z'
lastTimestamp: '2021-12-10T18:08:35Z'
count: 5
type: Warning
eventTime: null
reportingComponent: ''
reportingInstance: ''

Here is my PersistentVolume yaml:
apiVersion: v1
kind: PersistentVolume
metadata:
  name: nextcloud-rwx
  namespace: nextcloud
spec:
  capacity:
    storage: 32Gi
  accessModes:
    - ReadWriteMany
  azureFile:
    secretName: azure-secret
    shareName: aksshare
    readOnly: false
  mountOptions:
  - dir_mode=0777
  - file_mode=0777
  - gid=33
  - mfsymlinks

PersistentVolumeClaim yaml:
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
  name: nextcloud-rwx
  namespace: nextcloud
spec:
  accessModes:
    - ReadWriteMany
  storageClassName: ""
  resources:
    requests:
      storage: 32Gi

I've also tried changing uid and gid to 0, 1000, etc, and get an even more egregious permission denied message because it doesn't "match the fsgroup(33)" (hence why I tried with gid=33).
Any ideas would be greatly appreciated! Thank you for your time.


text:
Q: Nickel plated steel strip for li-ion Battery pack - Purpose of Nickel Plating? I am trying to build a battery pack from 18650 batteries, each interconnection is made from steel strip, most '18650 strip' has a steel core with nickel plating.
I have a question regarding the purpose of the nickel coating found on 'nickel coated steel strip' which is used for welding 18650 batteries together to build li-ion battery packs.

Is the nickel plating's purpose merely to stop the steel strip from rusting/corroding? Or does the nickel aid in the welding process as well?
I am using a spot welder similar to the one in the image below, high current is sent between the two electrodes creating high heat on the contact patches between the steel strip and battery top/bottom. This heat melts the metals together at the contact points.

Nickel is a better conductor than steel therefore if i am correct the nickel coating does not help in the spot welding process since the electrical resistance of nickel is lower than that of steel so more current needs to pass through nickel to get the same amount of heat production. Is there another explanation why (if true) nickel aids the welding process or is it merely to prevent rust/oxidation of the steel?
Does the same apply when using copper strip to connect the batteries together?
EDIT:
I was thinking maybe molten Ni has a better viscosity (more fluid) when molten compared to steel, which could be positive in the welding process as the gaps between the strip and battery get filled better. I have found the following table with some info regarding viscosity of molten metals:

Source: https://www.pnas.org/content/pnas/73/4/988.full.pdf
It appears Fe (iron) has a higher value for ϕ (Fluidity in reciprocal centipoise) so my theory is probably wrong...however nickel has a higher melting point than nickel so perhaps in the welding process the average fluidity of the nickel is still higher than the average fluidity of the steel at the surface of the strip (at the contact plane between the strip and battery housing). Could someone please tell me if this is of any influence and if my theory is somewhat accurate (and how much difference this (if existent) difference in fluidity would make)?
I have not yet figured out how the temperature influences the viscosity of the molten metal and how to calculate/obtain the factor which determines the ratio between fluidity/temperature... perhaps someone more knowledgeable will be able to give some insight into this
Thank you very much!

A: The welding process is an important step for the production process of a battery pack, because if we obtain an insufficient contact to the battery, the electrical resistance increases and we haven't gained much. And the welding process itself is an "art", where everybody has his/her own opinion. Of course there are many parameters, like the contact material on the battery side, which has to be taken into account, because there exists many combinations, which result in a brittle, undesirable joint. Also the surface consistency (waviness and cleanliness) is important, and nickel is definitely preferable compared to steel.
Nevertheless, I  reckon the main reasons for using nickel plated steel are not found in the fabrication process, but in the functionality of the final product.
The key idea is to obtain a "high" electrical conductivity -- that's why people use pure nickel instead of nickel plated steel if they need "high" drain currents.
The second reason, which you already mentioned, is probably the corrosion resistance. Again, I haven't gain much, if my product is not lasting.
So, while the simplicity of the fabrication process is an important factor -- copper has a higher el. conductivity, but the fabrication process is more involving -- the functionality is the main reason.

A: I can see 5 purposes for using a Ni plated steel strip:
1) Protection against corrosion.
2) Improved electrical conductivity. Ni has about half the resistivity of 1010 steel.
3) Mechanical resistance (due to steel).
4) Low price (also due to steel)
5) Weldability
If the steel could be Cu plated, item 2 would be maximized, while keeping item 1 property. But there are problems with liquid Cu diffusion into iron grain boundaries that poses a great challenge to make Cu plated product. See for example: http://files.aws.org/wj/supplement/WJ_1978_01_s9.pdf
Increased electrical conductivity impairs weldability as you said, and it would be much more difficult with Cu.
Another candidate is Zinc plated steel. It is very common as a way of protection against corrosion, and the electrical resistance of Zinc is slightly lower than Ni. However the low boiling point of zinc ($ 871^0$C, well below iron melting point) is a problem for the welding.


text:
Q: AngularJs templaturl error           when('/contact', {

              templateUrl: './Contact.html',
              controller: 'ContactController'
          }).
          otherwise(
            {
              redirectTo: '/home'
          });

I am having templateurl like this. When I try to execute, My template url is not working. I have attached link to my application Angular TemplateURL . Please help me on how to fix the issuse.

A: Is it showing a 404 error? If yes, then check the path that it tried for finding your partials. Make sure that the path you have mentioned is correct. It is relative to the index. It should be pages/'pagename'.html
when('/contact', {

          templateUrl: 'pages/Contact.html',
          controller: 'ContactController'
      })

A: Firstly you should first understand how relative path works. So, here it follows:

/ means the root of the current drive
./ means the current directory
../ means the parent of the current directory.

As you have used :templateUrl: './Contact.html', it will try to look into the current directory.
So you have to change the path of your template URL's like this:
 when('/contact', {

              templateUrl: './pages/Contact.html',
              controller: 'ContactController'
          }).
          otherwise(
            {
              redirectTo: '/home'
          });


text:
Q: How do I disable line numbers in Helm buffers? I'm using linum to show line numbers. What I want is to have them enabled by default, but disabled in certain major modes, like eshell, compilation, etc.
This works well, but what I can't figure out is how to disable them in Helm buffers.

*

*There doesn't seem to be a major mode I can hook into

*(add-hook 'helm-before-initialize-hook '(lambda () (linum-mode 0))) turns off line numbers globally. Not sure how to disable linum for the current buffer only, since Helm buffers usually appear alongside another one

*Tried advice around helm-find-files, but doesn't seem to work

A: I didn't have linum-off set up properly. It overrides a function which global-linum-mode calls, so the latter has to be active in order for it to work.
; init.el
(require 'linum-off)
(global-linum-mode t)


text:
Q: Sql Querying, group relationships Suppose I have two tables:
Group
(
    id integer primary key,
    someData1 text,
    someData2 text
)

GroupMember
(
    id integer primary key,
    group_id   foreign key to Group.id,
    someData   text
)

I'm aware that my SQL syntax is not correct :) Hopefully is clear enough. My problem is this: I want to load a group record and all the GroupMember records associated with that group. As I see it, there are two options.
A single query:
SELECT Group.id, Group.someData1, Group.someData2 GroupMember.id, GroupMember.someData
FROM Group INNER JOIN GroupMember ...
WHERE Group.id = 4;

Two queries:
SELECT id, someData2, someData2
FROM Group
WHERE id = 4;

SELECT id, someData
FROM GroupMember
WHERE group_id = 4;

The first solution has the advantage of only being one database round trip, but has the disadvantage of returning redundant data (All group data is duplicated for every group member)
The second solution returns no duplicate data but involves two round trips to the database.
What is preferable here? I suppose there's some threshold such that if the group sizes become sufficiently large, the cost of returning all the redundant data is going to be greater than the overhead involved with an additional database call. What other things should I be thinking about here?
Thanks,
Jordan

A: If you actually want the results joined, I believe it is always more efficient to do the joining at the server level. The SQL processor is designed to match sets of data.
If you really want the results of 2 sql statements, you can always send two statements in one batch separated by a semicolon, and get two resultsets back with one round trip to the DB.

A: How the data is finally used is an important and unknown factor.
I suggest the single query method for most applications. Proper indexing will keep the query more efficient than the two query method.
The single query method also has the benefit of remaining valid if you need to select more than one group.

A: If you are only ever going to be retreiving a single group record with each request to the database then i would go with the second option.  If you are retrieving multiple group records and associated group member records, go with the join as it will be much quicker.

A: In general, it depends on what type of data you are trying to display.
If you are showing a single group and all its members, performance differences between the two options would be negligible.
If you are showing many groups and all of their members, the overhead of having to make a roundtrip to the database for each successive group will quickly outweigh any benefit you got from receiving a little less data.
Some other things you might want to consider in you reasoning

*

*Result Set Size - For many groups and members, your result set size may become a limiting factor as the size to retrieve and keep it in memory increases.  This is likely to occur with the second option.  You may want to consider paging the data, so that you are only retrieving a certain subset at a time.

*Lazy Loading - If you are only getting the members of some groups, or a user is requesting the members one group at a time, consider Lazy Loading.  This means only making the additional query to get the group's members when needed.  This makes sense only in certain use cases, but it can be much more effective than retrieving all data up front.

A: Depending on the type of database and your frontend application, you can return the results of two SQL statements on one trip (A stored procedure in SQL Server 2005 for example).
If you are creating a report that requires many fields from the Group table, you may not want the increased amount of data with the first query.
If this is some type of data entry app, you've probably already presented the Group data to the user, so they could fill in the group id on the where clause (or preferably via some parameter) and now they need the member results.

A: It really, really, really depends on what use you will make of the data.
For insatnce, if you were assembling a list of group members for a mail shot, and you need the group name for each letter you're going to send to a member, and you have no use for the Group level then the single joined query makes a lot of sense.
But if, say, you're coding a master-detail screen or report, with a page for each group and displaying information at both the Group and the Member levels then the two separate queries is probably most useful.
Unless you are retrieving quite large amounts of data (tens of thousands of groups with hundreds of memebers per group, or similar orders of magnitude) it is unlikely you are going to see much difference between performances of the two approaches.

A: On a simple query like this I would to try to perform it in one query.  The overhead of two database calls will probably exceed the additional SQL processing time from the query.
A UNION clause will do this for you:
SELECT id, someData1, someData2
FROM Group
WHERE id = 4
UNION
SELECT id, someData, null
FROM GroupMember
WHERE group_id = 4;


text:
Q: MySQL extract results by delimeter I have a quick (hopefully simple) question.  I have some information stored in a MySQL database:
|info1=value1
|info2=value2
|info3=value3
|info4=value4
|info5=value5
|info6=value6

I need to be able to get a certain set of information form this.  Let's pretend that this set of data is in each record in a table called options.  I need to be able to extract info3 value information, meaning that I need to (for every record) recieved the "value3" section of the record.  I don't need "|info3=", just the "value3"; the actual value of "value3" is different for each record.

A: You question is simple, alright.
I don't think the same can be told about the answer:
select substring_index(
    substring_index(
       old_text
       ,'info3=',-1),'|',1)
from mw_text;

This should do what you want.
BUT, I really hope that this is just for play, otherwise, I would recomend that you review your database design.


text:
Q: How to set continuation for CompletableFuture from it's callback conditionally? Given the code below - how the readAllValuesFuture() method should be implemented?
Make a call and depending on the result of its Future:

*

*either make the next call and pass the result of the previous one

*or return an aggregated result of all previous calls.

package com.example.demo;

import org.junit.jupiter.api.Test;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;

public class TestFuture
{
    @Test
    public void testReadAllValues() throws Exception
    {
        counter = 0;
        var list = readAllValues();
        assert list.size() == 10;
        assert counter == 11;
    }

    @Test
    public void testReadAllValuesFuture() throws Exception
    {
        counter = 0;
        var list = readAllValuesFuture().get();
        assert list.size() == 10;
        assert counter == 11;
    }

    // Synchronous logic - plain and simple
    private List<Integer> readAllValues()
    {
        List<Integer> list = new ArrayList<>();
        Integer res = makeFirstRequest();
        while (res != null)
        {
            list.add(res);
            res = makeNextRequest(res);
        }

        return list;
    }

    // Futures - how to implement it?
    private CompletableFuture<List<Integer>> readAllValuesFuture()
    {
        return CompletableFuture.failedFuture(new UnsupportedOperationException());
    }

    private int counter = 0;

    // Assuming this is external code which cannot be changed
    private Integer makeFirstRequest()
    {
        counter++;
        return 0;
    }

    // Assuming this is external code which cannot be changed
    private Integer makeNextRequest(Integer prevValue)
    {
        counter++;
        if (++prevValue < 10)
        {
            return prevValue;
        }

        return null;
    }

    // Assuming this is external code which cannot be changed
    private CompletableFuture<Integer> makeFirstRequestFuture()
    {
        counter++;
        return CompletableFuture.completedFuture(0);
    }

    // Assuming this is external code which cannot be changed
    private CompletableFuture<Integer> makeNextRequestFuture(Integer prevValue)
    {
        counter++;
        if (++prevValue < 10)
        {
            return CompletableFuture.completedFuture(prevValue);
        }

        return CompletableFuture.completedFuture(null);
    }
}

Real-life use-case:
Implement listAllTables() from the example below using DynamoDbAsyncClient (DynamoDbAsyncClient.listTables() returns CompletableFuture<ListTablesResponse> instead of ListTablesResponse as DynamoDbClient.listTables() does):
https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/examples-dynamodb-tables.html

A: One way to achieve this is via Stream.iterate:
var values = Stream.iterate(
    makeFirstRequestFuture().get(),
    Objects::nonNull,
    previous -> {
        try {
            return makeNextRequestFuture(previous).get();
        } catch (InterruptedException | ExecutionException e) {
            throw new RuntimeException(e);
        }
    }
).toList();


text:
Q: Show column when ever the user input text in the search bar I'm doing Angular project and wondering how I can display the middle column when ever the user input any text in the search bar.
So right now, I have search bar for user input and three flex columns. The middle column are hidden when the page is open but I want it to show when ever the user put any text in the search box. Any help will be really appreacited.

.left {
  flex: 2;

}

.right {
  flex: 1;

}
.center{
  flex: 1;
  display: none;
}

.parent {
  display: flex;
  overflow: hidden;
  width: 95vw;
  margin-left: 30px;
}


text:
Q: Filling a string buffer when using Ocilib I'm using Ocilib to perform a bulk insert on a Oracle database but I'm having some trouble while filling a string buffer.
The documentation says:

For string/RAW arrays, the input array
MUST BE a contiguous block of data and
not an array of pointers. So to bind
an array of 10 elements for a
varchar2(30) column, binded variable
must be a like array[10][31]

And a sample proceeds to fill a buffer like this:
...
char tab_str[1000][21];
...
OCI_BindArrayOfStrings(st, ":s", (char*) tab_str, 20, 0);
...

for(i=0;i<1000;i++)
{
    sprintf(tab_str[i],"Name %d",i+1);
}
...

I'm trying to fill the string buffer while looping through a std::vector of MyClass. MyClass has a std::string member.
I'm trying to use the std::string::copy method to copy over the string contents to the buffer. But I don't know exactly how to index the buffer to do it.
...
OCI_BindArrayOfStrings(st, ":f2", NULL, VCHAR_SIZE, 0);
char** vc_buffer = (char**)OCI_BindGetData(OCI_GetBind(st, 2));
...
int i = 0;
for(vector<MyClass>::const_iterator it = myVec.begin(); it != myVec.end(); ++it)
{
    /* 1st try */ it->m_string.copy((vc_buffer + (i * VCHAR_SIZE)), VCHAR_SIZE);
    /* 2nd try */ it->m_string.copy(vc_buffer[i], VCHAR_SIZE);
    ++i;
    ...
}
...

The first way gives me buggy data in the database. The second makes me hit a null pointer.
What I'm doing wrong?
PS:
The second approach, along the approach proposed by Alessandro Vergani below, results in null strings inserted. The first approach gives this (somewhat bizarre) result:

The gvim window shows what it's supposed to look like, the apex screen shows what ends up in the database.

A: (Try:
std::vector<char> tab_str(myVec.size() * (VCHAR_SIZE + 1));
...
OCI_BindArrayOfStrings(st, ":s", &tab_str[0], VCHAR_SIZE, 0);
...
int offset = 0;
for(vector<MyClass>::const_iterator it = myVec.begin(); it != myVec.end(); ++it, offset += VCHAR_SIZE)
{
    it->m_string.copy(&tab_str[offset], VCHAR_SIZE);
    ...
}
...

I'm not sure you need to add the null terminator: if not, remove the -1 from the copy and remove the second line.


text:
Q: difference between text file and binary file Why should we distinguish between text file and binary files when transmitting them? Why there are some channels designed only for textual data? At the bottom level, they are all bits.

A: Distinguishing between the two is important as different OSs treat text files differently. For example in *nix you end your lines with just \n while in MS OSs you use \r\n and in Macs you use \n\r. Software such as FTP clients try to change the line endings on text files to match the destination OS by adding/removing the characters. This is to make sure that the text file will look properly on the destination OS.
for example, if you create a text file in *nix with line breaks and try to copy it to a windows box as a binary file and open it in notepad, you will not see any of the line endings, but just a clog of text.

A: Important to add to the answers already provided is that text files and binary files both represent bytes but text files differ from binary files in that the bytes are understood to represent characters. The mapping of bytes to characters is done consistently over the file using a certain code page or Unicode. When using 7 or 8-bit code pages you can spin the dial when reading these files and interpret them with an English alphabet, a German alphabet, Russian alphabet, or others. This spinning the dial doesn't affect the bytes, it does affect which characters are chosen to correspond to the bytes.
As others have stated, there is also the issue of the encoding of line break separators which is unique to text files and which may differ from platform to platform. The "line break" is not a letter in our alphabet or a symbol you can write, so other rules apply to it.
With binary files there is no implicit convention on character encoding or on the definition of a "line".

A: At the bottom level, they are all bits... true.  However, some transmission channels have seven bits per byte, and other transmission channels have eight bits per byte.  If you transmit ASCII text over a seven-bit channel, then all is fine.  Binary data gets mangled.
Additionally, different systems use different conventions for line endings: LF and CRLF are common, but some systems use CR or NEL.  A text transmission mode will convert line endings automatically, which will damage binary files.
However, this is all mostly of historical interest these days.  Most transmission channels are eight bit (such as HTTP) and most users are fine with whatever line ending they get.
Some examples of 7-bit channels: SMTP (nominally, without extensions), SMS, Telnet, some serial connections.  The internet wasn't always built on TCP/IP, and it shows.
Additionally, the HTTP spec states that,

When in canonical form, media subtypes of the "text" type use CRLF as the text line break.  HTTP relaxes this requirement and allows the transport of text media with plain CR or LF alone representing a line break when it is done consistently for an entire entity-body.

A: All files are saved in one of two file formats - binary or text. The two file types may look the same on the surface, but their internal structures are different.
While both binary and text files contain data stored as a series of (bits (binary values of 1s and 0s), the bits in text files represent characters, while the bits in binary files represent custom data.

A: All machine language files are actually binary files.
For opening a binary file, file mode has to be mentioned as "rb"or "wb"in fopen command. Otherwise all files are opened in default mode, which is text mode.
It may be noted that text files can also be stored and processed as binary files but not viceversa.
The binary files differ from text file in 2 ways:

*

*The storage of newline characters

*The EOF character

Eg:

*

*wt-t stands for textfile

*Wb-b stands for binaryfile

Binary files do not store any special character at the end either file end is verified by ueing their size itself.


text:
Q: How to get the current time of device android depending on the region with Kotlin? How to get the current time of the device where the apk is installed?
Here's my code, what should I change to get the current time depending on the region with Kotlin
val calendar = Calendar.getInstance()
            val date = SimpleDateFormat("yyyy-MM-dd hh:mm:ss")
            val t =   date.format(calendar.time)
            txt.text = t.toString()

Why I get the local time + 3h ??

A: You don't have to change anything, the code gives you the device's current time
However, since it may not be accurate for each device, it is recommended to receive it from the server in case of time.

A: Your code is implicitly using the JVM's default time zone. This doesn't seem to give you the result that you wanted. The solution is to specify time zone explicitly (which is usually a good idea anyway).
java.time
I am using java.time, the modern Java date and time API.
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss");

    ZoneId usersDesiredTimeZone = ZoneId.of("Africa/Tripoli");
    ZonedDateTime now = ZonedDateTime.now(usersDesiredTimeZone);

    String text = now.format(formatter);
    System.out.println(text);

When I ran this snippet just now, the output was:

2020-09-02 16:51:21

The time printed is 2 hours ahead of UTC because this is what Libya is using. Please substitute your own desired time zone.
Yet another change from your code is I am using uppercase HH for hour of day from 00 through 23 in the format pattern string. Lowercase hh is for hour within AM or PM from 01 through 12. I figured this was probably not what you had wanted.
Question: Doesn't java.time require Android API level 26?
java.time works nicely on both older and newer Android devices. It just requires at least Java 6.

*

*In Java 8 and later and on newer Android devices (from API level 26) the modern API comes built-in.

*In non-Android Java 6 and 7 get the ThreeTen Backport, the backport of the modern classes (ThreeTen for JSR 310; see the links at the bottom).

*On older Android either use desugaring or the Android edition of ThreeTen Backport. It's called ThreeTenABP. In the latter case make sure you import the date and time classes from org.threeten.bp with subpackages.

Links

*

*Oracle tutorial: Date Time explaining how to use java.time.

*Java Specification Request (JSR) 310, where java.time was first described.

*ThreeTen Backport project, the backport of java.time to Java 6 and 7 (ThreeTen for JSR-310).

*Java 8+ APIs available through desugaring

*ThreeTenABP, Android edition of ThreeTen Backport

*Question: How to use ThreeTenABP in Android Project, with a very thorough explanation.


text:
Q: Add/Subtract from each parameter in variadic template and forward the result Let's assume that I have a function which takes a variadic template of integers:
template < int... I > int dummy()
{
    // to each int in I add/subtract something
    // and forward the pack with modified values somewhere else
    // test< (I -/+ n)... >
}

And for each value in the parameter pack, I would like to perform a mathematical operation and forward the pack with the modified values to somewhere else.
For example to another type like this one:
template < int... I > struct test;

template < int _0 > struct test< _0 > {
    // use params...
};
template < int _1, int _0 > struct test< _1, _0 > {
    // use params...
};
template < int _2, int _1, int _0 > struct test< _2, _1, _0 > {
    // use params...
};
template < int _3, int _2, int _1, int _0 > struct test< _3, _2, _1, _0 > {
    // use params...
};

So that if the function is called like:
dummy< 1, 2, 3, 4>();

And I subtract 1 from each value in the parameter pack. It'll be equivalent to using test like:
test< 0, 1, 2, 3 >

This is not the scenario in which I need this but rather an example to illustrate what I mean.
I was looking tinto C++17 Fold expressions but from what I could understand it doesn't generate a modified parameter pack but rather folds them to a single value.
What is an efficient way with decent compile time of achieving this?
EDIT:
To give an example where I would use this. I would like to have a variadic user defined literal like:
template < char... I > int operator"" _test()
{
    //...
}

That I could call like:
18264_test;

But the received parameters are their ASCII decimals not the actual number.
So I would like to be able to have something like (I - '0')... which gives me the actual number.

A: It seems I had the answer all this time.
template < char C > int test()
{
    printf("%d_", C);
    return C;
}
template < char C1, char C2, char... Cs > int test()
{
    printf("%d_", C1);
    return C1 + test<C2, Cs...>();
}

template < char... I > int operator"" _show()
{
    return test< (I - '0')... >();
}

A: I'm not sure you want to use a user-defined literal, because then you're kind of limiting yourself on the sorts of input it can take. Instead you could define a free floating function that performs the operation and passes it on to test:
struct test
{
    static void apply()
    {
        std::cout << "test received integers ";
        (... , (std::cout << I << " "));
    }
};

template<int RHS, int... VALS>
constexpr auto SubtractAndForward()
{
    return test<(VALS - RHS)...>::apply();
}
int main()
{
    SubtractAndForward<1, 1, 2, 3>();
}

Demo1
test::apply uses a fold expression to print

test received integers 0 1 2

However, this feels awkward. Since you're always forwarding to test, why not encapsulate both operations in the same struct:
struct test
{
    template<int RHS, int... VALS>
    static auto SubtractAndApply()
    {
        return apply<(VALS - RHS)...>();
    }

    template<int... I>
    static void apply()
    {
        std::cout << "test received integers ";
        (... , (std::cout << I << " "));
    }
};

Demo2
This still feels a bit awkward. Let's also parameterize the predicate we send, so we can do addition or subtraction:
struct test
{
    template<template<class> class F, int RHS, int... VALS>
    static auto ComputeAndApply()
    {
        return apply<F<int>{}(VALS, RHS)...>();
    }

    template<int... I>
    static void apply()
    {
        std::cout << "test received integers ";
        (... , (std::cout << I << " "));
        std::cout << std::endl;
    }
};
int main()
{
    test::ComputeAndApply<std::minus, 1, 1, 2, 3>();
    test::ComputeAndApply<std::plus, 1, 1, 2, 3>();
}

Demo 3
Output:

test received integers 0 1 2
  test received integers 2 3 4


text:
Q: How can I a call stored procedure on a remote MySQL Ubuntu server? I have an Ubuntu server with MySQL and many Stored Procedures (server A) and another Ubuntu server with MySQL (server B).
I'd like to populate the database on server B with data from the stored procedures on server A.
At this point I'd like to test the connection with no success.
I tried this on server B:
mysql> EXEC server_A_IP.DB_name.username.sp_courses();

But it gives this error:

ERROR 1064 (42000): You have an error in your SQL syntax; check the
  manual that corresponds to your MySQL server version for the right
  syntax to use near 'EXEC
  server_ip.db_name.owner.sp_courses()' at line 1

This is an example of what I'd like to do eventually:
On server B I have this table:
mysql> describe Course;
+-------+-------------+------+-----+---------+-------+
| Field | Type        | Null | Key | Default | Extra |
+-------+-------------+------+-----+---------+-------+
| CID   | int(11)     | NO   | PRI | 0       |       |
| name  | varchar(50) | YES  |     | NULL    |       |
+-------+-------------+------+-----+---------+-------+
2 rows in set (0.00 sec)

The Stored Procedure on Server A returns data like this:
call sp_courses();-- where the parameter indicates level 1.Returns [courseID, name]

1   CS1
2   CS2
10  CS3
12  CS4
13  CS5S

Can I fill data into the table from stored procedure on a different server?

A: AFAIK, you can't call a procedure stored in server A from server B.
What I'd do is:

*

*Modify the procedure so the output is stored in a table.

*Use mysqldump to dump the data of this output table and store it in the other server.

Example:
On server A, the procedure can be something like this:
delimiter $$
create procedure my_procedure()
begin
    -- Create a table to store the output:
    drop table if exists temp_result;
    create table temp_result (
        CID int not null primary key,
        name varchar(50)
    );
    -- Populate the table
    insert into temp_result
        select ...
end $$
delimiter ;

On server B, execute the following statement in the shell, not in MySQL CLI:
mysqldump <options_A> db_A temp_result --no-create-db --add-drop-table | mysql <options_B> db_B

where:

*

*<options_A> The options needed to connect to server A from server B:
-h <IP of server A> -u <user> -p<password>.

*db_A The database in server A where the result is stored

*<options_B> The options needed to connecto to server B:
-h localhost -u <user> -p<password>

A: There is a way to send data to a remote table using stored procedures, the trick is use federated tables. I created tables in two servers and stored procedure to reproduce your situation:

*

*SERVER A: create table and insert some data
create table course_A
(
  CID int not null primary key,
  name varchar(50),
  year int
);

insert into course_A values
(1,'CS1P',2016),
(2,'CS1Q',2016),
(109,'CS1-CT',2016),
(120,'CS1PX',2016),
(121,'CS1S',2016);

*SERVER B: create a table with structure
create table course_B
(
  CID int not null primary key,
  name varchar(50)
);

*SERVER A: create a remote table connected to table in server B:
create table course_B_remote
(
  CID int not null primary key,
  name varchar(50)
)
ENGINE=FEDERATED
CONNECTION='mysql://user:password@SERVER_B_IP:3306/database/course_B';

Now, whatever to do with table_B_remote affects directly to table_B in SERVER B.

*SERVER A: Create stored procedure to send the query results from course_A table to course_B_remote:
delimiter $$
drop procedure if exists sp_coursesForYear$$
create procedure sp_coursesForYear(p_year int)
begin

    /*
     Your procedure code...
    */

    insert into course_B_remote (CID,name)
    select  CID, name
    from course_A
    where year = p_year;

end$$
delimiter ;

*Now, test the stored procedure:
server A prompt> call sp_coursesForYear(2016);
Query OK, 5 rows affected (0,00 sec)

*Check if it worked:
server B prompt> select * from  course_B;
+-----+--------+
| CID | name   |
+-----+--------+
|   1 | CS1P   |
|   2 | CS1Q   |
| 109 | CS1-CT |
| 120 | CS1PX  |
| 121 | CS1S   |
+-----+--------+
5 rows in set (0.00 sec)

*Enjoy!
Maybe you will need to alter your procedures to use the FEDERATED tables.
No enable FEDERATED tables see this answer.


text:
Q: an attempt was made to logon, but the network logon service was not started We've recently had a catastrophic raid failure on our servers, which were being backed up with shadow protect. After 3 days of copying I finally got our file server back in a VM. As we used a 'virtualboot' for the file server in the meantime, I effectively had two copies of the server on the network at once.
In order to copy back the files that changed, I tried to rename the file server, and change its IP address (I should also mention, the file server is a backup DC). When I renamed it, it came up with an error, so I rebooted. Now I can't login, it says "an attempt was made to logon, but the network logon service was not started"
I don't care if I have to recreate the Vm and reinstall windows, but I would like to be able to get the files off this VM. How can I get access to it?

A: Boot to Directory Services Restore Mode to log in to a DC with a non-domain account; press F8 during boot as soon as Windows starts to load.
The password for the Administrator user in this mode was set during the initial promotion of the domain controller, but if you've forgotten it, it can be reset with typical password reset tools for local accounts.
Once you're in, you can fix whatever's needed to get the services started - my money's on networking and name resolution configuration.

A: Go to the workstation with the problem, login with the with a local account:
Right click on computer, Click on Manage
Go to Services and Applications
Click on Services
Go to NetLogon service and start the service
Log off and Login with the network account


text:
Q: Google Container Registry access denied when pushing docker container I try to push my docker container to the google container registry, using this tutorial, but when I run
gcloud docker push b.gcr.io/my-bucket/image-name

I get the error :
The push refers to a repository [b.gcr.io/my-bucket/my-image] (len: 1)
Sending image list
Error: Status 403 trying to push repository my-bucket/my-image: "Access denied."

I couldn't find any more explanation (no -D, --debug, --verbose arguments were recognized), gcloud auth list and docker info tell me I'm connected to both services.
Anything I'm missing ?

A: Use gsutil to check the ACL to make sure you have permission to write to the bucket:
$ gsutil acl get gs://<my-bucket>

You'll need to check which group the account you are using is in ('owners', 'editors', 'viewers' etc.)
EDIT: I have experienced a very similar problem to this myself recently and, as @lampis mentions in his post, it's because the correct permission scopes were not set when I created the VM I was trying to push the image from. Unfortunately there's currently no way of changing the scopes once a VM has been created, so you have to delete the VM (making sure the disks are set to auto-delete!) and recreate the VM with the correct scopes ('compute-rw', 'storage-rw' seems sufficient). It doesn't take long though ;-).
See the --scopes section here: https://cloud.google.com/sdk/gcloud/reference/compute/instances/create

A: I am seeing this but on an intermittent basis. e.g. I may get the error     denied: Permission denied for "latest" from request "/v2/...."., but when trying again it will work.
Is anyone else experiencing this?

A: For me I forgot to prepend gcloud in the line (and I was wondering how docker would authenticate):
$ gcloud docker push <image>

A: In your terminal, run the code below
$ sudo docker login -u oauth2accesstoken -p "$(gcloud auth print-access-token)" https://[HOSTNAME]

Where
-[HOSTNAME] is your container registry location (it is either gcr.io, us.gcr.io, eu.gcr.io, or asia.gcr.io). Check your tagged images to be sure by running $ sudo docker images).
If this doesn't fix it, try reviewing the VM's access scopes.

A: You need to make sure the VM instance has enough access rights. You can set these at the time of creating the instance, or if you have already created the instance, you can also edit it (but first, you'll need to stop the instance). There are two ways to manage this access:
Option 1
Under the Identity and API access, select Allow full access to all Cloud APIs.

Option 2 (recommended)
Under the Identity and API access, select Set access for each API and then choose Read Write for Storage.

Note that you can also change these settings even after you have already created the instance. To do this, you'll first need to stop the instance, and then edit the configuration as mentioned above.

A: If you are using Docker 1.7.0, there was a breaking change to how they handle authentication, which affects users who are using a mix of gcloud docker and docker login.
Be sure you are using the latest version of gcloud via: gcloud components update.
So far this seems to affect gcloud docker, docker-compose and other tools that were reading/writing the Docker auth file.
Hopefully this helps.

A: Same problem here, the troubleshooting section from https://cloud.google.com/tools/container-registry/#access_denied wasn't very helpful. I have Docker and GCloud full updated. Don't know what else to do.
BTW, I'm trying to push to "gcr.io".
Fixed. I was using a VM in compute engine as my development machine, and looks like I didn't give it enough rigths in Storage.

A: I had the same problem with access denied and I resolved it with creating new image using Tag:
docker tag IMAGE_WITH_ACCESS_DENIED gcr.io/my-project/my-new-image:test

After that I could PUSH It to Container registry:
gcloud docker -- push gcr.io/my-project/my-new-image:test

A: Today I also got this error inside Jenkins running on Google Kubernetes Engine when pushing the docker container. The reason was a node pool node version upgrade from 1.9.6-gke.1 to 1.9.7-gke.0 in gcp I did before. Worked again after the downgrade.

A: You need to login to gcloud from the machine you are:
gcloud auth login


text:
Q: Casperjs div "still did not exist" - but it does I want to set up end-to-end testing of my website using CasperJS (1.1.0-beta5, with PhantomJS 2.1.5). I wrote basic tests that work: everything that I wrote explicitly in "index.html" is found by Casper (title, container div, etc.).
Anything my javascript renders after that is not found (even using waitForSelector or wait). I am using React.
If I go to the url I give to Casper (localhost), I see everything that must be there, and inspecting the page with dev tools shows that my divs exist. Casper just ignores my Javascript.
How can I even debug to find out what the problem is ?
Here is the basic HTML layout:

App.js inserts a div "#app" in "#app-container".
If I print the DOM that Casper sees with this.getPageContent(), I see only the above, and no "#app". If I capture a screenshot, I see the footer but the rest of the page is blank:

Here is the code for my test:
casper.test.begin('Webapp basic layout', 6, function suite(test) {
    casper.start(url, function () {
        test.assertHttpStatus(200);
        test.assertTitle('Varapp browser', '<title> found');
        test.assertExists('#app-container', 'Main app container exists');
        casper.waitForSelector("#app", function() {
            test.assertExists('#app', 'Sub app div exists');
        })
    });
    casper.run(function () {
        test.done();
    });
});

And here is the output:
# Webapp basic layout
PASS Webapp basic layout (6 tests)
PASS HTTP status code is: 200
PASS <title> found
PASS Main app container exists
FAIL "#app" still did not exist in 5000ms
#    type: uncaughtError
#    file: ...
#    error: "#app" still did not exist in 5000ms
#    stack: not provided

What am I doing wrong ?


text:
Q: Young adult fantasy novel with blind archer who closes his eyes when he shoots. Romance theme It is a book I read as a child, probably the second book I have ever read, so I don't remember much about it. I can only recall it was a fantasy book for children, the main characters (a boy and a girl) that have to leave their village because of some danger I cannot remember. At some point during their travel, they meet a man who always keeps his eyes closed. The boy asks why and the man responds

"because if I opened them, it would not make any difference".

So the guy was a blind man but he was so cool he was an archer and even taught the boy how to shoot. With the new skills (I assume the girl learned something from the man too) the two manage to defeat whatever antagonist there was and confess their feelings for each other. There might have been a kiss underwater.


text:
Q: Why I can't download the scala sbt from website http://www.scala-sbt.org/download.html? I use mac to download scala sbt but always get timeout or forward me to a 404 webpage on 4sync, I have no idea how and where to download sbt now? Does any one met the same issue?

A: You can also download from bintray,but there's no newest versions.
Try the following url: https://dl.bintray.com/sbt/native-packages/sbt/


text:
Q: Implement a binary hash like http://www.fileformat.info/tool/hash.htm I have been struggling for 4 days trying to implement a hash algorithm in c# which works like the FIPS 198 standards document. I have reached a point where I have a value of
06070405020300010e0f0c0d0a0b080976777475363636363636363636363636363636363636363636363636363636363636363636363636363636363636363653616d706c65202332
I took this value and inserted it into the binary hash tool on http://www.fileformat.info/tool/hash.htm and the SHA-1 value is what I am expecting, but I can't replicate this in c#.
Expected value:
SHA-1: 74766e5f6913e8cb6f7f108a11298b15010c353a
When I use the SHA1 class in c# I get the value a969fdc725114c8418ca5c23946bd09977054ff6, which is the same as me entering my value above in the String Hash tool.
Could someone please point me in the right direction to generate what I require.

A: You will need to convert your hex-string data into a byte array. There are plenty of examples online of how to do this. One example posted to SO already is here (use the StringToByteArray function). Once you have a byte array, pass this through the SHA-1 hash and you should get the output you require.


text:
Q: Not displaying the  message on eclipse console I am trying to run a simple Hello World program on Eclipse IDE - Version: 2020-03 (4.15.0) Build id: 20200313-1211 and it gives a Terminated message on console followed by the desired output. I am using java 11.0.7 2020-04-14 LTS on Ubuntu 20.04 LTS.
Code:
package miscellaneous;

public class Test {
    public static void main(String[] args) {
        System.out.println("Hello World!");
    }
}

Output:
<Terminated> Test[Java Application] /usr/lib/jvm/jdk-11.0.7/bin/java
Hello World!

How do I not display the terminated message on the console?
I have already gone through this post:
Console shows terminated message in eclipse

A: The terminated message is not part of your program's output. It is simply a status message from Eclipse telling you that the program has finished running. It is displayed in the view information area rather that the console output area.
You can't stop Eclipse displaying this message.


text:
Q: cabal install --disable-prof not working? To save time, I am trying to build a package (in a sandbox) with --disable-doc --disable-prof, but it's failing: when compiling some dependency (crypto-api), I get
Could not find module 'System.Entropy'
Perhaps you haven't installed the profiling libraries for package
'entropy-0.3.7@entro_GdlGosmsZhO5QKbUBFjD3f'?

Sure I have not, and I don't want to.
What's happening? (The workaround is to --disable-doc only.)

A: Odds are a package lower in the dependency tree is forcing profiling builds, and then failing when the package it depends on has not been built that way.

A: You used the wrong flags.
You need --disable-profiling --disable-documentation


text:
Q: Just-in-time debugger with ViewFinity/no admin rights My company uses ViewFinity to elevate processes that need admin rights in lieu of any kind of actual admin privileges. Visual studio is already elevated, but for some reason the JIT debugger doesn't run as admin. It is a separate .exe that kicks off when an exception occurs? How would I go about fixing this?

A: IT fixed the issue. Evidently when JIT debugger is launched, it launches a separate .exe (can't remember the name right now) which in turn launches visual studio.


text:
Q: Highlighting problem with Javascript: changes differently

var wordsToBeTyped = document.querySelector('h2').innerHTML.split('');
var place = 0;
var wrong = 0;
var correct = 0;
document.onkeydown = function(event) {

  if (event.key === wordsToBeTyped[place]) {
    correct = correct + 1;

    place = place + 1;
    document.getElementById('correct').innerHTML = 'Correct: You have ' + correct + ' correct!'

  } else {

    wrong = wrong + 1;
    document.getElementById('wrong').innerHTML = 'Wrong: You have ' + wrong + ' wrong'
    document.body.style.backgroundColor = 'red';
    setTimeout(function() {
      document.body.style.backgroundColor = 'skyblue'
    }, 500)
  }
  highlight(wordsToBeTyped[place])
}
highlight(wordsToBeTyped[place])

function highlight(text) {
  var inputText = document.querySelector('#checking');
  var innerHTML = inputText.innerHTML;
  var index = innerHTML.indexOf(text);
  if (index >= 0) {
    innerHTML = innerHTML.substring(0, index) + "" + innerHTML.substring(index, index + text.length) + "" + innerHTML.substring(index + text.length);
    inputText.innerHTML = innerHTML;
  }
}
h3 {
  display: inline-block;
}

body {
  background-color: skyblue;
  text-align: center;
}

.highlight {
  background: yellow;
}
<!DOCTYPE html>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <meta name="google" content="notranslate">
  <title>Typing Accuracy Test</title>
  <link href="style.css" rel="stylesheet" type="text/css" />

Typing Accuracy Test

lorem ipsum dolor sit amet, tritani debitis ea ius, nostrud albucius vis eu. civibus consequuntur cum ut, te albucius accusamus per, illum nominati temporibus nec eu. adversarium efficiantur ei qui. at vix falli tollit. an graece vituperata vix, iusto
    primis ponderum id eum, delenit definiebas vix in.

This code is supposed to run and highlight what you have typed so far. But, after to type toward the m, it just shows the span, instead of highlighting it. It is annoying, and I have tried to change the text to no spaces, but that doesn't work either. Above is my code. Thanks. It highlights everything after the m

A: A few errors here...
Avoid playing with innerHTML as much as you can. innerHTML as a getter will return all the markup in your Element, and as a setter will remove all the nodes that were inside it.
For you this is a problem because you do change the innerHTML of your Element: at every character, you are converting the next letter to be typed as a . So when you check the indexOf the character  (space), you find the one you did add in this markup.
To avoid that, use the textContent property of your Element, which will disregard all the markup.
But also, don't use indexOf to know where you are, it will still fail when a character was present before. So simply use the place counter you already have.

// grab textContent
var wordsToBeTyped = document.querySelector('h2').textContent.split('');
var place = 0;
var wrong = 0;
var correct = 0;
document.onkeydown = function(event) {
  event.preventDefault();
  if (event.key === wordsToBeTyped[place]) {
    correct = correct + 1;

    place = place + 1;
    // set textContent
    document.getElementById('correct').textContent = 'Correct: You have ' + correct + ' correct!'
  } else {
    wrong = wrong + 1;
    // set textContent
    document.getElementById('wrong').textContent = 'Wrong: You have ' + wrong + ' wrong'
    document.body.style.backgroundColor = 'red';
    setTimeout(function() {
      document.body.style.backgroundColor = 'skyblue'
    }, 500)
  }
  highlight(wordsToBeTyped[place])
}
highlight(wordsToBeTyped[place])

function highlight(text) {
  var inputText = document.querySelector('#checking');
  // grab textContent
  var innerText = inputText.textContent;
  if (place >= 0) {
    innerText = "" + innerText.substring(0, place) + innerText.substring(place, place + text.length) + "" + innerText.substring(place + text.length);
    // here you can set innerHTML
    inputText.innerHTML = innerText;
  }
}
h3 {
  display: inline-block;
}

body {
  background-color: skyblue;
  text-align: center;
}

.highlight {
  background: yellow;
}

Typing Accuracy Test

lorem ipsum dolor sit amet, tritani debitis ea ius, nostrud albucius vis eu. civibus consequuntur cum ut, te albucius accusamus per, illum nominati temporibus nec eu. adversarium efficiantur ei qui. at vix falli tollit. an graece vituperata vix, iusto
  primis ponderum id eum, delenit definiebas vix in.

A: You are checking for pure text change, and you are not taking account for position of your place. You should specify as text, not innerHTML. Perhaps you should parse wordsToBeTyped as a DOM Element and grab it's inner text value instead.


text:
Q: Minimizing Application to system tray using WPF ( Not using NotifyIcon ) I am finished making my application and now I want to incorporate " minimizing into the system tray feature " for it . I read up a good article  minimize app to system tray . I realized that these make use of the Windows.Form class .
Unfortunately I have used Windows Presentation Foundation WPF reference to make my applications UI . Now I see that the NotifyIcon is not supported in WPF. I see that there is an open source library on CodePlex that simulates the NotifyIcon properties WPF Contrib I have not used it as yet .
Now I am in a fix . Here are my questions :-
a) I don't want to incorporate a 3'rd party library just for one single component .
b) Can I do the minimizing feature without NotifyIcon on WPF? If yes then how can someone give me leads please ?
Or maybe I should revert my UI back to using Windows Forms ?

A: If you'll reconsider your reluctance to using an external component, I recommend WPF NotifyIcon. I've used it. It's straightforward and works well.
It does not just rely on the corresponding WinForms component, but is a purely independent control which leverages several features of the WPF framework in order to display rich tooltips, popups, context menus, and balloon messages.

A: I just came across this post today.
For reference, I also solved this some time back. It works very well and the only time I have had a bit of an issue is occasionally on some multi-display set ups.
This was before GITs and NuGets were the in-thing, I will place it in a GIT repo if there is interest.
CodeProject Article Here

A: Solution with System.Windows.Forms.NotifyIcon
Here is a thread , which helped me a lot .
https://stackoverflow.com/a/12428063/10305444
public partial class Window : System.Windows.Window{

public Window()
{
    InitializeComponent();

    System.Windows.Forms.NotifyIcon ni = new System.Windows.Forms.NotifyIcon();
    ni.Icon = new System.Drawing.Icon("Main.ico");
    ni.Visible = true;
    ni.DoubleClick +=
        delegate(object sender, EventArgs args)
        {
            this.Show();
            this.WindowState = WindowState.Normal;
        };
}

protected override void OnStateChanged(EventArgs e)
{
    if (WindowState == WindowState.Minimized)
        this.Hide();

    base.OnStateChanged(e);
}}


text:
Q: C++ htonll and back I have found the following code which is capable of converting an int64_t to network byte order. Now I need the opposite code, such that network byte order is converted back to my little endian machine.
The code is this.
int64_t decode(void* value){
    int64_t vv = *((int64_t*) value);
    int num = 42;
    if(*(char *)&num == 42) //test big/little endian
        return (((uint64)htonl(vv)) << 32) + htonl(vv >> 32);
    else
        return vv;
}

Thanks a lot!

A: The code for your htonll
#define htonll(x) ((((uint64_t)htonl(x)) << 32) + htonl((x) >> 32))

flips the bytes end to end. If you apply it twice, it restores the value to its original state. So the same function can be used for ntohll.

A: htonl can be done by below steps

*

*If its big endian system return the value directly. No need to do any conversion. If its litte endian system, need to do the below conversion.

*Take LSB 32 bit and apply 'htonl' and shift 32 times.

*Take MSB 32 bit (by shifting the uint64_t value 32 times right) and apply 'htonl'

*Now apply bit wise OR for the value received in 2nd and 3rd step.

Similarly for ntohll also
#define HTONLL(x) ((1==htonl(1)) ? (x) : (((uint64_t)htonl((x) & 0xFFFFFFFFUL)) << 32) | htonl((uint32_t)((x) >> 32)))
#define NTOHLL(x) ((1==ntohl(1)) ? (x) : (((uint64_t)ntohl((x) & 0xFFFFFFFFUL)) << 32) | ntohl((uint32_t)((x) >> 32)))

A: In C++23, we get std::byteswap, e.g.:
#include <bit>
#include <cstdint>

auto htonll(std::uint64_t h)
{
    return (std::endian::native == std::endian::big) ? h : std::byteswap(h);
}

Until then, this solution will work in constant expressions:
#include <cstdint>
#include <climits>
#include <bit>

constexpr auto htonll(std::uint64_t h)
{
    if (std::endian::native != std::endian::big) {
        static_assert(CHAR_BIT==8);
        constexpr auto shift_bytes1{8};
        constexpr auto shift_bytes2{16};
        constexpr auto shift_bytes4{32};
        h = ((h&UINT64_C(0x00FF00FF00FF00FF))<<shift_bytes1) | ((h&UINT64_C(0xFF00FF00FF00FF00))>>shift_bytes1);
        h = ((h&UINT64_C(0x0000FFFF0000FFFF))<<shift_bytes2) | ((h&UINT64_C(0xFFFF0000FFFF0000))>>shift_bytes2);
        h = ((h&UINT64_C(0x00000000FFFFFFFF))<<shift_bytes4) | ((h&UINT64_C(0xFFFFFFFF00000000))>>shift_bytes4);
    }
    return h;
}

A: Here's how I would do it using a union.  The bit-shifting method will work fine as well, but IMHO it's a little bit trickier to get right.
#include<stdlib.h>
#include<stdio.h>

union MyUnion {
   int64_t i64;
   int32_t i32[2];
};

int64_t htonll(int64_t hostFormatInt64)
{
   MyUnion u;
   u.i64 = hostFormatInt64;
   int32_t temp = u.i32[0];
   u.i32[0] = htonl(u.i32[1]);
   u.i32[1] = htonl(temp);
   return u.i64;
}

int64_t ntohll(int64_t networkFormatInt64)
{
   MyUnion u;
   u.i64 = networkFormatInt64;
   int32_t temp = u.i32[0];
   u.i32[0] = ntohl(u.i32[1]);
   u.i32[1] = ntohl(temp);
   return u.i64;
}

void Test(int64_t i)
{
   printf("Testing value %lli\n", i);
   int64_t networkI = htonll(i);
   printf("   Network format is %lli (0x%llx)\n", networkI, networkI);
   int64_t hostAgainI = ntohll(networkI);
   printf("   Back to host again %lli (0x%llx)\n", hostAgainI, hostAgainI);
   if (hostAgainI != i)
   {
      printf("ERROR, we didn't get the original value back!\n");
      abort();
   }
}

int main()
{
   // A quick unit test to make sure I didn't mess anything up :)
   int64_t i = 0;
   while(1)
   {
      Test(i);
      Test(-i);
      i += rand();
   }
   return 0;
}

A: Copy from c:\Program Files (x86)\Windows Kits\8.1\Include\um\WinSock2.h
#if !defined(NO_EXTRA_HTON_FUNCTIONS) && !defined(__midl) && (defined(INCL_EXTRA_HTON_FUNCTIONS) || NTDDI_VERSION>=NTDDI_WIN8)
/*
 * Byte order conversion functions for 64-bit integers and 32 + 64 bit
 * floating-point numbers.  IEEE big-endian format is used for the
 * network floating point format.
 */
#define _WS2_32_WINSOCK_SWAP_LONG(l)                \
            ( ( ((l) >> 24) & 0x000000FFL ) |       \
              ( ((l) >>  8) & 0x0000FF00L ) |       \
              ( ((l) <<  8) & 0x00FF0000L ) |       \
              ( ((l) << 24) & 0xFF000000L ) )

#define _WS2_32_WINSOCK_SWAP_LONGLONG(l)            \
            ( ( ((l) >> 56) & 0x00000000000000FFLL ) |       \
              ( ((l) >> 40) & 0x000000000000FF00LL ) |       \
              ( ((l) >> 24) & 0x0000000000FF0000LL ) |       \
              ( ((l) >>  8) & 0x00000000FF000000LL ) |       \
              ( ((l) <<  8) & 0x000000FF00000000LL ) |       \
              ( ((l) << 24) & 0x0000FF0000000000LL ) |       \
              ( ((l) << 40) & 0x00FF000000000000LL ) |       \
              ( ((l) << 56) & 0xFF00000000000000LL ) )

#ifndef htonll
__inline unsigned __int64 htonll ( unsigned __int64 Value )
{
    const unsigned __int64 Retval = _WS2_32_WINSOCK_SWAP_LONGLONG (Value);
    return Retval;
}
#endif /* htonll */

#ifndef ntohll
__inline unsigned __int64 ntohll ( unsigned __int64 Value )
{
    const unsigned __int64 Retval = _WS2_32_WINSOCK_SWAP_LONGLONG (Value);
    return Retval;
}
#endif /* ntohll */

#ifndef htonf
__inline unsigned __int32 htonf ( float Value )
{
    unsigned __int32 Tempval;
    unsigned __int32 Retval;
    Tempval = *(unsigned __int32*)(&Value);
    Retval = _WS2_32_WINSOCK_SWAP_LONG (Tempval);
    return Retval;
}
#endif /* htonf */

#ifndef ntohf
__inline float ntohf ( unsigned __int32 Value )
{
    const unsigned __int32 Tempval = _WS2_32_WINSOCK_SWAP_LONG (Value);
    float Retval;
    *((unsigned __int32*)&Retval) = Tempval;
    return Retval;
}
#endif /* ntohf */

#ifndef htond
__inline unsigned __int64 htond ( double Value )
{
    unsigned __int64 Tempval;
    unsigned __int64 Retval;
    Tempval = *(unsigned __int64*)(&Value);
    Retval = _WS2_32_WINSOCK_SWAP_LONGLONG (Tempval);
    return Retval;
}
#endif /* htond */

#ifndef ntohd
__inline double ntohd ( unsigned __int64 Value )
{
    const unsigned __int64 Tempval = _WS2_32_WINSOCK_SWAP_LONGLONG (Value);
    double Retval;
    *((unsigned __int64*)&Retval) = Tempval;
    return Retval;
}
#endif /* ntohd */
#endif /* NO_EXTRA_HTON_FUNCTIONS */

Use

Microsoft Visual Studio Professional 2015
  Version 14.0.25420.01 Update 3
  Microsoft .NET Framework
  Version 4.7.03062

Test code:
#include "stdafx.h"
#include <string>
#include <stdexcept>

#include <Shlwapi.h>
#pragma comment(lib, "shlwapi.lib")

int _getcharIfNeeded() {
    HWND consoleWnd = GetConsoleWindow();
    DWORD dwProcessId;
    GetWindowThreadProcessId(consoleWnd, &dwProcessId);
    if (GetCurrentProcessId() == dwProcessId)
    {
        printf("I have my own console, press enter to exit\n");
        return getchar();
    }
    else
    {
        return printf("This Console is not mine, good bye\n");
    }
}

#include <boost/algorithm/hex.hpp>
#include <boost/format.hpp>
#include <boost/format/group.hpp>
int wmain(int argc, wchar_t *argv[])
{
#define SMB_FILE_SEPARATOR_CHAR '\\'
#define OWNER_FILE_PREFIX "~$"
    std::string strFileName("\\\\10.23.57.72\\fromw12r2\\behavior\\~$tree file-editing prohibited.xlsx");
    const size_t posFileName = strFileName.find_last_of(SMB_FILE_SEPARATOR_CHAR);
    bool isOwnerFile = std::string::npos != posFileName ? 0 == strncmp(strFileName.c_str() + posFileName + 1, OWNER_FILE_PREFIX, strlen(OWNER_FILE_PREFIX)) : false;

    //https://stackoverflow.com/questions/16375340/c-htonll-and-back
//#define htonll(x) ((((uint64_t)htonl(x)) << 32) + htonl((x) >> 32))
#define HTONLL(x) ((1==htonl(1)) ? (x) : (((uint64_t)htonl((x) & 0xFFFFFFFFUL)) << 32) | htonl((uint32_t)((x) >> 32)))
#define NTOHLL(x) ((1==ntohl(1)) ? (x) : (((uint64_t)ntohl((x) & 0xFFFFFFFFUL)) << 32) | ntohl((uint32_t)((x) >> 32)))

    const char smb2_sesid_bytes[] = { 0x23, 0x00, 0x00, 0x11, 0x00, 0x00, 0x00, 0x00 };
    const uint64_t sessionId_reinterpret_bytes_in_host_order = *reinterpret_cast<const uint64_t*>(smb2_sesid_bytes);
    const uint64_t sessionId_in_network_order = htonll(sessionId_reinterpret_bytes_in_host_order);
    const std::string strHex = boost::algorithm::hex(std::string(reinterpret_cast<const char*>(&sessionId_in_network_order), sizeof(uint64_t)));

    std::ostringstream strSink;
    //https://en.cppreference.com/w/cpp/iterator/ostreambuf_iterator
    boost::algorithm::hex(std::cbegin(smb2_sesid_bytes), std::cend(smb2_sesid_bytes), std::ostreambuf_iterator<char>(strSink));
    printf(strSink.str().c_str());//std::cout << stream.str();

    printOptimizedComparison();

    std::stringstream stream; // #include <sstream> for this
    const int MaximalAccess = 0x001f01ff;
    //boost::io::group(hex, showbase, 40); //using boost::io::group;
    stream << boost::format("PID=%1% (%1$#08x), MaximalAccess=%2% (%2$#08x), 0x%3$08x\n") % GetCurrentProcessId() % MaximalAccess % 0x001f01ff;
    stream << boost::format("%08x\n") % MaximalAccess;
    printf(stream.str().c_str());//std::cout << stream.str();

    testRomanToInt("III", 3);
    testRomanToInt("IV", 4);
    testRomanToInt("IX", 9);
    testRomanToInt("LVIII", 58);
    testRomanToInt("MCMXCIV", 1994);

    //https://stackoverflow.com/questions/663449/what-is-the-best-way-to-attach-a-debugger-to-a-process-in-vc-at-just-the-right
#ifdef __DEBUG
    __debugbreak(); //__asm int 3
#endif
    //it should just silently wait until you attach your debugger to the process.
    //while (!::IsDebuggerPresent()) ::Sleep(100); // to avoid 100% CPU load

    return _getcharIfNeeded(); //return IsDebuggerPresent() && getchar();
}


text:
Q: Find inf and sup of a set with a pair of elements Find the infimum and supremum of the set D given by
$$D=\{(x,y)\in \mathbb{ZxZ}|x^2+y^2≤9\}$$
I suspect the supremum to be $9$ and the infimum to be $0$. But how do I prove it?

A: I'm not sure how you would order a set of points but I'll try to help.
The expression defining the set ($x^2+y^2\leq 9$) might look familiar. And in fact it is the Pythagorean Theorem. This means that the set can be thought as a set of right angle triangles whose hypotenuse is less than or equal to $\sqrt{9}=3$. Equivalently you can think it as the lattice points* inside a circle of radius 3.
Eitherway, you're now able to construct the set yourself. Here is the set but only including the points from the first quadrant. To get the others, you just have to add negative sign in front of the coordinates.
$$\{(0,0),(0,1),(0,2),(0,3),(1,0),(1,1),(1,2),(2,0),(2,1),(2,2),(3,0)\}$$
For example, if you choose to order the points accroding to the sum of the coordinates, we see that the point $(2,2)$ has the greates sum, 4. In this case the point $(2,2)$ is the maximum and $(-2,-2)$ the minimum. Since the set is finite, the minimum and maximum are infimum and supremum respecticely.
* Lattice points are the points with integer coordinates.


text:
Q: Getting a error while using npm I am getting this error while using npm.
'CALL "C:\Program Files\nodejs\node.exe" "C:\Program Files\nodejs\node_modules
\npm\bin\npm-cli.js" prefix -g' is not recognized as an internal or external com
mand,
operable program or batch file.
5.6.0
Can anyone help me with this?
Thanks in advance.

A: If you have installed Node.js and still can't use it through command line then you should set the environment variable for Node.js
You can use this link as well for a reference: https://www.youtube.com/watch?v=hiVKXJ2hAdo


text:
Q: In a razor why, why can't I use "??" (more inside) First of all, please forgive me if this question is too basic or otherwise laughable.  The question is, why doesn't this work in a Razor view:
@item.Clients.Where(u => u.IsActive).FirstOrDefault().Name.Any() ?? "(None Exist)"

If this Client Name field exists, then I want it to be displayed in this View, and if it doesn't exist, I need the "(None Exist)" string to be displayed.


text:
Q: WCF vs WebAPI and native mobile devices I've been working on a single-page web app that is entirely ajax-based (no POSTs) and for now I'm using ASMX for the web services while it's in development. The web services work with JSON data. For the release, I know I'll need to upgrade to either WCF or WebAPI.
Eventually, I plan to build native mobile applications that will work with the same web services as the web app. All things being equal, if I have to choose between the two, which option should I go with so that the web services can work with different client apps?
Thanks.

A: If your application is designed to be only accessible by mobile devices from various platform, it means you will have to find the common easiest denominator for all these platforms. So, in other terms, if interoperability is your concern, you will focus on one unique communication technology that all platform can use.
JSON + REST seems to be the common easiest denominator for many platforms today (of course including mobile ones). And if that's the only communication technology you will implement, WebAPI seems the obvious choice.
WCF is more extensible, more configurable, you can plug different bindings, different encodings, on different protocols, it implements SOAP, WS-*, it can be very fast (with carefully chosen bindings), you can also do JSON+REST with it, but you don't need all that power (and WCF can be also quite complex because of all these features), what you need seems to be ubiquity and simplicity. Given your requirements, I would choose WebAPI.

A: I developed a set of RESTful web services using WCF, and recently started a project to replace WCF with ASP.NET Web API.  My experience is that ASP.NET Web API is easier to learn than WCF and easier to work with.  I can also give you a couple of reasons why you would want to choose ASP.NET Web API:

*

*WCF urls include the '.svc' extension.  For example:  http://localhost/MyRestService.svc/.  This shouldn't cause a problem with clients, but it's ugly.  You can get rid of the .svc extension by using the IIS URL Rewrite module (see this blog post), but with ASP.NET Web API, you don't have the problem in the first place.

*WCF uses the DataContractJsonSerializer, which generates JSON that can be problematic for clients.  Specific examples include dates and dictionaries.  You can change the serializer used by WCF (see this SO question), but ASP.NET Web API uses JSON.NET by default, which is highly configurable.
If I was starting out today and creating a new RESTful web service, choosing ASP.NET Web API over WCF would be an easy choice as this is what it was designed for.


text:
Q: IndexOf function I have this below code which will fetch loggedin UserID
System.Security.Principal.WindowsPrincipal p = System.Threading.Thread.CurrentPrincipal as System.Security.Principal.WindowsPrincipal;
        //networkID=User.
        string strName = p.Identity.Name;
        int start;
        start = strName.IndexOf("\") + 1 ;

  strName = strName.Substring(start, strName.Length - start);

But start = strName.IndexOf("\") + 1 ; throwing out error saying Newline in constant. The logged in username I get is domainName\username and I want to use only username. Please help

A: Try IndexOf(@"\") or IndexOf("\\").

A: \ is an escape character - you must use either "\\" or @"\" to get this to work.

A: You have to escape your backslashes by doubling them:
start = strName.IndexOf("\\") + 1 ;

A: Your backslash is escaping your last quote.  use a double backslash to escape your backslash.
start = strName.IndexOf("\\") + 1 ;

A: \ is an escape character. You either need to escape it with another \ or use verbatim string literals:
start = strName.IndexOf("\\") + 1 ;

Or:
start = strName.IndexOf(@"\") + 1 ;


text:
Q: VirtualDocumentRoot Domains and Subdomains Is it possible to have VirtualDocumentRoot for normal domains and subdomains?
http://www.example.com/ or http://example.com

Uses:
/var/www/example.com/

And
http://*.example.com

Uses
/var/www/example.com/subdomains/*

What i have so far:
Pastebin - VirtualDocumentRoot Domains and Subdomains
The normal domain works except the subdomains, appearently it always redirects to the normal domain. This information i used is coming from Stackoverflow - Apache-multiple-virtualdocumentroot
# get the server name from the Host: header
UseCanonicalName Off

# this log format can be split per-virtual-host based on the first field
LogFormat "%V %h %l %u %t \"%r\" %s %b" vcommon
CustomLog logs/access_log vcommon

<VirtualHost *:80>
    ServerAdmin webmaster@localhost
    ServerName domain.com
    ServerAlias www.domain.com domain.com
    VirtualDocumentRoot /var/www/%-2.0.%-1/web

    # Possible values include: debug, info, notice, warn, error, crit,
    # alert, emerg.
    LogLevel debug
    ErrorLog /var/log/apache2/vhosts-error.log
    CustomLog /var/log/apache2/vhosts-access.log combined

    ServerSignature On
</VirtualHost>
<VirtualHost *:80>
    ServerName domain.com
    ServerAlias *.domain.com
    VirtualDocumentRoot /var/www/%-2.0.%-1/subdomains/%-3
</VirtualHost>

Update v2 [worked for me, just ignore the subdomains till now..]
<VirtualHost *:80>
    ServerName example.com
    ServerAlias www.example.com example.com
    Options Indexes FollowSymLinks

    VirtualDocumentRoot /var/www/%-2_%-1/web/

    <Directory />
            AllowOverride none
    </Directory>

    <Directory "/var/www/*/web/">
        RewriteEngine on
        RewriteBase /
        # If a directory or a file exists, use it directly
        RewriteCond %{REQUEST_FILENAME} !-f
        RewriteCond %{REQUEST_FILENAME} !-d
        # Otherwise forward it to index.php
        RewriteRule . index.php [L]

        <Files sitemap.xml>
            RewriteEngine Off
        </Files>
    </Directory>

        LogLevel debug
        ErrorLog /var/log/apache2/vhosts-error.log
        CustomLog /var/log/apache2/vhosts-access.log combined
</VirtualHost>

A: You can specify a folder on your server for each domain and/or sub-domain :)
See http://httpd.apache.org/docs/current/vhosts/examples.html for samples.
If you get problems with the subdomain or domain please check your DNS record to see if subdomains are enabled for your domain. Else add a 'A' record with your subdomain or an alias like *.doamin.com
Basiccly what this does, is pointing the subdomain to your server IP address.
Check this article for an easy guide to DNS : https://support.google.com/a/answer/48090?hl=en


text:
Q: Cannot run java as regular linux user I am having problems trying to run java as a normal user on linux.  It runs fine as root user but not as a regular user.
Any help would be apreciated.
Thanks
root@pro1 [~]# which java
/usr/local/jdk/bin/java
root@pro1 [~]# java -version
java version "1.6.0_22"
Java(TM) SE Runtime Environment (build 1.6.0_22-b04)
Java HotSpot(TM) 64-Bit Server VM (build 17.1-b03, mixed mode)
root@pro1 [~]# su istream
istream@xxxxxxxxx [/root]# which java
/usr/local/jdk/bin/java
istream@xxxxxxxxx [/root]# java -version
Error occurred during initialization of VM
Could not reserve enough space for object heap
Could not create the Java virtual machine.
istream@xxxxxxxxx [/root]#
Update:
Yes, limits was the problem.. The server is running cpanel and that is imposing some pretty strict limits on users.
Thanks for the info.

A: Are there any resource limitations in place for the istream user (run ulimit -a and compare) which root doesn't have, possibly virtual memory (RLIMIT_AS / ulimit -v) ?
If so, check if it gets applied by /etc/security/limits.conf and if you can make an exception for the istream user.


text:
Q: Unity Android Game is not Working Properly in Google Play Unity Game is working fine in Unity Editor, I even test it on Androidusing Unity remote 5. When I upload the game on Google Play Store, game is not working properly.
I have a gate on my runner game, gate has a collider and tag. On Google Play Store gate functions are not working! Google Play doesn't know this as an issue. So there wasn't PreLaunch Raport problem found.
Each testing is takes really much time because Google Play console update is takes much time.
What could be the reasons. Could it be code based?
I tested:
-Changing Unity version(from 2020.3.24f to 2021.3.8f).
-It reads collider and its tag.

A: Problem was in the vibrating script which is some-how not working properly,So it probably giving error while working on android phone,. I couldn't saw any error because it is playing on android device.
(Interestingly now Ads are not shown! If I will find the reason I will update here.)


text:
Q: Python Socket - Use Client in Seperate Function I am developing a basic server login system which I can use for almost anything, the problem is when you define clients like for example:
client, address = socket.accept()
data = client.recv(1024)
print(data)

So you can easily do this but what I want to do it something like this:
def clientPrint(client):
    while 1:
        data = client.recv(1024)
        print(data)
while 1:
    client, address = socket.accept()
    Thread(target=clientPrint, args=(client)).start()

So as you can see I want to use the client in another function but then I get this error:
Exception in thread Thread-1:
Traceback (most recent call last):
  File "C:\Python34\lib\threading.py", line 920, in _bootstrap_inner
    self.run()
  File "C:\Python34\lib\threading.py", line 868, in run
    self._target(*self._args, **self._kwargs)
TypeError: clientRecv() argument after * must be a sequence, not socket

This was just a rough idea of what I want to do, so is there anyway I can use a socket client in a function like how I wanted it? If someone could find me a solution to this I would be very greatful! If you need more code to get a better idea of what I want just ask in a comment and I will add it. I have already looked all over for something like this but sadly I haven't found anything.
Thanks in advance!

A: The problem is that in the last line:
Thread(target=clientPrint, args=(client)).start()

(client) does not create a tuple. To create a tuple with a single item you need to change it to (client,)
It is actually the comma that makes tuples. (Except for the special empty tuple syntax: ()) For example, this makes a tuple:
seq = 1, 2, 3

Trailing commas are also allowed, which is how you make a tuple with a single element.
seq = 1,

The parentheses are only there so that python doesn't think the comma is an argument separator.
Tuples and Sequences


text:
Q: Logging not captured on behave steps Ok so in my environment.py file I am able to log stuff by:
logging.basicConfig(level=logging.DEBUG, filename="example.log")

def before_feature(context, feature):
    logging.info("test logging")

but when I am inside the steps file I cannot perform logging:
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)

@given("we have a step")
def step_impl(context):
    logger.debug("Test logging 2")

The logging message inside the step does not show up. I am using the python behave module. Any ideas?
I have tried enabling and disabling logcapture when I run behave but it makes no difference.

A: By default, behave tends to capture logs during feature execution, and only display them in cases of failure.
To disable this, you can set
log_capture=false
in behave.ini
Or, you can use the --no-logcapture command line option
Further Reading : Behave API Reference, Behave LogCapture

A: what worked for me:
behave --no-capture --no-capture-stderr --no-logcapture

and add in the environment.py the follwing snipest:
    def after_step(context, step):
        print("")

Why: I disovered that behave does not log the last print statement of a step. So I just added a empty print after each step with the previous snipest.
Hope it helped

A: Importing logging from environment.py in steps.py solved problem for me.
from features.environment import logging
I am not sure but I guess the problem is that every time you import logging it rewrites your previous configs because disable_existing_loggers is True by default. (Here is the documentation paragraph explaining this)


text:
Q: onActivityResult not called in Fragment only in Activity in scanning appl I am new to Android. My scanning appl is not able to call onActivityResult  in fragment. I did check the other threads but unable to understand the issue.
public class BarCodeFrag extends Fragment {
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    private OnFragmentInteractionListener mListener;

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment SearchCatFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static BarCodeFrag newInstance(String param1, String param2) {
        BarCodeFrag fragment = new BarCodeFrag();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    public BarCodeFrag() {
        // Required empty public constructor
    }

//    @Override
//    public void startActivityForResult(Intent intent, int code) {
//        BarCodeFrag.startActivityForResult(intent, code);
//    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    //the custom view
    private SearchView myView;
    private Button scanBtn;
    private TextView formatTxt, contentTxt;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View rootView =  inflater.inflate(R.layout.fragment_barcode, container, false);

        //get reference to the custom view
//        myView = (SearchView) rootView.findViewById(R.id.androidATCView1);

        scanBtn = (Button) rootView.findViewById(R.id.scan_button);
        formatTxt = (TextView) rootView.findViewById(R.id.scan_format);
        contentTxt = (TextView) rootView.findViewById(R.id.scan_content);

        scanBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if(v.getId()==R.id.scan_button){
                    //instantiate ZXing integration class
                    IntentIntegrator scanIntegrator = new IntentIntegrator(getActivity());
                    //start scanning
                    scanIntegrator.initiateScan();
                   // startActivityForResult(scanIntegrator, 1888);

                }
                else{
                    //invalid scan data or scan canceled
                    Toast toast = Toast.makeText(getActivity().getApplicationContext(),
                            "No scan data received!", Toast.LENGTH_SHORT);
                    toast.show();
                }
            }
        });
        return rootView;
    }

    // TODO: Rename method, update argument and hook method into UI event
    public void onButtonPressed(Uri uri) {
        if (mListener != null) {
            mListener.onFragmentInteraction(uri);
        }
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        try {
            mListener = (OnFragmentInteractionListener) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString()
                    + " must implement OnFragmentInteractionListener");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    /**
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     *

     * See the Android Training lesson Communicating with Other Fragments for more information.
     */
    public interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        public void onFragmentInteraction(Uri uri);
    }

    public void onActivityResult(int requestCode, int resultCode, Intent intent) {
        //retrieve result of scanning - instantiate ZXing object
        super.onActivityResult(requestCode,  resultCode,  intent);
        IntentResult scanningResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, intent);
        //check we have a valid result

        Toast.makeText(getActivity().getApplicationContext(), "Inside onActivityResult" , Toast.LENGTH_LONG).show();

        if (scanningResult != null) {
            //get content from Intent Result
            String scanContent = scanningResult.getContents();
            //get format name of data scanned
            String scanFormat = scanningResult.getFormatName();
            //output to UI
            formatTxt.setText("FORMAT: " + scanFormat);
            contentTxt.setText("CONTENT: " + scanContent);

            Toast.makeText(getActivity().getApplicationContext(), "Reply: " + scanFormat + ":" + scanContent, Toast.LENGTH_LONG).show();

            CheckAvailability(scanFormat);
        }}

I intend to see FORMAT and CONTENT from scan. This appl is working an an individual appl, but when I add the code in a fragment to add to my other app - I am unable to see FORMAT and CONTENT. Any suggestions are welcome. Many thanks.


text:
Q: sed: string between single qoutes I want to put an capital E infront of every string.
It is important that I use sed.
Such that
(260,'\"$40 a Day\"',2002,'Color','USA','','2000100002',131,6.1,'2002-04-24')

becomes
(260,E'\"$40 a Day\"',2002,E'Color',E'USA',E'',E'2000100002',131,6.1,E'2002-04-24')

I have tried
sed "s/'.*'/E&/g"

but it only puts an E infront of the first string!
Regards Kim

A: The greedy matching of * is matching from the first single quote all the way to the very last one. Try this instead:
sed "s/'[^']*'/E&/g"

As John1024 warns above, this will not work if escaped single-quotes are allowed.

A: Another sed,
sed "s/,'/,E'/g"