text:
Q: I can't initialize multiple classes of similar type (child and parent) within a function I have a parent class , 'Scene' and multiple classes that inherit it. I want to take an 'id' value and initialize a certain class, but have a problem with duplicate types if a switch / if statements are used.
  if (sceneType == 1) {
     Scene scene = new Scene(jsonScene.getInt("id"));
  } else if (sceneType == 2) {
       EndingScene scene = new EndingScene(jsonScene.getInt("id"));
    } else if (sceneType == 3) {
      InformationScene scene = new InformationScene(jsonScene.getInt("id"));
    }  else if (sceneType == 4) {
      AnswerScene scene = new AnswerScene(jsonScene.getInt("id"));
    } else if (sceneType == 5) {
      ActionScene scene = new ActionScene(jsonScene.getInt("id"));
    }

  scene.doSomething();

scene.doSomething throws error as in the scope outside the if statements, scene has not been initialized.
Scene scene;

  if (sceneType == 1) {
     Scene scene = new Scene(jsonScene.getInt("id"));
  } else if (sceneType == 2) {
       EndingScene scene = new EndingScene(jsonScene.getInt("id"));
    } else if (sceneType == 3) {
      InformationScene scene = new InformationScene(jsonScene.getInt("id"));
    }  else if (sceneType == 4) {
      AnswerScene scene = new AnswerScene(jsonScene.getInt("id"));
    } else if (sceneType == 5) {
      ActionScene scene = new ActionScene(jsonScene.getInt("id"));
    }

  scene.doSomething();

Alternatively if I define scene in the scope of my function, initializing the different types of scene are duplicate local variables.
I also have the problem when a general function that's return type is specific to parent object, but if I want it to return the object type passed into it, rather than the parent by default.

A: When you declare a variable in a method, you can't re-declare it.
This code should works :
Scene scene;

if (sceneType == 1) {
 scene = new Scene(jsonScene.getInt("id"));
} else if (sceneType == 2) {
   EndingScene scene = new EndingScene(jsonScene.getInt("id"));
} else if (sceneType == 3) {
  InformationScene scene = new InformationScene(jsonScene.getInt("id"));
}  else if (sceneType == 4) {
  AnswerScene scene = new AnswerScene(jsonScene.getInt("id"));
} else if (sceneType == 5) {
  ActionScene scene = new ActionScene(jsonScene.getInt("id"));
}

scene.doSomething();

A: It is possible to use Dictionary<TKey, TValue> in C# or HashTable in Java to avoid multiple if else statements.
Let me show an example via C#.
Your base and derived classes:
public class Scene
{
    public string Name { get; set; }
}

public class AnswerScene : Scene { }

public class InformationScene : Scene { }

and scene types:
public enum SceneType
{
    Base, Answer, Information
}

And factory which creates an instance of Scene by SceneType:
public class SceneToType
{
    public Dictionary<SceneType, Scene> SceneByType { get; private set; } = new()
    {
        { SceneType.Information, new InformationScene() },
        { SceneType.Answer, new AnswerScene() },
        { SceneType.Base, new Scene() }
    };
}

and then you can create objects by calling a method:
Scene GetInstance(SceneType sceneType)
{
    return new SceneToType().SceneByType[sceneType];
}


text:
Q: How to combine pyspark dataframes with different shapes and different columns I have two dataframes in Pyspark. One has more than 1000 rows and the other only 4 rows. The columns also are not matching.
df1 with more than 1000 rows:
+----+--------+--------------+-------------+
| ID |  col1  |     col2     |     col 3   |
+----+--------+--------------+-------------+
|  1 | time1  | value_col2   |  value_col3 |
|  2 | time 2 |  value2_col2 | value2_col3 |
+----+--------+--------------+-------------+
...

df2 with only 4 rows:
+-----+--------------+--------------+
| key |     col_c    |     col_d    |
+-----+--------------+--------------+
| a   |  valuea_colc | valuea_cold  |
| b   | valueb_colc  |  valueb_cold |
+-----+--------------+--------------+

I want to create a dataframe looking like this:
+----+--------+-------------+-------------+--------------+---------------+--------------+-------------+
| ID |  col1  |     col2    |     col 3   |    a_col_c   |    a_col_d    |   b_col_c    |   b_col_d   |
+----+--------+-------------+-------------+--------------+---------------+--------------+-------------+
|  1 | time1  | value_col2  |  value_col3 |  valuea_colc |   valuea_cold | valueb_colc  | valueb_cold |
|  2 | time 2 | value2_col2 | value2_col3 | valuea_colc  | valuea_cold   |  valueb_colc | valueb_cold |
+----+--------+-------------+-------------+--------------+---------------+--------------+-------------+

Can you please help with this? I prefer not to use Pandas.
Thank you!

A: I actually figured this out using crossJoin.
https://spark.apache.org/docs/2.1.0/api/python/pyspark.sql.html explains how to use crossJoin with Pyspark DataFrames.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Special case of graph-theory cycle In graph theory, is there a name for a (simple) cycle with no path between any of its non-adjacent vertices? When the graph is planar, this could be called a face, but how about non-planar graphs?

A: I think you're talking about a chordless cycle, or sometimes an induced cycle.
A face in a planar graph doesn't necessarily conform to this so there is some conflict in your description.


text:
Q: Android FFMPEG video compression issue in Samsung Galaxy S4 device I am using this library to compress video in android. App gets crash when I try to compress video second time. It works fine on other android devices except Samsung Galaxy S4. It gives the following signal on crash.
Fatal signal 11 (SIGSEGV) at 0x7b820a94 (code=2), thread 960 (Thread-1277)

I searched a lot for this issue but couldn't find solution. Any help would be greatly appreciated.

A: Android ffmpeg wrappers have an issue where the second run will often cause a crash - ffmpeg was never really designed to be used this way and it looks like it is just a clean up issue at the end of each run.
There is a common trick to get around this which involved loading and unloading the library - a number of Android ffmpeg wrapper do this including:

*

*http://hiteshsondhi88.github.io/ffmpeg-android-java/


text:
Q: Validate XSD Schema with ISO-8859-1 I have a XML. And this XML i have to validate with e XSD. And the XSD requested a ISO-8859-1 encoding.
I have try with this Code but it is not working. See someone the fault?
    public boolean validateXML(Document doc) throws ParserConfigurationException, IOException {

    XMLOutputter xmlOutput = new XMLOutputter();
    String xml = xmlOutput.outputString(doc);

    try {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setValidating(true);
        factory.setNamespaceAware(true);

        final SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);

        factory.setValidating(true);
        final Schema schema = sf.newSchema(new StreamSource(getClass().getResourceAsStream(SCHEMA_PATH)));
        factory.setSchema(schema);

        factory.setAttribute("http://java.sun.com/xml/jaxp/properties/schemaLanguage", "http://www.w3.org/2001/XMLSchema");
        DocumentBuilder builder = factory.newDocumentBuilder();

        InputSource is = new InputSource(xml);
        is.setEncoding("ISO-8859-1");

        builder.parse(is);
        return true;
    } catch (ParserConfigurationException pce) {
        throw pce;
    } catch (IOException io) {
        throw io;
    } catch (SAXException se) {
        return false;
    }
}

And the top from XSD
<?xml version='1.0' encoding='ISO-8859-1' ?>

A: Do as the below way :
    public class XMLUtils {

  private XMLUtils() {}

  // validate SAX and external XSD
  public static boolean validateWithExtXSDUsingSAX(String xml, String xsd)
  throws ParserConfigurationException, IOException
  {
    try {
      SAXParserFactory factory = SAXParserFactory.newInstance();
      factory.setValidating(false);
      factory.setNamespaceAware(true);

      SchemaFactory schemaFactory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");
      SAXParser parser = null;
      try {
         factory.setSchema(schemaFactory.newSchema(new Source[] {new StreamSource( xsd )}));
         parser = factory.newSAXParser();
      }
      catch (SAXException se) {
        System.out.println("SCHEMA : " + se.getMessage());  // problem in the XSD itself
        return false;
      }

      XMLReader reader = parser.getXMLReader();
      reader.setErrorHandler(
          new ErrorHandler() {
            public void warning(SAXParseException e) throws SAXException {
              System.out.println("WARNING: " + e.getMessage()); // do nothing
            }

            public void error(SAXParseException e) throws SAXException {
              System.out.println("ERROR : " + e.getMessage());
              throw e;
            }

            public void fatalError(SAXParseException e) throws SAXException {
              System.out.println("FATAL : " + e.getMessage());
              throw e;
            }
          }
          );
      reader.parse(new InputSource(xml));
      return true;
    }
    catch (ParserConfigurationException pce) {
      throw pce;
    }
    catch (IOException io) {
      throw io;
    }
    catch (SAXException se){
      return false;
  }
}

public static void main (String args[]) throws Exception{
    System.out.println
        (XMLUtils.validateWithExtXSDUsingSAX
            ("c:/temp/YourXML.xml", "c:/temp/YourXSD.xsd"));

  }
}

output :(if it is validated)   true

I hope it would help you..

A: I have the Metohd validateXML. And i set the Outputter to "setEncoding("ISO-8859-1")"
Buy why is at the end the XML File staring with
<?xml version="1.0" encoding="UTF-8"?>

Methode validateXML
private void validateXML(Document doc) throws Exception {

    XMLOutputter xmlOutput = new XMLOutputter(Format.getPrettyFormat().setEncoding("ISO-8859-1"));

    String docStr = xmlOutput.outputString(doc);

    //InputStream inputStream = new ByteArrayInputStream(docStr.getBytes(Charset.forName("ISO-8859-1")));
    byte[] bytes = docStr.getBytes(Charset.forName("ISO-8859-1"));
    InputStream inputStream = new ByteArrayInputStream(bytes);

    Source xml = new StreamSource(inputStream);
    File xsdfile = new File(this.getClass().getClassLoader().getResource(SCHEMA_PATH).getFile());

    SchemaFactory schemaFactor = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    Schema schema = schemaFactor.newSchema(xsdfile);

    Validator validator = schema.newValidator();

    validator.validate(xml);

}


text:
Q: What are the common mistakes in 'tailored Scrum approaches'? I have seen this before. Management wants to be agile and be scrummified, but does not want to step out of the status quo. My latest observation is no different; here, the Scrum is 'tailored' to the organization; specifically into a weird many-people-process.
Here http://img684.imageshack.us/img684/6175/modifiedscrum.jpg
The diagram showing the different participants.
I am putting together a document listing why this will not work. Here are the obvious ones:
1. There are product owner agents (an obvious WTF), who report to the product owner: causing dilution of decision making capability
2. There is a role that looks similar to a manager in the traditional approach - development manager: an obvious attempt at command-and-control model
3. The ScrumMaster's role includes collecting timesheets, which are used to track progress instead of burndown charts: detrimental to agile's efforts to build teams with motivated individuals
Leaving the question "how would you convince the management?", my question is more at, "what else do you see as failures in this/similar 'tailored Scrum approaches'?
EDIT: The diagram might use a few more details
1. The development manager is not part of the development team, with not very clearly defined responsibilities, except: developer performance assessemnt, recruitment, etc.,
2. There are more than two teams (with ScrumMaster+development manager+dev team) with the same product owner for all teams!

A: Moved from the comments...
Have you considered giving it a go and seeing how it works before lobbying against it? As long as they are open to adapting the structure over time I don't see any fatal flaws in this plan other than that it doesn't follow the Agile dogma to the letter.
Another thing to consider is that you want to incorporate enough of the business leader's ideas into the approach so they feel ownership in the Agile adoption. If they do, they will be vested in making sure it succeeds instead of disparaging it (because their approach would have been better) if things get sideways. And it will inevitably go sideways, especially at first. People are usually resistant to change and are often clumsy for a while when they are forced to adopt a new way of doing things.
Make management a partner in the process not an adversary.

A: The Development Manager and to some extent the ScrumMaster are variations of the traditional role of the tech lead.  I don't see the Development Manager necessarily having any more or less command and control as you put it than a typical tech lead.
The Scrum Master is a little bit more special than that though.  The Development Manager shouldn't also be the Scrum Master but there is no reason why the Scrum Master couldn't just be the PM anyway since they have the most interest in timesheets.  Tracking time on a project schedule is not disjoint with the concept of User Stories, Points and Burndown Charts.
You do kind of have a point about the Product Owner Agent role.  I don't see a person in that role having any clear unique responsibility other than being an additional link in the chain of command.
The Product Owner is ridiculously important though.  He owns the product.  I am not going to explain the importance of it but if you have ever worked on a project where there was no clear product owner because the middle managers were too chicken-$$$$ to take any ownership of the PRODUCT direction and decisions regarding the PRODUCT then you will see how it completely sabotages all projects before they even start.

A: You need them to differentiate how the company is structured and how the people in a scrum development process are structured. This is fine for an org chart.
For a very large ERP project, you could have nearly separate section that have their own product owners. They may report to someone, but from the Scrum perspective, there needs to be one product owner working with the group assigned to that part of the project.
The development manager is more the person who may do the evaluations, organizing days off schedules and other manager duties that have nothing to do with development.
Just show them how you separate the two. No reason small scrum groups can't exist in a large corporation. You have to know where people fit in both worlds.

A: It's actually not that far off. It depends on what certain people's roles are.

*

*There can be more than one person in a team that fills the role of Product Owner (as in the decision-making entity that is responsible for requirements generation, prioritization and acceptance). On large projects one person simply cannot do it all. What is important is that there is a single communications path to and from the Product Owner, to which questions are directed and from which requirements directives come, however many people are behind them (or even in front of them) assisting with the process. In short, there should always be one guy you can call with a question, no matter who he talks to to get the answer or who he communicates the answer through. So, if the Agent is simply someone from the Product Ownership "team" who participates as a chicken in the IPMs and daily standups, and reports back to the PO, that's fine; the PO cannot be everywhere. If this is a person capable of making decisions independently of other agents or the Product Owner, or who is designed to restrict access to the PO, THAT can be a problem.

*Development Manager sounds like either "Project Manager" or "Team Lead" to me. It could also be "Architect", which is the guy responsible for maintaining a good design structure and deciding the enterprise-level patterns to follow in developing certain areas. There's usually only one Architect, like there's only one Product Owner, so if this guy is a "Project Manager" or "Architect" role it should be a cross-team job, not one per.

*I don't see BAs in this chart. At my last Agile job, BAs received and reviewed the raw stories, determined dependencies that would create schedule conflicts and a "critical path", and usually also did some QA. They were also the ones on the phone the most with the PO. That freed the coding teams to do what they do best - heads-down coding.
The idea of timesheets as opposed to a burndown to track progress does seem odd. It sounds like the contract was negotiated for time and materials, and they want TIME, not an estimate of time based on points complexity. That's fine, to a point, but the point of Agile is that your clients would rather pay per-point instead of per-hour; a point is a calibratable unit of work, and when its done you have a real product that should be worth that amount as a fraction of the whole project.

A: I don't think that is is obvious that things would fail.

There are product owner agents (an obvious WTF), who report to the product owner: causing dilution of decision making capability

Assuming that someone needs to represent customer (in case where real customer is absent) this is not a goof up. However, the criteria of success is the visualization of real customer needs.

There is a role that looks similar to a manager in the traditional approach - development manager: an obvious attempt at
  command-and-control model

This happens usually where a traditional tech guy is a not senior enough (or known to be good enough to do project manager but knows most tech stuff better than most. (unless it is other way). Real difference comes on the basis as to what they actually do.

The ScrumMaster's role includes collecting timesheets, which are used to track progress instead of burndown charts: detrimental to
  agile's efforts to build teams with motivated individuals

This is sounds surprising though. However, i believe most traditional software companies cannot get rid of timesheet. Donno why. But there is no alternative to tracking the project from the point of view of
There are few criteria that will make or break things.

*

*The real challenges in Agile is not process and accuracy with which one adheres to it. The real challenge is when you begin pure ritual rather than helping to simplify processes for developers so that they can concentrate on what they do good - programming!

*Getting to know the real need and iteratively going better at it. What you need is to get clarity (and transparency) across all people and personal commitment from all to get to achieve the right targets.
Of course, there are 12 core principles that you should know. My point is stick to those core concept - you can make agile work under any organization structure.
If this basic things fail, everything will fail - else all else is good.


text:
Q: Pandas Rename one column Values when not equal to multiple conditions I am new to coding and Pandas any help would be much appreciated.
I have a column I wish to rename values Locations A-00-UD, A-01-UD, A-02-UD would = Audit, T-00-UD , T-02-UD, T-03-UD would = Transit and all other values would = stock. The problem I have is naming all the other values as Stock as in the full data-frame column is 15,000 lines long and has hundreds of different locations I wish to name stock.
Location
A-00-UD
A-01-UD
A-02-UD
A-03-UD
T-00-UD
T-01-UD
T-02-UD
T-03-UD
A-45-TR
S-30-RT
D-20-ED
V-00-LM

A: You can use a dictionary to map the first character of Location:
mapper = {'A': 'Audit', 'T': 'Transit'}

df['Location'] = df['Location'].str[0].map(mapper).fillna('Stock')

Alternatively, using numpy.select, you can specify conditions, values for each condition and a default value:
df = pd.DataFrame({'Location': ['A-00-UD', 'T-01-UD', 'S-30-RT']})

conditions = [df['Location'].str[0] == 'A', df['Location'].str[0] == 'T']
values = ['Audit', 'Transit']

df['Location'] = np.select(conditions, values, 'Stock')

print(df)

  Location
0    Audit
1  Transit
2    Stock

A: Use numpy.select with isin for exact match:
m1 = df['Location'].isin(['A-00-UD', 'A-01-UD', 'A-02-UD'])
m2 = df['Location'].isin(['T-00-UD', 'T-02-UD', 'T-03-UD'])

Or with startswith for check first value:
m1 = df['Location'].str.startswith('A')
m2 = df['Location'].str.startswith('T')

df['new'] = np.select([m1, m2], ['Audit', 'Transit'], default='Stock')
print (df)
   Location      new
0   A-00-UD    Audit
1   A-01-UD    Audit
2   A-02-UD    Audit
3   A-03-UD    Audit
4   T-00-UD  Transit
5   T-01-UD  Transit
6   T-02-UD  Transit
7   T-03-UD  Transit
8   A-45-TR    Audit
9   S-30-RT    Stock
10  D-20-ED    Stock
11  V-00-LM    Stock


text:
Q: Properly set SeekBar style for Holo and pre-Holo APIs After setting SeekBar with Holo style, I got warning that it's not supported pre-Holo APIs.

If I leave it this way, will this crash the app or pull pre-Holo style anyway? It does not crash on the emulator and I don't have 2.3.3 device.
The reason for asking his is odd behaviour. I tried to manually set style for Holo and pre-Holo using res/values-v11/ directories and placing styles.xml in each and setting the style of SeekBar to style="@style/settings_seekbar" .
Style for API 11+ looked like this
<style name="settings_seekbar">
    <item name="android:seekBarStyle">@android:style/Widget.Holo.SeekBar</item>
</style>

and style for APIs older than 11 looked like this
<style name="settings_seekbar">
    <item name="android:seekBarStyle">@android:style/Widget.SeekBar</item>
</style>

So it looked like this would work. But on either device with Android 4.0+, I don't see Holo's theme, but the old thick-yellow theme.
If this is the proper way of settings styles (in case the first solution will crash  a device), where did I make a mistake thus Holo theme never appeared on newer devices?

A: It seems we can safely use a theme from the upper SDK because I found no indicators that it will ever crash the app.
If the theme does not exist, Android will use the appropriate lower-level theme.
The error we can see on the image is just a warning that UI will not look the same in the SDKs which do not support this theme.


text:
Q: Angular JS with HANA I have been trying to run a Angular JS application which is located in HANA. Since the Web IDE does not support Angular JS development, I have the application in Webstorm editor locally in my laptop.I am using a Resource override plug in to direct the location of my files towards local files. However when I run the index.html from the HANA server, I am getting HTTP 404 error.

A: Please verify that you have two files in the folder to allow web access:

*

*.xsaccess see content guide here

*.xsapp (empty file)


text:
Q: How to awk with condition / ommit some lines The goal:
I want to know how many test do I have during running my test suite.
I'm trying to get overall number of test scenarios written in BDD style and print that number in console.
All test files are in ./features directory. There are subdirectories (so I need to search recursively)
Some of tests are commented (using #)
Simple scenario looks like that:

  Scenario: blah-blah-blah
    Given blah
    When blah bloh
    Then bluh bluh

That's pretty simple and works as a charm:
grep -r "^\s*Scenario:" ./features/ | wc -l
The tricky part is there could be tests which have "Scenario Outline" keyword. On the bottom of test there's a table with examples.
Scenario may look like that:
  Scenario Outline: blah
    Given blah <score>
    When bloh <performance>
    Then blah-bloh-bluh <completion>

    Examples:
      | score | performance | completion |
      | 4/4   | 100         | 50         |
      | 3/4   | 75          | 50         |
      | 4/4   | 100         | 5          |

On the first line we've got headers - we shouldn't count them. So, in this case we have 3 tests.
So far I've done something like that:
find ./features -type f -exec sed -n -e  '/Scenario Outline/,/Scenario/ p' {} + | grep \| | wc -l
Unfortunately there are two issues I couldn't figure out:

*

*We're checking tables which exists between "Scenario Outline" and "Scenario". My solution does not match case when "Scenario Outline" is the very last test in file (there is no more scenario, just EOF).

*I count every line with '|' no matter there are real data or header of the table.

Thanks for every advice!

A: I'm not sure if pipes can occur anywhere else in the files, but if not the following command will count all lines starting with Scenario and all tables rows while skipping the first row.
find ./features -type f -print0 | \
   xargs -0 awk '/^\s*Scenario:/; /\|/ { if (intable) print; intable=1 } intable && $0 !~ /\|/ { intable=0 }' | \
   wc -l


text:
Q: What is the .NET equivalent to TApplication or how to call this Dll in .NET Managed Code? Here is the cpp code to call the dll function"
typedef void (__stdcall *Terminal)(TApplication*, TFileStream *k, HANDLE N, int D);

Here is my C# code to call the function"
[DllImport("somedll.dll", CallingConvention = CallingConvention.StdCall, CharSet = CharSet.Ansi)]
static extern void terminal(IntPtr Application, IntPtr FileStream, IntPtr CommHandle, int mode);

and the function call:
terminal(IntPtr.Zero, FileHandle.DangerousGetHandle(), CommHandle, 0);

if i call terminal with the Application ptr set to this.Handle i get a System.AccessViolationException was unhandled
  Message=Attempted to read or write protected memory. This is often an indication that other memory is corrupt.

A: You can't create a Delphi TApplication from .net. You can't create a Delphi TFileStream from .net. This DLL appears to be inaccessible from anything other than Delphi or C++ Builder.
The only way you could hope for it to work from .net would be if the DLL also exported functions that created instances of TApplication or TFileStream, which you could then pass on to the function in your question.
The TApplication class is a VCL class representing the application. It is the equivalent of the WinForms Application class. Likewise TFileStream is a VCL class wrapping file I/O in a stream-like interface. The .net FileStream class is similar. But you simply cannot synthesise working instances of Delphi/VCL classes from .net.


text:
Q: Why is playback whisper-quiet on iPhone using NuGet package Plugin.AudioRecorder? Using the Plugin.AudioRecorder NuGet in Xamarin Forms / iOS, I am able to record audio on iPhone 8 but on playback it is whisper quiet. How to increase the sound volume?
In AppDelegate.cs I have:
AudioPlayer.RequestAVAudioSessionCategory (AVAudioSessionCategory.PlayAndRecord);

A: By default playback was via the phone's upper speaker. Directing output to the lower speaker solves the problem.
In AppDelegate.cs, add:
AudioPlayer.OnPrepareAudioSession = x =>
            {
                // Route audio to the lower speaker rather than the upper speaker so sound volume is not minimal
                x.OverrideOutputAudioPort ( AVAudioSessionPortOverride.Speaker, out NSError error );
            };

A: AudioPlayer.OnPrepareAudioSession was not getting called for me. An alternative solution to direct audio output to the lower speaker:
var audioSession = AVAudioSession.SharedInstance();
var success = audioSession.SetCategory(AVAudioSession.CategoryPlayAndRecord, out var error);
if (success)
{
    success = audioSession.OverrideOutputAudioPort(AVAudioSessionPortOverride.Speaker, out error);
    if (success)
        audioSession.SetActive(true, out error);
}

I ran this code in my AppDelegate.FinishedLaunching() override


text:
Q: How can I send text to from one route (/client/1) to another route (/client/2) using ajax in rails? I am making a simple rails (4) application and realize that I really need to send text to each other who sit on different routes (/client/1 and /client/2) without reloading the page.
This is what I got so far.

*

*route (/client/1)
there is an input tag and I made this form with rails form helper to send XHR request to the associated controller

*In the controller, I grab the text by params and assigned it to an variable

*I made a js file named after the action and append the variable into a tag
This is working in  client/1 but I cannot figure out how to send the text to another route (/client/2).
Please help me to make this possible.
I appreciate your help in advance.
Thanks !!

A: You need a streaming mechanism.
First, to understand what this is about, I suggest you to watch this railscast. It's an old one but it explain clearly the basic principle of it http://railscasts.com/episodes/316-private-pub
Then you can also read this pretty good article http://www.sitepoint.com/streaming-with-rails-4/
Once you understand the principles, have a look at faye and ActionController::Streaming


text:
Q: Java убрать фон изображения Здравствуйте! Дописал игру на Java, с использованием изображений. Но есть проблема. Изображения находятся в JFrame(BufferedImage 100x100 пикселей). Фон убрал в фотошопе,но в игре он снова появляется. Как это убрать? Изображения отрисовываются на JPanel, которой я и задаю размер 100 на 100. Пример изображения ниже.

Код:
public class Stand extends JPanel { // Подставка
    private StandDirection direction;

    private BufferedImage image;

    private int standX = 250;
    private int standY = 350;

    public int getStandX() {
        return standX;
    }

    public void setStandX(int standX) {
        this.standX = standX;
    }

    public int getStandY() {
        return standY;
    }

    public void setStandY(int standY) {
        this.standY = standY;
    }

    public Stand(){
        try {
            image = ImageIO.read(new File("src\\images\\stand.png"));
        } catch (IOException e) {
            System.out.println("Неверный путь к изображению.");
        }
    }

    public void setDirection(StandDirection direction) {
        this.direction = direction;
    }

    public StandDirection getDirection() {
        return direction;
    }

    @Override
    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        g.drawImage(image, 0, 0, null);
    }
}

A: Я немного поэксперементировал с вашим изображением и близким к вашему кодом:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.LinearGradientPaint;
import java.awt.Point;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.SwingUtilities;

class TestPane extends JPanel {
    private BufferedImage img;

    public TestPane() {
        try {
            img = ImageIO.read(new File("stand.png"));
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

    @Override
    public Dimension getPreferredSize() {
        return img == null ? new Dimension(200, 200) : new Dimension(img.getWidth(), img.getHeight());
    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        Graphics2D g2d = (Graphics2D) g.create();
        LinearGradientPaint lgp = new LinearGradientPaint(
                new Point(0, 0),
                new Point(0, getHeight()),
                new float[] {0f, 1f},
                new Color[] {Color.GREEN, Color.YELLOW});
        g2d.setPaint(lgp);
        g2d.fillRect(0, 0, getWidth(), getHeight());
        if (img != null) {
            int x = (getWidth() - img.getWidth()) / 2;
            int y = (getHeight() - img.getHeight()) / 2;
            g2d.drawImage(img, x, y, this);
        }
        g2d.dispose();
    }
}

public class TestTransparency {
    public TestTransparency() {
        try {
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        }
        catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {}

        JFrame frame = new JFrame("Тест");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLayout(new BorderLayout());
        frame.add(new TestPane());
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                new TestTransparency();
            }
        });
    }
}

Проблем не обнаружил.


text:
Q: How to Python code an if else condition at a webdriver wait until juncture At the moment, I'm using a wait until pause in my selenium Python program:
    # wait until shipping estimate loaded
    element = WebDriverWait(driver, 10).until(
        EC.presence_of_element_located((By.CSS_SELECTOR, "#freightCalculatorForm > div > fieldset.col-xs-12.col-lg-6.col-md-6.text-center > div.freightCalcResult > div > p:nth-child(2)"))
    )

The problem is that if the wait until reaches the end of the allowed time, it will throw a timeout error and then stop my program.
But I want my program to continue at that point according to an if/else directive:
In other words, I want:
If the wait until succeeds in detecting the element
    # return the element
Else the wait until times out
    # do something else instead, and continue with the rest of the program

How can I code this if/else in Python selenium with the above wait until?

A: Instead of if-elif you can use try-except as following:
try:
    element = WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.CSS_SELECTOR, "#freightCalculatorForm > div > fieldset.col-xs-12.col-lg-6.col-md-6.text-center > div.freightCalcResult > div > p:nth-child(2)")))
    # do what you need to do in case the element found
except:
    # do what you want to do in case no element found

A: You can simply use try except pass statement
try:
    element = WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.CSS_SELECTOR, "#freightCalculatorForm > div > fieldset.col-xs-12.col-lg-6.col-md-6.text-center > div.freightCalcResult > div > p:nth-child(2)")))
except:
    pass


text:
Q: ActivateObject: Exception unhandled I am trying to use Media Foundation Transforms & I hit a snag where when I use MFTEnumEx, get 1 encoder back, and use ActivateObject I get this error:
Unhandled exception at 0x00007FF9C7084078 in endec.exe: Microsoft C++ exception: std::runtime_error at memory location 0x00000056FF75CC38. occurred at activate[0]->ActivateObject(IID_PPV_ARGS(&encoder))
Microsoft Windows Server 2016 Datacenter. 10.0.14393 N/A Build 14393. x64.
Code:
IMFTransform* get_encoder() {
    ComPtr<IMFTransform> encoder = NULL;
    IMFActivate **activate = nullptr;

    uint32_t flags = MFT_ENUM_FLAG_HARDWARE | MFT_ENUM_FLAG_SORTANDFILTER;

    // Unused for testing...
    MFT_REGISTER_TYPE_INFO input_info;// = NULL; // NULL pInputType means "match all"
    MFT_REGISTER_TYPE_INFO output_info;

    input_info.guidMajorType = MFMediaType_Video;
    input_info.guidSubtype = MFVideoFormat_ARGB32;

    output_info.guidMajorType = MFMediaType_Video;
    output_info.guidSubtype = MFVideoFormat_NV12;

    CLSID *clsids = NULL;
    uint32_t count = 0;
    _com_error error = NULL;

    //error = MFTEnum(MFT_CATEGORY_VIDEO_PROCESSOR, flags, input_info, &output_info, NULL, &clsids, &count);
    ThrowIfFailed(MFTEnumEx(MFT_CATEGORY_VIDEO_ENCODER, flags, NULL, NULL, &activate, &count),
        &count, "Unexpected error occurred with finding encoders"); // <--- ERROR

    if (!count && !activate[0]) {
        cout << "Did not find any encoders...\n";
        return nullptr;
    }

    cout << "Number of encoders available: " << count << endl;

    if (!activate[0]) {
        cout << "Couldn't get a valid activate obj\n";
    }

    ThrowIfFailed(activate[0]->ActivateObject(IID_PPV_ARGS(&encoder)), &flags,
        "Wasn't able to activate encoder");

    return encoder.Get();
}

Local variables at time of exception:
+       activate    0x0000016ebc24db20 {0x0000016ebdb1d950 {...}}   IMFActivate * *
+       clsids  0x0000000000000000 <NULL>   _GUID *
        count   1   unsigned int
+       encoder 0x0000000000000000 <NULL>   Microsoft::WRL::ComPtr<IMFTransform>
+       error   {S_OK}  _com_error
        flags   68  unsigned int
+       input_info  {guidMajorType={73646976-0000-0010-8000-00AA00389B71} guidSubtype={00000015-0000-0010-8000-00AA00389B71} }  __MIDL___MIDL_itf_mfobjects_0000_0008_0003
+       output_info {guidMajorType={73646976-0000-0010-8000-00AA00389B71} guidSubtype={3231564E-0000-0010-8000-00AA00389B71} }  __MIDL___MIDL_itf_mfobjects_0000_0008_0003```

A: Did you call CoInitializeEx and MFStartup ?
HRESULT hr = CoInitializeEx(NULL, COINIT_APARTMENTTHREADED | COINIT_DISABLE_OLE1DDE);

and
HRESULT hr = MFStartup(MF_VERSION, MFSTARTUP_LITE);

It's an example, use needed parameters.
At minimum, you need CoInitializeEx for your function "get_encoder".
Possibly, Microsoft Windows Server 2016 Datacenter can't do hardware encoding, because of hardware/software configurations, even if there is a hardware encoder registered.
For example, some multimedia services running missing.


text:
Q: How to convert this string into separate string objects New to Google Tag Manager and not sure how to do this. On my thankyou page, let's say there is:
var purchased =  "product1;product2;product3"

How would I separate each string in 'purchased' so that I have something like this (product), so then Tag Manager can understand there are 3 unique strings:
   var product = {"product1"}, {"product2"}, {"product3"}
or var product = {"product1", "product2", "product3"}

I tried these but it wasn't exactly what I needed:
var products = purchased.split(';');
var products = purchased.split(';').map(e => e);
    // both of these return ["product1, product2, product3"]

A: How about splitting by ;(space)? Your code leaves a space.
var products = purchased.split(';');


text:
Q: Cake PHP 2 turn off default console output from shell commands I've written a custom shell in Cake PHP 2 under the Console/cake my_shell command, and have added my own $this->out() messages in places. Each time I run my shell, I get the default cake output first such as the path, and a welcome message. I'd like to disable these specifically for my shell but can't seem to find a setting to do so.
Welcome to CakePHP v2.10.18 Console
---------------------------------------------------------------
App : app
Path: /Users/user/Sites/project/app/
---------------------------------------------------------------


text:
Q: Googe Maps: Do I have to use Ionic Native? I have just upgraded from Ionic 2 beta to rc3.  In order to eliminate compilation errors I changed my Google Maps implementation to use the Ionic native api.  This fixed my compilation errors, but I see that the Ionic native api has limitations. For example, there is no fitBounds function that is in googles api.
Question
Is it possible to use Ionic 2 rc3 with using Googles api directly and not the Ionic native api?
If so, How should I configure my app to use the api?
Or, is there any reason why I would want to use  the Ionic native api over accessing Googles api directly?
Thanks
package.json
  "dependencies": {
    "@angular/common": "2.1.1",
    "@angular/compiler": "2.1.1",
    "@angular/compiler-cli": "2.1.1",
    "@angular/core": "2.1.1",
    "@angular/forms": "2.1.1",
    "@angular/http": "2.1.1",
    "@angular/platform-browser": "2.1.1",
    "@angular/platform-browser-dynamic": "2.1.1",
    "@angular/platform-server": "2.1.1",
    "@ionic/storage": "1.1.6",
    "@types/google-maps": "^3.2.0",
    "@types/meteor": "^1.3.31",
    "@types/underscore": "^1.7.36",
    "accounts-base-client-side": "^0.1.1",
    "accounts-phone": "0.0.1",
    "angular2-moment": "^1.0.0-beta.6",
    "babel-runtime": "^6.18.0",
    "google-maps": "^3.2.1",
    "ionic-angular": "2.0.0-rc.3",
    "ionic-native": "2.2.3",
    "ionicons": "3.0.0",
    "meteor-client-side": "^1.3.5",
    "meteor-node-stubs": "^0.2.4",
    "meteor-rxjs": "^0.4.5",
    "meteor-typings": "^1.3.1",
    "moment": "^2.15.2",
    "rxjs": "^5.0.0-beta.12",
    "zone.js": "0.6.26"
  },

A: The other release candidates work with Googles api (noy just ionic-native)
I do have the following in my index.html
<script src="http://maps.google.com/maps/api/js?key=XXXXX"></script>
and in my pckage.json
"@types/googlemaps": "^3.25.40",
(run npm install @types/googlemaps --save-dev)
Added the following to declarations.d.ts
/// <reference path="../node_modules/@types/googlemaps/index.d.ts" />


text:
Q: Is it possible to create new cordova based ipad application in xcode I'm using Xcode 4.2 for ios development and installed cordova 1.5.0 for phonegap.
Installation successfully done.
I followed the tutorial in this site.
But it supports only for iPhone, How is it posible to create project for ipad in Cordova based application like Singleview based or like Empty application in xcode 4.2

A: In the summary section of the target settings there is a dropdown with the options iPhone, iPad and universal.
However, that tutorial is rather out of date - for a new project you really should be using Cordova 2.2 at this point, which has an entirely different setup process.
http://docs.phonegap.com/en/2.2.0/guide_getting-started_ios_index.md.html#Getting%20Started%20with%20iOS


text:
Q: How To Dynamically Insert To Table From SQL View Using PL/SQL How To Dynamically Insert To Table From SQL View Using PL/SQL:

*

*I want to dynamically insert to table from sql view using PLSQL Cursor when sql view has been changed!!!

*vi_customer is a sqlview(main data)

*customers_1 is a table

*IDENTITY_CUSTOMERS  is a identity column.

*v_cur_cust_view   cur_customer_view%rowtype
Code:
CREATE OR REPLACE PROCEDURE p_customer_1
IS
  CURSOR cur_customer_view
  IS
    SELECT *
    FROM vi_customer
    WHERE IDENTITY_CUSTOMERS IN
      (SELECT vi_cus.IDENTITY_CUSTOMERS FROM vı_customer vi_cus
    MINUS
    SELECT vı_customer.IDENTITY_CUSTOMERS
    FROM vı_customer
    INNER JOIN customers_1
    ON customers_1.IDENTITY_CUSTOMERS=vı_customer.IDENTITY_CUSTOMERS
      );
    v_cur_cust_view cur_customer_view%rowtype;
  BEGIN
    FOR v_cur_cust_view IN cur_customer_view
    LOOP
      INSERT
      INTO customers_1
        (
          cust_last_name,
          cust_emaıl,
          phone_number1,
          phone_number2,
          order_ıd,
          order_tımestamp,
          order_total,
          quantıty,
          unıt_prıce,
          category,
          fılename,
          ımage_last_update,
          product_ımage,
          product_name,
          lıst_prıce,
          mımetype,
          admın_user,
          created_on,
          expıres_on,
          password,
          products,
          user_ıd,
          user_name,
          st,
          state_name,
          customer_ıd,
          cust_fırst_name,
          IDENTITY_CUSTOMERS
        )
        VALUES
        (
          v_cur_cust_view.cust_last_name,
          v_cur_cust_view.cust_emaıl,
          v_cur_cust_view.phone_number1,
          v_cur_cust_view.phone_number2,
          v_cur_cust_view.order_ıd,
          v_cur_cust_view.order_tımestamp,
          v_cur_cust_view.order_total,
          v_cur_cust_view.quantıty,
          v_cur_cust_view.unıt_prıce,
          v_cur_cust_view.category,
          v_cur_cust_view.fılename,
          v_cur_cust_view.ımage_last_update,
          v_cur_cust_view.product_ımage,
          v_cur_cust_view.product_name,
          v_cur_cust_view.lıst_prıce,
          v_cur_cust_view.mımetype,
          v_cur_cust_view.admın_user,
          v_cur_cust_view.created_on,
          v_cur_cust_view.expıres_on,
          v_cur_cust_view.password,
          v_cur_cust_view.products,
          v_cur_cust_view.user_ıd,
          v_cur_cust_view.user_name,
          v_cur_cust_view.st,
          v_cur_cust_view.state_name,
          v_cur_cust_view.customer_ıd,
          v_cur_cust_view.cust_fırst_name,
          v_cur_cust_view.IDENTITY_CUSTOMERS
        );
    END LOOP;
    COMMIT;
  END;

Error:
Connecting to the database db_kg_0.
ORA-00917: missing comma
ORA-06512: at "DB_KG_0.P_CUSTOMER_1", line 15
ORA-06512: at line 2
Process exited.
Disconnecting from the database db_kg_0.

A: The right way to write this logic is to use insert . . . select, not a cursor and a loop:
INSERT INTO customers_1 ( . . . )
    SELECT . . .
    FROM vi_customer
    WHERE IDENTITY_CUSTOMERS IN (SELECT c.IDENTITY_CUSTOMERS
                                 FROM vı_customer c
                                 MINUS
                                 SELECT c.IDENTITY_CUSTOMERS
                                 FROM vı_customer c INNER JOIN
                                      customers_1 c1
                                      ON c1.IDENTITY_CUSTOMERS = c.IDENTITY_CUSTOMERS
                                );

A: RESOLVED!!!
insert into customers_1

(
                        cust_last_name,
                        cust_emaıl,
                        phone_number1,
                        phone_number2,
                        order_ıd,
                        order_tımestamp,
                        order_total,
                        quantıty,
                        unıt_prıce,
                        category,
                        fılename,
                        ımage_last_update,
                        product_ımage,
                        product_name,
                        lıst_prıce,
                        mımetype,
                        admın_user,
                        created_on,
                        expıres_on,
                        password,
                        products,
                        user_ıd,
                        user_name,
                        st,
                        state_name,
                        customer_ıd,
                        cust_fırst_name,
                        IDENTITY_CUSTOMERS)

select cust_last_name,
                        cust_emaıl,
                        phone_number1,
                        phone_number2,
                        order_ıd,
                        order_tımestamp,
                        order_total,
                        quantıty,
                        unıt_prıce,
                        category,
                        fılename,
                        ımage_last_update,
                        product_ımage,
                        product_name,
                        lıst_prıce,
                        mımetype,
                        admın_user,
                        created_on,
                        expıres_on,
                        password,
                        products,
                        user_ıd,
                        user_name,
                        st,
                        state_name,
                        customer_ıd,
                        cust_fırst_name,
                        IDENTITY_CUSTOMERS from vi_customer where IDENTITY_CUSTOMERS in (SELECT vi_cus.IDENTITY_CUSTOMERS
FROM vı_customer vi_cus
      MINUS
        SELECT
          vı_customer.IDENTITY_CUSTOMERS
        FROM
            vı_customer  INNER JOIN customers_1 on customers_1.IDENTITY_CUSTOMERS=vı_customer.IDENTITY_CUSTOMERS);


text:
Q: User matching algorithm So this problem we have users matching to other online users. However it is not just a one to one match. A user is given a selection of 5 other users to choose from, which are then marked as seen and should not be shown again when the user requests for another 5 users to be shown. More people can come online during the process.
The problem is, I want a way for each user to be shown in the selection for other users, with redis but an algorithm is mostly what im looking for. I'm trying to implement this in the fastest way possible, using redis if possible but I can also make calls to the database if it's needed.
My current solution is as follows, hopefully someone will have some tips to improve this from O(N) calls.
So each user needs to have a seen set of user_ids. We can have a redis list (queue) of onlineusers. Where we keep poppping users from the left until we find one that isn't in the user's seen set, save it, add to users seen, then push it on the right. Then once we get 5 of those we left push back the ones we left popped off that were already seen.
This is the best I could think of however it is O(N) each time we want to find 5 users for this one user to select from. It's possible (though not likely) that the user has seen a huge amount and is popping off the whole list.
To help understand this better. A naiive approach is to have every single user contain a copy of all online users in the form of a set. So then we simply pop 5 random set members. But this can't work because theres not enough space, and each time a user goes online they'd have to be added to each user's online users. Or deleted when they go offline and those operations are O(N) considering they are done for N users at O(1)
Does anyone have any tips to match users with other users?

A: It would be good to know about which kind of data we are talking about. How many users exist? How many will be online at average? How is the ratio of "seen users" compared to all users (sparse vs. dense)?
Modification of your algorithm
Don't pop the first but choose a random element from the set of online users. This should improve balancing and may help with amortized complexity depending on the ratio of these two sets!
Alternative Algorithm (more structured; still bad worst-case; should be good if sparse seen)

*

*Keep seen as a balanced tree (O(log n) insertion)

*Keep online as a balanced tree.

*While not enough users chosen:

*

*Search for first gap in seen (e.g. [0,1,3,7] -> 2; O(log n) according to SO-link)

*Search for first user >= gap-value (O(log n))

*If user < next_gap_neighbor (in example above: 3; next value after picked gap 2)

*-> pick

*Else

*-> add chosen-gap-value temporarily (for this moment; model-decision how often to update online) to seen OR limit search somehow to > chosen-gap-value (O(log n))

Depending on the data, this should work very good if data is huge and seen is sparse!


text:
Q: Webservice não aceita arquivo xml Estou gerando um XML, e envio para webservice, e ele sempre me retorna o mesmo erro, Erro 500, porém este erro é mto vago, consegui ter o seguinte retorno no erro:

:ServerCould not parse content
  type:javax.mail.internet.ParseException: Expected parameter name, got
  "/"

Segue como estou tentando enviar:
public static MemoryStream stringToStream(string dados)
    {
        MemoryStream memoryStream;
        try
        {
            byte[] byteArray = new byte[dados.Length];
            System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
            byteArray = encoding.GetBytes(dados);
            memoryStream = new MemoryStream(byteArray);
            memoryStream.Seek(0, SeekOrigin.Begin);
        }
        catch (Exception ex)
        {
            return null;
        }

        return memoryStream;
    }

    private void montaEnvelope(HttpWebRequest webRequest, XmlDocument document, string numero)
    {
        string soapEnvelope = string.Empty;

        //soapEnvelope += "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:ws=\"http://ws.issweb.fiorilli.com.br/\" xmlns:xd=\"http://www.w3.org/2000/09/xmldsig#\">";
        soapEnvelope += "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:e=\"http://www.betha.com.br/e-nota-contribuinte-ws\">";
        //soapEnvelope += "<soapenv:Header/><soapenv:Body><ws:gerarNfse>";
        soapEnvelope += "<soapenv:Header/><soapenv:Body><e:gerarNfse><nfseCabecMsg>";
        soapEnvelope += "<cabecalho xmlns=\"http://www.betha.com.br/e-nota-contribuinte-ws\" versao=\"2.02\"><versaoDados>2.02</versaoDados></cabecalho></nfseCabecMsg><nfseDadosMsg>";

           soapEnvelope += document.LastChild.OuterXml.Replace("<?xml version=\"1.0\" encoding=\"utf-8\"?>", string.Empty);
        //soapEnvelope += "<username>01001001000113</username><password>123456</password></ws:gerarNfse></soapenv:Body></soapenv:Envelope>";
        soapEnvelope += "</nfseDadosMsg></e:gerarNfse></soapenv:Body></soapenv:Envelope>";
        //soapEnvelope += "</e:gerarNfse></soapenv:Body></soapenv:Envelope>";
        MemoryStream stream = stringToStream(soapEnvelope);
        webRequest.ContentLength = stream.Length;
        Stream requestStream = webRequest.GetRequestStream();
        stream.WriteTo(requestStream);

        document.LoadXml(soapEnvelope);
        document.PreserveWhitespace = false;

        document.Save(@"E:\\NFSe-" + "RPS" + numero.ToString().PadLeft(15, '0') + ".xml");
        System.Xml.Linq.XDocument doc = System.Xml.Linq.XDocument.Load("E:\\NFSe-" + "RPS" + numero.ToString().PadLeft(15, '0') + ".xml");
        doc.Save("E:\\NFSe-" + "RPS" + numero.ToString().PadLeft(15, '0') + ".xml", System.Xml.Linq.SaveOptions.DisableFormatting);

        this.XmlDocNFSe = document;
    }

    private static string getSoapResponse(HttpWebRequest webRequest)
    {
        string soapResult = string.Empty;

        WebResponse webResponse = webRequest.GetResponse();
        StreamReader rd = new StreamReader(webResponse.GetResponseStream());
        soapResult = rd.ReadToEnd();

        XmlDocument xmlResponse = new XmlDocument();
        xmlResponse.LoadXml(soapResult);
        XmlNode responseNode = xmlResponse.LastChild.LastChild.FirstChild;

        XmlNamespaceManager ns = new XmlNamespaceManager(xmlResponse.NameTable);
        ns.AddNamespace("ns2", "http://www.abrasf.org.br/nfse.xsd");
        XmlNode codigo = xmlResponse.SelectSingleNode("//ns2:Codigo", ns);
        XmlNode mensagem = xmlResponse.SelectSingleNode("//ns2:Mensagem", ns);
        XmlNode correcao = xmlResponse.SelectSingleNode("//ns2:Correcao", ns);
        XmlNode numero = xmlResponse.SelectSingleNode("//ns2:Numero", ns);
        XmlNode codigoVerificacao = xmlResponse.SelectSingleNode("//ns2:CodigoVerificacao", ns);
        XmlNode data = xmlResponse.SelectSingleNode("//ns2:DataEmissao", ns);
        XmlNode outras = xmlResponse.SelectSingleNode("//ns2:Outras", ns);
        foreach (XmlNode node in xmlResponse.SelectNodes("//ns2:InfNfse", ns))
        {
            Id = (node.Attributes["Id"].Value);
        }
        try
        {
            cod = codigo.InnerText;
            msgm = mensagem.InnerText;
            cor = correcao.InnerText;
        }
        catch
        {
            Numero = numero.InnerText;
            CodigoVerificacao = codigoVerificacao.InnerText;
        }
        return responseNode.InnerXml;

    }

    private static HttpWebRequest getWebRequest(string url, string method)
    {
        HttpWebRequest webRequest = (HttpWebRequest)HttpWebRequest.Create(url);
        webRequest.Timeout = 100000;
        webRequest.Headers.Add("SOAPAction", method);
        webRequest.ContentType = "text/xml; //charset=\"utf-8\"";
        webRequest.Accept = "text/xml";
        webRequest.Method = "POST";
        return webRequest;
    }

private string post(string url, string method, string xml, X509Certificate2 certificate, string numero)
    {
        try
        {
            XmlDocument doc = new XmlDocument();
            doc.Load(xml);

            HttpWebRequest webRequest = getWebRequest(url, method);
            webRequest.Proxy = HttpWebRequest.GetSystemWebProxy();
            webRequest.UseDefaultCredentials = true;
            webRequest.Proxy.Credentials = CredentialCache.DefaultCredentials;
            WebProxy myProxy = new WebProxy();
            Uri myUri = new Uri("http://192.168.0.3:3128");
            myProxy.Address = myUri;
            myProxy.Credentials = CredentialCache.DefaultCredentials;
            //webRequest.Proxy = new WebProxy(MyProxyHostString, MyProxyPort);
            webRequest.Proxy = myProxy;
            webRequest.ClientCertificates.Add(certificate);

            montaEnvelope(webRequest, doc, numero);
            return getSoapResponse(webRequest);
        }

        catch (WebException webex)
        {
            WebResponse errResp = webex.Response;
            using (Stream respStream = errResp.GetResponseStream())
            {
                StreamReader reader = new StreamReader(respStream);
                msgm = reader.ReadToEnd();
                cod = "Erro";
            }
            return msgm;
        }
        //}
        //catch (Exception ex)
        //{
        //    return null;
        //}
    }

Não consigo ter outro retorno, o que estou fazendo de errado ?
Vou colocar o xml.
<?xml version="1.0" encoding="utf-8"?><soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:e="http://www.betha.com.br/e-nota-contribuinte-ws"><soapenv:Header /><soapenv:Body><e:gerarNfse><nfseCabecMsg><cabecalho xmlns="http://www.betha.com.br/e-nota-contribuinte-ws" versao="2.02"><versaoDados>2.02</versaoDados></cabecalho></nfseCabecMsg><nfseDadosMsg><soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:e="http://www.betha.com.br/e-nota-contribuinte-ws"><soapenv:Header /><soapenv:Body><e:gerarNfse><nfseCabecMsg><cabecalho xmlns="http://www.betha.com.br/e-nota-contribuinte-ws" versao="2.02"><versaoDados>2.02</versaoDados></cabecalho></nfseCabecMsg><nfseDadosMsg><GerarNfseEnvio xmlns="http://www.betha.com.br/e-nota-contribuinte-ws"><Rps><InfDeclaracaoPrestacaoServico Id="RPS000000000008963"><Rps><IdentificacaoRps><Numero>8963</Numero><Serie>999</Serie><Tipo>1</Tipo></IdentificacaoRps><DataEmissao>2018-12-17</DataEmissao><Status>1</Status></Rps><Competencia>2018-12-17</Competencia><Servico><Valores><ValorServicos>29</ValorServicos><ValorDeducoes>0.00</ValorDeducoes><ValorIss>0.87</ValorIss><Aliquota>3</Aliquota><DescontoIncondicionado>0</DescontoIncondicionado><DescontoCondicionado>0</DescontoCondicionado></Valores><IssRetido>2</IssRetido><ItemListaServico>0107</ItemListaServico><Discriminacao>Descricao 62</Discriminacao><CodigoMunicipio>0</CodigoMunicipio><ExigibilidadeISS>1</ExigibilidadeISS><MunicipioIncidencia>3107109</MunicipioIncidencia></Servico><Prestador><CpfCnpj><Cnpj>07652413000108</Cnpj></CpfCnpj><InscricaoMunicipal>5467630</InscricaoMunicipal></Prestador><Tomador><IdentificacaoTomador><CpfCnpj><Cpf>08297163008</Cpf></CpfCnpj></IdentificacaoTomador><RazaoSocial>Teste Mariana</RazaoSocial><Endereco><Endereco>RUA JARBAS PIMENTA</Endereco><Numero>514</Numero><Complemento>complemento cobrancaaeAaO</Complemento><Bairro>NOVA ERA</Bairro><CodigoMunicipio>3504800</CodigoMunicipio><Uf>SP</Uf><Cep>37170000</Cep></Endereco><Contato><Telefone>3538511836</Telefone><Email>marianac_costa@live.com</Email></Contato></Tomador><RegimeEspecialTributacao>1</RegimeEspecialTributacao><OptanteSimplesNacional>1</OptanteSimplesNacional><IncentivoFiscal>1</IncentivoFiscal></InfDeclaracaoPrestacaoServico><Signature xmlns="http://www.w3.org/2000/09/xmldsig#"><SignedInfo><CanonicalizationMethod Algorithm="http://www.w3.org/TR/2001/REC-xml-c14n-20010315" /><SignatureMethod Algorithm="http://www.w3.org/2000/09/xmldsig#rsa-sha1" /><Reference URI="#RPS000000000008963"><Transforms><Transform Algorithm="http://www.w3.org/2000/09/xmldsig#enveloped-signature" /><Transform Algorithm="http://www.w3.org/TR/2001/REC-xml-c14n-20010315" /></Transforms><DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1" /><DigestValue>XXvtJY4dUMxIcMWw+yUbSHNkfUE=</DigestValue></Reference></SignedInfo><SignatureValue>XoWPqLsjsojfsjFs6ZXXc/bGb0Vy7EcFc5QOe/ja88Nhi3dKV76LCogTz4GjYD0tByovmXixCfez3sSuyijeTTryj8vTAsQKBgDj/PFD08W/fJsE+zmOPxYCqAE2m2yBZD++afT3DOYDqYxkwGpF/o5YSaMAA3G1ilUvfPUqlq3VmT6NIiD1ffvZsh02TpTZMz35JTb0rptX/5tsswAaWJTwrMAljY23iibD4Pkl+fGXFKDHXWdHv1XSiSvSSK3Niost02OxqfxwWQedspFGgXnmpx3fee7qSyHPKavZu64KUvy8jNDKJkUNYg/V/DAe3ShQPbZrbUW6KemN6BM76A==</SignatureValue><KeyInfo><X509Data><X509Certificate>MIIIETCCBfmgAwIBAgIIU+7gQoD+KpcwDQYJKoZIhvcNAQELBQAwdDELMAkGA1UEBhMCQlIxEzARBgNVBAoTCklDUC1CcmFzaWwxNjA0BgNVBAsTLVNlY3JldGFyaWEgZGEgUmVjZWl0YSBGZWRlcmFsIGRvIEJyYXNpbCAtIFJGQjEYMBYGA1UEAxMPQUMgRE9DQ0xPVUQgUkZCMB4XDTE3MDMzMDEzMTMxMFoXDTIwMDMzMDEzMTMxMFowgeMxCzAJBgNVBAYTAkJSMRMwEQYDVQQKEwpJQ1AtQnJhc2lsMQswCQYDVQQIEwJNRzEWMBQGA1UEBxMNQk9BIEVTUEVSQU5DQTE2MDQGA1UECxMtU2VjcmV0YXJpYSBkYSBSZWNlaXRhIEZlZGVyYWwgZG8gQnJhc2lsIC0gUkZCMRYwFAYDVQQLEw1SRkIgZS1DTlBKIEEzMRQwEgYDVQQLEwtBUiBET0NDTE9VRDE0MDIGA1UEAxMrQ1JJU1RJQU5PIE1JR1VFTCBEQSBDT1NUQSBNRTowNzY1MjQxMzAwMDEwODCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAM0byY+OsP6+L8oJkNXJ/NqZDmsa9z/q29pPWa9fSetq5MDAN4l0X9/0L4AuVeGgCZOZF8FLKAOS8QgxQ6FUxTtQIkKp+kNMYC1NBONaQMdKKH7Uvdhssft5VAGvm6mRMG9HWSbFLCEyS3tHYnfTnzsQYvD2mAuWGIbkSQwtfaRJLal6NTzHO7TOkmIfBGt/MRHd7SZXQpTRE74hAIwwFArmJ4OhAgiBvU3/8uj2CPCK1bx/rRmbU7gbGEAPvG1aatPeo3iiFg/1egXJixWw1UCOS2Dr4g5tjoUVqiVgaxKVO52oF87DesP6hMeCS+FpsQhsaZtJis+b4pj1XmalO6UCAwEAAaOCAzUwggMxMB8GA1UdIwQYMBaAFDVIKApGqmUTTJWPHVJhlb3nE+OMMA4GA1UdDwEB/wQEAwIF4DBwBgNVHSAEaTBnMGUGBmBMAQIDNzBbMFkGCCsGAQUFBwIBFk1odHRwOi8vcmVwb3NpdG9yaW8uYWNkb2NjbG91ZC5jb20uYnIvYWMtZG9jY2xvdWRyZmIvYWMtZG9jY2xvdWQtcmZiLXBjLWEzLnBkZjCCAQUGA1UdHwSB/TCB+jBSoFCgToZMaHR0cDovL3JlcG9zaXRvcmlvLmFjZG9jY2xvdWQuY29tLmJyL2FjLWRvY2Nsb3VkcmZiL2xjci1hYy1kb2NjbG91ZHJmYnYyLmNybDBToFGgT4ZNaHR0cDovL3JlcG9zaXRvcmlvMi5hY2RvY2Nsb3VkLmNvbS5ici9hYy1kb2NjbG91ZHJmYi9sY3ItYWMtZG9jY2xvdWRyZmJ2Mi5jcmwwT6BNoEuGSWh0dHA6Ly9yZXBvc2l0b3Jpby5pY3BicmFzaWwuZ292LmJyL2xjci9kb2NjbG91ZC9sY3ItYWMtZG9jY2xvdWRyZmJ2Mi5jcmwwgZEGCCsGAQUFBwEBBIGEMIGBMFQGCCsGAQUFBzAChkhodHRwOi8vcmVwb3NpdG9yaW8uYWNkb2NjbG91ZC5jb20uYnIvYWMtZG9jY2xvdWRyZmIvYWMtZG9jY2xvdWRyZmJ2Mi5wN2IwKQYIKwYBBQUHMAGGHWh0dHA6Ly9vY3NwLmFjZG9jY2xvdWQuY29tLmJyMIHEBgNVHREEgbwwgbmBHk1BU1RFUlBPTlRPQE1BU1RFUlBPTlRPLkNPTS5CUqAkBgVgTAEDAqAbExlDUklTVElBTk8gTUlHVUVMIERBIENPU1RBoBkGBWBMAQMDoBATDjA3NjUyNDEzMDAwMTA4oD0GBWBMAQMEoDQTMjI1MDkxOTc5MDUzNDIzMzc2NzQwMDAwMDAwMDAwMDAwMDAwMDBNODAyMDExOFNTUE1HoBcGBWBMAQMHoA4TDDAwMDAwMDAwMDAwMDAdBgNVHSUEFjAUBggrBgEFBQcDAgYIKwYBBQUHAwQwCQYDVR0TBAIwADANBgkqhkiG9w0BAQsFAAOCAgEAKKTWmCZPTy+2qXTzY/mWd5dey5HAG09Ja5vIJc+vg+UTL//dCXsQMkWezcVFW2TZS1DxWEXda96ICn8Uadg2+Ilhr/qNyjburSlMJTxgKqXXWFmMyrPLsmZqC87Ofg2f7CyOgNRYnEEbH+m/r8UV3MYGnyZlAqLScRYdKENTordLJi/zzXIXJBwvlXS/5C/GFTqnat97qOTJ13KQD+tyIa4/+Vo2EuRUiliLa4/leeIst5mUmkQgAKxXOvWCtsOa6DKV2dyV+BSc7XeD4LTpyo3aZ8E7g7WuR2S8GPPEO9evwucqpeHm03gpi4UphcoLiJ+HJZC2gTyBgxGzPf+4W1EWRpaivhWXAwTHsie+PRsFg4ocYbwf2f4dbDMnrweaBIhugwofSFmuUocN8i7wbWuHb/bz4fIOLLEuJZRRUG8LO2w86gF3PO9U9UURYO8FWbeFtUIuXBEkUmSXdT6Nhf4b1zI2nu7ygN3HnkZR2bnCkUefOQBE47U7K3b3jwEVu0yKEKAXTtu8nYZ1WoKikkIkp/9+WpFUYZcy+cz/xixYO97cvlWpKq9IJmx5OPBBXBOMoxSqrLFs/Z9QdFwCmCGJo0m8qO4qRTXcvG0TXbI45+xK/WwArpEzBiY8beYcN+glsjlhoO+jqv/zhOKv+n66CRINgEDV+PCs535JEUw=</X509Certificate></X509Data></KeyInfo></Signature></Rps></GerarNfseEnvio></nfseDadosMsg></e:gerarNfse></soapenv:Body></soapenv:Envelope></nfseDadosMsg></e:gerarNfse></soapenv:Body></soapenv:Envelope>

A: Está fazendo complicado demais para usar esse serviço. Se me permite, confira a documentação em: https://e-gov.betha.com.br/e-nota-test/ambienteteste.faces. Lá tem os manuais e exemplos dos xmls esperados.
Segue uma nova abordagem para consumir esse serviço:
Adicione a referência do serviço no visual studio para o wsdl:
http://e-gov.betha.com.br/e-nota-contribuinte-ws/nfseWS?wsdl
No Soluction Explorer clique com o botão direito no projeto e vá em Add em seguida em Service Reference.
Em Address informe a URL do WSDL e clique em Go.
Em Namespace informe o nome desejado. Ex.: wsNfse
Clique em OK.
Após isso, veja o exemplo abaixo de como chamar o webservice:
(obs: é claro que está simplificado para teste, demonstrando o xml esperado conforme a documentação.)
using (var cli = new wsNfse.NfseWSClient())
            {
                string _nfseCabecMsg = $@"
                     < cabecalho xmlns = ""http://www.betha.com.br/e-nota-contribuinte-ws"" versao = ""2.02"" >< versaoDados > 2.02 </ versaoDados ></ cabecalho >
                    ";
                string _nfseDadosMsg = $@"
                    <GerarNfseEnvio xmlns = ""http://www.betha.com.br/e-nota-contribuinte-ws"">
                        <Rps>
                            <InfDeclaracaoPrestacaoServico  Id=""lote"">
                                <Rps>
                                    <IdentificacaoRps>
                                        <Numero></Numero>
                                        <Serie></Serie>
                                        <Tipo></Tipo>
                                    </IdentificacaoRps>
                                    <DataEmissao></DataEmissao>
                                    <Status></Status>
                                    <RpsSubstituido>
                                        <Numero></Numero>
                                        <Serie></Serie>
                                        <Tipo></Tipo>
                                    </RpsSubstituido>
                                </Rps>
                                <Competencia></Competencia>
                                <Servico>
                                    <Valores>
                                        <ValorServicos></ValorServicos>
                                        <ValorDeducoes></ValorDeducoes>
                                        <ValorPis></ValorPis>
                                        <ValorCofins></ValorCofins>
                                        <ValorInss></ValorInss>
                                        <ValorIr></ValorIr>
                                        <ValorCsll></ValorCsll>
                                        <OutrasRetencoes></OutrasRetencoes>
                                        <ValorIss></ValorIss>
                                        <Aliquota></Aliquota>
                                        <DescontoIncondicionado></DescontoIncondicionado>
                                        <DescontoCondicionado></DescontoCondicionado>
                                    </Valores>
                                    <IssRetido></IssRetido>
                                    <ResponsavelRetencao></ResponsavelRetencao>
                                    <ItemListaServico></ItemListaServico>
                                    <CodigoCnae></CodigoCnae>
                                    <CodigoTributacaoMunicipio></CodigoTributacaoMunicipio>
                                    <Discriminacao></Discriminacao>
                                    <CodigoMunicipio></CodigoMunicipio>
                                    <CodigoPais></CodigoPais>
                                    <ExigibilidadeIss></ExigibilidadeIss>
                                    <MunicipioIncidencia></MunicipioIncidencia>
                                    <NumeroProcesso></NumeroProcesso>
                                </Servico>
                                <Prestador>
                                    <CpfCnpj>
                                        <Cnpj></Cnpj>
                                    </CpfCnpj>
                                    <InscricaoMunicipal></InscricaoMunicipal>
                                </Prestador>
                                <Tomador>
                                    <IdentificacaoTomador>
                                        <CpfCnpj>
                                            <Cnpj></Cnpj>
                                        </CpfCnpj>
                                        <InscricaoMunicipal></InscricaoMunicipal>
                                    </IdentificacaoTomador>
                                    <RazaoSocial></RazaoSocial>
                                    <Endereco>
                                        <Endereco></Endereco>
                                        <Numero></Numero>
                                        <Complemento></Complemento>
                                        <Bairro></Bairro>
                                        <CodigoMunicipio></CodigoMunicipio>
                                        <Uf></Uf>
                                        <CodigoPais></CodigoPais>
                                        <Cep></Cep>
                                    </Endereco>
                                    <Contato>
                                        <Telefone></Telefone>
                                        <Email></Email>
                                    </Contato>
                                </Tomador>
                                <Intermediario>
                                    <IdentificacaoIntermediario>
                                        <CpfCnpj>
                                            <Cnpj></Cnpj>
                                        </CpfCnpj>
                                        <InscricaoMunicipal></InscricaoMunicipal>
                                    </IdentificacaoIntermediario>
                                    <RazaoSocial></RazaoSocial>
                                </Intermediario>
                                <ConstrucaoCivil>
                                    <CodigoObra></CodigoObra>
                                    <Art></Art>
                                </ConstrucaoCivil>
                                <RegimeEspecialTributacao></RegimeEspecialTributacao>
                                <OptanteSimplesNacional></OptanteSimplesNacional>
                                <IncentivoFiscal></IncentivoFiscal>
                            </InfDeclaracaoPrestacaoServico>
                        </Rps>
                    </GerarNfseEnvio>
                ";

                var retorno = cli.GerarNfse(new wsNfse.GerarNfse { nfseCabecMsg = _nfseCabecMsg, nfseDadosMsg = _nfseDadosMsg });
            }

Verifique a variável string de retorno!
Poderia também criar classes de acordo com o objetos XML e serializando os objetos para preencher os parâmetros de entrada em string e a string de retorno em objeto.
Segue duas funções úteis para isso:
/// <summary>
/// Serializa um objeto para uma string no formato XML apartir do objeto referênciado.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="value">Objeto</param>
/// <example>string xmlString = meuObj.XmlSerialize();</example>
/// <returns>String em formato XML do objeto referênciado</returns>
public static string ToXml<T>(this T value)
{
    if (value == null)
        return string.Empty;

    var xmlserializer = new System.Xml.Serialization.XmlSerializer(typeof(T));

    using (var stringWriter = new StringWriter())
    {
        using (var writer = System.Xml.XmlWriter.Create(stringWriter))
        {
            xmlserializer.Serialize(writer, value);
            return stringWriter.ToString();
        }
    }
}

/// <summary>
/// Deserializa uma string em formato XML em um objeto do tipo especificado.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="value">XML string</param>
/// <example>MinhaClasse obj = xmlString.XmlToObject<MinhaClasse>();</example>
/// <returns>Objeto do tipo especificado</returns>
public static T XmlToObject<T>(this string value)
{
    System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(typeof(T));
    using (StringReader rdr = new StringReader(value))
    {
        return (T)serializer.Deserialize(rdr);
    }
}

Espero ter ajudado!


text:
Q: Ruby on Rails can use remote-true without helpers? Can I use remote->true without helper?and set its interval?

A: First of all: use the link generating helper like:
<%= link_to 'Anywhere', anywhere_path, remote: true %>

which generates the correct HTML markup for you. Sure you don't need the helper, but you want to use it. ;)
Otherwise you would write this yourself:
<a href="<%= anywhere_path %>" data-remote="true">Anywhere

A: Rails UJS
remote: true is nothing more than a way to set a data attribute in your DOM elements:
<form accept-charset="UTF-8" action="/articles" class="new_article" data-remote="true" id="new_article" method="post">
  ...
</form>

It basically calls the Rails UJS "driver", which is nothing more than a way to call standardized javascript functionality out of scope of the typical application setup.
You can see the UJS "ajax" driver source here

Integration
Your question is regarding whether you need the "helpers" to invoke this technology, the short answer is "yes".
The Rails UJS driver is only going to work if you have an element which submits. The way that JS works is to "bind" events to elements, which then proceeds to fire the bound function if you trigger that event.
In the case of "typical" JS (JQuery), you'll be able to set up an Ajax request by the following:
#app/assets/javascripts/application.js
$(document).on("click", ".your_button", function(){
   $.ajax({
      ...
   });
});

By the way, the Rails UJS basically does this:
$(document).on("click", "a[data-remote]", function(){
    $.ajax({
        ....
    });
});

Now, the most important thing to note here is how both of these implementations bind your "click" / "submit" event to an ajax call. This is the basis of Javascript - any time you want to invoke the action, you have to bind to an event

Map
In respect to your question, the answer is that you will be best using your own ajax call unless you have a clear "action" to be called. What this means if you want to use something like long-polling, you'll have to call ajax yourself.
If you want to create a form, link or another element which will either be clicked, or be submitted, you'll be able to call the Rails UJS remote: true method.


text:
Q: How can I display the output of the parameters I have set from a child class? I need help accessing the variables I have inputted using the child class. I made an object for the child class in my main class, however, I do not know how will I have access to the inputs I have entered and display them at the end of the code.
public abstract class player {
    public abstract String name(String name);
    public abstract void race(int race);
    public abstract int[] getStatArray();
}

import java.util.Scanner;
public class childplayer extends player {
    Scanner sc = new Scanner(System.in);

    public String name(String name) {
        System.out.print("Enter your name: ");
        name = sc.nextLine();
        return name;
    }

    public void race(int race) {
        System.out.println("Race options: ");
        System.out.println("\t 1 - Human \n\t 2 - Elf \n\t 3 - Orc \n\t 4 - Angel \n\t 5 - Demon");
        System.out.print("Enter character's race: ");
        race = sc.nextInt();
        if((race>5)||(race<1)) {
            while ((race>5)||(race<1)) {
                System.out.print("Enter character's race: ");
                race = sc.nextInt();
            }
        }System.out.println(" ");
    }

    public int[] getStatArray(){
        int [] stat = new int [3];
        int x = 0, y = 0, pts = 0;
        System.out.println("Enter character's stats.");
        while(y<3) {
            System.out.print("Enter value: ");
            x = sc.nextInt();
            y++;
            pts = pts + x;
        }
        int i = 0;
        if(pts>10) {
            System.out.println("Invalid input. Try again.");
            while(i<3) {
                System.out.print("Enter value: ");
                x = sc.nextInt();
                i++;
                pts = pts + x;
            }
        }else {
            stat[i] = x;
            i++;
        }

        return stat;
    }

}

A: If you want to keep the values to use later then you need to store them. The best way to do this is simply with a class variable like so:
public class Childplayer extends Player {

    //Create class variables that store the values
    String name = "";
    int race = -1;
    int[] stat = new int [3];

Then we just modify your methods to use these variables, for example:
public String name(String name) {

    //Process the name
    if(someCondition){
        name = name +" Smith"
    }

    //Saved the passed in variable to the class variable `this.name`
    this.name = name;

    return this.name;
}

And another example:
public void race(int race) {
    //Saved the passed in variable to the class variable `this.race`
    this.race = race:
}

Then to get the information later we simply use:
//Earlier in the code
Childplayer playerA = new Childplayer();

//Some code here
//...

//Later in the code we can get the values
String name = playerA.name;
int storedRaceFromEarlier = playerA.race;

I strongly recommend making use of a constructor method to populate the class data. I have simplified the code and value checking for the sake of this example:
//Note that Java naming conventions require that classes should always have a capital letter at the start, I have fixed this in my example
public abstract class Player {
    //Example getter abstract methods that must be implimented
    public abstract String getName();
    public abstract int getRace();
    public abstract int[] getStatArray();
}

//Note that Java naming conventions require that classes should always have a capital letter at the start, I have fixed this in my example
public class Childplayer extends Player {
    Scanner sc = new Scanner(System.in);

    //Create class variables that store the values
    String name = "";
    int race = -1;
    int[] stat = new int [3];

    //Constructor method with exactly the same name as the class "Childplayer"
    //This method should be responsible for creating the object and populating data
    Childplayer(){
        //Set name
        System.out.print("Enter your name: ");
        name(sc.nextLine());
        System.out.print("Name set as " + name + "\r\n");

        //Set race
        System.out.println("Race options: ");
        System.out.println("\t 1 - Human \n\t 2 - Elf \n\t 3 - Orc \n\t 4 - Angel \n\t 5 - Demon");
        int result = -1;
        while ((result>5)||(result<1)) {
            System.out.print("Enter character's race: ");
            result = sc.nextInt();
        }
        //Set the race with the abstract method
        race(result);
        System.out.print("Race set as " + race + "\r\n");

        System.out.println("Enter character's stats.");
        int i = 0;
        while(i<3) {
            System.out.print("Enter stat value: ");
            //Save the stat to the class variable
            stat[i] = sc.nextInt();
            i++;
        }
    }

    //Abstract methods implemented to return the correct values
    public String getName(){
        return name;
    }

    public int getRace(){
        return race;
    }
    public int[] getStatArray(){
        return stat;
    }
}


text:
Q: Pandas DataFrame - splitting a column into 2 columns, based on another column struggling with this one using a pandas dataframe, I have data as follows:
Animal     Nationality   Type     Value
Leopard    India         Age      4.0
Elephant   India         Age      12.0
Leopard    India         Speed    30.0
Elephant   India         Speed    3.0
Leopard    China         Age      5.0
Leopard    China         Speed    27.0

I want to effectively merge the data into a dataframe as follows:
Animal     Nationality    Age      Speed
Leopard    India          4.0      30.0
Elephant   India          12.0     3.0
Leopard    China          5.0      27.0

I have looked up semi-similar problems, but have had no joy, I think due to the nature of changing the size of the dataframe, any help would be much appreciated.
Thanks in advance.

A: Use DataFrame.pivot_table or DataFrame.pivot:
new_df=df.pivot_table(index=['Animal','Nationality'],columns='Type',values='Value')
print(new_df)

Type                   Age  Speed
Animal   Nationality
Elephant India        12.0    3.0
Leopard  China         5.0   27.0
         India         4.0   30.0

new_df.reset_index(inplace=True)
print(new_df)

Type    Animal Nationality   Age  Speed
0     Elephant       India  12.0    3.0
1      Leopard       China   5.0   27.0
2      Leopard       India   4.0   30.0


text:
Q: Convergence in Kolmogorov distance Sequence of random variables $\left\{X_n\right\}_{n=1}^\infty$ converge to random variable $X$ in Kolmogorov distance if
$$\lim\limits_{n\to \infty}\left(\sup\limits_{x\in\mathbb{R}}|F_n(x)-G(x)|\right)=0,$$
where $F_n$ is distributive function of random variable $X_n$ and $G$ is distributive function of random variable $X$.
I know that convergence in Kolmogorov distance implies convergence in distribution (converge weakly, or converge in law). Also I know that convergence in distribution does not imply convergence in Kolmogorov distance. Somewhere I have been reading that convergence in distribution imply convergence in Kolmogorov distance when distribution function $G$ is absolutely continuous.
But I cannot find example when convergence in distribution is hold but convergence in Kolmogorov distance is not. Any help will be appreciated. Thanks

A: This is not really about convergence of random variables, but rather convergence in functions. Convergence in distribution is essentially point-wise convergence, whereas convergence in Kolmogorov distance is uniform convergence.
For the example, consider $G(x)$ to be the Heaviside step function (the CDF of the zero random variable), and let $F_{n}(x)$ be the CDF of the normal distribution with mean zero and variance $1/n$, which essentially looks like a logistic curve.
Then $F_{n}(x)$ converges pointwise to $G(x)$. This is clear for all $x \not = 0$. For $x = 0$, we can either define $G(0) = 1/2$ or just ignore it, since we don't actually need pointwise convergence for points where $G$ is discontinuous.
In contrast, not matter how large we choose $n$,
$$ \sup_{x} |F_{n}(x) - G(x)| = 1/2$$
since for $x$ slightly greater than zero, $G(x) = 1$ yet $F_{n}(x) \approx 1/2$. Therefore $F_{n}(x)$ does not converge to $G(x)$ in Kolmogorov distance.


text:
Q: Login to npm with multiple scopes npm allows to assign a scope to a registry at login like this:
npm login --scope=@my-company-name --registry=http://your-server-address:8080

Is it also possible to assign multiple scopes at a particular login?
Because docs say:

Scopes have a many-to-one relationship with registries: one registry can host multiple scopes, but a scope only ever points to one registry.

A: The solution is to login multiple times using different scopes:
npm login --scope=@scope1 --registry=http://your-server-address:8080
npm login --scope=@scope2 --registry=http://your-server-address:8080

After this you can use packages scoped with @scope1 and @scope2.


text:
Q: WPF/MVVM Wrap panel orientation I'd like to display basically a matrix of buttons, the number of buttons change in runtime.
My problem is that I want them to be next to each other to fill up all the space I give them. I thought WrapPanel is the perfect way to do that but it puts the buttons under each other and I have no idea how to solve it.
    <Grid>
    <WrapPanel Width="250" Height="50" Orientation="Horizontal" Margin="543,442,73,162"  >
        <ItemsControl ItemsSource="{Binding States}"   >
            <ItemsControl.ItemTemplate>
                <DataTemplate  >
                    <Button Width="50" Height="25"  Content="{Binding StateName}" Padding="0"  ></Button>
                </DataTemplate>
            </ItemsControl.ItemTemplate>
        </ItemsControl>
    </WrapPanel>...</Grid>

States is a list of Items that contains a name and a ID number. If i want to add or remove buttons I modify the list. So the buttons appear but in vertical order and they go beyond the limits of the WrapPanel so if it is not big enough only some appears. They only use 50 width from the 250 and more then the 50 height. In this case if I put 5 buttons in it only shows 2 of them.

A: Don't wrap ItemsControl inside WrapPanel. Instead set it as ItemsPanel of ItemsControl.
<ItemsControl ItemsSource="{Binding States}">
   <ItemsControl.ItemTemplate>
      <DataTemplate>
        <Button Width="50" Height="25"  Content="{Binding StateName}"
                Padding="0"/>
      </DataTemplate>
    </ItemsControl.ItemTemplate>
   <ItemsControl.ItemsPanel>
      <ItemsPanelTemplate>
         <WrapPanel/>
      </ItemsPanelTemplate>
   </ItemsControl.ItemsPanel>
</ItemsControl>


text:
Q: AWS EC2 default password I'm following this tutorial to host a website with an apache server. The thing is that the last step tells my to do
service apache2 reload

But it asks me for a password. I don't remember inserting a password for this VM, just the .pem I used to log in.
Is there a default password? Or how can I solve this? Sorry if this is basic, but the most complex thing I've done with servers is with wamp and xamp
Thanks!

A: Based on the comments, the solution was to use sudo:
sudo service apache2 reload