text:
Q: Breadth first printing for tree with multiple child nodes I have a tree data structure in which parent node can have any number of child nodes(>=0).(see sample_tree.jpeg) I want to create such tree. One of the possible approach thought by me is creating a linked list as shown in my_approach picture. Linked list are connected as shown. Can you help e here to write breadth first print with this structure??
Please write code in C++.
IF not possible, can u suggest suitable structure?

A: Storing every single node in a linked-list would be a (probably) poor way to manage it as you would have to know what order you should go to next, especially if you don't add them in the order you want to pirnt them out.
A better data structure would be to create a class for each node, and give it a private variable of a vector or linked-list of its children.
Then use a different class that would manage the printing of each node, by maintaing a FIFO queue for the order to print them.
some basic pseudo-code, as it was a while ago i did this:
class Node {
    public:
        ...
        void addChildren(vector<Node*>*);

    private:
       vector<Node*> _children;
};

void addChildren(vector<Node*>* queue) {
    for (unsigned int i = 0; i < _children.size(); i++) {
        queue->push_back(_children.at(i));
    }
}

where the queue variable is just a vector maintained by the main function (or another class if you wanted better encapsulation) which is iterated over. The only thing you would likely have to explicitly add is the first node to the queue.
Then when printing from the queue:
vector<Node*> queue;

//create your nodes statically or dynamically
//populate the queue with the first node

for (unsigned int i = 0; i < queue.size(); i++) {
    //print whatever you want from the node here

    //This adds the current node's children to the end of the FIFO queue
    queue.at(i)->getChildren(queue);
}

that should go over all the nodes and add them in a breadth first manner.
one note, i changed linked list to vector here because it's faster when you only need to add data to the end of the container.


text:
Q: Why is the template argument deduction not working here? I created two simple functions which get template parameters and an empty struct defining a type:
//S<T>::type results in T&
template <class T>
struct S
{
    typedef typename T& type;
};

//Example 1: get one parameter by reference and return it by value
template <class A>
A
temp(typename S<A>::type a1)
{
    return a1;
}

//Example 2: get two parameters by reference, perform the sum and return it
template <class A, class B>
B
temp2(typename S<A>::type a1, B a2)//typename struct S<B>::type a2)
{
    return a1 + a2;
}

The argument type is applied to the struct S to get the reference. I call them with some integer values but the compiler is unable to deduce the arguments:
int main()
{
    char c=6;
    int d=7;
    int res = temp(c);
    int res2 = temp2(d,7);
}

Error 1   error C2783: 'A
temp(S::type)' : could not deduce
template argument for 'A'
Error 2   error C2783: 'B
temp2(S::type,B)' : could not
deduce template argument for 'A'

Why is this happening? Is it that hard to see that the template arguments are char and int values?

A: It is looks like nondeduced context. According to C++ Standard 14.8.2.4/4:

The nondeduced contexts are:

*

*The nested-name-specifier of a type that was specified using a qualified-id.

*A type that is a template-id in which one or more of the template-arguments is an expression that references a template-parameter.

  When a type name is specified in a way that includes a nondeduced context, all of the types that comprise that type name are also nondeduced.  However, a compound type can include both deduced and nondeduced types.  [Example: If a type is specified as A<T>::B<T2>, both T and T2 are nondeduced.  Likewise, if a type is specified as A<I+J>::X<T>, I, J, and T are nondeduced.  If a type is specified as void f(typename  A<T>::B,  A<T>), the T in A<T>::B is nondeduced but the T in A<T> is deduced. ]

A: Deduction works in the forward direction:
template <class T> void f(T);

f(2); // can deduce int from T

Why is this happening?

It doesn't work in the backwards direction (your example):
template <class A> void g(typename S<A>::type);

Is it that hard to see that the template arguments are char and int values?

Template deduction can do some magical (Turing-complete) things, but I don't think this is one of them.
You might use something like (untested):
template <class SA> void h(SA a1)
{
    STATIC_ASSERT(same_type<SA, S<A>::type>::value);
    typedef typename SA::type A;

    ...
}

Using your favorite static assert library (Boost has two).

A: Just as first note, typename name is used when you mention a dependent name. So you don't need it here.

template <class T>
struct S
{
    typedef T& type;
};

Regarding the template instantiation, the problem is that typename S<A>::type characterizes a nondeduced context for A. When a template parameter is used only in a nondeduced context (the case for A in your functions) it's not taken into consideration for template argument deduction. The details are at section 14.8.2.4 of the C++ Standard (2003).
To make your call work, you need to explicitly specify the type:

temp<char>(c);

redpajama_set_name: RedPajamaStackExchange


text:
Q: Shortcut key to runtime added ContextMenu.Item I have need to add an Item to ContextMenu dynamically.
Like this:
context1.Items.Add("Reserved", Nothing, AddressOf Reserved_Click)

Then I would like that my "Reserved" Item can be fired with shortcut keys (say) Ctrl+R like with regularly added ShortcutKey through designer.
Question is: How to add shortcut (Ctrl+R) to "Reserved" item through code based on upper example?

A: You can add this directly on the ToolStripMenuItem itself. The ShortCut Enumeration is handy to assign the correct combined shortcut.
Dim tsItem As New ToolStripMenuItem("Reserved", Nothing, AddressOf Reserved_Click)
tsItem.ShortcutKeys = DirectCast(Shortcut.CtrlR, Keys)
tsItem.ShortcutKeyDisplayString = "CTRL + R"

context1.Items.Add(tsItem)

Alternatively, this will work too:
tsItem.ShortcutKeys = Keys.Control Or Keys.R


text:
Q: Custom domain templates with AngularJS Can someone please advise me what is the best method to setup AngularJS with multiple templates?
I have a web application which has the same functionality across our white labelled customers but each customer has different templates.
I'm thinking that we simply setup a folder of templates and make the server-side pick the appropriate templates for each domain name.

A: This depends on how you have structured (or can structure) your templates. Three possible cases:

*

*Aim to have the same client-side app for each user, but move all client-specific formatting to CSS. In this case, your server would just server a different stylesheet for each client, which could adjust things like branding, logo etc.

*Pass the client key through as a variable (for example, assigned to $rootScope). This would allow you to do things like specific ng-include where appropriate, if your customisation per client is non-trivial.

*Fully separated client-side app. Serve a versioned client-side app depending on the client. This would be the best choice if you have major, significant differences in functionality per client. Would work if you have generic data endpoints (i.e. RESTful), that are non-client-specific. However, this would add major overhead in terms of testing, QA etc - so would recommend as a last option.

I would consider the above cases in descending priority - if possible, use only stylesheets, otherwise minor switches / template changes, or as a last case, a fully separated app.


text:
Q: Start read at line X from website without using bandwidth? I am trying to read a website using a bufferedReader but it is using 3Mbps of my   internet and im trying to get it down, I know exectly on what line the text I want   to read is so is there a way i can skip to that line and only read the text   without using bandwidth on stuff I dont want and if this isnt working is there   another way I can read that line without using this much bandwidth.

A: Consider using HTML Parser like JSOUP. Jsoup uses a parse tree and it can be really fast.
Either way I don't think that there is a way to start from specific line, unfortunately.


text:
Q: Using type() with Annotations in python I am trying to learn how to use annotations.
I have this class:
class ApiItemPydanticWithTags(ApiItemPydantic):
    tags: str
ApiItemPydanticWithTags.__name__ = "ApiWIthTags"

I want to replicate this class creation with type():
ApiItemPydanticWithTags = type("ApiWIthTags", (ApiItemPydantic,), dict(tags: str = None))

But Obviously, dict(tags: str = None) does not work ...

A: I found out what I wanted to do with:
ApiItemPydanticWithTags = type(
    "ApiWIthTags", (ApiItemPydantic,), dict(__annotations__={"tags": str})
)


text:
Q: Why is repo not reinstalling after removing it from /etc/yum.repos.d? I removed a repo by deleting its file from /etc/yum.repos.d using rm -rf. Then I tried to install the same repo with dnf install but it is not showing up in /etc/yum.repos.d or when I run dnf repolist.
I assume there is a possibility that the package may still be memorized in dnf's cache so I've tried clearing the cache by typing
dnf clean expire-cache and even passing the --refresh option to dnf install but the repo still doesn't show.
How do I install a repository after removing it manually?

A: It's unclear what repo you deleted and tried to reinstall with your dnf install ... command but we can only assume that you tried to do something like this:
$ sudo dnf install -y http://download1.rpmfusion.org/free/fedora/releases/28/Everything/x86_64/os/Packages/r/rpmfusion-free-release-28-1.noarch.rpm
Fedora 28 - x86_64                                                                                411 kB/s |  60 MB     02:30
Last metadata expiration check: 0:00:00 ago on Mon 23 Jul 2018 02:06:48 AM UTC.
rpmfusion-free-release-28-1.noarch.rpm                                                                                40 kB/s |  20 kB     00:00
Dependencies resolved.
...
...
  Preparing        :                                                                                1/1
  Installing       : rpmfusion-free-release-28-1.noarch                                                                                1/1
  Verifying        : rpmfusion-free-release-28-1.noarch                                                                                1/1

Installed:
  rpmfusion-free-release.noarch 28-1

Complete!

Then deleted the .repo file like this:
$ sudo rm /etc/yum.repos.d/rpmfusion-free-updates.repo

And then tried to do install again:
$ sudo dnf install -y http://download1.rpmfusion.org/free/fedora/releases/28/Everything/x86_64/os/Packages/r/rpmfusion-free-release-28-1.noarch.rpm
RPM Fusion for Fedora 28 - Free                                                                                1.3 MB/s | 754 kB     00:00
Last metadata expiration check: 0:00:00 ago on Mon 23 Jul 2018 02:11:12 AM UTC.
rpmfusion-free-release-28-1.noarch.rpm                                                                                57 kB/s |  20 kB     00:00
Package rpmfusion-free-release-28-1.noarch is already installed, skipping.
Dependencies resolved.
Nothing to do.
Complete!

Solution
To get things back into shape you need to do a reinstall of this RPM not a install.
$ sudo dnf reinstall -y http://download1.rpmfusion.org/free/fedora/releases/28/Everything/x86_64/os/Packages/r/rpmfusion-free-release-28-1.noarch.rpm
Last metadata expiration check: 0:03:11 ago on Mon 23 Jul 2018 02:11:12 AM UTC.
rpmfusion-free-release-28-1.noarch.rpm                                                                                44 kB/s |  20 kB     00:00
Dependencies resolved.
...
...
  Preparing        :                                                                                1/1
  Reinstalling     : rpmfusion-free-release-28-1.noarch                                                                                1/2
  Erasing          : rpmfusion-free-release-28-1.noarch                                                                                2/2
  Verifying        : rpmfusion-free-release-28-1.noarch                                                                                1/2
  Verifying        : rpmfusion-free-release-28-1.noarch                                                                                2/2

Reinstalled:
  rpmfusion-free-release.noarch 28-1

Complete!

And if we confirm, the deleted .repo file is back:
$ ls -l /etc/yum.repos.d/rpmfusion-free-updates.repo
-rw-r--r--. 1 root root 1264 Apr 24 11:27 /etc/yum.repos.d/rpmfusion-free-updates.repo

Without the URL?
If you want, you can do this without even knowing the URL to the original RPM that was used to setup/install this repo.
Check for the name of the RPM:
$ rpm -qa|grep rpmfus
rpmfusion-free-release-28-1.noarch

Then do the dnf reinstall ... with just the RPM's name instead:
$ sudo dnf reinstall -y rpmfusion-free-release
Last metadata expiration check: 0:10:00 ago on Mon 23 Jul 2018 02:11:12 AM UTC.
Dependencies resolved.
...
...
  Preparing        :                                                                                1/1
  Reinstalling     : rpmfusion-free-release-28-1.noarch                                                                                1/2
  Erasing          : rpmfusion-free-release-28-1.noarch                                                                                2/2
  Verifying        : rpmfusion-free-release-28-1.noarch                                                                                1/2
  Verifying        : rpmfusion-free-release-28-1.noarch                                                                                2/2

Reinstalled:
  rpmfusion-free-release.noarch 28-1

Complete!

And check that the file's back:
$ ls -l /etc/yum.repos.d/rpmfusion-free-updates.repo
-rw-r--r--. 1 root root 1264 Apr 24 11:27 /etc/yum.repos.d/rpmfusion-free-updates.repo

What if I don't know the RPM's name?
If you're in the odd predicament that you cannot figure out or recall what RPM to use to reinstall you're still not completely out of luck.
You can see what file you deleted from your history command and then run this rpm command to learn what RPM provided it:
$ rpm -qf /etc/yum.repos.d/rpmfusion-free-updates.repo
rpmfusion-free-release-28-1.noarch

And then do the reinstall with the RPM's name as described above.
What if the RPM wasn't installed via DNF or YUM?
In your particular case it turns out that the RPM you mentioned: geogebra-classic-6.0.477.0-201807062103.i386.rpm, isn't an RPM that contains any YUM .repo files.
$ rpm -qpl geogebra-classic-6.0.477.0-201807062103.i386.rpm  | grep yum
$

In this scenario, neither dnf nor yum can provide any assistance because neither knows the URL to reinstall/download this RPM. This is because this RPM was likely originally merely downloaded and installed directly.
When an RPM is installed in this manner, dnf & yum are blinded to the URL and are merely installing whatever RPM you instruct them to do via the file that's on your local HDD.
Your only recourse in this scenario is to re-download the RPM in question and reinstall it manually using either dnf, yum or rpm.
References

*

*6.5. Adding, Enabling, and Disabling a DNF Repository

*DNF - Fedora Wiki

*RPMFusion Repo

*Third party repositories


text:
Q: Find fourth coordinates given other three points Find coordinates of $D$, given coordinates of $A,B,C$, torsion angle and angle between $BCD$.
Is there any other way other than the torsion angle equation,
 $$n_1=\langle b_1\times b_2\rangle \;\text{ and }\; n_2=\langle b_2\times b_3\rangle $$
 $$\phi = \cos^{-1}\left(\frac{n_1.n_2}{\|n|\ \|m\|} \right)\tag{A}  $$
I will have to write a program to calculate the co-ordinates, so the eqn $(A)$ is bit problematic to use, since $D$ contains the variables here. Can you suggest a better way?

A: After a long wait, I found my answer. The forum was of literally no help, since no one could give the solution.
Please find the details in this paper: Molecular Distance Geometry Problem


text:
Q: flexDirection is causing images to disappear so I have my images displaying one after another like I want them to. Instead of them being vertical though, I would like them to display horizontally. Originally, I was trying to use flexDirection: 'row' while then setting scrollview to horizontal to achieve this but flexDirection seems to make the images disappear all together.
I was putting flexDirection in the View at line 60. I also tried creating another parent view to hold flexDirection but that gave me the same result.
Please copy and paste this into snack.expo.io to see exactly what I am referring to!
Thank you for any insight at all!
import React, { useState } from 'react';
import {
  Pressable,
  StyleSheet,
  Text,
  View,
  useWindowDimensions,
  Dimensions,
  Image,
  Animated,
  PanResponder,
  TouchableOpacity,
  ScrollView,
  ImageBackground,
  Platform,
} from 'react-native';
import { SearchBar } from 'react-native-elements';

import {
  scale,
  verticalScale,
  moderateScale,
  ScaledSheet,
} from 'react-native-size-matters';

import { MaterialCommunityIcons } from '@expo/vector-icons';

const screenResolutions = () => {
  var SCREEN_HEIGHT = useWindowDimensions().width;
  var SCREEN_WIDTH = useWindowDimensions().height;
};

const images = [
  { id: '1', uri: require('./assets/snack-icon.png'), text: 'Test' },
  { id: '2', uri: require('./assets/snack-icon.png') /*text: "Test"*/ },
  { id: '3', uri: require('./assets/snack-icon.png') /*text: "Test"*/ },
  { id: '4', uri: require('./assets/snack-icon.png') /*text: "Test"*/ },
];

const pressableTest = () => {
  let textlog = '';
  const [state, setState] = useState(0);
};

export default class Home extends React.Component {
  renderImages = () => {
    return images.map((item, i) => {
      return (
        <View
          style={{
            paddingLeft: scale(10),
            paddingRight: scale(10),
            paddingBottom: scale(15),
          }}>
          <TouchableOpacity
            onPress={() => this.props.navigation.navigate('VenueDetails')}>
            <ImageBackground
              source={item.uri}
              style={{
                width: '100%',
                height: scale(225),
                shadowColor: '#000',
                shadowOffset: { width: 1, height: 4 },
                shadowOpacity: 1,
              }}
              imageStyle={{ borderRadius: 10 }}>
              <View
                style={{
                  position: 'absolute',
                  bottom: 10,
                  left: 10,
                  justifyContent: 'flex-start',
                  alignItems: 'flex-start',
                }}>
                <Text style={styles.name}>Name</Text>
                <View style={{ flexDirection: 'row', alignItems: 'center' }}>
                  <Text style={styles.category}>Category</Text>
                  <Text style={styles.dot}>⬤</Text>
                  <Text style={styles.money}>$$</Text>
                  <Text style={styles.dot}>⬤</Text>
                  <Text style={styles.starRating}>★★★</Text>
                </View>
              </View>
            </ImageBackground>
          </TouchableOpacity>
        </View>
      );
    });
  };

  state = {
    search: '',
  };

  updateSearch = (search) => {
    this.setState({ search });
  };

  render() {
    const { search } = this.state;

    return (
      <ScrollView
        style={{ flex: 1, backgroundColor: '#272933', horizontal: 'true' }}>
        <View style={{ flex: 1, marginTop: 15 }}>{this.renderImages()}</View>
      </ScrollView>
    );
  }
}

const styles = ScaledSheet.create({
  starRating: {
    color: 'white',
    fontSize: '20@s',
    textShadowOffset: { width: 2, height: 2 },
    textShadowRadius: 2,
    textShadowColor: '#000',
  },

  category: {
    color: 'white',
    fontSize: '20@s',
    textShadowOffset: { width: 2, height: 2 },
    textShadowRadius: 2,
    textShadowColor: '#000',
  },
  name: {
    fontWeight: 'bold',
    color: 'white',
    fontSize: '25@s',
    textShadowOffset: { width: 2, height: 2 },
    textShadowRadius: 2,
    textShadowColor: '#000',
  },
  dot: {
    color: 'white',
    fontSize: '5@s',
    paddingLeft: '5@s',
    paddingRight: '5@s',
    textShadowOffset: { width: 2, height: 2 },
    textShadowRadius: 2,
    textShadowColor: '#000',
  },
  money: {
    color: 'white',
    fontSize: '20@s',
  },

});

A: i dont use react , but your image view ( the one you return from render images ) should have a width or a flex-basis prop , and you container (scrollview > view) should have display : flex and width of 100vw
i made it work : here

.flex-box {
 width : 100vw ; // or %
 display : flex ;
 overflow-x : scroll ;
 flex-wrap : no-wrap ;
}
.flex-item {
 width : 200px ; // or % or flex-basis with no shrink or min-width
}

Edit : i changed to no-wrap and fixed width instead of basis to make it scrollable horizentally .
if a container is set to 100% flex no-wrap , and its children have a fixed width they will overflow horizontally in web we simply put overflow-x : scroll ; to make it scrollable and view all overflowed items .


text:
Q: Loop function for a list of codes I have a list of codes that start with importing column D of an excel sheet which has a hyperlink. Then, the code moves onto importing the text version of the hyperlink and further proceeds with textual analysis.
However, my code does this analysis once for one hyperlink and I have to manually change the row number to each time I run the code.
I would like for Mathematica to automate the import/textual analysis for all the hyperlinks in column D of the excel file. The textual analysis codes are more than 30 lines and I was not entirely sure if it would be possible to automate this process. Could anyone please help?
Below is the code for only the first few lines as I do not think the textual analysis code is relevant and too long to paste here (which will go inside the loop).  Thank you and I truly appreciate your help in advance!
Code below:
SetDirectory[]
dataset = Dataset[Import["proxy2020sampler.xlsx"]];
dataset1 = dataset[1, All, 4];

importing only column D which contains the hyperlinks
The excel file looks like below:

dataset2 = dataset1[21];

i have to manually update this number for each time the program runs the textual analysis
data = Import[dataset2, "Plaintext"];

Below is about 40 lines of textual analysis.


text:
Q: Delete Duplicates VBA I am trying to erase duplicate rows starting from bottom, but it isnt working. It keeps two copies but deletes other duplicate items.
With wb_DST.Sheets(sWs_DST)
    lncheckduplicatescolumn = .Cells(.Rows.Count, "A").End(xlUp).row
    wb_DST.Sheets(sWs_DST).Range(("A13:A" & lncheckduplicatescolumn - 2 & ":" & "AW13:AW" & lncheckduplicatescolumn - 2)).Sort key1:=wb_DST.Sheets(sWs_DST).Range("A13:A" & lncheckduplicatescolumn - 2), order1:=xlDescending, Header:=xlNo

    Dim row As Range
    Dim rng As Range
    Dim cell As Range
    Dim i As Integer
    Set rng = wb_DST.Sheets(sWs_DST).Range("A13:A" & lncheckduplicatescolumn - 2)
    For Each cell In rng
        If cell.Value = cell.Offset(-1, 0).Value Then
            .cell.Offset(-1, 0).EntireRow.Delete
        End If
    Next
End with

If Excel shows
Column A       Column B
A                 1
A                 2
A                 3

I want the code to retain the last row, and delete the ones above it.
The result should be
Column A            Column B
A                    3

Thanks,

A: Work from the bottom up and loop until all 'higher' (i.e. in a row less than current) are removed.
dim dup as variant, r as long, lncheckduplicatescolumn as long
With wb_DST.Sheets(sWs_DST)
    lncheckduplicatescolumn = .Cells(.Rows.Count, "A").End(xlUp).row
    for r = lncheckduplicatescolumn  to 2 step -1
        dup = application.match(.cells(r, "A").value, .columns(1), 0)
        if dup < r then .rows(dup).delete
    next r
end with

This will take a few more cycles than is absolutely necessary but the operation is efficient enough that it should not make a significant difference.

A: Dim x as integer
Dim y as string
Dim J as integer
Dim I as integer

x = activesheet.range("A" & Activesheet.range("A1").endxl.down).count 'This will count the total number of rows.

for i = x to 2 'this should count backwards from bottom to top, since you have headers, stop at row 2
 y = Activesheet.range("A" & i).value 'places value in a variable
      For j = x - i - 1 to 1 'this is another loop, but it should start above the whatever the cell that Y got its value
        if activesheet.range("a" & j).value = y then 'comparison
            'do what you need to delete the row
        end if

Next
Next

I think this will go start at the bottom, put that first value in a variable, and then will go through the rest of the list check the values to see if is compatible. The second for loop might need to be adjusted.

A: not a pretty answer - but from what it looks like, you should be ending up with the last and first occurrence of the duplicate:
 Column A    Column B
 A           1
 A           3

To patch your answer (there are more elegant ways), you could find the last row again after the loop is finished and check for one last duplicate:
 For Each cell In rng
    If cell.Value = cell.Offset(-1, 0).Value Then
        .cell.Offset(-1, 0).EntireRow.Delete
    End If
 Next

redefine your last row
 lncheckduplicatescolumn = .Cells(.Rows.Count, "A").End(xlUp).row

and check for one more duplicate
 If Range("A" & lncheckduplicatescolumn).Value = Range("A" & lncheckduplicatescolumn).Offset(-1, 0).Value Then
    .cell.Offset(-1, 0).EntireRow.Delete
 End If


text:
Q: Run python script from C# via command prompt I'm developing a Winform application. I want to run python script from c# via command prompt (i'm using System.Diagnostics.Process class)
I have a function to run python script that need to pass a python script file name.
        public void Run(string cmd)
        {
            Process p = new Process()
            {
                StartInfo = new ProcessStartInfo()
                {
                    FileName = "python",
                    CreateNoWindow = true,
                    UseShellExecute = false,
                    ErrorDialog = false,
                    RedirectStandardInput = true,
                    RedirectStandardOutput = true,
                    RedirectStandardError = true,
                    WorkingDirectory = Directory.GetCurrentDirectory() + @"\PythonScripts",
                    Arguments = string.Format("{0}", cmd)
                },
                EnableRaisingEvents = true,
                SynchronizingObject = this
            };
            p.OutputDataReceived += (s, e) => SetOutputText(e.Data);
            p.ErrorDataReceived += (s, e) => SetErrorText(e.Data);
            p.Start();
            p.BeginOutputReadLine();
            p.BeginErrorReadLine();
        }

It works correctly until I print a string that contain  unicode character.
My test.py code contains just a single line.
print("xin chào việt nam")

When I compiled this test.py command prompt from start it worked perfectly. But when I compiled from c# via command prompt I got this error:
Traceback (most recent call last):
File "test.py", line 1, in <module>    \ufeffprint("xin chào vi\u1ec7t nam")
File "C:\Users\D Serious\AppData\Local\Programs\Python\Python36\lib\encodings\cp1252.py", line 19, in encode
return codecs.charmap_encode(input,self.errors,encoding_table)
[0]UnicodeEncodeError: 'charmap' codec can't encode character '\u1ec7' in position 11: character maps to <undefined>

I think the problem here caused by C# when it run command prompt and read the python script, the process can not decode utf8 correctly. Thank you.

A: After hours finding the reason, I found it. Python decoding doesn't have problem, that is command prompt problem. So that I fix my function to:
public void Run(string cmd)
{
    Process p = new Process()
    {
        StartInfo = new ProcessStartInfo()
        {
            FileName = "cmd",
            CreateNoWindow = true,
            UseShellExecute = false,
            ErrorDialog = false,
            RedirectStandardInput = true,
            RedirectStandardOutput = true,
            RedirectStandardError = true,
            WorkingDirectory = Directory.GetCurrentDirectory() + @"\PythonScripts",
            StandardOutputEncoding = Encoding.UTF8,
            StandardErrorEncoding = Encoding.UTF8,
            StandardInputEncoding = Encoding.UTF8
        },
        EnableRaisingEvents = true,
        SynchronizingObject = this
    };
    p.Start();
    using (StreamWriter sw = p.StandardInput)
    {
        sw.WriteLine("chcp 65001");
        sw.WriteLine("set PYTHONIOENCODING=utf-8");
        sw.WriteLine($"python {cmd}");
    }
    p.OutputDataReceived += (s, e) => SetOutputText(e.Data);
    p.ErrorDataReceived += (s, e) => SetErrorText(e.Data);

    p.WaitForExit();
    p.BeginOutputReadLine();
    p.BeginErrorReadLine();
}

I added sw.WriteLine("chcp 65001"); and sw.WriteLine("set PYTHONIOENCODING=utf-8"); to get better decode unicode. Thank for your attention


text:
Q: how to started new project for spring mvc My project name is colormanagment, this project developing started spring MVC.
So, I to create project and new controller configurations and view JSP file management location. Can anybody give sample example or example link means it's very useful for me.

A: Spring provides a project as example. It is also mentioned in their documentation. So I advise you to take a look at this project :
https://github.com/spring-projects/spring-petclinic/

A: Here is a link to some example on Spring MVC http://spring.io/blog/2011/01/04/green-beans-getting-started-with-spring-mvc/
And JavaBrains has some good Spring Video tutorials http://javabrains.koushik.org/spring.html
You can also download the springsource tool suite here http://spring.io/tools/sts/all then go to the file menu select new >> Spring Project >> Spring MVC Project. This is a simple spring MVC project with a Controller, XML configurations and a JSP view. I believe this a great starting point cause the application is simple and you can build with it as a foundation
Hope these help

A: It is available in their documentation. You could also refer this:
http://www.tutorialspoint.com/spring/spring_web_mvc_framework.htm


text:
Q: Extend method for generic List<> types TL;DL: simplify method<returnType, ListType>(this List<ListType>, ...) to method<returnType>(this List<anyType>, ...) for generic Lists
I'm looking to write an extension method that allows me to get the values of all properties "P" within a List of (any type of object)
So far, I got this method to work:
public static T[] selectAll<T, U>(this List<U> list, string property)
{
    List<T> r = new List<T>();          // prepare a list of values of the desired type to be returned
    foreach(object o in list)
    {
        Type mt = o.GetType();          // what are we actually dealing with here? (List of what?)   <-- This should be the same as Type U
        IList<PropertyInfo> props = new List<PropertyInfo>(mt.GetProperties());          // Get all properties within that type
        foreach(PropertyInfo p in props)
        {
            if (p.Name == property)                   // Are we looking for this property?
                r.Add((T)p.GetValue(o, null));        // then add it to the list to be returned
        }
    }
    return r.ToArray();
}

Because you can't simply have an unknown return type, I understand that it's necessary to indicate the return type in the method call, e.g:
List<Control> SomeListOfControls = ...
string[] s = SomeListOfControls.selectAll<string, Control>("Text");
But, since the Type of the items within that list is rather irrelevant for this method, I want to eliminate the Type variable from the equation.
I wish I could simply call
List<Control> SomeListOfControls = ...
string[] s = SomeListOfControls.selectAll<string>("Text"); <-- You know damn well what this List consists of >.<
for example.
But I can't think of a way to do this.
Even before compiling I can see that
public static T[] selectAll<T>(this List<> list, string property)

is an Unexpected use of an unbound generic name (meaning List<>).
And List<object> fails to register as an extension for all kinds of List<?extends object>, so to speak.
How, if at all possible, can I make this work?
PS: It seems like there might be a "native" way (.net or even C# in general) to retrieve a collection of <T> P from a collection that may have properties P of type T - I couldn't figure it out using select and all... But if there is: I'd be happy to learn about it :)

A: Looks like you are looking for non-generic version for parameter - either IList or IEnumerable would work
public static T[] selectAll<T>(this IList list, string property){
    ...
}

A: Aftermath (what went wrong where)
Although I had imported (using) both
System.Collections.Generic

and
System.Collections.Specialized

I was not aware that the classes those namespaces are partially inheriting from are in fact in System.Collections. I thought I was getting both halves of a cake, whereas I was getting two fillings while missing the crust.
So when ever I tried using an IEnumerable, for example, my dear and trusty IDE (Visual Studio 2017) would not accept it without a type indicator <T>.
For anybody coming here through Google with the same problem:
Using both .Generic and .Specialized will not have you covered, much of what the collection types draw from is in the parent System.Collections.
public static T[] selectAll<T>(this IList list, string property)
{
    // ...
}

and
public static T[] selectAll<T>(this IEnumerable list, string property)
{
    // ...
}

may serve you right.
Although, for my case as outlined above,
public static T[] selectAll<T>(this IEnumerable<object> list, string property)
{
    // ...
}

Worked just as well (whereas IList<object> failed to register as an extension of List<?>
The naming of spaces and concepts can be quite misleading:
I would consider IList<Type> to be specialized (by Type), and IList generic (Since it's applicable to all <Type>s) - but in C# world, it's the other way around: IList by itself is considered "non-generic" - the question of generic...ness is approached from the outside (how is it treated in context) rather than the inside (what does (or can) it contain) - something a high-level programmer like me might intuitively get wrong.
In summary:

*

*System.Collection consists of more than the sum of its classes

*Intuitively generic collections are called non-generic because the lower-level powers that be said so

*System.Collections.IEnumerable seems to apply to all kinds of Lists

*Reading up on official docs is generally useful. (Wait... generally or specifically? Oh, who knows anymore :P )


text:
Q: PHP add css class to element randomly using php let's say I have a array with e.g. 3 css class names - I also have a loop of e.g. 50 items and I'd like to randomly assign one of the three classes to an element - however, most of the items should not get any class at all - is there a way to do this?
to make it more clear - I'd like to set up a tiled gallery in Wordpress using css grid - every few picture I'd like to either add a class: big, wide, or tall - a gallery can have any number of pictures.
thank you in advance for your input.

A: Use array_rand to get an item from an array where is stocked your class names
php manual


text:
Q: Trying to run my flutter project on Emulator but keep getting this error FAILURE: Build failed with an exception.

*

*What went wrong:
Execution failed for task ':app:mergeDebugResources'.

/Users/mac/.gradle/caches/transforms-2/files-2.1/6dfce29e8bb57325e0dac8088b7ee1b8/material-1.8.0-alpha01/res/values/values.xml: Error: Can't determine type for tag '?attr/colorSurface'

*

*Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

BUILD FAILED in 1m 36s
Exception: Gradle task assembleDebug failed with exit code 1


text:
Q: Jersey REST Exception java.lang.ArrayIndexOutOfBoundsException at org.objectweb.asm.ClassReader.readInt I am using Jersey 1.2 for building RESTful services using JDK1.5
When I test REST services, I am getting the following exception.

java.lang.ArrayIndexOutOfBoundsException: 2884779   at
      org.objectweb.asm.ClassReader.readInt(Unknown Source)   at
      org.objectweb.asm.ClassReader.accept(Unknown Source)    at
      org.objectweb.asm.ClassReader.accept(Unknown Source)    at
      com.sun.jersey.spi.scanning.AnnotationScannerListener.onProcess
      (AnnotationScannerListener.java:130)    at
      com.sun.jersey.core.spi.scanning.uri.FileSchemeScanner$1.
      f(FileSchemeScanner.java:83)    at
      com.sun.jersey.core.util.Closing.f(Closing.java:68)

I have created a simple class for testing
@Path("/employee")
public class TestRest {

    @GET
    @Produces( { MediaType.TEXT_HTML })
    public String getClichedMessage() {

        return "Hello Smith";
    }
}

How can I resolve this issue?
My jar versions
jersey-server-1.2.jar
jersey-core-1.2.jar
grizzly-servlet-webserver-1.9.18-i.jar
asm-3.1.jar
jsr311-api-1.1.jar

A: check your annotation
  @POST
  @Produces(MediaType.TEXT_HTML) also try

Also try
you are having an incorrect version of asm.jar on your classpath. Make sure:
your deployed lib folder contains the same jars as target/app.war/WEB-INF/lib
you don't have two versions of the asm.jar
you don't have conflicting versions in maven

A: In my case I had this code
@GET
@Path("/get_something")
@Produces(MediaType.APPLICATION_JSON)
public Message<String> getSomething(@QueryParam("p_item") String p_item,  @QueryParam("p_items") List<String> p_items) throws Exception {
    ...
    p_items.forEach(s -> {
       try {
           // something that throws IOException
       } catch (IOException e) {
           throw new RuntimeException(e);
       }
    });
    ...
}

After I changed forEach to regular loop it worked.

A: I was using apache server 8.5.59 and getting same exception.
Now I moved to apacher server version 8.5.12.
It is working fine.
Please find jar details

*

*asm-3.1.jar

*jersey-bundle-1.1.5.1.jar

JDK : Zulu 8.36.0.2
Eclipse : Oxygen.2 Release (4.7.2)


text:
Q: Does JSch need sftp/ssh client installed I am using JSch to transfer a file to a remote server. I have configured it to use sftp channel with user/password and StrictHostKeyChecking set to 'no'. Since I have open channel set to sftp, does JSch require sftp/ssh client to be installed on the client machine?

A: No,JSch is a pure Java implementation of SSH2.
http://www.jcraft.com/jsch/


text:
Q: Power bi - Use Slicer selection in filtering data I am new to Power bi but i want to use Slicer(user selection) while filter data with comparison by 'Greater Than' instead of equal to.
I have data of devices with LastUpdated date column. and slicer with few list of dates for 15 days gap (calendar would be better but as it is not available yet sticking with dates list)
When user select a date in Slicer i want to filter the data whose Lastupdated Date is greater than equal to selected date. How to achieve this? tried columns,measures..
Any help is appreciated.

A: I think you can create a measure that links the Date list table and the Device table, even if there is no relationship between them. However the measure must be present in your visualization otherwise the slicer will not affect it.
I've created a measure that calculates the maximum date for those rows which last update date is greater or equal than the slicer selection.
CalculatedLastUpdate =
CALCULATE (
    MAX ( DeviceTable[LastUpdate] ),
    FILTER (
        DeviceTable,
        DeviceTable[LastUpdate] >= MINX ( DateList, DateList[Date] )
    )
)

DateList - a table containing a column [Date] with you date range.
DeviceTable - a table containing device data.

Now you can delete LastUpdate column from your visualization in order to avoid two columns with the same data.
Let me know if it helps.

A: I don't know about earlier , but now you can modify the date slicer to do as "after" the given date (you can do so by clicking on the icons present in the rightmost side of the slicer visual itself , wher you can select mode of slicer as between , after ,list , dropdown etc.)...which I believe means that you get all data for dates greater than the selected dates for the given column used in slicer which in your case will be LastUpdate.


text:
Q: Why the previously entered text disappears from the TextView when Interstitial is closed I have a microphone button with which the user enters text into the TextView with his speech, after every second click on the stop microphone button Interstitial appears, however, when Interstitial appears and when Interstitial is closed, the previously entered text disappears from the TextView, when the microphone start button is started again, the previously entered text reappears. What needs to be done to keep the text visible when the Interstitial is closed. I tried onAdClosed but failed. Can anyone specifically answer, thanks!
InterstitialAd.java
InterstitialAd.load(getApplicationContext(),
                        mContext.getString(R.string.admob_interstitial_id),
                        new AdRequest.Builder().build(),
                        new InterstitialAdLoadCallback() {

                            @Override
                            public void onAdLoaded(@NonNull InterstitialAd interstitialAd) {
                                interstitialAd.show((Activity) mContext);
                            }

                            public void onAdClosed() {
                                returnedText.setVisibility(View.VISIBLE);
                            }
                        }
                );

The Start - Stop microphone button is located in the MainActivity.java and calls Interstitial from InterstitialAd.java
InterstitialLaunch interstitialLaunch = new InterstitialLaunch();
interstitialLaunch.inter_launched(MainActivity.this);

A: I think because after the ad, your fragment calls onCreate again (which follows with the normal lifecycle of fragment methods') creating the fragment from zero, if that's the case then what you need is to store UI data somewhere before showing the ad and fetch it later everytime onViewCreated (as an example but writing your code in onCreateView/onStateRestored will also do the job), you can store your data using a ViewModel or in SharedPreferences
you can start reading about viewModel from here :
ViewModel | Android Developers
you can also start reading about sharedPerfreneces from here :
Save key-value data |Android Developers


text:
Q: How can I find a specific line in a file without using regular expressions in Perl? I have a file that I want to read in using the File::Slurp module then search that file for a specific line. I know Perl has regular expressions but the strings I'm searching for are user-generated so don't want to have to worry about escaping everything. I could write a foreach loop to do this but was wondering if there's a function in Perl that will do this for me? Everything I see online about finding text in Perl uses regular expressions.

A: Like this?
use List::Util qw<first>;

my $line
    = first { index( $_, $something_users_are_looking_for ) > -1 }
      <$file>
    ;

And if you want 'em all.
my @lines
    = grep { index( $_, $something_users_are_looking_for ) > -1 }
      <$file>
    ;

A: You can just use a regular expression. You don't have to worry about escaping everything, Perl has the quotemeta function for that (or alternatively, "\Q\E").

A: Can you just use a string literal using q()?
print(q(This string can contain regex: (\n\t*\n)(\n)));


text:
Q: Angular 4 and Nodejs http post request implementation error I created small test application using Angular 4 and Nodejs. I want to insert a text field value to the database either Mongo or mysql.
Following files I created server.js for running nodejs, Created server>router folder with another file api.js and Angular 4 user component created.
What i did code shown below
user.component.html
<form (submit)="addHobby(hobbies,hobby.value)">
  <input type="text" #hobby>
  <input type="submit" value="Submit">
</form>

user.component.ts
addHobby(arrHob,hobby) {
    if(arrHob.indexOf(hobby) == -1) {
      this.hobbies.unshift(hobby);
      this.dataService.postHobby(hobby).subscribe((posts) => {
        console.log(posts);
      })
    }
    return false;
  }

Services folder contain data.service.ts
postHobby(hobby) {
    return this.http.post('/api/insertHobby',hobby).map(res => res.json().data);
  }

server router folder contain api.js
router.post('/insertHobby', (req, res) => {
    console.log("Welcome to post method");
    console.log(req.body.data);
})

When form submitting i'm getting output as only welcome to post method
req.body.data i'm getting as *'Undefined'* How to resolve this issue. Any way thanks to everyone..

A: since you are not passing the variable as object , you need to pass it in object format as below :
postHobby(hobby) {
return this.http.post('/api/insertHobby',{hobby: hobby}).map(res => res.json().data);
}


text:
Q: Is that possible disable device switch in Visual Studio Code when develop flutter? Is that possible disable device switch in Visual Studio Code when develop flutter ?
What's my condition:

*

*I have simulator opened, and debug for a while, code for a while.

*Then I need to plugin my phone to charge power of phone. But vscode too clever to switch the device to my phone automatic.

*And then when I debug, I always found why it's build slow now?  And found out that it's debugging on my phone now...
Any idea to solve this ?
PS: I didn't always have usb power for my phone beside my computer.

A: It seems that it's possible to disable that (default is on). Go to User Settings -> Extensions -> Dart & Flutter

You can also select device with this action:


text:
Q: How can I Identify a line in a csv file based on a variable value and start iterating over the file lines from that line onwards in Groovy? I am using Jmeter to send multiple HTTPS requests to some API. I need to compose the XML body of these requests with different data each time.
I have a csv file which looks like this:
iDocType,iDocId,iName,iDate
P,555551555,Braiden,2022-12-31
I,100000001,Dominique,2024-12-10
P,100000002,Joyce,2025-11-15
.........

And I have this piece of code in a JSR223 PreProcessor (under the HTTPS Sampler) which creates multiple XML objects and populates them one by one with csv values and finally gives this object to Jmeter to use in the sampler as request body data:
def writer = new StringWriter()
def xml = new groovy.xml.MarkupBuilder(writer)
def pReqID = 'ID0000'

def numberOfNodes = 3

//input from csv file
travelDocNbr = vars.get('iDocId').toInteger();

def lines = new File("TestData\\test.csv").readLines()

xml.nodes() {
    1.upto(numberOfNodes, { lineNo ->
        xml.object(a: 'false', b: 'false', pReqID: pReqID + (lineNo).toString()) {
            xml.al(ad: '2021-09-20', alc: 'bla', bla: '2021-09-20T11:00:00.000Z', sn: 'AB8912')
            xml.doc(docType: lines.get(lineNo).split(',')[0],
                    docId: lines.get(lineNo).split(',')[1],
                    name: lines.get(lineNo).split(',')[2],
                    date: lines.get(lineNo).split(',')[3])
            }
        }
    )
}

def nodeAsText = writer.toString()
//log.info(nodeAsText)

vars.put('passengers3XmlObj', nodeAsText)

This always gives this result:
<nodes>
  <object a='false' b='false' pReqID='ID00001'>
    <al ad='2021-09-20' alc='bla' bla='2021-09-20T11:00:00.000Z' sn='AB8912' />
    <doc docType='P' docId='555551555' name='Braiden' date='12/31/2022' />
  </object>
  <object a='false' b='false' pReqID='ID00002'>
    <al ad='2021-09-20' alc='bla' bla='2021-09-20T11:00:00.000Z' sn='AB8912' />
    <doc docType='P' docId='100000001' name='Dominique' date='12/10/2024' />
  </object>
  <object a='false' b='false' pReqID='ID00003'>
    <al ad='2021-09-20' alc='bla' bla='2021-09-20T11:00:00.000Z' sn='AB8912' />
    <doc docType='P' docId='100000002' name='Joyce' date='11/15/2025' />
  </object>
</nodes>

The problem is that this script starts composing objects from the first value in the CSV file and always creates the same XML object in each sampler request's body.
I need it to change values from the CSV each time. For this, I was thinking if I could have a variable which always changes in each sampler iteration, like the iName value (I get a different one on each sampler iteration thanks to the CSV Data Set config test element) and use that to find the line in the CSV file and start composing objects from that line onwards.
So, for example, given that the csv file has just the 3 lines mentioned at the beginning and I have the value "Dominique" stored in a variable I want to pass it to a function and get the following result:
<nodes>
  <object a='false' b='false' pReqID='ID00001'>
    <al ad='2021-09-20' alc='bla' bla='2021-09-20T11:00:00.000Z' sn='AB8912' />
    <doc docType='P' docId='100000001' name='Dominique' date='12/10/2024' />
  </object>
  <object a='false' b='false' pReqID='ID00002'>
    <al ad='2021-09-20' alc='bla' bla='2021-09-20T11:00:00.000Z' sn='AB8912' />
    <doc docType='P' docId='100000002' name='Joyce' date='11/15/2025' />
  </object>
  <object a='false' b='false' pReqID='ID00003'>
    <al ad='2021-09-20' alc='bla' bla='2021-09-20T11:00:00.000Z' sn='AB8912' />
    <doc docType='P' docId='555551555' name='Braiden' date='12/31/2022' />
  </object>
</nodes>

Can someone please tell me how this can be done?
UPDATE:
Thanks to @injecteer, I ended up with this code which, in my implementation, does not work as intended :
def pReqID = 'ID0000'

def numberOfNodes = 10
String startFrom = 'Dominique'

int pos = -1

// @injecteer
def text = new File("TestData\\\validTravellerDocuments.csv").text

// @injecteer
def csv = text.readLines().drop( 1 ).withIndex().collect{
  def ( docType, docId, name, date ) = it[ 0 ].trim().split( ',' )
  if( -1 == pos && startFrom == name ) pos = it[ 1 ]
  [ docType:docType, docId:docId, name:name, date:date ]
}

//here the skipped lines are reodered to the bottom, if needed
def reoderedCsv = -1 < pos ? csv[ pos..-1 ] + csv[ 0..<pos ] : csv
log.info reoderedCsv

def writer = new StringWriter()
new groovy.xml.MarkupBuilder(writer).nodes() {

    reoderedCsv.take numberOfNodes eachWithIndex{ data, ix ->
         object(a: 'false', b: 'false', pReqID:"$pReqID${ix + 1}" ) {
            al ad:'2021-09-20', alc:'bla', bla:'2021-09-20T11:00:00.000Z', sn:'AB8912'
            doc data
         }
         log.info "$data -> ${data.getClass()}"
    }
}

def nodesAsText = writer.toString()
log.info(nodesAsText)

The current problem is that the  section gets populated in this manner:
If I ask for 10 nodes, I get a behavior like this:
<doc>D</doc>
...
<doc>o</doc>
...
<doc>c</doc>
...
<doc>T</doc>
...
<doc>y</doc>
...
<doc>p</doc>
...
<doc>e</doc>
...
<doc>,</doc>
etc...

A: If you want to get the number of line where Dominique text is present it can be done using findIndexOf() function like:
def dominiquePosition = lines.findIndexOf { line -> line.contains('Dominique') }

then you can start building your XML from the position retrieved in the above line:
dominiquePosition.upto(numberOfNodes, { lineNo ->

The iteration can be obtained using vars.getIteration() function where vars stands for JMeterVariables class instance. See Top 8 JMeter Java Classes You Should Be Using with Groovy article for more details on this and other JMeter API shorthands available for the JSR223 Test Elements

A: I'd put the code in a natural groovy way.
UPDATE:
I added some more CSV lines to demonstrate how numberOfNodes affects the output.
def pReqID = 'ID0000'

def numberOfNodes = 2
String startFrom = 'Dominique'

int pos = -1

def csv = """\
iDocType,iDocId,iName,iDate
P,555551555,Braiden,2022-12-31
I,100000001,Dominique,2024-12-10
P,100000002,Joyce,2025-11-15
P,555551555,Braiden,2022-12-31
I,100000001,Dominique,2024-12-10
P,100000002,Joyce,2025-11-15
""".readLines().drop( 1 ).withIndex().collect{
  def ( docType, docId, name, date ) = it[ 0 ].trim().split( ',' )
  if( -1 == pos && startFrom == name ) pos = it[ 1 ]
  [ docType:docType, docId:docId, name:name, date:date ]
}

//here the skipped lines are reodered to the bottom, if needed
def reoderedCsv = -1 < pos ? csv[ pos..-1 ] + csv[ 0..<pos ] : csv

def writer = new StringWriter()
new groovy.xml.MarkupBuilder(writer).nodes() {

    reoderedCsv.take numberOfNodes eachWithIndex{ data, ix ->
         object(a: 'false', b: 'false', pReqID:"$pReqID${ix + 1}" ) {
            al ad:'2021-09-20', alc:'bla', bla:'2021-09-20T11:00:00.000Z', sn:'AB8912'
            doc data
         }
    }
}

println writer

prints:
<nodes>
  <object a='false' b='false' pReqID='ID00001'>
    <al ad='2021-09-20' alc='bla' bla='2021-09-20T11:00:00.000Z' sn='AB8912' />
    <doc docType='I' docId='100000001' name='Dominique' date='2024-12-10' />
  </object>
  <object a='false' b='false' pReqID='ID00002'>
    <al ad='2021-09-20' alc='bla' bla='2021-09-20T11:00:00.000Z' sn='AB8912' />
    <doc docType='P' docId='100000002' name='Joyce' date='2025-11-15' />
  </object>
</nodes>

with numberOfNodes = 3 and more the code print the desired output of yours


text:
Q: Problem with core plot barchart plotting I am constructing an application that plots a barchart.
when i wrote this line
num=(NSDecimalNumber *)[NSDecimalNumber numberWithInt:index];
return num;

in the method
-(NSNumber *)numberForPlot:(CPTPlot *)plot field:(NSUInteger)fieldEnum recordIndex:(NSUInteger)index

it works properly
but i need to pass a float number to plot
for that i wrote
num=(NSDecimalNumber *)[NSDecimalNumber numberWithFloat:f1];
return num;

then all of the bars appears together
i tried to adjust the barofset and barwidth but no solution
can anyone help me
thanks in advance

A: Assuming these numbers are for the CPTBarPlotFieldBarLocation field, you need to check the corresponding plot space range (xRange for vertical bars and yRange for horizontal). Make sure the location and length of the plot space range are appropriate for the range of numbers you're returning for this field. It sounds like the length is too large.


text:
Q: Input to show currency So I have an input that is type number. Once user saves this, it creates a tile, then the user can edit, and with editing, it populates fields with existing values. This tile pulls bound info via Angular so I can simply put the currency filter in there. This means, the number input in my html just shows as number, and not as currency. Is there a way in HTML 5 for this to show at least the decimal places even if an amount is something like "10.00" versus just "10"?
I have tried using step attribute as step="any".
Here is my input code:

    How much are you claiming for each date above?
    <input type="number" name="amount" class="form-control" id="claimAmount" min="0.00" step="any" placeholder="$0.00" data-ng-model="recurInfo.amount" ng-required="true" navia-min="0.01" navia-max="10000" ng-pattern="/^\d*(\.\d{0,2})?$/">


text:
Q: Solving $\dot{x}(t) = \sqrt{\dot{x}(0)^2 - k[x(t)^2 - x(0)^2]}$ for $x(t)$ Let $\dot{x}$ mean $\frac{d}{dt}x$.
When doing a (one dimensional) physics problem where one were supposed to find the velocity $v_x(t)$ I arrived at the solution
$$v_x(t) = \sqrt{v_0^2 - k(x^2 - x_0^2}).$$
Where $v_0 = v_x(t=0)$ and $x_0 = x(t=0)$ are known. One could infer this from knowing the acceleration as a function of the position $x$.
I became curious if one could find the position as a function of time, $x(t)$, from this equation since to me it seems to be a differential equation of the form
$$\dot{x}(t) = \sqrt{\dot{x}(0)^2 - k[x(t)^2 - x(0)^2]}$$ which I guess could be written as $$\dot{x}(t)^2 - \dot{x}(0)^2 = -k[x(t)^2 - x(0)^2]$$
But since I have a very limited knowledge of differential equations (I think I've only done some linear ones before) I don't know if this is possible to solve for $x(t)$ and in that case how?


text:
Q: Nested JSON in mysql table I have a table db.Geometry in my mysql database that has a column called FORM containing  json strings all of this type:
{"type":"polygon","corners":[{"x":43.790000915527344,"y":2.6940000057220463,"floor":0},{"x":44.884937766905495,"y":8.128635658848992,"floor":0},{"x":24.52993631732053,"y":12.229635729420892,"floor":0},{"x":23.434999465942386,"y":6.795000076293945,"floor":0}],"floor":0}}

What I am looking for is to unnest this and create instead a table with the columns: type, x,y,floor. Now, if it had been so that the string had had the following appearance:
{"corners":[{"x":43.790000915527344,"y":2.6940000057220463,"floor":0},{"x":44.884937766905495,"y":8.128635658848992,"floor":0},{"x":24.52993631732053,"y":12.229635729420892,"floor":0},{"x":23.434999465942386,"y":6.795000076293945,"floor":0}],"floor":0}

I would have done the following thing:
SELECT ID, Tab.*
    FROM db.Geometry
        CROSS JOIN JSON_TABLE(
            db.Geometry.FORM-> '$.corners',
            '$[*]' COLUMNS (
                x VARCHAR(255) PATH '$.x',
                y VARCHAR(255) PATH '$.y',
                floor VARCHAR(255) PATH '$.floor'
            )
    ) Tab;

But this obviously does not work in the situation I actually have because I do not handle the "type":"polygon" part of the json string. It return an empty table.
What do I need to add to my code to deal with this? Thankful for any insight.

A: Maybe you need in
SELECT Geometry.ID, jsontable1.type, jsontable1.object_floor, jsontable2.*
FROM Geometry
CROSS JOIN JSON_TABLE( Geometry.FORM,
                       '$' COLUMNS ( type VARCHAR(255) PATH '$.type',
                                     corners JSON PATH '$.corners',
                                     object_floor INT PATH '$.floor' ) ) jsontable1
CROSS JOIN JSON_TABLE( jsontable1.corners,
                       '$[*]' COLUMNS ( ROWID FOR ORDINALITY,
                                        x VARCHAR(255) PATH '$.x',
                                        y VARCHAR(255) PATH '$.y',
                                        corner_floor VARCHAR(255) PATH '$.floor' ) ) jsontable2

https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=5d95a6a3392409ebf851fc9a87840926


text:
Q: Choose the correct statement Let $A$ be any $m \times n$ matrix of rank $n$ with real entries. Then choose the correct statement-

*

*$Ax=b$ has a solution for any $b$.

*$Ax=0$ does not have a solution.

*If $Ax=b$ has a solution, then it is unique.

*$y^tA=0$ for some non-zero $y$.

Rank=$n$ means $n \le m$, and option 2, is clearly false as $0$ is a solution.
My guess is 3, as  it has a solution iff $A$ is invertible, correct and then it is unique. I am not sure about fourth.

A: The rank-nullity theorem implies
$$
\dim\DeclareMathOperator{null}{null}\null(A)+\DeclareMathOperator{rank}{rank}\rank(A)=n
$$
Since $\rank(A)=n$, it follows that
$$
\dim\null(A)=0
$$
But this implies that the linear map $\Bbb R^n\to\Bbb R^m$ given by $\vec x\mapsto A\vec x$ is injective. Hence if $A\vec x=\vec b$ has a solution, then the solution is unique.
So option (3) certainly holds. Can you think of counterexamples to the others?


text:
Q: To apply type_id operator during the construction Code:
#include <iostream>
#include <typeinfo>
#include <cassert>

using std::cout;
using std::endl;

long unsigned int hash_in_constructor;

struct A
{
    virtual void foo()
    {
        cout << "A" << endl;
    }

    A()
    {
        hash_in_constructor = typeid(this).hash_code();
    }
};

int main()
{
    cout << hash_in_constructor << endl;
    cout << typeid(A).hash_code();
}

DEMO
I expected that hash_in_constructor equals to typeid(A).hash_code() because 12.7/5:

When typeid is used in a constructor (including the mem-initializer or
  brace-or-equal-initializer for a non-static data member) or in a
  destructor, or used in a function called (directly or indirectly) from
  a constructor or destructor, if the operand of typeid refers to the
  object under construction or destruction, typeid yields the
std::type_info object representing the constructor or destructor's
  class.

but it is not true. Why?

A: You have to use typeid(*this) instead of typeid(this), otherwise you will get the type information for A*, which is of course different from A.

A: There are two obvious problems:

*

*hash_in_constructor is only set when A::A is executed, when an instance of A is constructed.
You read it before constructing an instance of A, so it hasn't been set (just been statically initialized to zero).

*you're comparing typeid(A) with typeid(A*), and they're different. The this pointer is a pointer, remember.
Examine the output of this version of your code:
#include <iostream>
#include <typeinfo>

using std::cout;
using std::endl;

long unsigned int hash_in_constructor;

struct A {
    virtual void foo() {
        cout << "A" << endl;
    }

    A() {
        hash_in_constructor = typeid(this).hash_code();
    }
};

int main() {
    cout << "static init = " << hash_in_constructor << endl;
    A a;
    a.foo();
    cout << "after ctor = " << hash_in_constructor << endl;
    cout << "typeid(&a) = " << typeid(&a).name() << " : " << typeid(&a).hash_code() << endl;
    cout << "typeid(a) = " << typeid(a).name() << " : " << typeid(a).hash_code() << endl;
    cout << "typeid(A) = " << typeid(A).name() << " : " << typeid(A).hash_code() << endl;
}

which outputs:
g++ -std=c++1y -Wall -Wextra -pedantic -pthread main.cpp -lcxxrt -ldl && ./a.out
static init = 0
A
after ctor = 15127845526165118748
typeid(&a) = P1A : 15127845526165118748
typeid(a) = 1A : 1295143305205299629
typeid(A) = 1A : 1295143305205299629


text:
Q: Исчезает виджет из строки таблицы Pyside2 Есть таблица в Pyside2
 self.table_classes =  QtWidgets.QTableWidget()
 self.table_classes.setColumnCount(3)
 self.table_classes.setHorizontalHeaderLabels(['Название класса', 'Цвет',''])
 header_class = self.table_anno.horizontalHeader()
 header_class.setSectionResizeMode(0, QtWidgets.QHeaderView.ResizeToContents)
 header_class.setSectionResizeMode(1, QtWidgets.QHeaderView.ResizeToContents)
 self.table_classes.setFixedWidth(300)
 self.table_classes.setColumnWidth(2, 50)

В третьей колонке находится кнопка выбора цвета. Строка таблицы добавляется по кнопке "Добавить класс"

После того как я добавляю новую строку, то виджет с кнопкой выбора цвета исчезает. И я не могу поменять цвет в строке выше

Код добавления строки
    self.button_color = QtWidgets.QPushButton()
    self.button_color.clicked.connect(Form.change_color)
    self.button_color.setFixedWidth(50)
    self.button_color.setIcon(QtGui.QIcon('back2.png'))

    def addTableRow_Class(self):
        rows = self.ui.table_classes.rowCount()
        self.ui.table_classes.setRowCount(rows + 1)
        self.ui.table_classes.setCellWidget(rows, 2, self.ui.button_color)

Почему кнопка исчезает из предыдущей строки?

A: Попробуйте так:
import sys
from PyQt5.Qt import *

class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.centralWidget = QWidget()
        self.setCentralWidget(self.centralWidget)

        self.table_classes =  QTableWidget()
        self.table_classes.setColumnCount(3)
        self.table_classes.setHorizontalHeaderLabels(['Название класса', 'Цвет','btn'])
        self.table_classes.horizontalHeader().setSectionResizeMode(QHeaderView.ResizeToContents)
        self.table_classes.setColumnWidth(2, 50)

        self.btn_add = QPushButton('Добавить')
        self.btn_add.clicked.connect(self.add_row)
        self.btn_del = QPushButton('Удалить')

        layout = QGridLayout(self.centralWidget)
        layout.addWidget(self.table_classes, 0, 0, 4, 1)
        layout.addWidget(self.btn_add, 1, 1)
        layout.addWidget(self.btn_del, 2, 1)

    def add_row(self):
        rowPosition = self.table_classes.rowCount()
        button_color = QPushButton()
        button_color.clicked.connect(lambda: print(rowPosition))
        button_color.setFixedWidth(50)
        button_color.setIcon(QIcon('im.png'))

        self.table_classes.insertRow(rowPosition)
        self.table_classes.setCellWidget(rowPosition, 2, button_color)

if __name__ == "__main__":
    import sys
    app = QApplication(sys.argv)
    mw = MainWindow()
    mw.show()
    sys.exit(app.exec_())


text:
Q: Need System Settings Icon back on Launcher So plain and simple. I've never uses Ubuntu in my life. I was playing around with the launcher shortcuts on the left side of my window, and I decided to "unlock system settings" from the launcher. How do I get it back since clearly system settings is something I would like to use. The icon for system settings is the Grey cog wheel looking thing. I looked around in some files but can't seem to find it anywhere. If anyone knows how I can get this back, please let me know right away and I will be sure to be more careful next time. Also to reiterate: The icon was removed by me, this has nothing to do with any update issues or corrupted icons disappearing after updates. This was entirely my fault.
Thank you in advance

A: You can lock any app to Launcher by dragging its icon from Dash and releasing it somewhere on Launcher, or by opening it from Dash, right clicking on its Launcher icon and selecting Lock to Launcher.


text:
Q: Converting complex Map data structure to F# I am pretty new to the language F#, let alone functional programming, and I am having trouble implementing a Map data structure. The C# type equivalent of this Map would be:
var map = new Dictionary<int, Dictionary<int, Tuple<char, Tuple<int, int>[]>[]>>();

I've tried to implement this myself and searching online, but my inexperience with the language is letting me down.
Is anyone able to show me:

*

*An immutable implementation of this structure

*A mutable implementation

A: The mere translation is pretty straightforward:

*

*Dictionary either becomes Map (if you want an immutable structure) or stays as it is (if you want mutability)

*Tuple<a, b> becomes a * b in the type declaration, and (x, y) in the variable usage.

Hence, if we go with immutability, we get:
Map<int, Map<int, (string * (int * int)[])[]>>

But that's, quite frankly, unreadable. Fortunately, F# has the perfect solution for this: type abbreviations.
That complex type can be decomposed into a bunch of aliases, or abbreviations, which express the problem domain more clearly to a human reader. For example, you could have:
type Cell = int * int

type Zone = Cell []

type Battleship = string * Zone

type Flotilla = Battleship []

type TaskForce = Map<int, Flotilla>

type Fleet = TaskForce []

type NavalTheater = Map<int, Fleet>

which is the exact same type as above, but it's a lot more readable, for most use cases. And it has zero overhead, as the abbreviations will be simply replaced with the native types during compilation.

A: For example like this:
let t1 = (2,3)
let t2 = ("a",t1)
let m1 = Map([1,t2])
let m2 = Map([2,m1])

The signature of this is:
val it : Map<int,Map<int,(string * (int * int))>> = map [(2, map [(1, ("a", (2, 3)))])]

This is using lists not array.
For the mutable part you already show the implementation. Just use
System.Collections.Generic.Dictionary

Not sure but maybe this is helpful for you: F# map to C# Dictionary


text:
Q: Draw overlay on camera iOS Users need to be able to take photo of their ID. I need to add a blue frame to camera view as a guide. Guide should have same aspect ratio on all device sizes and fit a label with instructions. Can I accomplish this using UIImagePicker?
Here is some incomplete code. Thanks for any help.
UIImageView *overlayImage = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@""]];
CGRect overlayRect = CGRectMake(0, 0, self.view.frame.size.height - 16, self.view.frame.size.width - 16);
[overlayImage setFrame:overlayRect];
[self.imagePicker setCameraOverlayView:overlayImage];

A: Use AVCaptureDevice, AVCaptureSession, AVCaptureVideoPreviewLayer and AVCapturePhotoOutput.
Set AVCaptureDeviceInput as input of capture session, and photo output as output of capture session. Initialize AVCaptureVideoPreviewLayer with AVCaptureSession and add to your view.layer thought addSublayer. You can use UIViewController from storyboard or programmatically instantiated controller, add picture of overlay or cornered view.layer.borderWidth or UIBezierPath. Set up controller as AVCapturePhotoCaptureDelegate, add delegate methods. Use capturePhoto(with:delegate:) method. Enjoy.


text:
Q: Amsthm numbering depending on section depth I'm using amsthm and thmtools to define custom theorem environments, definition environments, etc. All such environments share the same counter.
Is it possible to vary the numbering format depending on the section depth? I want to achieve the following numbering format:
1 Section
1.1 Theorem
1.2 Definition
1.1 Subsection
1.1.1 Theorem
1.1.2 Lemma

A: i'm not sure if you want something like this:
\documentclass{article}
\usepackage{amsmath}
\usepackage{amsthm}
\swapnumbers
\newtheorem{theorem}{Theorem}[section]
\newtheorem{definition}[theorem]{Definition}
\newtheorem{lemma}[theorem]{Lemma}
\usepackage{thmtools}

\usepackage{xpatch}
\makeatletter
\newif\ifsection
\newif\ifsubsection
\preto\section{\sectiontrue\subsectionfalse}
\preto\subsection{\sectionfalse\subsectiontrue}
\patchcmd{\@xsect}% <cmd>
  {\ignorespaces}% <search>
  {\ifsection
    \numberwithin{theorem}{section}
    \else
    \numberwithin{theorem}{subsection}
    \fi
    \setcounter{theorem}{0}\relax\ignorespaces}% <replace>
  {}{}% <success><failure>
\makeatother
\begin{document}

\section{Section}
\begin{theorem}
Th 1
\end{theorem}
\begin{definition}
Df 1
\end{definition}
\subsection{Subsection}
\begin{theorem}
Th 2
\end{theorem}
\begin{lemma}
Lm 1
\end{lemma}
\section{Two}
\begin{theorem}
Th 3
\end{theorem}
\begin{lemma}
Lm 2
\end{lemma}
\subsection{Other}
\begin{theorem}
Th 4
\end{theorem}
\subsection{Other 2}
\begin{definition}
Df 2
\end{definition}
\end{document}

A: You can prefix the theorem counter with a section-specific numbering scheme:

\documentclass{article}
\usepackage{amsthm,etoolbox}
\newtheorem{theorem}{Theorem}
\newtheorem{definition}[theorem]{Definition}
\newtheorem{lemma}[theorem]{Lemma}

\makeatletter
\@addtoreset{theorem}{section}% Reset theorem counter with every section
\@addtoreset{theorem}{subsection}
\@addtoreset{theorem}{subsubsection}
\newcommand{\theoremprefix}{}
\let\thetheoremsaved\thetheorem
\renewcommand{\thetheorem}{\theoremprefix\thetheoremsaved}
\let\sectionsaved\section
\patchcmd{\@startsection}{\par}{\renewcommand{\theoremprefix}{\csname the#1\endcsname.}}{}{}
\makeatother

\begin{document}

\section{Section}
\begin{theorem}
Th 1
\end{theorem}
\begin{definition}
Df 1
\end{definition}
\subsection{Subsection}
\begin{theorem}
Th 2
\end{theorem}
\begin{lemma}
Lm 1
\end{lemma}
\section{Two}
\begin{theorem}
Th 3
\end{theorem}
\begin{lemma}
Lm 2
\end{lemma}
\subsection{Other}
\begin{theorem}
Th 4
\end{theorem}
\subsection{Other 2}
\begin{definition}
Df 2
\end{definition}


text:
Q: pushing to remote repo using github cli and it's stuck at push (refer to the screenshot below)
I am trying to push my changes using Github CLI and it's not working - basically stuck at the push command.
I tried closing github and restarting but its still stuck at this. I haven't tried pushing it from terminal.


text:
Q: how to define multiple URLs for the background image of `` so that if one of them was broken, the other one works? I used this code for background image of <body> :
 background: url("http://www.uplooder.net/img/image/39/45732833fc8fdcfd8277ca248d5b608f/QHD.jpg") no-repeat center center fixed;

This image acts really important for my website that if it misses, the whole site will be ugly.
How can I define another additional link so that if the server in which the image is uploaded stops working, the the image gets fetched from the other link?

A: With CSS 3 you can set multiple backgrounds  so if one fails to load you got other one as backup

body {
  background: url('http://placehold.it/1920x860/ffffff/000000'), url('http://placehold.it/1920x860');
  height: 100vh;
  background-size: cover;
  background-position: center;
  margin: 0;
  padding: 0;
}

First background image fails to load here so the other one shows

body {
  background: url('http://placeholdasdf.it/1920x860/ffffff/000000'), url('http://placehold.it/1920x860');
  height: 100vh;
  background-size: cover;
  background-position: center;
  margin: 0;
  padding: 0;
}

A: I recommend using JavaScript.
Leave one image as default in the css like you have it.  Then, once the page is loaded, make a GET request using jQuery to that image.  If it returns a 404 error, then repeat for the next image.  When it finally finds an image that doesn't give a 404, you can again use jQuery to set that as the background image.

A: Download the image and put it in your server.
If you don't have the rights, you shouldn't use it either way.


text:
Q: Adding a SSL App engine with custom subdomain pointing to Google Storage bucket Current App:

*

*Goole App Engine on a custom domain: myapp.com

*Google Cloud Storage bucket on a custom subdomain (it uses DNS): images.myapp.com

*I have SSL certificate with the images subdomain

My question is: Is possible to have this configuration with SSL?
Things I have tried:

*

*Load balancer. I cannot figure out how to redirect everything that is not /images/* to the GAE (it seems it only works with backends)

*dispatch.yaml. I think it only works for the services you deploy

*In App Engine Settings I have added images.myapp.com, but as the redirection of images.myapp.com is done at DNS level, the secure layer is lost

Any suggestion or idea is more than welcome.
Thank you!

A: The limitation comes from the Cloud Storage bucket presented as a website under a custom domain - you can't use SSL with that. From You want your content served through HTTPS:

SSL is not currently supported by the Cloud Storage webservers; thus,
  you can only use a CNAME redirect with HTTP and not with HTTPS. If you
  wish to serve content through HTTPS from your bucket, we recommend you
  use a third-party Content Delivery Network with Cloud Storage.
  Alternatively, you can serve your static website content from
  Firebase Hosting instead of Google Cloud Storage.

If the content of your site meets the Code and static data storage quota you can serve your website through GAE, as static content (through a google CDN), which can be mapped to a custom domain and use SSL. See:

*

*Serving Static Files

*Hosting a static website on Google App Engine
If your content exceeds the mentioned quota then you can still serve it through your app, but dynamically, with your app accessing the content stored on GCS and serving it - more expensive as you'll be using instance hours for it.


text:
Q: Python csv module vs pandas.read_csv and Python xlrd vs pandas.read_excel In python, we can use either the csv module or the pandas.read_csv function to handle csv files.  For Excel files we can use the xlrd module or the pandas.read_excel function.
I use pandas a lot and I feel that the read_csv and read_excel functions come in handy for me.
Can anyone explain me what are the pros and cons of each of these methods?

A: Important note: xlrd No longer supports .xlsx files!
This change happened in version 2.0.0
However regarding CSV files I think it would be interesting to do a speed comparison between pandas and csv.
My experience is that the pandas module reads CSV files more strictly. If a column is all numbers and one row is empty, pandas produces a NaN value unless you use df.fillna('', inplace=True) or something similar. This can be annoying if you have mixed data types or if you expect None or blank values in a column.  The csv library seems to handle this a little nicer.
When I used csv on python2, utf-8 was a nightmare, but I assume that's better now with python3.


text:
Q: Firebase v9 onSnapShot in async function while being called in useEffect React I'm using Firebase v9, I'm building a chat app, I need to do some async work before calling onSnapShot to get the chat data :
      const getChat = async () => {
        // I need to await for user data before doing anything else.
        // I'll need some user data to build the query which
        // I'll be using in onSnapShot later on.
        const user = await getUserData();
        console.log(user);

        const collectionRef = collection(db, "messages");
        const q = query(
        collectionRef, where("user_id", "==", user.id), orderBy("createdAt"));

        const unsubscribe = onSnapshot(q, (snapshot) => {
          const data = snapshot.docs.map((doc) => {
            const entry = doc.data();

            return {
              id: doc.id,
              message: entry.message,
            };
          });
          setChatLines(data);
        });

        return unsubscribe;
      };

Then in useEffect :
  useEffect(() => {

    const unsubscribe = getChat();

    return () => {
      unsubscribe();
    };
  }, []);

The problem here is that unsubsribe is a promise, because getChat is async, but I still want to await getUserData() before onSnapShot is called, because I'll be needing the user data in the onSnapShot query later.
Is there a way to make this work while being able to unsubscribe correctly in useEffect cleanup function ?

A: In this case I would suggest using a React ref to hold the unsubscribe function to be used in an useEffect cleanup function.
const unsubscribeRef = React.useRef();

const getChat = async () => {
  const user = await getUserData();

  const collectionRef = collection(db, "messages");
  const q = query(
  collectionRef, where("user_id", "==", user.id), orderBy("createdAt"));

  const unsubscribe = onSnapshot(q, (snapshot) => {
    const data = snapshot.docs.map((doc) => {
      const entry = doc.data();

      return {
        id: doc.id,
        message: entry.message,
      };
    });
    setChatLines(data);
  });

  unsubscribeRef.current = unsubscribe;
};

useEffect(() => {
  getChat();

  return () => {
    unsubscribeRef.current?.();
  };
}, []);

An alternative would be an additional asynchronous function in the useEffect hook callback body that can wait for getChat Promise to resolve.
useEffect(() => {
  let unsubscribe;

  const getChatAndSubscribe = async () => {
    unsubscribe = await getChat();
  }

  getChatAndSubscribe();

  return () => {
    unsubscribe?.();
  };
}, []);


text:
Q: Token from Header is null in chrome and in IE11 it is work fine I have an web app ( using spring boot on back-end and angular 2 on front-end).
 My problem: I am trying to store in local storage the token which is send from the server... the token is received in the header but when I try to get it from the header it is null in google chrome, but in IE 11 it's working fine...
//service.ts
    @Injectable()
export class LoginService {

  constructor(private _http : Http) { }

  loginUser(user){
    let headers = new Headers({ 'Content-Type': 'application/json' });
    let options = new RequestOptions({ headers: headers })
    return this._http.post('http://localhost:8080/api/login', JSON.stringify(user));
  }
}

here is where I am trying to save in local storage and also to print in console(in console is null and also in local storage is saved as null)
 //login.componenet.ts
onLoginSucces(response) {
        console.log(response.headers.get("X-AUTH-TOKEN"));
        localStorage.setItem('auth-token',response.headers.get("X-AUTH-TOKEN"));
        console.log(localStorage.getItem('auth-token'));
        this.loggedIn=true;
        this.loginStatus = true;
        this._router.navigateByUrl("/home");
      }

      onLogFailed(error) {
        console.log(error.status);
        this.loginStatus = false;
      }

      onLogin() {
        this._loginService.loginUser(this.userLogin).
        subscribe(
          data => this.onLoginSucces(data),
          err => this.onLogFailed(err)
          );
      }

may be i have a problem in CORS but I don't think so( it is working on IE 11)
//CORSFilter.java
public class CORSFilter extends GenericFilterBean {

  @Override
  public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
      throws IOException, ServletException {

    if (((HttpServletRequest) req).getMethod().equals("OPTIONS")) {

      HttpServletResponse response = (HttpServletResponse) res;
      response.setHeader("Access-Control-Allow-Origin", "*");
      response.setHeader("Access-Control-Allow-Methods", "POST, PUT, GET, OPTIONS, DELETE");
      response.setHeader("Access-Control-Allow-Headers",
          "Content-Type, x-requested-with, X-AUTH-TOKEN");
      response.setHeader("Access-Control-Expose-Headers", "X-AUTH-TOKEN");

    } else {

      chain.doFilter(req, res);

    }
  }

enter image description herehere is a picture with the Header response...

A: I don't know why but somehow the google chrome must have installed the allow-controll-origin extension


text:
Q: Strange behavior for the date() function linux I have found a strange behaviour for the date() function when using bash.
When I use date -d "2008-10-12 +1 days", the date function returned
date: invalid date '2008-10-12 +1days'
Even it returned error when trying:
date -d "2008-10-12"
--> date: invalid date '2008-10-12'
However, it works for:
date -d "2008-10-13 +1days"
--> Tue Oct 14 00:00:00 CLST 2008
date -d "2008-10-11 +1days"
--> Sun Oct 12 01:00:00 CLST 2008
date -d "2007-10-12 +1days"
--> Sat Oct 13 00:00:00 CLT 2007
... and so on
It seems the date() does not recognize "just" 2008-10-12. Is it a bug? Am I doing something wrong?
I am using CENTOS 7
All the best

A: In RHEL 7 there were many changes happened to somany commands. To change the time and date earlier we used to use date command and now we need to use timedatectl command (preferred) instead.
http://www.freedesktop.org/software/systemd/man/timedatectl.html
So as there is a new latest command with more features included they might have limited it (Not sure on that). But from this version I have been using timedatectl command which is really great one.


text:
Q: How do I add Eclipse or GitEye to Ubuntu 18.04.1 Desktop Favourites list? How do I add Eclipse or GitEye to Ubuntu 18.04.1 Desktop Favourites list?
When I run them and right-click on them in Favourites list, the only options are "All Windows" and "Quit" options. I have successfully added other programs (but can't re-arrange - another issue).
The two programs I'm trying to add might be both java programs.

A: First please open terminal and go to your home directory.
After that create desktop file inside with this command:
nano .local/share/applications/eclipse.desktop
inside add something like:
[Desktop Entry]
Name=Eclipse IDE
Type=Application
Exec=/home/your_Path_To_Eclipse/eclipse/eclipse
Terminal=false
Icon=/home/your_Path_To_Eclipse/eclipse/icon.xpm
Comment=Integrated Development Environment
NoDisplay=false
Categories=Development;IDE;
Name[en]=Eclipse

After that save the file and search Eclipse inside applications. If you find it in the results press on the icon right mouse button Add to Favorites.
Now should appear inside your favorite list.
Good Luck!


text:
Q: I need advice on calculating this limit of a function resulting in $-\frac14\pi$ I am looking for advice on solving this limit of a function.
I am struggling to find the correct process:
$$\lim\limits_{x\to-\infty}\operatorname{arccotg}\frac{x}{(x^2-4)^{\frac12}}$$

A: Note that $\text{arccotg}$ is the inverse function of $\cot$. (I'm using whichever version always outputs within the range $[-\pi/2, \pi/2]$.)
The $\operatorname{arccotg}$ function is continuous near infinity (and therefore respects limits), so the answer is:
$$\operatorname{arccotg} \lim_{x \to -\infty} \frac{x}{\sqrt{x^2-4}}$$
That limit expression is (by L'Hôpital)
$$\lim_{x \to -\infty} \frac{1}{1/2 (x^2-4)^{-1/2} 2x} = \lim_{x \to -\infty} \frac{\sqrt{x^2-4}}{x} = \lim_{x \to \infty} -\sqrt{1-\frac{4}{x^2}}$$
By continuity of the square root near infinity, that is
$$-\sqrt{\lim_{x \to \infty} \left( 1-\frac{4}{x^2} \right)} = -1$$
So the entire answer is $\operatorname{arccotg}(-1)$, which by oddness is $-\text{arccotg}(1) = -\frac{\pi}{4}$.

A: With equivalents, one sees at once that
$$\frac x{(x^2-4)^{\tfrac12}}\sim_{-\infty}\frac x{\lvert x\rvert}\to -1,$$
hence by continuity,
$$\operatorname{arccot}\frac x{(x^2-4)^{\tfrac12}}\enspace\text{tends to}\enspace\operatorname{arccot}(-1)=\frac{3\pi}4. $$
as the range of $\operatorname{arccot}$ is $(0,\pi)$.


text:
Q: Proof/Explanation of Dependence of Two Random Variables (Drawing Cards with Replacement) "Two Cards are picked from a deck with replacement. Let X= number of aces, and Y= number of kings.
X and Y are both discrete random variables that can take on 0,1 and 2."
I'm trying to show whether or not X an Y are independent in the case that the sampling is done with replacement. I first assumed that X and Y are independent simply because replacement was involved but my calculations showed otherwise.
edit: Confirmed in the comments that X and Y are not independent. Can someone please provide a proof that X and Y are dependent and explain the error in the following attempt a proof that they are independent:
$P(X,Y) = P(X \cap Y) = P(X|Y)\times P(Y) $
but $P(X|Y) = P(X)$ because the sampling is done with replacement
so $P(X,Y) = P(X)\times P(Y)$ thus X and Y are independent.
In particular, can anyone explain why this particular scenario of drawing two cards with the random variables as they are defined makes X and Y dependent even though they are sampled with replacement? I understand now that how many X are selected changes the probability of how many Y are selected and I can sense that this has to do with the constraint of how many cards are selected in the event, i.e. the more of one type that are selected changes not the probability of selecting the second type but instead, it changes the amount of the second type that can be selected.
And since the random variable is defined as the amount of the card selected, its clear that this is the heart of the issue. However, I'm having trouble articulating or reasoning further about why this makes sampling with replacement or without replacement irrelevant to the question of dependence/independence of the variables. If anyone could shed light from this angle, I would greatly appreciate it.
Reference: another post  asks about the joint probability function of this situation without replacement.

A: The lack of independence is intuitively clear. If you got two aces in your two picks then you have a lot of information about the number of kings. So the ace count and the king count are not independent.
For me this is a convincing "proof" of dependence. It may not be enough for you or your instructor. I leave it to others to find the error in your formal argument.


text:
Q: Why are my listeners trigger happy Now I'm aware that adding listeners, then setting fields would trigger the change. So I set my fields then add listeners.
Ive even added a boolean as it was being triggered, to avoid this. However after OnResume. All my listeners are fireing. Can someone please explain why, and how to stop it. Thanks.
Here is my code/work flow:
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

   spn1.setSelection(2);
   spn2.setSelection(15); // Gets replaced by the listener to 2, when it shouldnt!

   UseListeners = false; // Ignores fired events with an IF statement.

   addListeners();

   //UseListeners = true;
}

@Override
protected void onResume() {
    super.onResume();
    UseListeners = true;
}

private void addListeners() {
    spn1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
            try{
                if(UseListeners){
                    spn2.setSelection(spn1.getSelectedItemPosition());
                }
            } catch (Exception e)
            {
            }
        }
        @Override
        public void onNothingSelected(AdapterView<?> arg0) {
        }
    });
 }

Surely after OnResume, nothing is even changing so it shouldnt be firing. On resume literally just sets boolean to true. And it is the last state before the app is running so I'm not sure where and why its then triggering. Its Super is called before being allowed to use triggers too.

A: I think that listeners are invoked after layout is created. It's looks like creating view happens at some point after onPause() method, so insted of setting your boolean flag in onPause() you should set it in listener.
See here and here.


text:
Q: mvc dropdown list not showing saved data I have a 'User details' view where I would like users to be able to edit their details.
All fields are populating as expected except for my Genderchoice list which defaults to 'please select' instead of whatever was saved(male /female).  I had to convert it from a string list to a selectitem list in order to make it display, is this the problem with retrieving the data?  When debugging I can confirm that the data is being saved.
 @Html.EditorFor(m => m.DateOfBirth, "BootstrapHorizontalString")
 @Html.EditorFor(m => m.Gender, "BootstrapHorizontalDropdown", new { list = Model.GenderChoice.Select(m=> new SelectListItem { Text = m, Value = m }) });

A: Check in the controller you are assigning the model value correctly and it's getting returned properly


text:
Q: change svg text positioning with css For some reason i can't change the Svg text tags x and y variables with CSS
even though it should be working and is working with Svg  and .
it works if i add the x and y postions directly on the html.
Html:
<svg id="main">
   <g id="g2">
      <circle id="c2" class="resize"/>
      <rect id="r2" class="resize"/>
      <text id="t2" class="resize">texthing</text>
   </g>

css
#t2{
  x:250px;
  y:150px;
}

A: I have used these 2 types of solutions for this problem but the first solution is the best for me using top left right

svg g #t2{
  /*you can use top left right like the example below*/
  top:100px;
  left:200px;

}
<svg id="main">
       <g id="g2">
          <circle id="c2" class="resize"/>
          <rect id="r2" class="resize"/>
          <text id="t2" class="resize">texthing</text>
       </g>

there is also another way of doing this is using transform translate like:
t2{ transform:translate(100px, 100px) }


text:
Q: Writing to Windows CMD from Java I'm trying to be able to input commands into the command prompt on Windows from Java. I use processBuilder, open the command prompt, and get the output stream, but when I try to write to that, nothing seems to happen. Do I need to include something else, or am I going about this all wrong?
I know that I can pass arguments including commands into the command prompt when I initially start it, but my goal is to be able to open the window first, then interact with it second, not at the same time.
My code:
    ArrayList<String> commands = new ArrayList<>();
    commands.add("cmd.exe");
    commands.add("/c");
    commands.add("start");

    ProcessBuilder pb = new ProcessBuilder(commands);

    Process p = pb.start();

    BufferedWriter stdin = new BufferedWriter(new OutputStreamWriter(p.getOutputStream()));

    stdin.write("dir");
    stdin.newLine();
    stdin.flush();

I've tried searching, but I haven't found any satisfactory answers. This code is what I've managed to piece together from that search.
My end goal is to be able to write a user interface for youtube-dl, a command line program, so I can get more experienced with such things. I'd like the user to be able to pick from several options, then execute the program based on their selection.

A: I was trying to do manually the youtube-dl thing, since youtube dl thing is an automatic script that uses a lot of CMD Commands.
Back to the topic, use:
Runtime.getRuntime().exec()


text:
Q: Discord JS: How do I delete all messages the bot has sent in DM's? I'm trying to make my bot delete all DM's from a user ID. How would I get about doing this?
I have tried using the DMchannel function but I am struggling. The following code is what I have tried
const dmCount = client.users.get("508625644792446986").dmChannel
var fetched =  dmCount.fetchMessages({limit: 99});
dmCount.bulkDelete(fetched)

I don't see what I'm doing wrong here, any suggestions on how to fix this?
The error is:
TypeError: Cannot read property 'fetchMessages' of null

A: I'm not for sure, but I think a user's direct message guild/channel will always = "null" because it's not in a server. You could do a command that only activates when the channel/guild = "null". But I don't think you can delete messages that were direct messaged sadly (at least with current Discord.js).


text:
Q: Paging library when used inside a nestedscrollview loads all data I am using paging library to load data and populate my recyclerview which is placed inside a nestedscrollview. But it is like, pagination works automatically until all the data fetched from API. I know this is because of the nestedscrollview. But unfortunately my layout needs scrollview as i have a top section other than recyclerview in this fragment.
This is my layout
<android.support.v4.widget.NestedScrollView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fillViewport="true"
   >
   <android.support.constraint.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

   //have a layout here which scrolls with recyclerview

      <Recyclerview />

   </ConstraintLayout>

</NestedScrollView>

Everything works fine when i do not use nestedscrollview. There is an open issue in googlesamples git repo regsrding this problem.
https://github.com/googlesamples/android-architecture-components/issues/215
Is anyone have idea how can we implement pagination when a recyclerview is inside a scrollview with pagination library from Android jetpack. I know we can implement traditional kind of pagination attaching listener to nestedscrollview, but i am looking to implement pagination with architecture component library.
https://developer.android.com/topic/libraries/architecture/paging/

A: Using the below code will solve the issue.
Here is the view hierarchy:
<androidx.coordinatorlayout.widget.CoordinatorLayout
    android:id="@+id/coordinator_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <com.google.android.material.appbar.AppBarLayout
        android:id="@+id/appbar_layout"
        android:background="@color/white"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <com.google.android.material.appbar.CollapsingToolbarLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            app:layout_scrollFlags="scroll|exitUntilCollapsed"
            app:titleEnabled="false">

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

                <!-- Put here elements that you need above the recycler view -->

            </LinearLayout>

        </com.google.android.material.appbar.CollapsingToolbarLayout>

    </com.google.android.material.appbar.AppBarLayout>
    <!-- RecyclerView -->
    <androidx.recyclerview.widget.RecyclerView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:nestedScrollingEnabled="true"
        app:layout_behavior="@string/appbar_scrolling_view_behavior"
        android:scrollbars="vertical"
        app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager" />

</androidx.coordinatorlayout.widget.CoordinatorLayout>

Note: Be sure that you have given id to CoordinatorLayout and AppBarLayout so that it will retain scroll position on the back stack.

A: The problem is recyclerview inside nested scrolview. Paging library has nothing to do with it. The behavior would be same if you try to load data on scroll listener of recyclerview.

A: The paging library does not work well with nestedScroolView. So you have to change your NesteScrollView to ScroolView with android:nestedScrollingEnabled="true", something like this:
<ScrollView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:nestedScrollingEnabled="true"
   >
   <android.support.constraint.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

   //have a layout here which scrolls with recyclerview

      <Recyclerview />

   </ConstraintLayout>

</ScrollView>