text:
Q: Transform text selected in a Textbox selected with a keyboard shortcut I want to transform the selected text in a TextBox when I press a shortcut, as shown in the picture (the example is adding tags but it could be a different change):

How do I do this?

A: In textbox selected event you should handle following insructions:

*

*Get text from textbox

*Save it to array or something like that

*Give HTML tags and give array inside HTML tags

*Set it to screen again

A: You can use the TextBox.KeyUp event
private void textBox1_KeyUp(object sender, KeyEventArgs e)
{
    if (e.Control && e.KeyValue == 49)
    {
        if (textBox1.SelectionLength > 0)
        {
            textBox1.SelectedText = String.Format("<h1>{0}</h1>", textBox1.SelectedText);
        }
    }
}


text:
Q: парсинг 1 track.ru Для начала хочу получить код html странички по треку, но при выполнении всех махинаций...текст с датами и местами отслеживания посылки на странице отсутствует.
import requests
from bs4 import BeautifulSoup
from selenium import webdriver
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.common.exceptions import TimeoutException
import time
import re

chromeOptions = webdriver.ChromeOptions()
prefs = {'profile.managed_default_content_settings.images':2}
chromeOptions.add_experimental_option("prefs", prefs)
driver =
webdriver.Chrome("C:\\Users\\Yres\\Downloads\\chromedriver_win32\\
chromedriver.exe")
#driver = webdriver.Chrome(chrome_options=chromeOptions)
driver.get('https://1track.ru/tracking/RU341961010HK')

time.sleep(30)
#driver.headless =True
#element = WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.CLASS_NAME, "modal-dialog")))
#driver.find_element_by_class_name ("btn ").click()

driver.find_element_by_class_name ("close").click()
driver.get('https://1track.ru/tracking/RU341961010HK')
source = driver.page_source
#driver.quit()

soup = BeautifulSoup(source, "html.parser")
print(soup)

#s = requests.Session()

redpajama_set_name: RedPajamaStackExchange


text:
Q: Why true and false can be strings in Javascript Unlike many programming languages, true and false in Javascript can be 'true' and 'false'.
Why can they be strings?

A: They are not strings. true and false exists as well, as a primitive boolean type.
What is possible is to convert strings to boolean values.
As can be seen here:
http://jsfiddle.net/M6CT2/3/
You only get one true output because it is a non-empty string so it is true, but the boolean is different from the string.
The casting to boolean also returns true when the string is 'false' because, as mentioned above, it is non-empty.

A: $ node
> typeof(true) 'boolean'
> typeof(false) 'boolean'
>


text:
Q: Android -- Live wallpaper OPENGL I'm created an OPENGL activity that it's a 3D Cube and moves and does different things. How can I use this OPENGL activity to use it like an android wallpaper?
Could you pass me links or different stuff?
Thanks

A: Some links:
http://www.rbgrn.net/content/354-glsurfaceview-adapted-3d-live-wallpapers
http://www.learnopengles.com/how-to-use-opengl-es-2-in-an-android-live-wallpaper/
http://mindtherobot.com/blog/376/android-ui-making-a-live-wallpaper-fire-simulation/


text:
Q: Linux - cleanup: find large groups of files by similar filenames Question:
on a Linux File System, I am trying to locate large numbers of files with similar name patterns; for cleanup. The issue here is that I have no idea what such patterns would look like; this is what the script should show us.
Example:
e.g., a typical outcome of the script could be:
"we have accumulated around 10k files looking like 'create_some_kind_of_log_*.log'
and 19k files matching '/some_kind_of_dir/daily_blah_file*.dat'"
Before we would not be 'aware' that these files are being accumulated in such large numbers; they were under the radar because of their small size.
Any input would be appreciated!
Cheers
Edit
Maybe a workaround would be to just look for directories where there are a large number of files; this could also help in the analysis.
Thanks!!

A: I've modified the answer in case it is of use. This will produce a list of directories ranked by the number of files each holds.
find . -type d | xargs ls -dl | awk '{print $2, $9}' > f.tmp
sort -nr f.tmp


text:
Q: App Crash after signing app with resource shrinking and Proguard This is the first time I got this type of exception while building a signed APK. I searched a lot but could not find any useful information to fix this.
Any information will help me a lot. Because I already spend a lot of time fixing this. I also want to reduce the APK size.
I am creating a signed APK with below release settings and proguard
release {
    minifyEnabled true
    shrinkResources true
    proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}

Proguard:
-dontwarn okhttp3.internal.platform.*
-dontwarn java.nio.file.*
-dontwarn org.codehaus.mojo.animal_sniffer.IgnoreJRERequirement
-dontwarn okio.**
-dontwarn retrofit2.Platform$Java8
-dontwarn javax.annotation.**
-dontwarn kotlin.Unit
-dontwarn retrofit2.-KotlinExtensions

After building a signed APK, I tried testing that and found that google and facebook login is not working (I am not using any other way to log in) and also app crash when I open Privacy policy or Terms Activity which request an API endpoint using Retrofit 2.
implementation 'com.squareup.retrofit2:retrofit:2.5.0'
implementation 'com.squareup.retrofit2:converter-gson:2.5.0'

Below is the logcat of the crash.
2018-12-31 15:24:42.054 15126-15126/com.sathi E/UncaughtException: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.sathi.c.a.i$a.a()' on a null object reference
        at com.sathi.activities.PrivacyPolicyActivity$1.a(Unknown Source)
        at com.sathi.c.d$3.a(Unknown Source)
        at d.h$a$1$1.run(Unknown Source)
        at android.os.Handler.handleCallback(Handler.java:751)
        at android.os.Handler.dispatchMessage(Handler.java:95)
        at android.os.Looper.loop(Looper.java:154)
        at android.app.ActivityThread.main(ActivityThread.java:6776)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1496)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1386)
2018-12-31 15:24:42.281 15126-15126/com.sathi E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.sathi, PID: 15126
    java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.sathi.c.a.i$a.a()' on a null object reference
        at com.sathi.activities.PrivacyPolicyActivity$1.a(Unknown Source)
        at com.sathi.c.d$3.a(Unknown Source)
        at d.h$a$1$1.run(Unknown Source)
        at android.os.Handler.handleCallback(Handler.java:751)
        at android.os.Handler.dispatchMessage(Handler.java:95)
        at android.os.Looper.loop(Looper.java:154)
        at android.app.ActivityThread.main(ActivityThread.java:6776)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1496)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1386)

I don't know what is the cause of this exception. Any information will help. Thanks in advance!
Update:
These are the Java Compile Warning which I am getting while building a sign APK file without Proguard but keeping minifyEnabled true.

Answer:
Thanks to Reaz's Answer
The issue was the model class which I used to get the response from Retrofit
I added below line in my Proguard
-keepclassmembers class com.sathi.models.** { *; }

A: You need to keep the classes. Turning the warnings down will not keep the classes and will shrink accordingly by proguard. In that case, the libraries from Google or Facebook might behave incorrectly.
Same thing goes for the classes used to call the APIs. When you are trying to serialize the JSON data from your API response into a class, the class members should have the exact names where the values returned can be mapped correctly.
I am sharing the rules from my project for your reference. Hope that helps!
-keep class com.google.** { *; }
-keep class com.github.** { *; }
-keep class com.android.** { *; }
-keep class junit.** { *; }
-keep class com.example.com.mymodels.** { *; }
-keepclassmembers class com.example.com.mymodels.** { *; }

From your logcat, I think the model classes that you are using for parsing the responses from your API is causing the error. Can you please keep the classes and let me know if that crashes your program?


text:
Q: Quantum state - Probability of finding it in its initial state after a certain time.
Consider a normed quantum state $|\Psi(0)\rangle$ and let $\Delta_\Psi E\equiv \langle (\hat{H}-\langle\hat{H}\rangle_\Psi)^2\rangle_\Psi^{1/2}$ be the energy uncertainty.
a. Compute the probability that the system is still in state $|\Psi(0)\rangle$ after a time $\delta t$. (Meaning $|\langle\Psi(\delta t)|\Psi(0)\rangle|^2$.
b. Determine the energy uncertainty of a one-dimensional harmonic oscillator in the state $|n\rangle$, whereas $\hat{H}=\hbar \omega(\hat{N}+1/2)$ and $\hat{N}|n\rangle=n|n\rangle$.
c. Let $|\Psi(0)\rangle =1/\sqrt{2}(i|1\rangle-|3\rangle)$. What's the energy uncertainty of that state at time t=0 and when is the probability of it being still in the initial state after $\delta t$ less than 0.9?

Hello everyone,
I've been doing exercises from my workbook and I'm kinda stuck at this one (and I tried looking for a exercises manual of that book, but apparently there is none).
As far as a. goes I have no idea how to start there. I'm guessing this is a different expression for the Born Rule, but I never really understood how to apply on a particular problem (but I get the theory of the rule a bit, but apparently not enough).
As for b: I just thought of taking the expressions for H and N and plug it into the term for the energy uncertainty (I will leave out the hats):
$\Delta_\Psi E=\langle(\hbar\omega(N+1/2)-\langle(\hbar\omega(N+1/2))^2\rangle_\Psi\rangle_\Psi^{1/2}=\langle(\hbar\omega(N+1/2)-\hbar\omega(n+1/2))^2\rangle_\Psi^{1/2}=\langle(\hbar\omega N-\hbar\omega n\rangle_\Psi^{1/2}=\langle\hbar^2 \omega^2N^2-2\hbar^2\omega^2Nn+\hbar^2\omega^2n^2\rangle_\Psi^{1/2}=0.$
Is that right?
And I'm also lost on c. there.

A: $\newcommand{\ket}[1]{\lvert #1\rangle}$
$\newcommand{\bra}[1]{\langle #1\rvert}$
a. States evolve according to the Schroedinger equation, whose formal solution is given by exponentiating the Hamiltonian
$$ \Psi(t) = e^{-itH}\Psi(t=0) $$
Without further knowledge the best answer to the question is, that the "survival probability" is given by
$$ \lvert \bra{\Psi(0)}e^{-itH}\ket{\Psi(0)} \rvert^2 $$
If an eigenbasis $\{\ket{n}\}$of the Hamiltonian (this is a general feature and not constraint to the harmonic oscillator!) is known, one may expand states as linear combinations
$$ \Psi(t) = \sum_k a_k(t) \ket{k} $$
Inserting into the above expression yields
$$ \bra{\Psi(0)}e^{-itH}\ket{\Psi(0)} = \sum_k\sum_m a_k^* \bra{k}e^{-itE_m}a_m\ket{m} = \sum_m e^{-itE_m} \lvert a_m\rvert^2$$
where the $a_m$ are the expansion coefficients of $\Psi(0)$ and $E_m$ are the eigenvalues of $H$.
b. You are correct. The system is in an eigenstate of the Hamiltonian so the uncertainty in energy must vanish. Make sure you understand this intuitively!
c. At least for $t=0$ you should be able to do it. The calculation is pretty much identical to part b. Use the results from a. for the seconds part. You will get an implicit equation for $t$.
I could be more explicit, but I urge you to try for yourself. It's the only way to learn properly. Get some clarity on the mathematical structure of the theory. Pick up a (different) textbook if you're not content with the current material. If you're still really stuck then, ask back.


text:
Q: Authbind Permission Error when binding socket to port I'm running a Jupyter Notebook server on my Mac, and I'm trying to use authbind to run the notebook server on port 443. I've created the file /etc/authbind/byport/443, changed the ownership to the account running the server, and changed the permissions to 777. I've checked that the server is configured to run on port 443. However, when I run authbind jupyter notebook here are the last few lines of error output:
File "/Users/asianzhang/anaconda3/lib/python3.6/site-packages/tornado/netutil.py", line 197, in bind_sockets
    sock.bind(sockaddr)
PermissionError: [Errno 1] Operation not permitted
Also, I checked that nc could bind to port 443 without a problem.
Could you tell me what I'm doing wrong?

A: In order to use the port 443, you should create the file /etc/authbind/byport/443 instead of /etc/authbind/byport/80 and set ownership to the user running the server.

A: You need to add the flag --deep to the command


text:
Q: Rails respond_with outputting json and trying to call it as a method I created a simple api that responds with json. When I try to call it from a browser, I get the appropriate json response, but when I try to call it remotely from actionscript, it seems like it trys to call the json as if it is a method. This is the controller action:
  def matcher
    @conn = Connection.first
    if(@conn)
      respond_with({:conn => @conn, :status => :ok}.to_json)
    else
      respond_with({:status => :no_content}.to_json)
    end
  end

And this is the server response when it gets the call
Started POST "/connection/matcher/1.json" for 127.0.0.1 at 2010-11-11 22:57:24 -0800
  Processing by ConnectionsController#matcher as JSON
  Parameters: {"stratus_string"=>"bad1de003755eaa01a2920f0091d0dd66beaf2d34f651b09a578afb1b54e5686", "user_id"=>"1", "id"=>"1"}
  Connection Load (0.5ms)  SELECT "connections".* FROM "connections" LIMIT 1
Completed   in 24ms

NoMethodError (undefined method `{"conn":{"created_at":"2010-11-12T06:55:13Z","id":6,"stratus_string":"474735730abe81d7622d377bd0bf816c3f94721ece3eddf670bf3a74b1c2356c","updated_at":"2010-11-12T06:55:13Z","user_id":1},"status":"ok"}_url' for #<ConnectionsController:0x000001030e4350>):
  app/controllers/connections_controller.rb:7:in `matcher'

Why is rails trying to execute the json response? I don't get it.
UPDATE:
Here is the actionscript code that makes the call, although I don't see why it makes a difference.
        this.restService = new HTTPService();
        this.restService.url = "http://localhost:3000/connection/matcher/1.json";
        this.restService.method = "POST";

        this.restService.addEventListener("result", onRestResult);
        this.restService.addEventListener("fault", onRestFault);

        var request:Object = new Object();
        request.user_id = user;
        request.stratus_string = id;
        this.restService.cancel();
        this.restService.send(request);

Thanks!

A: I'm curious why it works in the browser. I would expect it to fail there as well.
Check the source for the respond_with:
def respond_with(*resources, &block)
  raise "In order to use respond_with, first you need to declare the formats your " <<
        "controller responds to in the class level" if self.class.mimes_for_respond_to.empty?

  if response = retrieve_response_from_mimes(&block)
    options = resources.extract_options!
    options.merge!(:default_response => response)
    (options.delete(:responder) || self.class.responder).call(self, resources, options)
  end
end

It's apparent why it tries to use it as a method.
I guess that you're stuck with:
respond_to do |format|
  format.html # some.html.erb
  format.json  { render :json => {:conn => @conn, :status => :ok}.to_json }
end

A: respond_with is a responder and takes an object as a parameter, not json.  It determines the appropriate response based on the action.
http://ryandaigle.com/articles/2009/8/10/what-s-new-in-edge-rails-default-restful-rendering
If you want to render your own json, you use respond_to.


text:
Q: Java Regex names (with spaces and special characters) I am building a program for a French soccer federation.
The names should be able to consist of "letters, spaces, ', - , è and é".
But I am having trouble finding a good regex for this?

A: Well, if there is no other rules for names, this piece of code should work:
String name = "namé";
Pattern pattern = Pattern.compile("[A-Za-z'èé\\s\\-]*");
Matcher matcher = pattern.matcher(name);
System.out.println(matcher.matches());


text:
Q: Strange C# Weak Reference Behaviour I'm spending some time learning how weak references work in C# and I came across this odd behaviour.
In the sample code below, the first test passes and the second fails.  It seems that you can't modify an instance of an object after construction but before creating a weak reference to it, without stopping the weak reference working in the expected manner.
private class Simple
{
    public Simple() { X = "Hello"; }
    public string X { get; set; }
}

[Test]
public void CreatingWeakReferenceBeforeModifying()
{
    var a = new Simple();
    var aRef = new WeakReference(a);
    a.X = "World";  // First modification to a after creating reference
    a = null;
    GC.Collect();
    Assert.That(aRef.IsAlive, Is.False);  // This assertion passes
}

[Test]
public void CreatingWeakReferenceAfterModifying()
{
    var b = new Simple {X = "World"};  // First mod to b before creating ref
    var bRef = new WeakReference(b);
    b = null;
    GC.Collect();
    Assert.That(bRef.IsAlive, Is.False);  // This assertion fails
}

Have I missed something here?

A: I suspect that you'd only see this in certain circumstances - it's particularly likely under a debug build, especially under the debugger.
This statement:
var b = new Simple {X = "World"};

is effectively:
var tmp = new Simple();
tmp.X = "World";
var b = tmp;

So even though you're setting b to null, there's still a local variable on the stack which has a reference to the object.
When running in an optimized scenario, I'd expect the GC to notice that the local variable will never be read again, and ignore it as a GC root - but possibly the way you're running it isn't letting the GC be that aggressive.


text:
Q: Enabling multiple Monobehaviour Components in a game object So, i'm trying to make a Multiplayer Game here with various game objects and scripts in c# for every object on the scene.
Thing is, when i spawn the player controlled objects every player shares control over scripts for each spawned gameObject on the scene, that means, when somebody presses "s" for example, every player moves backwards, and that's not how i want game to behave.
--So, the only way i know to solve this, is by spawning 'em with all their scripts (the components) disabled and enable 'em with another script on the gameobject, but i had to make a script to enable every component one by one, and it got really time comsuning to create or edit a new script every time i add a new one to new units n' so on, so i figured out i could do something like this script below.
 using System.Collections;
 using System.Collections.Generic;
 using UnityEngine;
 using UnityEngine.Networking;

 public class PlayerNetControl : NetworkBehaviour {

  public MonoBehaviour[] components2enable;

  public override void OnStartLocalPlayer()
  {
     foreach (MonoBehaviour cmp in components2enable)
     {
         cmp.enabled = true;
     }
  }
}

after doing this, i expected every "monobehaviour component" i added to the script using unity, to be enabled when for the player who controlled the game object only, but it does nothing, i check the components on the gameobject testing this out, they are all still disabled.
Also, is there any way for me to solve this problem in any other way than the one i know? if so, i would love you to illuminate me teaching me how.
Please help, i've started coding recently and i really need help with C#

A: Check for islocalplayer.
I think this solves all your problems.
https://docs.unity3d.com/ScriptReference/Networking.NetworkBehaviour-isLocalPlayer.html


text:
Q: Is it possible to make a local Chrome web app with offline sensible-data storage? I would like to create a 100% offline web app in Chrome that stores sensible data. Are there any security issues and if yes, which ones?
Thank you

A: You can't easily make offline apps that are based on file:// urls, you can however create apps that are hosted on a server that are made to work entirely offline.
Read about AppCache, LocalStorage, WebSQL, IndexedDB and FileSystem API's
If you really really don't want to host it, package your code up as a Packaged App


text:
Q: How to check the internet connectivity within the network in Android (using internet of some other device through HOTSPOT) I have a requirement where I want to check whether there is any internet connectivity when I am connected with the network.
For example, I have device A and device B.
Device A is connected with hotspot with that of device B. In device A, I get it as connected with Wi-Fi and in device B - one device connected with hotspot.
Now, if I remove the internet from device B (not the tethering hotspot), then in device A, it still shows - connected with Wi-Fi but there is no internet connectivity.
Classes like ConnectivityManager help in determining whether a device is connected with the network not about the internet connectivity.
I want to track this issue. Is there any way to achieve this?

A: It can be a ridiculous solution but i think also it could be real solution:
public boolean isOnline() {
    ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo netInfo = cm.getActiveNetworkInfo();
    if (netInfo != null && netInfo.isConnected()) {
        try {
            URL url = new URL("http://www.google.com");
            HttpURLConnection urlc = (HttpURLConnection) url.openConnection();
            urlc.setConnectTimeout(3000);
            urlc.connect();
            if (urlc.getResponseCode() == HttpURLConnection.HTTP_OK) {
                return new Boolean(true);
            }
        } catch (MalformedURLException mue) {
            // TODO Auto-generated catch block
            mue.printStackTrace();
        } catch (IOException ie) {
            // TODO Auto-generated catch block
            ie.printStackTrace();
        }
    }
    return false;
}

A: Try the below function to check your internet connection:
    public static boolean isInternetConnected(Context mContext) {

        try {
            ConnectivityManager connect = null;
            connect = (ConnectivityManager) mContext
                    .getSystemService(Context.CONNECTIVITY_SERVICE);

            if (connect != null) {
                NetworkInfo resultMobile = connect
                        .getNetworkInfo(ConnectivityManager.TYPE_MOBILE);

                NetworkInfo resultWifi = connect
                        .getNetworkInfo(ConnectivityManager.TYPE_WIFI);

                if ((resultMobile != null && resultMobile
                        .isConnectedOrConnecting())
                        || (resultWifi != null && resultWifi
                                .isConnectedOrConnecting())) {
                    return true;
                } else {
                    return false;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return false;
    }

Add the following permissions to your manifest file,
  <uses-permission android:name="android.permission.INTERNET" />
  <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />


text:
Q: How to align React bootstrap NavBar to the left I've created a React Bootstrap navbar, however, I'm not able to get it aligned to the left.
NavBar code that I'm using:
import React from "react";
import { Navbar, Nav, Container, NavDropdown } from "react-bootstrap";

export default function NavBar() {
  return (
    <Navbar bg="light" expand="lg">
      <Container>
        <Navbar.Brand href="#home">
          My NavBar
        </Navbar.Brand>
        <Navbar.Toggle aria-controls="basic-navbar-nav" />
        <Navbar.Collapse id="basic-navbar-nav">
          <Nav className="me-auto">
            <Nav.Link href="#home">Home</Nav.Link>
            <Nav.Link href="#link">Link</Nav.Link>
            <NavDropdown title="Dropdown" id="basic-nav-dropdown">
              <NavDropdown.Item href="#action/3.1">Action</NavDropdown.Item>
              <NavDropdown.Item href="#action/3.2">
                Another action
              </NavDropdown.Item>
              <NavDropdown.Item href="#action/3.3">Something</NavDropdown.Item>
              <NavDropdown.Divider />
              <NavDropdown.Item href="#action/3.4">
                Separated link
              </NavDropdown.Item>
            </NavDropdown>
          </Nav>
        </Navbar.Collapse>
      </Container>
    </Navbar>
  );
}

My App.js code:
import React from "react";
import NavBar from "./components/NavBar";

function App() {

  return (
    <main>
      <NavBar />

    </main>
  );
}

export default App;

This is what the NavBar looks like:

How can I get the Brand "My Nav Bar" to move to the left?
Code Sandbox: https://codesandbox.io/s/charming-galois-g590u1?file=/src/App.js

A: Just remove Container. Explanation: Container adds extra padding left and right on large screens.
https://react-bootstrap.netlify.app/components/navbar/#containers


text:
Q: Python PyTest : How to read examples from external excel file for Scenarios Outline Instead of passing data from Examples: I want to pass the data from excel. as in that step I just want to compare expected and actual results for batch automation. I have 100s of test data to be tested for the same scenario.
I could pass the test data from excel in Behave. But with PyTest BDD,I am not able to do it. I got the data from excel in a list. But in scenario, it is sending the whole list in first run itself.
How can I iterate through the list and run the same scenario multiple times?
Scenario Outline: Browser Test
When I visit the URL <base>/<page>/<ordNumber>/<custName>

Then the browser contains test <custNumber>

Examples:

 | base                         | page   | ordNumber | custName |

 | http://www.stackoverflow.com | orders | 123       | John     |

 | http://www.stackoverflow.com | orders | 456       | Mike     |

 | http://www.stackoverflow.com | orders | 789       | Tom      |


text:
Q: Guardar clientes dentro de uma ArrayList Levando em consideração as classes abaixo, como eu posso - dentro da classe Banco - armazenar dentro da ArrayList todos os meus clientes?
Banco
public class Banco {
    private ArrayList<Conta> contas;

    public Banco() {
        contas = new ArrayList<Conta>();
    }
}

Cliente
public class Cliente {
    private String nome;
    private String telefone;

    public String getNome() {
        return nome;
    }
    public void setNome(String nome) {
        this.nome = nome;
    }
    public String getTelefone() {
        return telefone;
    }
    public void setTelefone(String telefone) {
        this.telefone = telefone;
    }
}

Conta
public class Conta {
    private int numero;
    private double saldo;
    private Cliente cli;

    public Conta() {

    }

    public int getNumero() {
        return numero;
    }
    public void setNumero(int numero) {
        this.numero = numero;
    }
    public double getSaldo() {
        return saldo;
    }
    public void setSaldo(double saldo) {
        this.saldo = saldo;
    }
    public Cliente getCli() {
        return cli;
    }
    public void setCli(Cliente cli) {
        this.cli = cli;
    }
}

A: Usa um método na classe Banco similar ao setCli() da classe Conta.
Tipo assim:
public class Banco {
    private ArrayList<Conta> contas;

    public Banco() {
        contas = new ArrayList<Conta>();
    }

    public void setConta(Conta conta) {
        contas.add(conta)
    }
}

A: Levando em consideração as classes da forma que está, você pode criar um método na classe Banco que retorna todos os clientes em um ArrayList.
public ArrayList<Cliente> listarClientes(){
    ArrayList<Cliente> clientes = new ArrayList();
    for(Conta conta : contas){
        clientes.add(conta.getCli());
    }
    return clientes;
}

public ArrayList<Cliente> listarInadimplentes(){
    ArrayList<Cliente> inadimplentes = new ArrayList();
    for(Conta conta : contas){
        if(conta.getSaldo()<0)
            inadimplentes.add(conta.getCli());
    }
    return clientes;
}


text:
Q: Text box size should grow when typing I am looking for a effect in the text box.
Initially the size of the text box will be small and when type in, the text box should grow bigger. Is there any jquery plugin available for this effect? If not how can this be achieved.?

A: $("#mytextbox").keyup(function() {
    $(this).attr("maxLength", $(this).attr("maxLength") + 1);
    $(this).attr("size", $(this).attr("size") + 1);
});

Be aware that if the user presses a function key with the textbox focused, the size will increase regardless. You should instead monitor the textbox for changes in its value:
$("#mytextbox").keyup(function() {
    $(this).attr("size", $(this).val().length + 1);
});

Note that the second method will also support copy/pasting into the input field, whereas the first one will not, although you'll have to make sure the user has enough room to copy something in (right now, the size is set to +1 of the current value, meaning the user can only input one character at a time before the size is increased).

A: var $text = $('myselector')
$text.keyup(function() {
    $(this).attr({size : $(this).val().length});
});

This takes the size directly from the string length of whatever is input in the textbox.

A: have a look at this jquery plugin:
http://www.unwrongest.com/projects/elastic/


text:
Q: what exactly is the danger of an uninitialized pointer in C I am trying get a handle on C as I work my way thru Jim Trevor's "Cyclone: A safe dialect of C" for a PL class. Trevor and his co-authors are trying to make a safe version of C, so they eliminate uninitialized pointers in their language. Googling around a bit on uninitialized pointers, it seems like un-initialized pointers point to random locations in memory. It seems like this alone makes them unsafe. If you reference an un-itilialized pointer, you jump to an unsafe part of memory. Period. But the way Trevor talks about them seems to imply that it is more complex. He cites the following code, and explains that when the function FrmGetObjectIndex dereferences f, it isn't accessing a valid pointer, but rather an unpredictable address — whatever was on the stack when the space for f was allocated.
What does Trevor mean by "whatever was on the stack when the space for f was allocated"? Are "un-initialized" pointers initialized to random locations in memory by default? Or does their "random" behavior have to do with the memory allocated for these pointers getting filled with strange values (that are then referenced) because of unexpected behavior on the stack.
Form *f;
   switch (event->eType) {
   case frmOpenEvent:
   f = FrmGetActiveForm(); ...
   case ctlSelectEvent:
   i = FrmGetObjectIndex(f, field); ...
}

A:
What does Trevor mean by "whatever was on the stack when the space for f was allocated"?

He means that in most assembly languages, separate instructions are used to reserve space on the stack and to write an initial value inside the newly reserved space. If a C program uses an uninitialized variable, the program will typically at run-time execute the instruction that reserves stack space but no instruction that sets it. When the pointer is used, it will literally contain the bit pattern that was on the stack before space was reserved. In the good cases this will be an invalid address. In the bad cases this will happen to be a valid address, and the effects will be unpredictable.
This is only a typical behavior. From the theoretical point of view, using an indeterminate value is undefined behavior. Much stranger things than simply accessing an invalid address or a valid one can happen (examples with uninitialized data (not addresses) used accidentally or purposely).

Here is the sort of dangers that a restricted subset of C such as Cyclone aims to prevent:
int a, *p;

int main(int c, char **v){
  int l, *lp, i;
  if (c & 1)
    a = l + 1;      // danger
  if (c & 2)
    *lp = 3;        // danger
  if (c & 4)
    {
      p = &a;
      for (i=0; i<=1; i++)
        {
          int block_local;
          *p = 4;   // danger
          p = &block_local;
        }
    }
}

In the last dangerous line, in practice, it is most likely that 4 will be written to variable block_local, but in reality, at the second iteration, p is indeterminate, the program is not supposed to access *p, and it is undefined behavior when it does.

A: On modern OS's the danger is a core dump. On earlier systems without memory management and possibly memory mapped i/o to external HW the dangers are of completely different magnitude.


text:
Q: What is the default font displayed in bokeh plots? I could not find this information in the documentation. Does anyone what the default font is?

A: Helvetica, though different sizes and styles are used in different places.
https://github.com/bokeh/bokeh/blob/d213e3d755f09f57d2a58da3c1dcba939a3b90bf/bokeh/core/property_mixins.py#L164


text:
Q: (AdapterView> parent, View view, int position, long id) What does the > symbol do? I'm aware this is simple, but I couldn't find a list of symbols and their meanings on the Android Developer website. Just want to know what the ? symbol means, in general, in Java; and if its meaning changes depending on case.
For example, if the meaning changes if used in (AdapterView<?> parent, View view, int position, long id), as opposed to another use; I wouldn't imagine it does but I figured I'd ask in case.
Thanks!

A: It's a wildcard. <?> is the same as <? extends Object> - any type.
The way wildcards are usually used is <? extends Foo> (any class that extends Foo) or <? super Foo> (any class that is a supertype of Foo)
Here is an example of usage of <?>:
Consider the following method, printList:
public static void printList(List<Object> list) {
for (Object elem : list)
System.out.println(elem + " ");
System.out.println();
}

The goal of printList is to print a list of any type, but it fails to achieve that goal — it prints only a list of Object instances; it cannot print List, List, List, and so on, because they are not subtypes of List. To write a generic printList method, use List<?>:
public static void printList(List<?> list) {
for (Object elem: list)
System.out.print(elem + " ");
System.out.println();
}

Because for any concrete type A, List is a subtype of List<?>, you can use printList to print a list of any type:
List<Integer> li = Arrays.asList(1, 2, 3);
List<String> ls = Arrays.asList("one", "two", "three");
printList(li);
printList(ls);

See this for more info: Wildcards (The Java™ Tutorials > Learning the Java Language > Generics (Updated))


text:
Q: Adding asp.net code before doctype Is this valid to do, I have asp.net code right before the !doctype html tag and It's throwing Internet Explorer into quirks mode...Can this code be added right after the doctype and still work just fine?
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="index.aspx.cs" Inherits="somepage.index" %>

<!doctype html>


text:
Q: How to count occurrences of a string in nested tuple list? I have a nested tuple list in python:
myList = [(12345, "John Doe"), (345678, 'Marie Doe'), (434566, 'Marie Doe'), (665533, 'Marie Doe'), (23456, 'John Doe'), (657332211, 'Amanda Doe')]

and trying to produce occurrences for names as two separate lists:
occurrences = [2, 3, 1]
names = ['John Doe', 'Marie Doe', 'Amanda Doe']

so far this one gave me a total number of items in my nested tuple, but not sure how I can produce the above:
Total = len(myList)

Could someone help me with this? Thank you in advance!

A: What you can do is create a dict where keys are names and values are their count in myList.
 myList = [(12345, "John Doe"), (345678, 'Marie Doe'), (434566, 'Marie Doe'), (665533, 'Marie Doe'), (23456, 'John Doe'), (657332211, 'Amanda Doe')]

# Initializing a dict with key: name and value: 0.
dict_name_count = {name: 0 for _, name in myList}

# Iterating over tuples in `myList`, picking name (the second entry in tuple) ignoring the number.
for _, name in myList:
    dict_name_count[name] += 1

print(dict_name_count)
# Results in: {'John Doe': 2, 'Marie Doe': 3, 'Amanda Doe': 1}

# To get separate lists:
names = list(dict_name_count.keys())
occurrences = list(dict_name_count.values())

A: here is what I would do using pandas:
import pandas as pd

df = pd.DataFrame(myList).groupby(1, as_index=False).count()

occurrences = df[0].to_list()
names = df[1].to_list()

Outputs:
names : ['Amanda Doe', 'Joe Doe', 'John Doe', 'Marie Doe']
occurrences : [1, 1, 1, 3]

A: You can unpack the names into a list, then just run counts of that list:
all_names = [elem[1] for elem in myList]
names = []
occurrencs = []
for name in set(all_names):
    names.append(name)
    occurrences.append(all_names.count(name))

A: try this
    myList = [(12345, "John Doe"),
          (345678, 'Marie Doe'),
          (434566, 'Marie Doe'),
          (665533, 'Marie Doe'),
          (23456, 'John Doe'),
          (657332211, 'Amanda Doe')
          ]
namelist=[name[1] for name in myList]
names=[]
for name in namelist:
    if name not in names:
        names.append(name)

occurrences=[namelist.count(name) for name in names]
print(occurrences)
print(names)


text:
Q: How to add ellipses to each cluster of 3D scatter plot using updatemenus in plotly R? I wanted to create 3D scatter plot in R plotly and add ellipses to each cluster of plot using updatemenue. (Something similar to "Relayout Button" section in  https://plot.ly/r/custom-buttons/#relayout-button but for 3D one). I'm able to add ellipses using ellipse3d to plotly plot but I don't know how to make it interactive with updatemenue layout.
I wrote below code but not adding updatemenus yet. Would you please give me a help?
df<-
structure(list(C = structure(c(1L, 1L, 1L, 2L, 2L, 2L, 3L,
3L, 3L, 4L, 4L, 4L), .Label = c("h", "j", "k", "l"), class = "factor"),
R = structure(c(1L, 2L, 3L, 1L, 2L, 3L, 1L, 2L, 3L, 1L,
2L, 3L), .Label = c("a", "b", "c"), class = "factor"),
p1 = c(-58.2553800845032, -56.8446241583638, -57.4730903743034,
9.69295162882175, 23.2783600609086, 17.5961245834489, 27.1776771896781,
31.8555589999195, 31.1329423894753, 5.49176565720366, 12.9720812431292,
13.3756328645854), p2 = c(1.89343789795219, 2.96630118684064,
3.36783254906029, 22.1036613994383, 19.1821210966211, 26.161634708624,
0.00600630960161123, 6.18082767371698, 1.73282189156538,
-26.351364716711, -26.6021818789505, -30.641098117759), p3 = c(1.98930539820297,
3.3628193816464, 4.50430994627108, -16.0161352497141, -10.0505758631406,
-3.19889710494869, 8.92935203885341, 7.00720243933593, 22.7494673296249,
-11.7929746942337, -5.26783717642642, -2.21603644547113)), .Names = c("C",
"R", "p1", "p2", "p3"), class = "data.frame", row.names = c(NA,
-12L))

library(plotly)
library(corpcor)
library(rgl)
x=df$p1; y=df$p2;  z=df$p3
col <- c("orange", "blue", "purple", "green")
p <- plot_ly(df, x =x, y = y, z = z,type = "scatter3d",
         mode = "markers", marker = list(color = col[df$C],
         showscale = FALSE)
       #, text = paste(df$C, df$R)
      )
groups <- df$C
levs <- levels(groups)
group.col <- c("red", "blue", "yellow", "green")
for (i in 1:length(levs)) {
group <- levs[i]
selected <- groups == group
xx <- x[selected]; yy <- y[selected]; zz <- z[selected]
co<- cov(cbind(xx,yy,zz))
S<- make.positive.definite(co)
ellips <- ellipse3d(S, centre=c(mean(xx),mean(yy),mean(zz)), level = 0.95)
p<- add_trace(p, x = ellips$vb[1,], y = ellips$vb[2,], z = ellips$vb[3,]
           ,type = 'scatter3d', size = 1
            ,opacity=0.002
            #,color= group.col[i]
            ,showlegend = FALSE)
 }
print(p)


text:
Q: Scrolling a DIV beneath an absolutely postitioned element I have a simple website that features a scrollable div. It works fine, but I also need an absolutely positioned div over the top of it -- and I still need it to scroll as if it wasn't there.
You can see a crude JSFiddle here: http://jsfiddle.net/41rawrks/
You can scroll the div with your mousewheel (or trackpad), but if the cursor goes over the other element (like below), you can't scroll anymore. Can I change this?

I imagine it's because the DOM no longer considers the cursor to be "over" the scrollable element once it hits the draggable one (even though the draggable element is absolutely positioned within the scrollable one).
What can I do?
I wouldn't have thought it was possible, but this site does it!
http://weareeli.dk

A: If you switch the overflow from #scrollDiv80s to its parent #wrapper80s it works as you want:
#scrollDiv80s div {
    border: 1px solid black;
}
#wrapper80s, #wrapper90s, #wrapper00s {

    overflow-y: scroll; /* look at this */
    overflow-x: hidden; /* look at this */
    height: 100%;
    padding-left: 0px;
    padding-right: 0px;
    position: relative;
}
.decadeHeader {
    background-color: red;
    position: absolute;
    width: 100%;
    z-index: 99999;
    font-size: 28px;
    text-align: center;
}
.decadeHeader:hover {
    cursor: grab;
    cursor: -webkit-grab;
}
#scrollDiv80s  {
    /* overflow from child removed */
    border: none;
    height: 100%;
}

A: The .decadeHeader never scrolls, so it can pass the scroll event to the element underneath.
You need to add some children to .decadeHeader to get this to work. Something like:
Just include the script "_ezswipe.js" from https://github.com/TNT-RoX/android-swipe-shim in your html.
<script src="_ezswipe.js" type="text/javascript"></script>

Then add the class "_ezswipe" to
<div class="decadeHeader ui-draggable ui-draggable-handle _ezswipe">

Lastly add a little code to pass the event on.
function catchEvent(e) {
    document.querySelector('#scrollDiv80s').scrollTop += (e.detail.delta.y*-1);
}
var el = document.querySelector("._ezswipe");
el.addEventListener("swipeMove", catchEvent, true);

Fiddle here http://jsfiddle.net/41rawrks/7/

A: The solution was a mixture of everything already mentioned.
pointer-events: none stopped the scroll getting stuck, but prevented the dragging option from working. The answer was to add pointer-events: none to the draggable element only when the column wasn't scrolling.
Monitoring the scroll event (without mouseclick) was easy, but I used the jQuery debounce to detect when scrolling had stopped.
scrollers.scroll($.debounce( 250, function(){
    // Re-enable drag event
    $(this).next('.decadeHeader').css('pointer-events', 'auto');
}));

Simple solution and works a treat!

A: You can either add pointer-events: none in CSS to the blocking element (no support in IE10 and below I think) or try adding e.preventDefault to a mouseenter/mouseover event on that element.


text:
Q: inotify api stops working after reporting once or twice I wanted to test inotify, so took a couple of examples from internet, modified it to learn various aspects, but failed as it didn't work like i wanted to. First i tried to watch over a directory where it worked pretty nicely.
So i extended that example for file with some modification, but it works for one time only and gets blocked on read function
#include <sys/inotify.h>
#include <unistd.h>
#include <stdio.h>

#define EVENT_SIZE  (sizeof (struct inotify_event))
#define BUF_LEN        (16 * (EVENT_SIZE + 16))

int main()
{
    int fd;
    fd = inotify_init();
    if (fd < 0)
        perror("inotify_init()");
        int wd;
        wd = inotify_add_watch(fd, "target", IN_CLOSE_WRITE);
    if (wd < 0)
        perror("inotify_add_watch");

    char buf[BUF_LEN];
    int len;

    while(1) {

         len = read(fd, buf, BUF_LEN);

         printf("after read\n");

        if (len > 0)
        {
            int i = 0;
            while (i < len)
            {
                struct inotify_event *event;
                event = (struct inotify_event *) &buf[i];

                printf("wd=%d mask=%x cookie=%u len=%u\n",
                    event->wd, event->mask,
                    event->cookie, event->len);

                if (event->mask & IN_MODIFY)
                printf("file modified %s", event->name);

                if (event->len)
                printf("name=%s\n", event->name);

                i += EVENT_SIZE + event->len;
             }
        }

    }

    return 0;
}

So, i shifted to select(), but here also, it works once,reports twice then stop reporting the changes.
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/inotify.h>

#define EVENT_SIZE  ( sizeof (struct inotify_event) )
#define BUF_LEN     ( 1024 * ( EVENT_SIZE + 16 ) )

int main( int argc, char **argv )
{
int length, i = 0;
int fd;
int wd;
char buffer[BUF_LEN];

struct timeval timeout;

fd = inotify_init();

if ( fd < 0 ) {
   perror( "inotify_init" );
}

wd = inotify_add_watch( fd, "target",
                      IN_CLOSE_WRITE );
fd_set rfds,rfdss;
int ret;

/* zero-out the fd_set */
FD_ZERO (&rfds);
FD_ZERO (&rfdss);
FD_SET (fd, &rfds);

timeout.tv_sec = 5;
timeout.tv_usec = 0;

while(1){
    printf("Before select\n");
    //rfds = rfdss;
    ret = select (fd + 1, &rfds, NULL, NULL, NULL);
    printf("After Select\n");
    timeout.tv_sec = 5;
    timeout.tv_usec = 0;
    if (ret < 0)
            perror ("select");
    else if (!ret){
    }
            /* timed out! */
    else if (FD_ISSET (fd, &rfds)){
            printf("file changed============\n");
            length = read( fd, buffer, BUF_LEN );
    }
}

  ( void ) inotify_rm_watch( fd, wd );
 ( void ) close( fd );

 exit( 0 );
}

A: A bit of research showed that that the popular editors save it in different way.
Instead of overwriting that file directly, they actually make a temporary file and then replace original file with new temporary one. So what actually happens is the file which you were actually watching no longer exists and therefore any changes that would be making won't be reflected back.
Editors that actually follow this method are(many more may exist)
Gedit, Geany, vi
Editors that directly overwrite the file is(many more may exist)
nano
Hence even though code was correct, anomalous behavior of editor can be problematic

A: For the blocking read call, see: https://stackoverflow.com/a/914520/149111
You may also want to switch from IN_CLOSE_WRITE to IN_ALL_EVENTS to make sure you're not missing something; likely a delete:
It is a best practice to watch the dir that contains the file(s) of interest rather than the individual files, as this will consume fewer resources in the kernel.  It will also allow you to observe "atomic" file replacement operations where the writer creates a temporary file on the file system (perhaps in the same dir), write to the temporary file and then at the end rename(2) it over the top of the original file.
This style of replacement ensures that observers of the file will only ever notice the complete content of the file and not a half-written version of it.


text:
Q: If I use .Net Core 2.0 my software must by open software? If I  use .Net Core 2.0 my software must by 'open software' or what?
Sorry for my English.

A: No.
.NET Core is under MIT licence.
That means you are not required to make your software open-source if you use or redistribute it with your application.

A: Disclaimer: I am not a lawyer. This answer is not substitute for legal advice.
You are not required to open source a product developed to run on .NET Core (any version).
To be clear, .NET Core uses a MIT License, which you must include in any distribution of .NET Core. However, this license only applies to .NET Core, and not to a software developed to run on it. Thus, if you are merely targeting .NET Core, you do not have to worry about this. This is the case for most people that use .NET Core.

However, if you take portions of the source code of .NET Core to include in your product, or if you modify and distribute a modified .NET Core, then you should release under MIT License.
Disclaimer: I am not a lawyer. I am an engineer with some legal experience. And that experience is not in sublicensing code that has been released under the MIT license. I say below that your modifications should remain available under MIT License because it clearly states that you shall keep it. Even if my reading on the license is wrong, doing so should keep you on the safe side.
Note: You can sublicense under a different license, however your modifications should remain available under MIT License. If you really want to do this, I advise to clearly label what files or code blocks comes from the .NET Core source code and to reference in source the appropriate licenses in each instance. This is much easier if you can keep all your modifications of the .NET Core source to a separate project.
Modifying or using the source code is the odd case. You do this by going out of your way to take parts or the totality of the source code from the .NET Core repositories and using that in your project. If you are NOT modifying or using portions of the .NET Core source code, you do not have to worry about this. If you want to modify .NET Core for a privative product, in theory, you could negotiate a different license with Microsoft; I cannot help you with that.


text:
Q: how to use dropdown virtualScroll in primeng 6 I have a dropdown with 100+ elements loaded dynamically from angular function in particular conditions.
This loading takes several seconds. No http calls are pending, this time is used by priming component (dropdown) for delete and create elements (options).
I would to try use new functionality virtualScroll present in primeng v7.
My project has angular 4.x and primeng v6. I haven't found basics requirements for primeng 7. I tried to upgrade to project 7 but project still broken.
Is there documentation for the migration from primeng 6 to primeng 7? Or is there possibilities to use virtualscroll with primeng 6?

A: You can update like this..
1st method:
uninstall the previous version as npm uninstall primeng

then reinstall it like npm install primeng

2nd method:
npm update primeng


text:
Q: Why does new T-SQL of SQL Server 2008 work on database in compatability mode 80? Experimenting with new features of T-SQL, I've run into a puzzle. Here is some new syntax supported by SQL 2008 and I'd expect it to work on databases set for compatibility mode 100 (i.e. 2008) and not work for compat mode 80 (i.e. 2000). Yet this works for a database set for SQL SERVER 2000 compatibility mode on a SQL 2008 instance of Standard edition:
use MDS    -- this db is compat mode 80
go
CREATE TABLE dbo.Employees
(
Name VARCHAR(50) NULL,
Email VARCHAR(50) NULL,
Salary money NULL
)
INSERT INTO dbo.Employees(Name, Email, Salary)
VALUES('Scott', 'scott@example.com', 50000.00),
  ('Jisun', 'jisun@example.com', 225000.00),
  ('Alice', 'al@example.com', 75000.00),
  ('Sam', 'sam@example.com', 45000.00)

SELECT * FROM dbo.Employees
drop table dbo.Employees

A: I noticed this too, and found this statement on MSDN:

Sets certain database behaviors to be
  compatible with the specified version
  of SQL Server.

The compatibility mode affects "certain" behaviors, and not ALL behaviors. See the ALTER DATABASE documentation for details.

A: The compatibility mode setting is used to control certain relatively obscure (imho) aspects of databae engine behavior. It does not block or prevent the use of extensions to the T-SQL language from being used on databases migrated from prior versions--for example, a database backed up from SQL 2000 and restored on SQL 2008 will support CTEs and the new multi-value INSERT statements.
The actual details of what is controlled by the database compatibility mode are buried in several articles in Books Online; this is a good starting place for researching this.

A: I don't see how this could work in compat mode 80.  Try adding this line before you create your table:
sp_dbcmptlevel 'MDS'

Does it return 80?


text:
Q: Is there a way to stop Django from automatically adding "_id" to foreign keys does anyone know if it's possible to stop Django from adding the "_id" to foreign keys? As an example: i have a table services and recites. Services has as foreign key the recites id (primary key of recites) which i name re_id. I get the classical error:
(1054, "Unknown column 'services.re_id_id' in 'field list'")

where the second/last "_id" is added automatically and i would like to stop that. I also know that one way to prevent the error is to avoid using "_id" but i wonder if theres a way to use it anyway. THANKS!
EDIT
this are my two table in the models.py (services is behandlung, and rechnung is recites)
class Behandlung(models.Model):
    id = models.AutoField(primary_key=True, unique=True)
    datum = models.DateField()
    behandlung_hn_nr = models.CharField(max_length=30)
    ext4MyHealthIDDoc = models.ForeignKey('Doctors', models.DO_NOTHING, to_field='ext4MyHealthIDDoc',null=True)
    istpreis = models.FloatField()
    leistungs_text = models.CharField(max_length=75)
    ext4MyHealthIDService = models.ForeignKey('Leistung', models.DO_NOTHING, to_field='ext4MyHealthIDService',null=True)
    re_id = models.ForeignKey('Rechnung', models.DO_NOTHING, null=True,unique=False, blank=True)
    bezahlt_am = models.DateField(null=True)
    storniert = models.BooleanField(null=True, default=0)

    def __str__(self):
        return self.leistungs_text

    class Meta:
        managed = True
        db_table = 'behandlung'

class Rechnung(models.Model):
    re_id =models.AutoField(primary_key=True)
    doctor = models.ForeignKey('Doctors', models.DO_NOTHING, to_field='ext4MyHealthIDDoc')
    erstellt_am = models.DateField()
    rechnungsnummer = models.CharField(max_length=50,null=True)

    class Meta:
        managed=True
        db_table='rechnung'


text:
Q: Neural network with 'tanh' as activation and 'cross-entropy' as cost function did not work I have implemented a simple neural network. It works well with 'sigmoid + cross-entropy', 'sigmoid + quadratic cost', and 'tanh + quadratic cost', but it did not work with 'tanh + cross-entropy' (no better than randomly guess).  Can anybody please help me figure out why? Just see the code of FullConnectedLayer:
class FullConnectedLayer(BaseLayer):
    """
    FullConnectedLayer
    ~~~~~~~~~~~~~~~~~~~~
    Data members:
    sizes       ---- <type list> sizes of the network
    n_layers    ---- <type int> number of sublayers
    activation  ---- <type Activation> activation function for neurons
    weights     ---- <type list> to store weights
    biases      ---- <type list> to store biases
    neurons     ---- <type list> to store states (outputs) of neurons
    zs          ---- <type list> to store weighted inputs to neurons
    grad_w      ---- <type list> to store gradient of Cost w.r.t weights
    grad_b      ---- <type list> to store gradient of Cost w.r.t biases
    ---------------------
    Methods:
    __init__(self, sizes, activation = Sigmoid())
    size(self)
    model(self)
    feedforward(self, a)
    backprop(self, C_p)
    update(self, eta, lmbda, batch_size, n)
    """

    def __init__(self, sizes, activation = Sigmoid(), normal_initialization = False):
        """
        The list ''sizes'' contains the number of neurons in repective layers
        of the network. For example, sizes = [2, 3, 2] represents 3 layers, with
        the first layer having 2 neurons, the second 3 neurons, and the third 2
        neurons.

        Note that the input layer may be passed by other layer of another type
        when connected after the layer, and we don't set biases for this layer.
        Also note that the output layer my be passed to other layer if connected
        before the layer, in this case, just assign the outputs to its inputs.
        For examle, Layer1([3, 2, 4])->Layer2([4, 6, 3])->Layer3([3, 2]). Just
        assign the output of Layer1 to the input Layer2, it will be safe.
        """

        BaseLayer.__init__(self, sizes, activation)

        if normal_initialization:
            self.weights = [np.random.randn(j, i)
                    for i, j in zip(sizes[:-1], sizes[1:])]
        else:
            self.weights = [np.random.randn(j, i) / np.sqrt(i)
                    for i, j in zip(sizes[:-1], sizes[1:])]
        self.biases = [np.random.randn(j, 1) for j in sizes[1:]]

        self.grad_w = [np.zeros(w.shape) for w in self.weights]
        self.grad_b = [np.zeros(b.shape) for b in self.biases]

    def feedforward(self, a):
        """
        Return output of the network if ''a'' is input.
        """
        self.neurons = [a] # to store activations (outputs) of all layers
        self.zs = []
        for w, b in zip(self.weights, self.biases):
            z = np.dot(w, self.neurons[-1]) + b
            self.zs.append(z)
            self.neurons.append(self.activation.func(z))
        return self.neurons[-1]

    def backprop(self, Cp_a):
        """
        Backpropagate the delta error.
        ------------------------------
        Return a tuple whose first component is a list of the gradients of
        weights and biases, whose second component is the backpropagated delta.
        Cp_a, dC/da: derivative of cost function w.r.t a, output of neurons.
        """
        # The last layer
        delta = Cp_a * self.activation.prime(self.zs[-1])
        self.grad_b[-1] += delta
        self.grad_w[-1] += np.dot(delta, self.neurons[-2].transpose())

        for l in range(2, self.n_layers):
            sp = self.activation.prime(self.zs[-l])  # a.prime(z)
            delta = np.dot(self.weights[-l + 1].transpose(), delta) * sp
            self.grad_b[-l] += delta
            self.grad_w[-l] += np.dot(delta, self.neurons[-l - 1].transpose())

        Cp_a_out = np.dot(self.weights[0].transpose(), delta)

        return Cp_a_out

    def update(self, eta, lmbda, batch_size, n):
        """
        Update the network's weights and biases by applying gradient descent
        algorithm.
        ''eta'' is the learning rate
        ''lmbda'' is the regularization parameter
        ''n'' is the total size of the training data set
        """
        self.weights = [(1 - eta * (lmbda/n)) * w - (eta/batch_size) * delta_w\
                for w, delta_w in zip(self.weights, self.grad_w)]
        self.biases = [ b - (eta / batch_size) * delta_b\
                for b, delta_b in zip(self.biases, self.grad_b)]

        # Clear ''grad_w'' and ''grad_b'' so that they are not added to the
        # next update pass
        for dw, db in zip(self.grad_w, self.grad_b):
            dw.fill(0)
            db.fill(0)

Here is the code of the tanh function:
class Tanh(Activation):

    @staticmethod
    def func(z):
        """ The functionality. """
        return (np.exp(z) - np.exp(-z)) / (np.exp(z) + np.exp(-z))

    @staticmethod
    def prime(z):
        """ The derivative. """
        return 1. - Tanh.func(z) ** 2

And here is the code of cross-entropy class:
class CrossEntropyCost(Cost):

    @staticmethod
    def func(a, y):
        """
        Return the cost associated with an output ''a'' and desired output
        ''y''.
        Note that np.nan_to_num is used to ensure numerical stability. In
        particular, if both ''a'' and ''y'' have a 1.0 in the same slot,
        then the expression (1-y) * np.log(1-a) returns nan. The np.nan_to_num
        ensures that that is converted to the correct value(0.0).
        """
        for ai in a:
            if ai < 0:
                print("in CrossEntropyCost.func(a, y)... require a_i > 0, a_i belong to a.")
                exit(1)

        return np.sum(np.nan_to_num(-y * np.log(a) - (1-y) * np.log(1-a)))

    @staticmethod
    def Cp_a(a, y):
        """
        Cp_a, dC/da: the derivative of C w.r.t a
        ''a'' is the output of neurons
        ''y'' is the expected output of neurons
        """
        #return (a - y) # delta
        return (a - y) / (a * (1 - a))

Edit:
    Seems the problem is that the range of tanh is -1 to +1, which is illegal for cross-entropy. But if I just want a tanh activation and a cross-entropy cost, how should I deal with it?

A: The answer is late but I think it's worth mentioning.
If you want to use a tanh activation function, instead of using a cross-entropy cost function, you can modify it to give outputs between -1 and 1.
The same would look something like:
((1 + y)/2 * log(a)) + ((1-y)/2 * log(1-a))
Using this as the cost function will let you use the tanh activation.

A: Looks like you're using tanh in your output layer, where tanh has the range -1, +1 and the expected outputs are in the range 0, +1. This doesn't matter for the Sigmoid which does produce outputs in the range 0, +1.

A: Cross entropy expects it's inputs to be logits, which are in the range 0 to 1.
The Tanh method transforms the input to values in the range -1 to 1 which cross entropy can't handle.
Some possible fixes would be to rescale the input in the final layer in the input is tanh and the cost cross-entropy.


text:
Q: update project classpath with ant after retrieving dependencies in ivy that's a part of my build.xml
<property name="dir.ivy" value="${user.home}/.ivy2" description="Local Ivy Repository" />

<target name="retrieve" depends="clean,init">

    <!-- Resolve dependencies -->
    <ivy:resolve file="ivy.xml"/>
    <ivy:retrieve type="jar" conf="${ivy.configuration}" pattern="${dir.ivy}/[artifact]-[revision].[ext]"/>

    <!-- Update classpath -->
    ???

</target>

After i downloaded the dependencies, defined in my ivy.xml, from artifactory or maven i would like to add them to my project classpath without adding them manually from Project - Configure Build Path... and without compiling my classes.
Any ideas?

A: The cachepath task can be used create an ivy managed classpath.
For an example see:

*

*How to avoid copying dependencies with Ivy

A: Finally i've found a solution, i used the Apache IvyDE plugin for eclipse to update the project classpath.


text:
Q: Hangman Code Issue (Java) I am trying to create a simple hangman program in java for a school assignment and I have it working for the most part. The main problem I have with it is that it keeps printing out the hidden word twice. It also only goes through and asks the user to enter an word 8 times when it should be 15 times. Can someone tell me where I went wrong?
// Its in a separate method.
public static void application1() throws Exception {
    // Tells the user about the game.
    System.out.println("Welcome to Hangman!");
    System.out.println("Please try to guess the word within 15 letters.");

    String option = "";

    // Creates a array of all the phrases.
    String answer[] = new String[20];
    answer[0] = "computer";
    answer[1] = "radio";
    answer[2] = "calculator";
    answer[3] = "teacher";
    answer[4] = "bureau";
    answer[5] = "police";
    answer[6] = "geometry";
    answer[7] = "president";
    answer[8] = "subject";
    answer[9] = "country";
    answer[10] = "environment";
    answer[11] = "classroom";
    answer[12] = "animals";
    answer[13] = "province";
    answer[14] = "month";
    answer[15] = "politics";
    answer[16] = "puzzle";
    answer[17] = "instrument";
    answer[18] = "kitchen";
    answer[19] = "language";

    do {
        // Creates a random number to choose which word to choose from.
        int rand = (int)(Math.random() * 20 + 0);

        StringBuffer word = new StringBuffer("");

        // This makes the unknown word as long as the actual word.
        for (int i = 0; i < answer[rand].length(); i++) {
            word.append("_");
        }

        System.out.println(word);

        char input = ' ';

        // This is where it checks the input and replaces the letters.
        for (int i = 0; i < 15; i++) {
            input = (char) System.in.read();

            for (int j = 0; j < answer[rand].length(); j++) {
                if (input == answer[rand].charAt(j)) {
                    word.setCharAt(j, input);
                }
            }

            // This is where the hidden word get printed twice.
            System.out.println(word);
        }

        // Asks the user if they want to restart the application.
        System.out.println("Would you like to try again? (Y/N)");
        option = input();

    } while (option.equalsIgnoreCase("y"));
}

A: Use a Scanner to get your input.
Scanner in = new Scanner(System.in);
String line = in.nextLine();
char input = line.charAt(0);

I think System.in.read(); is returning the entered character and the enter key. (the \n char).
That makes your cycle run twice for each input, printing two times and looking like it only accepts 8 chars.

A: if (word.equals(answer[rand])) {
    System.out.println("Congratulations! You guessed the word!");

    // Asks the user if they want to restart the application.
    System.out.println("Would you like to try again? (Y/N)");
    option = input();
}
else if (i == 14) {
    System.out.println("Sorry, you did not guess the word.");

    // Asks the user if they want to restart the application.
    System.out.println("Would you like to try again? (Y/N)");
    option = input();

    // Returns to the main menu.
    menu();
}

This doesn't recognize the word is correct.


text:
Q: How to upload local PowerPoint file to SharePoint directory via Python I am automating some of my reports and require the ability to upload files to a SharePoint directory to which I have access. The goal would be to have this script run via Task Scheduler (which I already know how to set up).
Not sure where to start with this, but I have seen a few threads trying to do this using the sharepoint and requests modules, but still somewhat stuck.
Any help is much appreciated. Thanks.

A: I ended up looking up command-line approaches as suggested, and I put this together which worked well:
# maps local network drive to SharePoint directory (any open drive works)
os.system('net use r: {}'.format(sharepoint_url))

# uploads updated local file to SharePoint directory
os.system('copy {} r:\{}'.format(output_file_path, output_file_name))

# disconnects mapped network drive
os.system('net use r: /delete')

Hope this helps someone down the line.


text:
Q: New HDD for old laptop. What's the optimal partitioning scheme? I have an old Acer Aspire One AOA150. It has a 160Gb HD and 1.5 Ram Gb with two partitions: Recovery (4GB) and XP (154 Gb).
It's physically light and easy to carry. I want to install linux (lubuntu 17) on it and take it everyday to work.
I bought a Toshiba L200 drive and plan to install it.
I have thought of the following partitioning scheme:
(they will be aligned to the Mb due to Advanced Format on the drive)

Extended

*

*Swap 5 Gb.

*/ 300 Gb.

*Home 400 Gb.

Primary XP 300 Gb.
Primary Recovery 4 Gb.
Is this a good partitioning scheme for performance and frequent Linux usage?
What's the better linux tool for proper partition alignment? I have a gparted boot pendrive and a ubuntu boot pendrive.
I will have to prepare the XP boot as well (I intend to keep it without reinstalling). Files might have to be manually copied due to different sector sizes (drive is an Advanced Format drive). Any other way to transfer disk contents despite different sector sizes?
boot.ini will have to be fixed to default=multi(0)disk(0)rdisk(0)partition(4)\WINDOWS and ntloader will have to be added maybe from recovery console.
Am I missing something? Any advice/suggestion? Thanks.
Thanks.

A: 300Gb for / for what?

*

*25Gb is more than enough for a desktop to install all the software you need.

*even for a server (mysql defaults to /var/ for its database) I would expect the personal files to set so it will be on another partition.

I myself would do ...

*

*/ 25 Gb

*/home 10 Gb. Don't use this for personal data. See ~./config/users-dirs.dirs on how to change the default directories.

*remainder to a partition (as an example: /data). Use this for personal data. Set it up with all the directories /home/$USER/ normally has.

Plus points:

*

*A re-install of your system with keeping your settings: format /, mount /home and /data.

*A re-install of your system without keeping your settings: format /, format /home and mount /data.

*A backup only requires you to copy /data over to a USB disk

*The personal partition can be encrypted if needed.

*And, if wanted, you can use /data/ for all users so you share the same desktop with all users simply by  setting up a "group".


text:
Q: In which location are the files saved after uploading in Liferay? I have made a portlet that uploads a document from a form.
I have tried by making a simple dynamic java project and made a form to upload the document, that document is saved in LiferayWorkspace/.metadata/plugins/.../project/document.docx.
Now I have used this form in the portlet and it saves the document, which works fine, but I was wondering where did it save my uploaded document?
I have searched the tomcat directory and possible areas already.
Also if anyone could tell me where does in liferay 6.1 using "Dynamic Data List" portlet, documents are placed after uploading.

A: Liferay has its configuration settings stored in portal-ext.properties which is placed in liferay-portal-tomcat-6.1/liferay-portal-6.1/ directory.
you can change from there as well
#
# FileStore
#
dl.store.file.system.root.dir=${liferay.home}/data/document_library

A: The default store folder is portal-folder/data/document_library but you can change it by liferay configuration.

A: These are the properties in ROOT/WEB-INF/lib/portal-impl.jar/portal.properties which define where liferay stores the documents, you can override these properties by creating a portal-ext.properties and including your custom value:
#
# FileSystemStore
#
dl.store.file.system.root.dir=${liferay.home}/data/document_library

Additionally,
You can also set the temp (temporary) directory for the files uploaded, i.e. when you use UploadRequest to the get the file from request liferay stores them temporarily on the server:
#
# Set the temp directory for uploaded files.
#
#com.liferay.portal.upload.UploadServletRequestImpl.temp.dir=C:/Temp


text:
Q: ZFS dedup performance optimization I'm running a VDI server. Many of the VDI users are installing the same apps on their desktops, so zfs set dedup=on vdipool/myDesktop comes in handy.
How can I optimize the performance impact of zfs dedup?
What performance dragdown can I expect?
Is there a way to assign a dedicated CPU thread to the dedup process, so that the rest of the system is only minimally impacted?

A: On 100% SSD storage, the performance impact might be bearable if you have enough RAM for 100% of your deduplication hash table to be in RAM all the time. Making sure you have enough RAM for all of that metadata is the only optimisation that can be made.
If you are on spinning rust, the extreme on-disk fragmentation is going to make the performance completely unusable.
In general, if you are not actually seeing at a minimum 10:1 deduplication ratio, it isn't worth the enormous performance impact.

A: With the recent introduction of allocation classes (and "special" vdevs) you might have good enough performance with deduplication on a non-SSD pool, assuming you have a fast SSD to hold the metadata (which includes the deduplication data).
Before you add a "special" vdev, do some experiments, and get to know the feature. In my understanding, a failure of the "special" vdev takes the whole pool with it. Furthermore, you cannot remove a "special" vdev.
https://www.reddit.com/r/zfs/comments/cm594b/why_is_nobody_talking_about_the_newly_introduced/

A: If duplicated blocks would happen completely randomly, on a quasi-level distribution, then yes, fragmentation would be a serious issue on HDD media. But in practical scenarios, not this happens. In practical scenarios, the overwhelming majority of the dupe blocks happen as the part of dupe (or very similar) files, resulting that they happen in bunches. Thus, it does not cause a serious fragmentation problem.
Beside that, the solution of the problem of the fragmentation is the defragmentation, and not to avoid using this very useful feature.
However, zfs has simply no defragmentation tool or feature. The only way to defrag a zfs volume is rebuilding it. Beside that, it has some licensing problems. But there is still a lot of work in it, and many people find it useful. Hopefully someone will once implement the defragmentation (maybe even online defrag!), until then we should honor what we have.


text:
Q: Snapshot state is 'running' even after cancelling the upload task in AngularFire2's Firebase Storage I am using AngularFire2 to upload a file in Firebase Storage:
this.task = this.storage.upload(uploadPath, file);

this.task.snapshotChanges()
            .subscribe(snapshot => {
                this.snapshot = snapshot;
            });

It works as expected, however, when I cancel the task through the cancel() method, snapshot doesn't change, thus state is running, instead of cancelled. Why is that?
this.task.cancel();
// this.snapshot.state === 'running', not 'cancelled'

A: Seems to be a real bug
The last event is not emitted on the snapshotChanges() however it will be emitted in the .then() promise
this._task.snapshotChanges()
  .subscribe(snapshot => {
    this.snapshot = snapshot; // To get updates on progress
  });
this._task.then(snapshot => {
  this.snapshot = snapshot; // To know when it is done
}).catch(snapshot => {
  this.snapshot = this._task.task.snapshot; // To know whenever there is an error/cancel from user
});


text:
Q: JavaScript- storing the mouse X and Y positions in variables, and continuously updating them as the mouse is moved I have an HTML5 canvas which is displaying a number of images. Some of these images are draggable, and some are not. I've added the draggable functionality using a local copy of the KineticJS library (I'm using a local copy since there are one or two functions I wanted to edit slightly).
What I'm looking to do at the moment, is create a couple of JS variables to store the current location of the cursor whenever it is 'on' the canvas. The reason I want to be able to do this, is so that I can detect where the cursor is when the user is dragging one of the draggable images, and check whether or not they have dragged it to the correct location.
I've written the following function to do this:
function getMousePosition(mouseX, mouseY){
    mouseX = e.clientX;
    mouseY = e.clientY;
    console.log("mouseX = " + mouseX);
    console.log("mouseY = " + mouseY);
}

and I'm calling this function from within the KineticJS _mousemove function, so that this function now looks like this:
_mousemove: function(evt) {
    this._setUserPosition(evt);
    var dd = Kinetic.DD;
    var obj = this.getIntersection(this.getUserPosition());
    getMousePostion(mouseX, mouseY);

    if(obj) {
        var shape = obj.shape;
        if(shape) {
            if((!dd || !dd.moving) && obj.pixel[3] === 255 && (!this.targetShape || this.targetShape._id !== shape._id)) {
                if(this.targetShape) {
                    this.targetShape._handleEvent('mouseout', evt, shape);
                    this.targetShape._handleEvent('mouseleave', evt, shape);
                }
                shape._handleEvent('mouseover', evt, this.targetShape);
                shape._handleEvent('mouseenter', evt, this.targetShape);
                this.targetShape = shape;
            }
            else {
                shape._handleEvent('mousemove', evt);
            }
        }
    }
    /*
     * if no shape was detected, clear target shape and try
     * to run mouseout from previous target shape
     */
    else if(this.targetShape && (!dd || !dd.moving)) {
        this.targetShape._handleEvent('mouseout', evt);
        this.targetShape._handleEvent('mouseleave', evt);
        this.targetShape = null;
    }

    // start drag and drop
    if(dd) {
        dd._startDrag(evt);
    }
}

The problem I'm having, is that when I view my page in a browser, and move the cursor over the canvas, I get the Firebug console error: "getMousePostion is not defined" with every movement of the cursor. Some of these errors only say that, and some of them have a small '+' next to them.
If I expand one of the errors that has a '+' next to it, I get the following additional information:
_mousemove()kinetic.js (line 3443)
evt = mousemove clientX=15, clientY=229
(?)()kinetic.js (line 3417)
evt = mousemove clientX=15, clientY=229

Each error that is expandable show different figures for clientX and clientY, which shows that my function clearly is getting the x & y coordinates of the cursor as it moves around the canvas. So what I'm wondering is why I'm getting the errors telling me that getMousePosition is not defined?

A: You are trying to get properties of an object that doesn't exist, ie e. Instead of passing mouseX and mouseY to the function, you should be passing and event object.
//you're passing parameters that don't exist in _mousemove
function getMousePosition(mouseX, mouseY){
    mouseX = e.clientX; //and trying to use e, which doesn't exist
    mouseY = e.clientY;
    //also passed parameters aren't meant to be used as local variables like this
    console.log("mouseX = " + mouseX);
    console.log("mouseY = " + mouseY);
}

Change the parameter you pass to be an event object, and create mouseX and mouseY as local variables, and it should work. Another VERY big problem is that in _mousemove you are calling the function getMousePostion. Notice the spelling. You forgot an 'i'.
function getMousePosition(e){
    var mouseX = e.clientX;
    var mouseY = e.clientY;
    console.log("mouseX = " + mouseX);
    console.log("mouseY = " + mouseY);
}

_mousemove: function(evt) {
    ...
    getMousePosition(evt);
    ...


text:
Q: Запуск консольной команды в Python не от имени супер пользователя, когда скрипт запущен с sudo моя Python программа работает с консольной через subprocess.run, и всё работало отлично когда я запускал скрипт не от имени супер пользователя а просто
python3 main.py

Но понадобилось запустить этот же скрипт только с использованием sudo, и некоторые консольный команды, который я использую через subprocess.run не работает, например pactl. Из всего из этого у меня вопрос как запуская скрипт от имени суперпользователь, в самом скрипте через subprocess.run запускать команды без использования прав root

A: Перед запуском скрипта выполни source /etc/profile


text:
Q: What are relations of $S_4$, if generators are $a=(12)$, $b=(1234)$? I think, relations could be $a^2=e$, $b^4=e$, $ababab=e$, $b^2 a b^2 a b = b a b^2 a$.
By two first relations and $b^3 = ababa$ (it is result of our relations),  we can present any element that is generated by $a$ and $b$, as a sequence, where there are not more than one consecutive $a$ and not more than two consecutive $b$. By the last relation we can put all squares of $b$ to the beginning of sequence. We can remove  3 or more consecutive $ab$ by third relations. And also we have $ab^2ab^2ab^2ab^2=e$ as result of relations, so we can remove 4 or more of consectutive $ab^2$ from the beginning of sequence.
But, I'm not sure that we need exactly 4 relations, that there are not  3 relations that would be sufficient.

A: Here is another proof that $G = \langle x,y | x^2=y^4=(xy)^2=1 \rangle$ presents $S_4$.
Since we know that $S_4$ is a homomorphic image of $G$, we have $|G| \ge 24$, so it is enough to prove that $|G| \le 24$.
Let $H = \langle y \rangle \le G$. It is enough to prove that $|G:H| \le 6$, and to do that we will prove that $G = \bigcup_{Hg \in C} Hg$, where $$C = \{H,Hx,Hxy,Hxy^{-1},Hxy^2,Hxy^2x\}.$$
Since $G$ is generated by $x$ and $y$, it is enough to prove that $Hgx \in C$ and $Hgy \in C$ for all $Hg \in C$.
Most of these are straightforward.
Note that $xyx = y^{-1}x^{-1}y^{-1}=y^{-1}xy^{-1}$ so $Hxyx = Hxy^{-1}$ and similarly $Hxy^{-1}x = Hxy$.
Finally $$xy^2xy = xy(yxy) = xy(xy^{-1}x)= (xyx)y^{-1}x = y^{-1}xy^{-1}y^{-1}x = y^{-1}xy^2x,$$
so $Hxy^2xy = Hxy^2x$.

A: As Derek Holt mentions in the comments you have $S_4 \cong \langle x,y | x^2 = y^4 = (xy)^3 = 1 \rangle$, so for the generators $a = (1\ 2)$ and $b = (1\ 2\ 3\ 4)$ three relations $a^2 = b^2 = (ab)^3 = 1$ suffice.
Let $G = \langle x,y | x^2 = y^4 = (xy)^3 = 1 \rangle$. In $S_4$ you have a normal subgroup $V \cong C_2 \times C_2$ of order $4$, generated by $b^2 = (1\ 3)(2\ 4)$ and $ab^2a^{-1} = (1\ 4)(2\ 3)$.
So consider in $G$ the subgroup $N = \langle z, w \rangle$ where $z = y^2$ and $w = xy^2x^{-1}$. We would expect that $N$ is a normal subgroup and $N \cong C_2 \times C_2$.
For normality, it is clear that $xzx^{-1} = w$, $xwx^{-1} = z$, and $yzy^{-1} = z$. It remains to check that $ywy^{-1} \in N$. For this, using $(yx)^3 = 1$ and $x^2 = 1$ we find that $yxy = xy^{-1}x$ (as suggested in a comment). Then \begin{align*}
ywy^{-1} &= yxy^2xy^3 \\ &= (yxy)(yxy)y^2 \\ &= (xy^{-1}x)(xy^{-1}x)y^2 \\ &= xy^2xy^2 \\ &= wz.
\end{align*}
Certainly $N$ has $C_2 \times C_2$ as a quotient. Check that $(zw)^2 = 1$ so in fact $N \cong C_2 \times C_2$: \begin{align*} (zw)^2 &= y^2xy^2xy^2xy^2x \\ &= y(yxy)(yxy)(yxy)yx \\ &= y(xy^{-1}x)(xy^{-1}x)(xy^{-1}x)yx \\ &= y(xy^{-3}x)yx \\ &= yxyxyx = (yx)^3 = 1.\end{align*}
Then $G/N$ is generated by $\overline{x}$, $\overline{y}$ with $(\overline{x})^2 = (\overline{y})^2 = (\overline{x}\overline{y})^3 = 1$, so $G/N$ is a quotient of $S_3$.
Conclude $G \cong S_4$.


text:
Q: Node getting empty array as result when post request I am testing my post method on Postman.
Whenever I post the result it would display empty array [].
I console logged it on the node side and it returns empty array as well.
CREATE TABLE users (
    user_id SERIAL PRIMARY KEY,
    username TEXT,
    email TEXT,
    password TEXT
)

INSERT INTO users (username, email, password) VALUES ($1, $2, $3);

app.post('/api/users', function(req, res, next) {
    db.post_user([req.body.username, req.body.email, req.body.password], function(err, user) {
        console.log(user);
        if(err) res.status(500).send(err);
        else res.json(user);
    })
})

I am not exactly sure why I am getting empty array instead of actual data passing in.
var express = require('express');
var bodyParser = require('body-parser');
var session = require('express-session');
var cors = require('cors');
var massive = require('massive');
var config = require('./config');
var app = express();

app.use(bodyParser.json());
app.use(cors());

var db = massive.connect({connectionString: config.connectionString},     function(err, localdb){
    db = localdb;
    app.set('db', db);

});

app.get('/api/users', function(req, res, next) {
    db.get_users(function(err, users) {
        if(err) res.status(500).json(err);
        else res.json(users);
    })
})
app.post('/api/users', function(req, res, next) {
    db.post_user([req.body.username, req.body.email, req.body.password], function(err, user) {
        console.log(req.body);
        if(err) res.status(500).send(err);
        else res.json(user);
    })
})

app.listen(3000, function() {
    console.log("I am listening");
})

A: Because you need to do something like:
let query = "INSERT INTO users (username, email, password) VALUES (?, ?, ?)"
let values = [req.body.username, req.body.email, req.body.password]
connection.query(query, values).then(function(user...)

Depend of what Library are you using


text:
Q: Html as string on MVC5 Razor Currently, I store Html in database and populate into a Dropdownlist like this I'm using @funcion in Razor:
private string getHtmlTemplate()
{
    string value = "<select id='htmlTemplate'><option value=''>Html Template</option>";
    int i = 0;
    foreach (AdminHtmlTemplateModel htmlTemplateModel in Model.GetAdminHtmlTemplates())
    {
        value += string.Format("<option value='{0}'>{1}</option>", htmlTemplateModel.templateCode, htmlTemplateModel.templateName);
        //value += string.Format("<option value='{0}'>{1}</option>", i++, htmlTemplateModel.templateName);
        templateCodes.Add(htmlTemplateModel.templateCode);
    }

    value += "</select>";
    return value;
}

The problem is Html that was stored on templateCode was conflicted/merged with current html file

How to resolve this issue, I still want those Html value to work work with Editor.
I try some way like as on value of option tag just passing index and on function:
@fucntion{
 private string getHtmlTemplate()
{
    string value = "<select id='htmlTemplate'><option value=''>Html Template</option>";
    int i = 0;
    foreach (AdminHtmlTemplateModel htmlTemplateModel in Model.GetAdminHtmlTemplates())
    {
        value += string.Format("<option value='{0}'>{1}</option>", i++, htmlTemplateModel.templateName);
    }

    value += "</select>";
    return value;
 }
}

<script>
$("#htmlTemplate").kendoDropDownList({
        change: function (e) {
            editor.exec("inserthtml", { value:@Model.GetAdminHtmlTemplateCodeByIndex(@:e.sender.value()) });
        }
    });
</script>

But it won't work because we can't pass jquery value of razor to function, right?
Please help me. Thanks

A: Thanks guys,
After few hours to research, I found that I can use snippets to resolve my issue instead of use CustomControl in Kendo UI MVC.
private List<AdminHtmlTemplateModel> getHtmlTemplate()
{
    ////string value = "<select id='htmlTemplate'><option value=''>Html Template</option>";
    ////int i = 0;
    ////foreach (AdminHtmlTemplateModel htmlTemplateModel in Model.GetAdminHtmlTemplates())
    ////{
    ////    //value += string.Format("<option value='{0}'>{1}</option>", htmlTemplateModel.templateCode, htmlTemplateModel.templateName);
    ////    value += string.Format("<option value='{0}'>{1}</option>", i++, htmlTemplateModel.templateName);
    ////    templateCodes.Add(htmlTemplateModel.templateCode);
    ////}

    ////value += "</select>";
    ////return value;
    return Model.GetAdminHtmlTemplates();
}

@(Html.Kendo().Editor().Enccode(false)
                                              .Name("EmailBody")
                                              .Tools(tools => tools
                                                  .ViewHtml()
//.CustomTemplate(ct => ct.Template(getHtmlTemplate())) // before
.Snippets(s => //after fixed
{
    foreach (var item in getHtmlTemplate())
   {
        s.Add(item.templateName, item.templateCode);
    }
})

That's all. And it resolve my problem to insertHtml inside Kendo UI MVC Editor.


text:
Q: Google Cloud Platform - Regex for metric I'm sending data to GCP with this format:
t,26.40;h,42.60;c,3.68;n,0.32;s,216
The letters mean:
t- Temperature
h- humidity
c- CO
n- NO2
s- sound
To create the metrics in the GCP (to use it on the stackdriver), I need a regular expression to get the values that I want. I want to create a metric for each value. What should be the regex for the values that I want? Per example, the regex for "26.40" is different for the "42.60"... I have no idea about regex rules... I can modify the format that I'm sending data easily (at least I think). Any help would be perfect!
PS: Google Cloud Platform uses re2

A: This will match the line you've provided:
t,(\d+(?:\.\d+)?);h,(\d+(?:\.\d+)?);c,(\d+(?:\.\d+)?);n,(\d+(?:\.\d+)?);s,(\d+(?:\.\d+)?)
If you're not always going to have those letters in that order, try this and iterate through multiple matches:
([a-z]),(\d+(?:\.\d+)?)


text:
Q: Log4j not finding custom appender using a property file I'm trying to configure log4j in an Eclipse plugin project using the following XML property file, that includes a custom appender called EclipseLoggingAppender:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">

<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/" debug="true">
  <appender name="eclipseErrorView" class="com.lior.ibd.utils.logging.EclipseLoggingAppender"/>

<appender name="console" class="org.apache.log4j.ConsoleAppender">
    <param name="Target" value="System.out"/>
    <layout class="org.apache.log4j.PatternLayout">
      <param name="ConversionPattern" value="%-5p %c{1} - %m%n"/>
    </layout>
  </appender>

  <root>
    <priority value ="debug" />
    <appender-ref ref="console" />
  </root>
  <logger name="com.lior">
    <level value ="warn" />
    <appender-ref ref="eclipseErrorView" />
  </logger>

</log4j:configuration>

I pass this property file to the following statement in the code:
DOMConfigurator.configure(filename);

But when loading the application I get the following error message:
log4j:ERROR Could not create an Appender. Reported error follows.
java.lang.ClassNotFoundException: com.lior.ibd.utils.logging.EclipseLoggingAppender

Anyone knows what's the deal? could be a classpath issue?..

A: for starters you can only have one <root> element.  You want something more like
<appender name="eclipseErrorView" class="com.mypackage.EclipseLoggingAppender">
  <filter class="org.apache.log4j.varia.LevelRangeFilter Source code of org.apache.log4j.varia.LevelRangeFilter">
    <param name="LevelMin" value="WARN" />
  </filter>
</appender>

<root>
  <priority value ="debug" />
  <appender-ref ref="console" />
  <appender-ref ref="eclipseErrorView" />
</root>

How have you added your custom logger to the classpath?

A: Yes, this is a classpath issue. Log4j is looking for class com.lior.ibd.utils.logging.EclipseLoggingAppender.
(probably appender that wrote someone in your organisation?)
If you remove lines:
 <appender name="eclipseErrorView" class="com.lior.ibd.utils.logging.EclipseLoggingAppender"/>

and
 <logger name="com.lior">
   <level value ="warn" />
   <appender-ref ref="eclipseErrorView" />
 </logger>

log4j should handle it.
Or add EclipseLoggingAppender to classpath by locating a appropriate jar file and add it to the classpath. I.e. run
java -cp appender.jar com.mypackage.MyClass


text:
Q: how to create a list item with checkbox kivymd? I want to create a list item with a a check box on the left like in the image:
enter image description here

A: from kivy.lang import Builder
from kivy.properties import StringProperty

from kivymd.app import MDApp
from kivymd.uix.list import IRightBodyTouch, OneLineAvatarIconListItem
from kivymd.uix.selectioncontrol import MDCheckbox
from kivymd.icon_definitions import md_icons

KV = '''
<ListItemWithCheckbox>:

    IconLeftWidget:
        icon: root.icon

    RightCheckbox:

MDBoxLayout:

    ScrollView:

        MDList:
            id: scroll
'''

class ListItemWithCheckbox(OneLineAvatarIconListItem):
    '''Custom list item.'''

    icon = StringProperty("android")

class RightCheckbox(IRightBodyTouch, MDCheckbox):
    '''Custom right container.'''

class MainApp(MDApp):
    def build(self):
        return Builder.load_string(KV)

    def on_start(self):
        icons = list(md_icons.keys())
        for i in range(30):
            self.root.ids.scroll.add_widget(
                ListItemWithCheckbox(text=f"Item {i}", icon=icons[i])
            )

MainApp().run()

https://kivymd.readthedocs.io/en/latest/components/list/#custom-list-item


text:
Q: Why do multiple forces or wave act together in such a way that one wave/force does not affect the action of other? In case of force I am referring to principle of physical independence of forces. What is the theoretical proof of it? Is it something just empirical?
In case of waves, we get to observe that after superposition two waves propagate in such a way that nothing happened between them. Why does it happen and what is its proof(theoretical)?
I am just curious about these. I basically asked two questions in one because I think these two questions are almost the same and perhaps have pretty answers. I have looked for answers to these questions on internet but couldn't find anything related by far.
Any link regarding answers to this will also be very helpful
Thank you.

A: "Why" questions often don't have an answer in physics. Physics describes how the universe behaves. It does not say why it does so.
Sometimes you can answer. A complex law might be derived from a simple law. Why is the complex law true? Because the simple law is. But that just makes a new question. Why is the simple law true? Eventually you come to a law that is not derived from anything.
For these laws, and all laws of physics, the ultimate thing that decides if they are true is if they agree with experiment. So yes, they are empirical.
Keep in mind there are two things. There is the way the universe behaves. And there is physics, a mathematical description of the way the universe behaves. The math is chosen to match the behavior. Physicists get used to deriving one mathematical law from another, and then doing experiments to verify the math matches the universe. They quickly start to think of the math and behavior as the same thing.
For your question about multiple forces, the relevant laws are Newton's laws. The second law describes the relationship between force and acceleration. Both of these are vectors.
People usually think of vectors as little arrows. But really they are things with a size and direction that behave reasonably when added together. Little arrows are the most common example of this.
So a physicist watches a tug of war where the two teams pull equally hard. He sees that neither team moves. He says the two teams exert equal forces in opposite directions. Forces are vectors. Equal and opposite vectors add to $0$. $F = ma$, so $a = 0$. Objects at rest stay at rest unless a (non-$0$) force acts on them.
Physicists think about the universe in terms of a mathematically consistent set of laws. The universe behaves this way because these laws say so.
But the part you are asking about is why do both teams stay still when each pulls equally hard. They just do. That is just the way the universe works.
You can see that adding the math makes it a lot easier to talk about the behavior and verify it. You use numbers to say how hard each team is pulling and how they are accelerating. Without numbers, it is hard to be precise about things. And that is why physicists think the way they do.
We owe this way of thinking to Galileo. He showed that the behavior of the universe could be precisely described by mathematical laws. He laid down the first simple laws of motion. Not long afterward, Newton greatly expanded his ideas, and revolutionized how we think about nature.
Before this, the behavior of the universe was a branch of philosophy called natural philosophy. People thought of the reason the wind blows in terms clouds with faces blowing. Aristotle said a moving rock comes to rest because it is the nature of rocks (earth) to be at rest. A disturbance might temporarily change this, but the nature of the rock will assert itself. This is different from celestial object like the sun, planets, and stars (fire, air). Their nature is to move.
For more on this, see Sean Carroll's first episode of The Biggest Ideas in the Universe | 1. Conservation


text:
Q: Time stamp at R prompt possible?
Possible Duplicate:
R: Display a time clock in the R command line

Is there any way to configure R so that it will display a time stamp before the prompt ">"?
Thanks a lot
EC

A: This will do it:
options(prompt=paste(Sys.time(),"> "))

I forget how to make it update though. I'll try to check when I get a sec...
Ahh found it:
updatePrompt <- function(...) {options(prompt=paste(Sys.time(),"> ")); return(TRUE)}
addTaskCallback(updatePrompt)