text:
Q: Transmission coefficient The transmission coefficient can be calculated as
$$T=\left ( 1+\frac{1}{4}\frac{\left ( p_{0}^{2}-p_{1}^{2} \right )^{2}}{p_{0}^{2}p_{1}^{2}} \sin^2 \left( \frac{p_1 a}{\hbar} \right )\right )^{-1}$$
where $p_0 = \sqrt{2mE}$, and $p_1 = \sqrt{2m ( E - V_0 )}$.
What happens to the transmission coefficient when $p_1 a =n\pi\hbar$? What is the relationship between the de Broglie wavelength of the particle in region $0\leq x\leq a$ and the width of the potential barrier in this case.
Here's what I think, for very large energy $E$ the comparison reduces to
$$T = \left(  \sin^2 \left( \frac{p_1 a}{\hbar} \right) \right)^{-1}
\quad \text{and} \quad
T = \left(  \sin^2 \left ( n \pi \right) \right)^{-1} \, .$$
I'm very much left clueless at this point. Some hints would be helpful.

A: Because
$\sin^2(\frac{n\pi h}{h}) = 0 $
Then T is just $1^{-1} = 1$
You must be asking what is the wavelength inside and outside the barrier
when the particle is outside the barrier it must have more energy and thus a smaller wavelength
Outside the barrier
$p_0 = \sqrt{2mE} = \sqrt{2mK_0} = \sqrt{2m  \frac{p^2}{2m}} = p_a$
and the De Broglie equation states that
$\lambda = \frac{h}{p}$
so  $\lambda_1 = \frac{h}{p_a}$
We are taking $E$ as $K$ because it is actually $E-V_0$ where $V_0$ is 0
Inside the barrier
$p_1 = \sqrt{2m(E-V_0)}$
$p_1 = \sqrt{(2mK_1)}$
$p_1 = p_b$
$\lambda_2 = \frac{h}{p_b} = \frac{1}{n\pi}$
$p_a > p_b$
so $\lambda_1 < \lambda_2$
which makes sense because the kinetic energy is greater outside


text:
Q: round values by row instead of columns Rather than pivoting is it possible to round values of a dataset by rows instead of columns? The standard way is to round columns using mutate_at or now with across but I would prefer to do by specific rows:
library(tidyverse)

set.seed(10)
df <- data.frame(let = sample(letters, 20),
                 x = rnorm(20),
                 y = rnorm(20) + 10,
                 z = rnorm(20) + 30)
df

#for rows where "let" = i, j, k, h round to 2 decimal places using ~round(., 2)
round_2 = c("i", "j", "k", "h")

#for rows where "let" = a, b, c, d, e round to  decimal places using ~round(., 0)
round_0 = c("a", "b", "c", "d")

#typical type approach with columns
#df %>%
#  mutate(across(matches("x|y"), ~round(., 0)))
#df %>%
#  mutate(across(matches("z"), ~round(., 2)))

Maybe rowwise could be used here?
thanks

A: data.table solution
library( data.table )
setDT(df)
cols = c("x", "y", "z")
df[ let %in% round_2, (cols) := round( .SD, digits = 2), .SDcols = cols][]
df[ let %in% round_0, (cols) := round( .SD, digits = 0), .SDcols = cols][]

#     let            x         y        z
#  1:   k -0.710000000  9.870000 29.94000
#  2:   i -0.370000000  9.220000 29.81000
#  3:   j -1.320000000 10.090000 31.01000
#  4:   p  1.280597456 10.064564 30.07160
#  5:   l  0.667415054 10.115208 31.36119
#  6:   h  1.690000000 11.770000 30.82000
#  7:   g  0.001261409  9.186451 30.52619
#  8:   s -0.742461312  9.910625 29.57074
#  9:   o  0.609684421 10.314817 30.16474
# 10:   r -0.989606379  7.939459 29.22681
# 11:   x -0.034848335  9.400197 29.62148
# 12:   t  0.847159906  9.046434 31.65189
# 13:   w  1.525498006 10.557506 28.32389
# 14:   b  0.000000000 10.000000 29.00000
# 15:   u  0.210143002 10.973221 29.42507
# 16:   v -0.081721617 10.101948 31.08997
# 17:   q  0.013249400  8.119381 30.12649
# 18:   f -1.203106335  8.456234 29.27683
# 19:   n -0.261154359  9.766260 31.42620
# 20:   c  1.000000000 11.000000 31.00000

A: Since let column is available inside the mutate function you could do:
df %>%
  mutate_at(c('x', 'y', 'z'), ~round(., case_when(
    let %in% round_0 ~ 0,
    let %in% round_2 ~ 2
  )))

For dplyr >= 1.0.0:
df %>%
  mutate(across(matches('x|y|z'), ~round(., case_when(
    let %in% round_0 ~ 0,
    let %in% round_2 ~ 2
  ))))

Result:
   let     x     y     z
1    k -0.71  9.87 29.94
2    i -0.37  9.22 29.81
3    j -1.32 10.09 31.01
4    p    NA    NA    NA
5    l    NA    NA    NA
6    h  1.69 11.77 30.82
7    g    NA    NA    NA
8    s    NA    NA    NA
9    o    NA    NA    NA
10   r    NA    NA    NA
11   x    NA    NA    NA
12   t    NA    NA    NA
13   w    NA    NA    NA
14   b  0.00 10.00 29.00
15   u    NA    NA    NA
16   v    NA    NA    NA
17   q    NA    NA    NA
18   f    NA    NA    NA
19   n    NA    NA    NA
20   c  1.00 11.00 31.00

redpajama_set_name: RedPajamaStackExchange


text:
Q: Automatically generating API Documentation I am a junior Java developer and I have been working on a big project recently. A part of it was creating RESTful Web services using Jersey for third party clients. Now, after finishing the project, I am tasked to document all the web service calls (I know I should have started that from the beginning) Is there any straightforward tool/Eclipse plugin that generates automatically the API  documentation without a lot of hassle ?

A: I have used enunciate, it parses the javadoc and JAX-RS annotations of your service classes to generate documentation:
https://github.com/stoicflame/enunciate/wiki
There is a maven plugin that works well.It also generates client libraries in various languages as well as sample xml for xml based services.


text:
Q: Flutter: cannot find symbol MethodCallHandler I'm trying to get my Flutter app to receive data from other apps via iOS/Android sharing dialogs. Basically I want to be able to receive http links.
While there are a couple of plugins that allow to share from Flutter, I can't seem to find anything when it comes to receiving data (at least not cross-platform).
I've been working through this example from the official Flutter documentation, but it doesn't work.
MainActivity.java throws the exception "cannot find symbol MethodCallHandler".
MainActivity.java:

package com.example.flutterlink;

import android.content.Intent;
import android.os.Bundle;

import java.nio.ByteBuffer;

import io.flutter.app.FlutterActivity;
import io.flutter.plugin.common.ActivityLifecycleListener;
import io.flutter.plugin.common.MethodCall;
import io.flutter.plugin.common.MethodChannel;
import io.flutter.plugins.GeneratedPluginRegistrant;

public class MainActivity extends FlutterActivity {

  private String sharedText;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    GeneratedPluginRegistrant.registerWith(this);
    Intent intent = getIntent();
    String action = intent.getAction();
    String type = intent.getType();

    if (Intent.ACTION_SEND.equals(action) && type != null) {
      if ("text/plain".equals(type)) {
        handleSendText(intent); // Handle text being sent
      }
    }

    new MethodChannel(getFlutterView(), "app.channel.shared.data").setMethodCallHandler(
            new MethodCallHandler() {
              @Override
              public void onMethodCall(MethodCall call, MethodChannel.Result result) {
                if (call.method.contentEquals("getSharedText")) {
                  result.success(sharedText);
                  sharedText = null;
                }
              }
            });
  }

  void handleSendText(Intent intent) {
    sharedText = intent.getStringExtra(Intent.EXTRA_TEXT);
  }
}

Any hints?

A: The documentation was updated a few days ago and now includes the missing import import io.flutter.plugin.common.MethodChannel.MethodCallHandler;


text:
Q: MYSQL (large) UPDATE performance is essentially I/O bound: what lessons to learn? I have this fairly large myISAM table (95M+ rows) to update once a day (5M+ rows).
The query is straightforward
UPDATE main_table a JOIN updated_values b ON a.id=b.id set a.theCount=b.theCount;

Time to execute

*

*SSD RAID 5 : 960s

*ramDisk : 124s

*MEMORY tables : 20.1s

These figures show that the UPDATE call is I/O bound (20s to execute when the data is already in memory...). Not clear, however, what to do. RamDisks and MEMORY tables require writing the data to a stable medium. Converting a table from MEMORY to MyISAM takes forever. Such that the fastest solution appears to be to copy the MyISAM files to the ramDisk, update, and copy back to the SSD raid, which takes less than 20s RT.
Is there any way to configure mySQL buffers such that there would be no need to bother with a ramDisk? (this system runs on a Mac)


text:
Q: incomplete gamma function in python? the scipy.special.gammainc can not take negative values for the first argument. Are there any other implementations that could in python? I can do a manual integration for sure but I'd like to know if there are good alternatives that already exist.
Correct result: 1 - Gamma[-1,1] = 0.85

Use Scipy: scipy.special.gammainc(-1, 1) = 0

Thanks.

A: I typically reach for mpmath whenever I need special functions and I'm not too concerned about performance.  (Although its performance in many cases is pretty good anyway.)
For example:
>>> import mpmath
>>> mpmath.gammainc(-1,1)
mpf('0.14849550677592205')
>>> 1-mpmath.gammainc(-1,1)
mpf('0.85150449322407795')
>>> mpmath.mp.dps = 50 # arbitrary precision!
>>> 1-mpmath.gammainc(-1,1)
mpf('0.85150449322407795208164000529866078158523616237514084')

A: I just had the same issue and ended up using the recurrence relations for the function when a<0.
http://en.wikipedia.org/wiki/Incomplete_gamma_function#Properties
Note also that the scipy functions gammainc and gammaincc give the regularized forms Gamma(a,x)/Gamma(a)

A: Still an issue in 2021, and they still haven't improved this in scipy.  Especially it is frustrating that scipy does not even provide unregularised versions of the upper and lower incomplete Gamma functions.   I also ended up using mpmath, which uses its own data type (here mpf for mpmath floating - which supports arbitrary precision).  In order to cook up something quick for the upper and lower incomplete Gamma function that works with numpy arrays, and that behaves like one would expect from evaluating those integrals I came up with the following:
import numpy as np
from mpmath import gammainc

"""
In both functinos below a is a float and z is a numpy.array.
"""

def gammainc_up(a,z):
    return np.asarray([gammainc(a, zi, regularized=False)
                       for zi in z]).astype(float)

def gammainc_low(a,z):
    return np.asarray([gamainc(a, 0, zi, regularized=False)
                       for zi in z]).astype(float)

Note again, this is for the un-regularised functions (Eq. 8.2.1 and 8.2.2 in the DLMF), the regularised functions (Eq. 8.2.3 and 8.2.4) can be obtined in mpmath by setting the keyword regularized=True.


text:
Q: How to use javascript to store variables to window correctly? I am trying to use JSNI (gwt's javacript interface) to set/get variable to/from js object:window like this:
private final native <T> T get(String key)/*-{
    return $wnd.key;
}-*/;

private final native void set(String key, Object value)/*-{
    $wnd.key = value;
}-*/;

///// js equivalent should like this
function get(String key){
    return window.key;
}

function set(String key, var value){
    window.key = value;
}

and if I set a variable: var_1 to window:
var var_1={"id":"id_1","name":"name_1"}
set("key_1",var_1)

then
get("key_1")

I will get var_1 correctly
and then set another variable var_2 to window
var var_2={"id":"id_2","name":"name_2"}
set("key_2",var_2)

then,try to get key_1 again
get("key_1")

unexpectedly,var_2 will be returned
so,the problem is obvious:the get() function will always return the last set variable no matter what key is.Questions are:
1,Why?
2,How to make it right?

A: After Changing to
private final native <T> T get(String key)/*-{
    return $wnd[key];
}-*/;

private final native void set(String key, Object value)/*-{
    $wnd[key] = value;
}-*/;

Both set and get work as expected now.

A: You don't need to deal with JSNI for this, you already have some useful methods in the Element class, so just cast the object Window to an element and that is.
This code should work:
Element window = ScriptInjector.TOP_WINDOW.cast();

window.setPropertyJSO("key_jso", JsArray.createArray());
JavaScriptObject jso = window.getPropertyJSO("key_jso")

window.setPropertyBoolean("key_boolean", true);
boolean b = window.getPropertyBoolean("key_boolean")

// and the same with:
// setPropertyDouble, getPropertyDouble
// setPropertyInt, getPropertyInt
// setPropertyString, getPropertyString
// setPropertyObject, getPropertyObject

If you are using gwtquery, a library I recomend to always import in any gwt project, you can simply do:
import static com.google.gwt.query.client.GQuery.*;

$(window).prop("key", value);
boolean b = $(window).prop("key");
// or
boolean b = $(window).prop("key", Boolean.class);
// And the same with any type (JavaScriptObject, Double, Integer ...)


text:
Q: How to start slideshow in PowerPoint using com32 I am trying to control my PowerPoint presentation using python via com.
There is an article on how to do this here and it suggest I do the following:
app = win32com.client.Dispatch("PowerPoint.Application")
objCOM = app.Presentations.Open(FileName="path_to_file", WithWindow=1)
objCOM.SlideShowWindow.View.Next()

If I do this, I get the error
 (-2147352567, 'Ausnahmefehler aufgetreten.', (0, 'Microsoft PowerPoint', 'Presentation.SlideShowWindow : Invalid request.  There is currently no slide show view for this presentation.', '', 0, -2147188160), None)

On the last line. It seems, that Open does not start the slide show.
I have been looking through the documentation of the PowerPoint object model here, but was unable to find a way to start the slide show of a presentation.
Any suggestions on how to do this?

A: Call SlideShowSettings.Run() after opening the file:
import win32com.client as win32
app = win32.Dispatch("PowerPoint.Application")
objCOM = app.Presentations.Open(FileName="path_to_file", WithWindow=1)

#START THE SLIDESHOW
objCOM.SlideShowSettings.Run()

objCOM.SlideShowWindow.View.Next()


text:
Q: Universal Send email html or plain text php Been there for days wraps over the fact that I can create a script that sends HTML mail template, and in case the user has a client who can not read HTML and plain text listing is possibly the receiving HTML email off.
Please some universal advice on how to do it. I went through the whole internet and I really do not know.
Thank you so much for your advice.

A: You should add html and plain text version of email called multipart/alternative in same email body:
<?php

        $from = "a asd";
        $email = "sd@dfsds.com";
        $email = "sdsad@sdfsdf.com";

                $semi_rand = md5(time());
                $mime_boundary = "==MULTIPART_BOUNDARY_$semi_rand";
                $mime_boundary_header = chr(34) . $mime_boundary . chr(34);
                $boundary = "nextPart";
                $headers = "From: \"".$from."\" <".$email.">\n";

                $headers .=  "To: ". $new_to ."\n";

                $headers .= "Reply-To: \"". $from. "\" <" . $email . ">\r\n";
                $headers .= "Return-Path: <". $email .">\r\n";
                $headers .= "MIME-Version: 1.0\r\n";
                $headers .= "Content-Type: multipart/alternative;\n boundary=" . $mime_boundary_header ;
                $headers .= "\n--$boundary\n"; // beginning \n added to separate previous content
                $headers .= "Content-type: text/plain; charset=iso-8859-1\r\n";
                $headers .= "\n--$boundary\n";
                $headers .= "Content-type: text/html; charset=iso-8859-1\r\n";
                $headers .= "Content-Transfer-Encoding:base64\r\n";
$body = "

--$mime_boundary
Content-Type: text/plain; charset=us-ascii
Content-Transfer-Encoding: 7bit

". strip_tags($messageBody) ."

--$mime_boundary
Content-Type: text/html; charset=us-ascii
Content-Transfer-Encoding:base64

". chunk_split(base64_encode($messageBody)) ."

--$mime_boundary--";

mail(null,$sub,$body,$headers,"-f".$email);

A: Why don't you use MailChimp for that? It seems to have all the features you want.


text:
Q: L298N H-Bridge : Powering 4 motors using (6) aa batteries vs (4) aa I am currently wiring up my raspberry pi, H-Bridge and (4) 3-6v ratting motors. My question is, how will performance change based on me using 6 or 4 batteries to power motors? I noticed some tutorials using (6) aa batteries totaling 9V. Why waste two extra batteries and risk too much voltage? Besides the motor ratting is 3-6v; wouldnt 9volts fry the motors? Ive read the H-Bridge has a 5v regulator. Does this mean even if you supply more then 5volts the h-bridge will keep it at 5v?

A: *

*The L298 is a very old technology part.  It drops about 3V total from battery to load -- so a 9V source would only be 6V at the motor in the end.

*Dry cells only deliver 1.5V/cell when they are freshly charged and moderately loaded.  At heavy load, or any load when they're discharged, they supply less.  If you want to suck the life out and not throw away batteries with charge left, design for 0.9V/cell

*6 cells times 0.9V/cell works out to 5.4V.  Subtract out the 3V drop for the L298, and you have 2.4V.

A: The L298N chip itself will only supply the motors with the supply voltage, and change it based on PWM values. Many common L298N boards are available in project kits, with the chip itself, a heatsink, a 5V regulator, and  terminal blocks etc. I think you have one of these - they are very common online, for example, an example listing of one. These have a 5V regulator that you can use (if you want) to power the Pi - as long as your input source is larger than 5 (should be over 7V), the regulator will fix the output pin at 5V. The voltage into the motors should depends on the voltage that the motor is rated at - using 6 AAs will make it faster than only 4 AAs, but the motor needs to be able to handle 9V.
From your question it appears you are concerned about the regulator - rest assured, there is a limit (based on the regulator) where the regulator will keep working, and will supply a constant 5V out regardless of the supply voltage. Since the Pi runs off of 5V (USB power) it can be run from there, which means you only need 1 power supply. The motors would be your main area of concern - a 3-6V motor should not be connected to a 9V supply. You should use a 6V regulator, buck-boost converter, or potential divider to reduce the voltage. Otherwise, stick to 4AAs which should give you 6V nicely.


text:
Q: Vuejs how to pass data from main.js to App.vue with props I'm having an issue where the App component and HelloWorld component are not getting passed data from main.js. This should be a rather simple thing to do in Vue.

You can see in the image that the root element has counter defined as 10, it's just not being populated in any of the child components. almost like line 12 in main.js is not taking any effect. If I click  and  it says 'counter: undefined'. What am I doing wrong? I've been beating my head against the wall for a few hours now.
Here is my main.js
import Vue from 'vue'
import App from './App.vue'

Vue.config.productionTip = false

new Vue({

  components: {App},
  data: {
    counter: 10
  },
  template: '<App :counter="counter" />',
  //computed: {
  //  counterInc: function () {
  //    return this.counter++
  //  }
  //},
  methods: {
    updateCounter (x) {
      this.counter = x
    }
  },

  render: h => h(App)
}).$mount('#app')

Here is my App.vue

<template>

    <HelloWorld msg="Our Message" :counter="counter"/>

</template>

Here is my helloworld.vue

<template>

{{ msg }}

      Here lies all of our operations for automating some strenuous tasks.

Get Started {{ counter }}

Generate Purchase Price

</template>

A: So I don't personally use the render function much, but what you can do to get your code working is supply the initial template in the actual html page and mount the Vue instance to it. I've made a codepen here : https://codepen.io/crustyjew/pen/jeWPgY
The essentials are to remove your render function, add the following to html

  <app :counter="counter" />

leaving .$mount('#app') to mount it to that html you provide.

A: If you don't want to use the template compiler-included vue build, then you can implement a render function like this to pass prop values:
render: h => h(App, {
  props: {
    'counter': 10
  }
})

(Source: https://v2.vuejs.org/v2/guide/render-function.html#createElement-Arguments - the h argument of render functions is an alias for createElement.)

A: Matti gave you already an answer, but you may want to think about your project structure. It shouldn't be the goal to pass data from your root component to the lowest child component.
In your case you have two options:

*

*Use events to emit an event from your component to update the state in another component. See https://v2.vuejs.org/v2/guide/components-custom-events.html for more information.

*Use a state management like vuex. Vuex is used to handle you state globally. You can access the state with getters from all your components, without passing your data manually to each component, which needs access to the data. Furthermore vuex provides actions/mutations, which allows you to update the state. For more information see https://vuex.vuejs.org/.

For small projects vuex might be to much overhead for an equal result. But if you project gets bigger and bigger it's really hard to know what's going on in your components, when passing data through multiple components.


text:
Q: Should all SE network sites only accept questions that have a single acceptable answer? From my experience on the SE network so far, the intent of an SE network site is to provide a singular correct answer to each question. Basically, if someone has a question that's answered on an SE network, and they google it, they want the question to appear first so that person just needs to check the accepted answer for that question. This works fine for many of the SE sites: SO, SU, SF and many of the other sites get questions that have 1 answer that works for most people and maybe a few other answers that can be used if the popular vote answer does not work for whatever reason.
However, there are also a number of exchange sites that are based on an entirely different question logic:

*

*Worldbuilding has a focus on basically crowdsourcing answers to open-ended questions with no cut & dry answer. They are less "this is the right answer" and more "this & this & this are consequences of the statement from the question", where each consequence can be found in a different answer and accepting 1 answer usually is not really an option because it means choosing the most correct answer from several correct answers.

*Parenting allows people to get feedback on issues they encounter while parenting, which depending on the situation might not be the right answer to the next user to visit.

*Code Review is similar to Worldbuilding in that there are usually multiple correct answers, but each answer has their own merit and brings a different nitpick to the code provided in the question.

*Programming Puzzles & Code Golf is based on a competitive mentality where each answer is a separate contestant to the competition, complete with leaderboards, scoring rules and restrictions that can vary from "no loophole abuse" to "your code may not include the letter E". The main difference is that the "best" answer potentially can change days or even weeks later, when a new contestant tries their luck and beats the current leader.

There are other exchanges that have a similar issue: the basic way in which their field works and the tendency to have soft, open-ended questions where there can be more than 1 answer that's correct and most answers are equally correct. The SE paradigm started by the 3 original sites in this network where there is 1 acceptable, canonical answer and maybe a few backup methods just plain does not work for these exchanges, because they're based on an entirely different methodology.
I am NOT trying to say that these SE sites should be removed, closed or otherwise impeded though. These exchanges have their own right of existence, because they still have a purpose and a devoted audience. They also still have the main focus of the SE network in them: questions and answers, guided by a reputation and voting system to weed out the bad answers. However, they use their system in a different way: instead of "this answer/question has helped me, I shall upvote it", it's "this question/answer is intriguing and interesting to read, I shall upvote it". this is not a wrong way, it's just a different way. And they still help people: many of these SEs get traffic from outside the network from people trying to find answers to problems they have.
The main difference is that these softer SEs usually have a bigger focus on discussions instead of decisions. That is one of the places where the SE framework in my opinion starts to work AGAINST these softer exchanges: the SE framework focuses on getting a correct answer, with discussion being relegated to chatrooms with far fewer users, much downtime and a rep requirement. Moderators are encouraged to move discussions to these chat rooms, making it harder for people to remain interested in them because they can't consult the question that prompted the discussion as easily. Comment threads are moved to chatrooms, sometimes even before they're finished, often hiding astute remarks and observations that are part of these comments and can easily change the quality of the answer or question they're part of.
I think banning these SE sites is not really a good idea. They're popular, they're interesting and they fill a niche (for example: googling World building gives the SE site as the second page where users can place their own requests for comment, after Reddit which has an entirely different format). They need their own solution, but I'm not sure what that would be.

A: Perhaps the most exact SE, namely Mathematics, has multiple acceptable solutions, as there are multiple methods to solve a problem.
The most useful or elegant answers will float to the top through voting. The acceptance mark is a way to give the asker a way to say thank you to the most helpful answer.

A:
TL;DR;
Often is the case whereby it's better to have and not need, than to need and not have.
Not always, of course, but the accepted answer function is not causing any problems by being present and not used. While it may be very rare to be able to accept an Answer on some specific sites/tags, that does not mean that it will never be used.

Regarding your examples

Worldbuilding .. no cut & dry answer... are less "this is the right
  answer" and more "this & this & this are consequences of the statement
  from the question" ... it means choosing the most correct answer from
  several correct answers.

If that is what the Question author wants to base their "accept" mark on, then yes, but that is not the only reason to accept an Answer.
It just means choosing the Answer which the Question asker preferred. And this can be personal reasons and not necessarily anything to do about quality or being correct. They could choose a non-correct Answer if they wish, perhaps it made them laugh, or whatever reason.
Worldbuilding front page shows 8 accepted Answers.

Parenting.. Which depending on the situation might not be the right
  answer to the next user to visit.

Accepted Answers are not to represent what might be useful to others, it literally is just that the Question asker preferred that Answer for whatever reason.
Parenting front page shows 4 questions with accepted Answers.

Code Review.. usually multiple correct answers, but each answer has
  their own merit and brings a different nitpick to the code provided in
  the question.

This doesn't stop Question author choosing an Answer which helped them the most.
Code review front page shows 7 questions with accepted Answers.

Programming Puzzles & Code Golf .. The main difference is that the
  "best" answer potentially can change days or even weeks later, when a
  new contestant tries their luck and beats the current leader.

Question author can change their chosen accepted Answer. Also, Answers changing, even being improved, doesn't necessarily invalidate the Question asker's reasons to accept a particular Answer.
Programming Puzzles & Code Golf front page shows 1 question with an accepted Answer.

The problems you've highlighted above are present on most if not all sites - in that it can be tricky choosing which Answer to accept. But if there is no obvious one based on the Question author's preferences etc, then they can just not accept. It's not imperative to choose one.

SE is SE is Q&A

the SE framework focuses on getting a correct answer, with discussion
  being relegated to chatrooms with far fewer users, much downtime and a
  rep requirement. Moderators are encouraged to move discussions to
  these chat rooms, making it harder for people to remain interested in
  them because they can't consult the question that prompted the
  discussion as easily.

If a question needs extended discussion in comments then either:

*

*The question is not fit for the Stack Exchange Q&A format

*The commentors are not asking for the right verifications

*The question is unclear

*It's extended and should be in chat

I know this isn't always the case, but the problem is you want to discuss something, e.g. about a Parenting question or Answer, but this is not a discussion site. It is literally and always a Q&A site, where we get answers to our questions, not have discussions.
FWIW I do sympathise here, as will many others. Sometimes it would be nice to make it a forum on some questions :)
Maybe use the site's Meta to advertise/drive more people to chat where you can chew the fat as desired/required.

Stats
It would be useful to get stats to show "total accepted answers" on sites/tags you feel the function is pointless. It only takes a handful of accepted usages and we have a strong argument to keep the function.

A: The Granddaddy of them all - Stack Overflow - doesn't have the requirement that there's one (and only one) acceptable answer. There is no rule that states that the questioner must accept an answer. In fact all the green acceptance tick means is "this answer helped me the most". It can be awarded to any answer and that answer doesn't have to be the "best" answer.
To any problem, programming or not, there are potentially many solutions and the Q&A format of Stack Exchange is working just fine. The various answers compete for votes from the rest of the community and the one(s) that people think offer the best solution to the problem rise to the top.
The fact that the concept of accepting an answer is less meaningful on some sites isn't an issue - it just makes it more special when an answer is accepted.
Discussion isn't banned outright - it's extended discussion that's discouraged. There's enough space in comments and chat to discuss an answer and with editing it can be improved and extended as required (just as we're doing here). One of the key points about Stack Exchange is that answers aren't set in stone once they've been posted. They can (and indeed should) be improved as flaws etc. are pointed out, or new information comes to light.
Also, don't forget that answers don't necessarily have to address the whole question - especially on sites that allow broader, softer questions - they can just focus on one aspect leaving other aspects of the question to be addressed by other answers.


text:
Q: Obtaining Cypher queries for creating existing nodes and relationships in future Is their any way to obtain/generate Cypher queries for creating all nodes and relationships in the future, say on another machine, on completely new installation of Neo4j (in the same way that in examples there is set of Cypher queries given for creating Movie graph).

A: The neo4j-shell has a dump command that can output the complete Cypher dump. I'm not sure how well it performs with large graphs.
neo4j-shell -c dump > backup.txt

A: Depending on what you are trying to achieve, GraphGists might be of interest as a way to publicly document and share Cypher queries. You can use @MartinPreusse's suggestion as a way to generate the Cypher queries.


text:
Q: Using dynamic linq extensions with jqgrid on one to many relationships Im not sure if the title of the question is correct if not let me know and i will change it. Okay so firstly im using jgrid in a asp.net application. I have a helper that sets up the page size, rows and does the sorting. The issue is i can only sort on parameters for the current table it does not work when the parameter name is from a separate table connected through a relationship.
The linq extension is for orderBy and thenBy, they both take a string parameter and sort order parameter. I have tried setting the string parameter as "WaterSample.Name", watersample being another table from a relationship and name a parameter in that table but unfortunately i cannot do it this way in c# since i am using an anonymous type. So my question is can i make the line extensions search through the relationships to find match the property name. Sorry if this is a bit confusing im still fairly new to linq.
i have included the class below that contains the extensions.
namespace Helpers
{
    [ModelBinder(typeof(GridModelBinder))]
    [Serializable]
    public class JqGridSettings
    {

        public int PageIndex { get; set; }
        public int PageSize { get; set; }
        public string SortColumn { get; set; }
        public string SortOrder { get; set; }
        public string SortColumn2 { get; set; }
        public string SortOrder2 { get; set; }
        public string SortColumn3 { get; set; }
        public string SortOrder3 { get; set; }

        public JqGridSettings()
        {
        }

        /// <summary>
        /// Initializes a new instance of the GridSettings class.
        /// </summary>
        /// <param name="stringData">The string that represents the a GridSettings object.</param>
        public JqGridSettings(string stringData)
        {
            var tempArray = stringData.Split(new[] { "#;" }, StringSplitOptions.None);
            PageSize = int.Parse(tempArray[0]);
            PageIndex = int.Parse(tempArray[1]);
            SortColumn = tempArray[2];
            SortOrder = tempArray[3];
        }

        /// <summary>
        /// Build a string used to cache the current GridSettings object.
        /// </summary>
        /// <returns>A string that represents the current GridSettings object.</returns>
        public override string ToString()
        {
            return string.Format("{0}#;{1}#;{2}#;{3}", PageSize, PageIndex, SortColumn,SortOrder);
        }

        public IQueryable<T> LoadGridData<T>(IQueryable<T> dataSource, out int count)
        {
            var query = dataSource;
            //
            // Sorting and Paging by using the current grid settings.
            //
            query = query.OrderBy<T>(SortColumn, SortOrder);
            if (String.IsNullOrEmpty(SortColumn2) == false)
            {
                query = query.ThenBy<T>(SortColumn2, SortOrder2);
            }
            if (String.IsNullOrEmpty(SortColumn3) == false)
            {
                query = query.ThenBy<T>(SortColumn3, SortOrder3);
            }
            count = query.Count();
            //
            if (PageIndex < 1)
                PageIndex = 1;
            //
            var data = query.Skip((PageIndex - 1) * PageSize).Take(PageSize);
            return data;
        }
    }

    public static class LinqExtensions
    {
        public static IQueryable<T> OrderBy<T>(this IQueryable<T> query, string sortColumn, string direction)
        {
            var methodName = string.Format("OrderBy{0}", direction.ToLower() == "asc" ? "" : "descending");
            var parameter = Expression.Parameter(query.ElementType, "p");
            var memberAccess = sortColumn.Split('.').Aggregate<string, MemberExpression>(null, (current, property) => Expression.Property(current ?? (parameter as Expression), property));

            var orderByLambda = Expression.Lambda(memberAccess, parameter);
            var result = Expression.Call(typeof(Queryable),methodName,new[]{query.ElementType, memberAccess.Type},query.Expression,Expression.Quote(orderByLambda));

            return query.Provider.CreateQuery<T>(result);
        }

        public static IQueryable<T> ThenBy<T>(this IQueryable<T> query, string sortColumn, string direction)
        {
            var methodName = string.Format("ThenBy{0}", direction.ToLower() == "asc" ? "" : "descending");
            var parameter = Expression.Parameter(query.ElementType, "p");
            var memberAccess = sortColumn.Split('.').Aggregate<string, MemberExpression>(null, (current, property) => Expression.Property(current ?? (parameter as Expression), property));

            var orderByLambda = Expression.Lambda(memberAccess, parameter);
            var result = Expression.Call(typeof(Queryable), methodName, new[] { query.ElementType, memberAccess.Type }, query.Expression, Expression.Quote(orderByLambda));

            return query.Provider.CreateQuery<T>(result);
        }
    }

    public class GridModelBinder : IModelBinder
    {
        public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            try
            {
                var request = controllerContext.HttpContext.Request;
                return new JqGridSettings
                {
                    PageIndex = int.Parse(request["page"] ?? "1"),
                    PageSize = int.Parse(request["rows"] ?? "50"),
                    SortColumn = request["sidx"] ?? "",
                    SortOrder = request["sord"] ?? "asc",
                };
            }
            catch
            {
                //
                // For unexpected errors use the default settings!
                //
                return null;
            }
        }
    }

}

Thank you for any help or suggestions.


text:
Q: PL/SQL Remove Characters While Loop Im working on an assignment, the goal being to write a procedure that has 2 inputs a string and a char and remove the char from the string.
Example: RemoveAll(123-456-789, '-') will output: 123456789.
create or replace procedure MyRemoveAll
        (p_text varchar2, p_char_1 char) as
        v_temp varchar2(100);

   BEGIN

    v_temp := p_text;

    WHILE instr(v_temp, p_char_1) != 0 LOOP
        v_temp := substr(v_temp, 1, instr(v_temp, p_char_1)-1)
            || substr(p_text, instr(v_temp, p_char_1)+1);
        END LOOP;

    dbms_output.put_line (v_temp);

    END;
   /

   exec MyRemoveAll('123456789', '*');
   exec MyRemoveAll('123-456789', '-');
   exec MyRemoveAll('123*456*789', '*');

I don't get any errors when the procedure is created, and the first two executions work correctly. I've tried just running:
dbms_output.put_line (instr(123*456*789, *));
Which gave me an output of 4. So it should register for the condition of the while loop, but SQL Plus just stops at the loop. (Like it's doing an infinite loop, but it isn't).
Anyone have any ideas?

A: I think you need to replace p_text with v_temp in your second substr call. That way each time you loop through you are working with the updated v_temp and not the original p_text.
Here is what it would look like:
create or replace procedure MyRemoveAll
        (p_text varchar2, p_char_1 char) as
        v_temp varchar2(100);

BEGIN

 v_temp := p_text;

 WHILE instr(v_temp, p_char_1) != 0 LOOP

     v_temp := substr(v_temp, 1, instr(v_temp, p_char_1)-1)
         || substr(v_temp, instr(v_temp, p_char_1)+1);
END LOOP;

 dbms_output.put_line (v_temp);

 END;
/

All three of your examples work with this code.
Bobby


text:
Q: Text over a image slideshow - jQuery cycle2 I'm using jquery cycle2 plugin for the slideshow. Now i'm facing a challenge. I'm able to make the slideshow with the use of that plugin but the thing is i want to write some text on top of the image and the text needs to appeared only for that particular image. But if I use make the slideshow div position relative and the text div position absolute using css nothing's happening.
Code HTML :

            Alpha

Code CSS :
.cycle-slideshow {
position: relative;
}
#text1 {
    position: absolute;
    top: 200px;
}

Anyhelp will be very much pleased.

A: Follow the steps described in the documentation:

*

*Add a div with the class .cycle-overlay inside the cycle slideshow

*

*Add CSS rules

*Add the data-cycle-title and data-cycle-desc attributes on the slides. Leave empty if necessary.

Demo here

A: this may help u.if stil this not working means ur slide div may contain large z-index than ur text div
.cycle-slideshow {
position: relative;
z-index:1;

}
#text1 {
    position: absolute;
    top: 200px;
    color:#fff;
    z-index:2;

}

http://jsfiddle.net/TDSFF/


text:
Q: TypeScript Transformers: Transform imported file Is there a way for a TypeScript transformer to modify an imported file that is not a "SourceFile"?
For example in this repl: https://repl.it/@AndrewLeedham56/rollup-plugin-ts-external-repro#transformer.js (using @wessberg/rollup-plugin-ts) I am trying to add a React like import to each file, but Child.tsx is treated as external so they are not included in the outputted bundle. The problem here is that my visitor is only traversing SourceFile's and Child.tsx is not a SourceFile. So I am wondering if there is a way to traverse and modify imported files?
Any insight would be greatly appreciated, Thanks.


text:
Q: how to fit strip.text.x if the heading string is too long data frame: x
Date          Duration  Test
1/1/2012      10        This is the first that took place on1/1/2012
2/1/2012      3         This test peformed the best result

I am having challenges around heading for the strip.text.x fitting the graph. Has anybody have any recommendations how can I address this?
ggplot(x, aes(Date, Duration, group=Test, colour=Test))
+ geom_line()
+ geom_smooth(method="lm", se=T, size=1)
+ facet_wrap(~Test, scale="free")
+ opts(strip.text.x = theme_text(size=8, colour="navyblue"))

A: If you can use facet_grid rather than facet_wrap, you can use the functionality of the labeller argument to arbitrarily wrap the text. (facet_wrap does not (yet) have a labeller argument.)
Make x reproducible
x <-
structure(list(Date = structure(c(-719143, -718778), class = "Date"),
    Duration = c(10L, 3L), Test = c("This is the first that took place on1/1/2012",
    "This test peformed the best result")), .Names = c("Date",
"Duration", "Test"), row.names = c(NA, -2L), class = "data.frame")

Helper function to wrap labels (discussed in more detail on the ggplot2 wiki)
library("plyr")
label_wrap_gen <- function(width = 25) {
    function(variable, value) {
      laply(strwrap(as.character(value), width=width, simplify=FALSE),
            paste, collapse="\n")
    }
}

Plotting code. Changed to points since just two values were given so lines and smoothing don't make sense. But those were not the focus of the question anyway.
ggplot(x, aes(Date, Duration, group=Test, colour=Test)) +
  geom_point() +
  facet_grid(~Test, scale="free", labeller=label_wrap_gen(width=10)) +
  opts(strip.text.x = theme_text(size=8, colour="navyblue"))

EDIT:
Since facet_grid won't work for you, you could embed the newlines into the Test variable directly and then use facet_wrap.
x$Test <- laply(strwrap(as.character(x$Test), width=10, simplify=FALSE),
                paste, collapse="\n")
ggplot(x, aes(Date, Duration, group=Test, colour=Test)) +
  geom_point() +
  facet_wrap(~Test, scale="free") +
  opts(strip.text.x = theme_text(size=8, colour="navyblue"))

I don't understand your other question about headers made in the comment. Perhaps make a new, clearer question out of that.

A: This is now available in ggplot2::label_wrap_gen.


text:
Q: SoapUI xPath match tests I'm writing some tests for my web service right now and can't find a lot of information regarding xPath match and Contains. Looking for examples as well.
1) For example, I would like to check if the date has format YYYY-MM-DD.
Do i have to write regex expression in expected result?
http://prntscr.com/jhlxml
2) How can I check if answer equals to one of allowed values (using xsd enumeration)?
http://prntscr.com/jhm07g

A: If you have control over the WSDL, those sorts of format and simple content validations can be built into the XML Schema within your WSDL that defines your response messages. Then, just use a Schema Compliance assertion on your test step.


text:
Q: Anchor settings not working My VB.Net application is using anchoring to force certain controls to resize to their container, eg a list box on a form.  This is all pretty standard and easy to do.  However having just released the application into production I've found that on one user's computer the anchoring seems to just be ignored.  She has Windows 7, as do I.
So far example what should look like this:

instead looks like this

I asked her to try a higher resolution on her screen but that didn't to help.
On one of them I was able to fix it by manually setting the width and height in form load properties of the control instead of anchoring it, but it seems a bit backward.

A: It looks to me like the form has been resized to be too small for the anchoring to work correctly. Set the .MinimumSize property of the form to ensure the form does not get too small for your layout.
Older staff sometimes reduce the screen dpi to make text easier to read, which means the screen may not be big enough to display the form. To fix this, set the screen dpi back to something reasonable and increase the text size for readability.

A: Turned out to be that the display issues were caused by user having the "Font Size" setting on her computer set to 200%. To be honest I didn't even know you could do that.


text:
Q: Pytorch - handling picutres and .jpeg files (beginner's questions) I am new at Pytorch, and have a couple of questions regarding the way pictures are being handled:
1) In the "training a classifier" tutorial, the pictures are PIL files, and are being handled via the following commands (where "transform" also turns the PIL format into a tensor format):
trainset = torchvision.datasets.CIFAR10(root='./data', train=True,
                                    download=True, transform=transform)
trainloader = torch.utils.data.DataLoader(trainset, batch_size=4,
                                          shuffle=True, num_workers=2)

It seems like trainset[1] (and also for the other indices) consists of a tensor, and a number.  I want to define a new variable "image" that will consist of the tensor part of trainset[ 1 ] and then print it - how can I do it?
2) Assume that I have a different dataset that I want to classify. It consists of .jpeg images that are located in the folder "C:/temp/dataset". How can I define the variable "trainset" to consist of these images?
Thanks a lot in advance!

A: For your first question:
image = trainset[1][0]

print(image)

For your second question:
from PIL import Image
import numpy as np
import os

def load_image(infilename):
    """This function loads an image into memory when you give it
       the path of the image
    """
    img = Image.open(infilename)
    img.load()
    data = np.asarray(img, dtype="float32")
    return data

def create_npy_from_image(images_folder, output_name, num_images, image_dim):
    """Loops through the images in a folder and saves all of them
       as a numpy array in output_name
    """
    image_matrix = np.empty((num_images, image_dim, image_dim, 3), dtype=np.float32)
    for i, filename in enumerate(os.listdir(images_folder)):
        if filename.endswith(".jpg"):
            data = load_image(images_folder + filename)
            image_matrix[i] = data
        else:
            continue
    np.save(output_name, image_matrix)

So I would write something like this:
create_npy_from_image(path_to_images_folder, "trainset.npy", numer_of_images_in_your_folder, DIM)
DIM is 64 for example if your images are 64x64x3
You can then load the saved array with np.load and then convert it to a pytorch tensor using from_numpy function.
Let me know if this works. Good luck!


text:
Q: How to count the number of bank accounts that belong to one user in Oracle SQL I've got a few questions regarding the use of GROUP BY in SQL,
How do you count the number of open bank accounts that belong to one specific user?
I tried to write the most correct sentence possible so that the SQL could count all the associated accounts of each user, instead the result is somewhat easy? It just shows 1s in all the queries...
SELECT DISTINCT RPAD(CLI.NOMBRE || '  ' ||CLI.APELLIDOS,30) "Nombre y Apellidos",
                SUM(CUE.SALDO) "Saldo", COUNT(CUE.COD_CUENTA) "Cuentas Abiertas"
from CLIENTE CLI,
     CUENTA CUE
WHERE CLI.COD_CLIENTE = CUE.COD_CLIENTE
GROUP BY CLI.NOMBRE, CLI.APELLIDOS, CUE.SALDO, CUE.COD_CUENTA

In my case, I tried looking for users with name and surnames and also count the accounts that users have opened, instead, the query repeats names and the "Counter" shows 1s as result
[Result][1] ;
[The E/R Diagram][2]
Thanks in advance!!!
[1]: https://i.stack.imgur.com/AQDac.png
[2]: https://i.stack.imgur.com/jlVte.png

A: You are grouping by SALDO and COD_CUENTA and that prevents traditional aggregation counts to show the result you want.
However, you can use a window function: you need to tell the COUNT() function about the scope it needs to operate adding OVER(PARTITION BY cli.cod_cliente).
For example:
select distinct
  rpad(cli.nombre || '  ' || cli.apellidos, 30) as "nombre y apellidos",
  sum(cue.saldo) as "saldo",
  count(cue.cod_cuenta) over(partition by cli.cod_cliente) as "cuentas abiertas"
from cliente cli
join cuenta cue on cli.cod_cliente = cue.cod_cliente
group by cli.nombre, cli.apellidos, cue.saldo, cue.cod_cuenta

NOTE: Please use modern join syntax, not those joins from the 80s. I updated your query.


text:
Q: Value of bindings in SML? can someone please explain why is "ans" is bound to value of 16 in here after evaluation - this is a correct answer?
I thought the answer 3 since we're calling function f and sending values 1 and 2 as function f doesn't also see the values 5 and 10 but I guess I am wrong.
val x = 1

val y = 2

val f = fn y => x + y

val x = 5

val y = 10

val ans = f x + y

A: I think I figured it out. Here goes:
The function f doesn't get evaluated until the end. So at:
val ans = f x + y

... the function f gets called with the recent value x which is 5 because the value of the previous x is being shadowed. So at:
val f = fn y => x + y

... the value received becomes the value of y. and here the function f takes the value the previous x which is 1 so that's a total of 6 (x comes from static environment). Then:
val ans = f x + y

we get back here: 6 + 10 = 16

A: What you are seeing is sometimes called lexical scoping. The function f was defined in the scope of a certain binding for x, that scope is the only scope that matters in understanding what f does when f is invoked. The fact that x has a different meaning in the scope in which f is invoked doesn't affect the meaning of f itself. In the context of functional programming anything else would violate referential transparency. In the scope of a binding such as
val x = 1

it should be possible to freely replace x by 1. Thus your definition of f should be equivalent to the definition:
def f y = 1 + y

as, indeed, it is.


text:
Q: How to form likelihood function of a variable that follows a quadratic function I am having difficulty understanding likelihood functions.
If we have a probability density function of a random variable $X$ like this:
$f_{X} (x)=ax^2 + bx + c$ (i.e a simple quadratic polynomial), then how to go about finding the likelihood function for x.
All examples of a likelihood function involve some parameter theta. In this example, what is that theta?

A: In likelihood estimation we look for a function of the likelihood of the data, for various values of theta. So in MLE, the data is given, and theta is a variable. In your example, a, b and c are your theta's.
The likelihood function will be the product of the probability density function f(x) over all x (all the data). Your example will probably not have a solution. But, just for the idea, your likelihood function should represent the likelihood, given the data, for all possible theta values.


text:
Q: Choosing a column db I am trying to evaluate and use column db for my application.
I have evaluated InfiniDb and InfoBright. Can you suggest some other Column DB's

A: Your question might suggest that column-store database are NoSQL database.
Those are two different kind of database / way of representing datas that should not be confused.
I do personally use LucidDB that works like a charm. I use it for Business Intelligence use, and LucidDB is optimized for Business Intelligence. One of the activest member of the community Nicholas Goodman , someone really influent in the world of Open Source BI.
For this use, it is really well though and I would recommend it for this use.

A: There's a good list on wikipedia


text:
Q: Check if user has changed the device passcode in Swift or Objective C I'm wondering if there's a way to check if a user has changed the device passcode since the last time he oppenend my app.
I know it's possible to get this information with fingerprints (added or removed fingerprints) with something like this:
let context = LAContext()
context.canEvaluatePolicy(.DeviceOwnerAuthenticationWithBiometrics, error: nil)

if let domainState = context.evaluatedPolicyDomainState
    where domainState == oldDomainState  {
    // Enrollment state the same

} else {
    // Enrollment state changed

}

but I would like to know if it's possible just with the device passcode.
Thanks in advance!


text:
Q: Python Socket Handling Multiple Connection I'd like to let more than one client connect to my server, and have the server send them different items. For example send "hi" to the first client and "goodbye" to the second . Here's my code:
Server

import socket
file_num = 0
inp = raw_input("Name of the wordlist file = ")
inp2 = input("Number of lines for every wordlist = ")
with open(inp) as in_file:
    for line_num, line in enumerate(in_file):
        print line_num
        if not line_num % inp2:
            file_num += 1
        with open("out{0}.txt".format(file_num), "a") as out_file:
            out_file.writelines(line)
def upload(host, port):
    server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    server_socket.bind((host, port))
    server_socket.listen(5)
    filename = open("out1.txt", "rb")
    print "Server Waiting for client on port ", port
    while 1:
        client_socket, address = server_socket.accept()
        print "Connection from ", address
        while 1:
            for line in filename:
                server_data = line
                if server_data.lower() == 'q':
                    client_socket.send(server_data)
                    client_socket.close()
                    break
                else:
                    client_socket.send(server_data)

                client_data = client_socket.recv(1024)
                if client_data.lower() == 'q':
                    print "Quit from client"
                    client_socket.close()
                    break
                else:
                    print "<-- client: ", client_data
        break
upload("localhost", 4000)

and then my client program
Client

import socket

port = 4000
host_server = "localhost"
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client_socket.connect((host_server, port))
z = 1
print "Type 'Q' or 'q' to QUIT"
f = open("pino.txt", "w")
while 1:
    server_data = client_socket.recv(1024)
    f.writelines(server_data)
    if server_data.lower() == 'q':
        print "Quit from server"
        client_socket.close()
        break
    else:
        print "<-- server: ", server_data
        client_data = ("Sent "+str(z))
        z = z+1
        if client_data.lower() != 'q':
            client_socket.send(client_data)
        else:
            client_socket.send(client_data)
            client_socket.close()
            break
f.close()

Hope you give me the solution cause this will be cool if it works, another thing I'd like for this program is if the filename under def upload would change for every client. For example the first client will get out1 and the 7th will get out7. Thanks in advance.
P.S. I'm new to python so if you could explain me what you changed it would be great, don't ask me to use Twisted cause Id like to do this with the normal python socket .

A: I've had this problem myself :-)
So what you're trying to do is have multiple connections, however usually socket uses the main thread, making it hard to have more than one connection.
To fix this we need to use something called Threading, it allows you to surpass operations onto other threads. So you need to create a new thread when every connection is made:
import socket
from _thread import *

file_num = 0
inp = raw_input("Name of the wordlist file = ")
inp2 = input("Number of lines for every wordlist = ")
with open(inp) as in_file:
    for line_num, line in enumerate(in_file):
        print line_num
        if not line_num % inp2:
            file_num += 1
        with open("out{0}.txt".format(file_num), "a") as out_file:
            out_file.writelines(line)
def upload(host, port):
    server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    server_socket.bind((host, port))
    server_socket.listen(5)
    filename = open("out1.txt", "rb")
    print "Server Waiting for client on port ", port
    while 1:
        client_socket, address = server_socket.accept()
        print "Connection from ", address
        while 1:
            for line in filename:
                server_data = line
                if server_data.lower() == 'q':
                    client_socket.send(server_data)
                    client_socket.close()
                    break
                else:
                    client_socket.send(server_data)

                client_data = client_socket.recv(1024)
                if client_data.lower() == 'q':
                    print "Quit from client"
                    client_socket.close()
                    break
                else:
                    print "<-- client: ", client_data
        break
start_new_thread(upload, ("localhost", 4000))
#NOTICE!!! If this line doesn't work ^^^
#Then replace it with:
#thread.start_new_thread(upload, ("localhost", 4000))

Hope this helps! :-)
Please tell me if it doesn't,
for I have not tested this, I've just done it before :)
Thanks,
~Coolq


text:
Q: Why is RStudio freezing when I try to extract confidence intervals and odds ratios from a glmer Poisson model? I'm trying to run a mixed effects model. I've included a simplified version of it below;
Poisson1 =
    glmer(
    formula =
      wheezing_InD ~
      age_InD +
      (1|countryfactor),
    family=poisson(link="log"),
    data = Data46)

I am then trying to get the ORs and confidence intervals from it using the code below:
exp(cbind(OR = coef(Poisson1), confint(Poisson1)))

A sample of the data is as follows (in dput form):
structure(list(wheezing_InD = c("0", "1", "1", "0", "0",
"0", "0", "0", "1", "0", "0", "0", "0", "1", "0",
"0", "1", "1", "1", "0"), age_InD = c(55L, 24L, 23L,
30L, 40L, 43L, 37L, 38L, 18L, 23L, 28L, 33L, 27L, 54L, 23L, 23L,
42L, 48L, 31L, 18L), countryfactor = structure(c(1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L), .Label = c("cameroon", "ghana", "kenya"), class = "factor")), row.names = c(NA,
20L), class = "data.frame")

The code runs fine, but the software freezes when trying to compute the confidence intervals. It gets stuck at "Computing profile confidence intervals ..." and won't progress until I manually abort the code.
This method of extracting ORs + CIs has worked for me in the past with fixed effects binomial models. Is there a reason it isn't working here?
Thanks in advance


text:
Q: Sounds recaptured from the air In this story, a scientist reasoned that every sound that had ever been generated in the Earth's atmosphere was still reverberating, albeit very faintly. He invented a machine that would isolate and magnify scraps of sound from yesteryear. And that's all I remember. It must have been published in an English-language anthology before 1970, and it was likely in the 19th century or early 20th century, because it is now understood that Brownian motion represents a natural limit on how faint a sound can be before it is randomized.

A: Could this be "The Automaton Ear" by Florence McLandburgh? This short story was first published in 1873, as you suspected in the nineteenth century, and was included in an anthology, "The Automaton Ear, and Other Sketches" in 1876 (so indeed,"before 1970" by some margin!), and more recently in 2015 in "The Feminine Future: Early Science Fiction by Women Writers".
The story deals with a scientist who builds an elaborate amplifying device, essentially a souped-up "ear trumpet", to pick up sounds from events that occurred millennia ago:

As a particle of the atmosphere is never lost, so sound is never lost.
A strain of music or a simple tone will vibrate in the air forever and
ever, decreasing according to a fixed ratio. The diffusion of the
agitation extends in all directions, like the waves in a pool, but the
ear is unable to detect it beyond a certain point. It is well known
that some individuals can distinguish sounds which to others under
precisely similar circumstances are wholly lost. Thus the fault is not
in the sound itself, but in our organ of hearing, and a tone once in
existence is always in existence.

The short story is available as a free ebook here.


text:
Q: Remove x lines before and y lines after nth line (which matches a pattern) in a file I'm trying to remove a four line block from a text file if the second line matches the Regex N+.  The text file is composed of many repeating 4 line formats, ie:
@HEADER1
ACTGCNNNT
+
583@#!NMY
@HEADER2
ANNTGCGGG
+
4123N@!&*

The first line of the four block pattern will always start with @, however @ can appear anywhere in the fourth line as well, and since the pattern I'm looking for, N+ can also appear in the fourth line, I can't simply grep for N+.
Any ideas would be much appreciated :)

A: sed -ne:n -e's/\n/&/3;tp'  \
          -e'$!{N;bn' -e\} \
     -e:p -e'/\n.*N.*\n/p' \
<in >out

If your input occurs in regular blocks of four lines per, and if you're looking for at least one N that doesn't occur on the last of these four, then the above bit of sed should suit your needs. It does assume that your entire input file will be blocked off on four-line groups. If this is not the case just let me know and I can make it a little less presumptuous.
Anyway, first sed gathers 4 input lines - or pulls in input lines until 3 \newline delimiters are found in pattern space - and next it looks for an N which does not occur on either the first or last of the 4 lines just gathered. If it finds it, it prints the four-line group, else nothing is printed and the next cycle will begin with the next 4-line group.
But apparently, you're trying to remove the block in question. In that case:
sed -e'$!N;/\n.*N/{$!N;$!N;d' -e'};n;n' <in >out

...will do the trick. It first appends the Next input line to pattern space, then checks for an N which occurs on the second line of a 4-line block, and, if one is found, sed pulls in two more lines on any line which is !not the $last before deleting the entire block. If the second line didn't match N, it overwrites pattern space twice with the next input line - auto-printing as it does - and autoprints the last of these as well.
You might also use the first bit of sed and just do /\n.*N.*\n/!p instead of p for the last address, too, of course. That may be advantageous in that you can more easily alter it by switching the 3 there to any other number of lines per block which might interest you.

A: Perl to the rescue!
Save as remove-blocks.pl, run as perl remove-blocks.pl input_file > output_file.
#!/usr/bin/perl
use strict;
use warnings;

my @four_lines;                      # Buffer to hold a block.
while (<>) {                         # Read the input line by line.
    if (@four_lines < 3) {           # Not reading the last line?
        push @four_lines, $_;        # Save it to the buffer.

    } else {
        print @four_lines, $_ if $four_lines[1] !~ /N+/;
        undef @four_lines;           # Clear the buffer.
    }
}


text:
Q: Pages show all rows when using get_context_Data for paginate_by in ListView The pagination in this simple generic view in Django is working, but each page displays all rows, and not the rows for that page.
How can I select the only the records needed for a given page?
class ArticleList(ListView):
    """Get all articles"""
    model = Article
    template_name = "blog/articles.html"
    paginate_by = 4

    def get_context_data(self, **kwargs):
        context = super(ArticleList, self).get_context_data(**kwargs)
        context['articles'] = Article.objects.select_related().all()

        return context

A: Because you've overridden the articles object in get_context_data to return everything. The default implementation does the pagination there, but you've replaced that with your non-paginated queryset.
Instead, define get_queryset and add the select_related there.

A: Here's how I ended up solving it at first:
class ArticleList(ListView):
"""Get all articles"""
model = Article
template_name = "blog/articles.html"
paginate_by = 1

def get_context_data(self, **kwargs):
    context = super(ArticleList, self).get_context_data(**kwargs)
    p = Paginator(Article.objects.select_related().all(), self.paginate_by)
    context['articles'] = p.page(context['page_obj'].number)

    return context

However, after everyones help the best way is:
class ArticleList(ListView):
"""Get all articles"""
model = Article
template_name = "blog/articles.html"
paginate_by = 1
context_object_name = "articles"

def get_queryset(self):
    return Article.objects.all().order_by('-date')

Thanks all.


text:
Q: Why module 'ui.bootstrap' is not available? I am trying this simple tutorial to try UI Bootstrap:
https://scotch.io/tutorials/how-to-correctly-use-bootstrapjs-and-angularjs-together
But I am running into two problems.

SyntaxError: expected expression, got '<' at  ui-bootstrap-1.3.3.js:5:0

This is the first problem. I have not edited anything in the file, yet it says unexpected token for the very first line <!DOCTYPE html>
And the other one is as below:

Error: [$injector:modulerr] Failed to instantiate module app due to:
  [$injector:modulerr] Failed to instantiate module ui.bootstrap due to:
  [$injector:nomod] Module 'ui.bootstrap' is not available! You either misspelled the module name or forgot to load it. If registering a module ensure that you specify the dependencies as the second argument.

I saw answers to all the related questions, some of them suggesting to include the other dependencies while other suggesting to make sure of the order of the dependencies. Tried everything but no joy.
Below is my html and js code. Please have a look
HTML

Example of Angular and the normal Bootstrap JavaScript components

This will work

Buttons

      Breakfast

      Lunch

      Dinner

{{ bigData | json }}

Collapse

    Toggle Panel

          Collapsible Group Item #1

Ad vegan excepteur butcher vice lomo. Leggings occaecat craft beer farm-to-table, raw denim aesthetic synth nesciunt you probably haven't heard of them accusamus labore sustainable VHS.

{{ isCollapsed }}

JS
angular.module('app', ['ngAnimate', 'ngTouch', 'ui.bootstrap'])

.controller('mainController', function($scope) {

  // BUTTONS ======================

  // define some random object
  $scope.bigData = {};

  $scope.bigData.breakfast = false;
  $scope.bigData.lunch = false;
  $scope.bigData.dinner = false;

  // COLLAPSE =====================
  $scope.isCollapsed = false;

});

Not sure what's going wrong.
Edit
Version details area as follows
Bootstrap v3.3.6
angular
angular-animate
angular-touch
all are having version AngularJS v1.5.3

A: Make sure ui-bootstrap-1.3.3 is loaded correctly in your app.
Please find working plunker below:
http://plnkr.co/edit/evG4XQ9ih9Cx0d1WF6YU?p=preview

A: you are missing ui-bootstrap-tpls.js file.
add this file in your page.
see example working plunkr

A: In my case, in a legacy application (AngularJS 1.3), it was because I put angular-ui-bootstrap to bower.js rather than package.js.
After I put it to package.js, ran npm install, copied to some source directory, and added to imports, it worked.
import '../js/dependencies/ui-bootstrap-tpls-0.14.3.min'

It is probably not the right way to do it, though.
I think it should be imported from bower_modules.
import '../bower_components/angular-ui-bootstrap/???';

But, the Bower hosting does not work anymore and an attempt to install through bower install fails with HTTP 502.
Also, what's weird, it worked unless I registered a provider:
.config(['$tooltipProvider', function ($tooltipProvider) { ...

This way, Angular started complaining that '$tooltipProvider' is not known.
Hope this helps, although I do not know much about the old AngularJS, so take it as potentially mediocre solution.


text:
Q: How to change height of bottom bar? I have a website but there is a problem I can't change bottom bar height.
Tried it in CSS but really can't change it.
Can you help me?
As you can see, there is brown bottom bar. Thank you so much.
http://havana.royalmedia.sk/humenne/

A: Add height property to footer (if I understand right what you won't):
 .footer {
            background-color: #120a06;
            border-top: 4px solid #a36830;
            bottom: 0;
            height: 100px;
            padding: 10px 0 0;
            position: fixed;
            text-align: left;
            width: 100%;
            height:100px; /*add this*/
  }

A: just remove height in .footer class.
footer {
    position: fixed;
    padding: 10px 0 0 0;
    bottom: 0;
    width: 100%;
    background-color: #120a06;
    border-top: 4px solid #a36830;
    text-align: left;
}

this will show entire data in footer


text:
Q: When is a product of two two-parameter Mittag-Leffler functions a Mittag-Leffler function? I am studying properties of the two-parameter Mittag-Leffler function.
$$  E_{\alpha,\beta}(z)=\sum_{k=0}^\infty \dfrac{z^k}{\Gamma(\alpha k+\beta)}.$$
I am particularly interested in recurrences and relations, such as the duplication formulas.
However, I am seeking some relation in which a product of two two-parameter Mittag-Leffler functions is a Mittag-Leffler function, does anyone know something about this? Maybe about powers, but not necessarily.
This is a repost of this question: https://mathoverflow.net/questions/402681/when-is-a-product-of-two-two-parameter-mittag-leffler-functions-a-mittag-leffler.
Thank you in advance!


text:
Q: google dataproc - image version 2.0.x how to downgrade the pyspark version to 3.0.1 Using dataproc image version 2.0.x in google cloud since delta 0.7.0 is available in this dataproc image version. However, this dataproc instance comes with pyspark 3.1.1 default, Apache Spark 3.1.1 has not been officially released yet. So there is no version of Delta Lake compatible with 3.1 yet hence suggested to downgrade.
I have tried the below,
pip install --force-reinstall pyspark==3.0.1

executed the above command as a root user on master node of dataproc instance, however, when I check the pyspark --version it is still showing 3.1.1
how to fix the default pyspark version to 3.0.1?

A: The simplest way to use Spark 3.0 w/ Dataproc 2.0 is to pin an older Dataproc 2.0 image version (2.0.0-RC22-debian10) that used Spark 3.0 before it was upgraded to Spark 3.1 in the newer Dataproc 2.0 image versions:
gcloud dataproc clusters create $CLUSTER_NAME --image-version=2.0.0-RC22-debian10

A: To use 3.0.1 version of spark you need to make sure that master and worker nodes in the Dataproc cluster have spark-3.0.1 jars in /usr/lib/spark/jars instead of 3.1.1 ones.
There are two ways you could do that:

*

*Move 3.0.1 jars manually in each node to /usr/lib/spark/jars, and remove 3.1.1 ones. After doing pip install for the desired version of pyspark, you can find the spark jars in /.local/lib/python3.8/site-packages/pyspark/jars. Make sure to restart spark after this: sudo systemctl restart spark*

*You can use dataproc init actions (https://cloud.google.com/dataproc/docs/concepts/configuring-clusters/init-actions?hl=en) to do the same as then you won't have to ssh each node and manually change the jars.
Steps:

*

*Upload the updated Hadoop jars to a GCS folder, e.g., gs:///lib-updates, which has the same structure with the /usr/lib/ directory of the cluster nodes.

*Write an init actions script which syncs updates from GCS to local /usr/lib/, then restart Hadoop services. Upload the script to GCS, e.g., gs:///init-actions-update-libs.sh.
 #!/bin/bash

 set -o nounset
 set -o errexit
 set -o xtrace
 set -o pipefail

 # The GCS folder of lib updates.

 LIB_UPDATES=$(/usr/share/google/get_metadata_value attributes/lib-updates)

 # Sync updated libraries from $LIB_UPDATES to /usr/lib

 gsutil rsync -r -e $LIB_UPDATES /usr/lib/

 # Restart spark services
 service spark-* restart

*Create a cluster with --initialization-actions $INIT_ACTIONS_UPDATE_LIBS and --metadata lib-updates=$LIB_UPDATES.


text:
Q: Gmail get api: Fetch messages of ALIAS email I have an alias to an existing email. I am able to send & receive on alias email. Now, I'm only looking to get emails that were sent & received by alias using Gmail get api
 email= xxx@gmail.com
alias_email= xxx+agent@gmail.com

Request API: https://www.googleapis.com/gmail/v1/users/<alias_email>/messages
Response
{
 "error": {
  "errors": [
   {
    "domain": "global",
    "reason": "forbidden",
    "message": "Delegation denied for xxx@gmail.com"
   }
  ],
  "code": 403,
  "message": "Delegation denied for xxx@gmail.com"
 }
}

Does Gmail allow fetching of alias email data ?


text:
Q: Variance of Random Vector in the Circular Orthogonal Ensemble Let $x$ be a (uniformly) randomly chosen column of a random orthogonal matrix (of size $K$ x $K$) distributed according to Haar measure. What is $\mathbb{E}[x]$, $\mathbb{E}[x x^T]$, $Cov(x, x)$, and $Var(x x^T)$?
It seems we can calculate this if we can compute the first four raw moments of $x_i$ for some index $i$.


text:
Q: How to get total messages sent/received per user in ejabberd? I am trying to get total messages received/sent per user in ejabberd server + also in MUC. Can i get this info in ejabberdctl command ? Or any module available ?

A: No, you do not have that info available. You would have to write a custom module register the hook you would like to track, for example user_send_packet, user_receive_packet. See for reference: https://docs.ejabberd.im/developer/hooks/
From that custom plugin, you can perform the storage and calculation you want.
Note that counting per user on a large server will be very consuming.


text:
Q: FLUTTER: Blend imaged with Median Filter i need to blend a lot of images taken with camera plugin (ui.Image format) using a median filter like in photoshop.
I currently usi canvas with drawImage and Paint.BlendMode (i'm using lighten which makes a kinda similar effect), but there is no "median" blend mode.
Median filter is done by taking a median value of every single channel RGB of all the images.
So... is there anything for median filter in dart/flutter, or i need to check manually all the image pixels? In this second case, how can i convert ui.Image in a class which allows me to get the single pixel and write it in another image?
Example:
color = image.getPixel(x, y);

newImage.setPixel(x, y, color);

Thank you in advance!

A: You can convert ui.image to RGB in flutter, but such manipulation will be prohibitively slow. You need some additional package, e.g. https://pub.dev/packages/photofilters or some other.


text:
Q: Type promoting abs implemention While std::abs (or ::abs for C devs) does not promote the return value and therefor not handle std::numeric_limit<T>::min(), I would like to have an abs implementation, which does more 'secure' processing.
template <typename T>
typename std::make_unsigned<typename std::enable_if<std::is_signed<T>::value, T>::type>::type secure_abs( T value ) {
    if( value >= 0 )
        return value;

    if( value == std::numeric_limits<T>::min() )
        return *reinterpret_cast<typename std::make_unsigned<T>::type*>(&value);

    return -value; //TODO: Prevent promotion to int
}

The thing I have not figured out yet, is how to prevent the conversion warning after the promotion to int (when removing the minus).
Is there any more elegant/correct way of removing the minus?
EDIT:
Should now be correct for INT_MIN and 2complement.

A: Since type promotion to int is inevitable when using arithmetic operations with types which "rank" is lower than int I see only 2 ways how to overcome this warning:

*

*Complex. return adder(!value, 1); where adder function is a
bitwise summator. You may find how it is implemented in hardware and
implement one yourself.

*Simple. return static_cast<T>(-value). Since you doesn't have any arithmetic operation which may cause overflowing of the type T it is absolutely safe to "cancel" promotion to int


text:
Q: A well-known lemma about curvilinear circles!
Let $AB$ be a chord of a circle $\Gamma$. Let $\omega$ be a circle tangent to chord $AB$ at $K$ and internally tangent to $\omega$ at $T$. Then ray $TK$ passes through the midpoint $M$ of the arc $AB$ not containing $T$.

** This question might be asked before. If them don't down vote. Just close it marking duplicate and send me the link of the question. I search out but failed to find **.
I tried my best by doing angle chasing but failed.I think radical axis will not work as well. If anyone have any pure geometry answer please post. I think inversion will work. But i know inversion a little. But I guess Inversion around $M$ will work. Please help me.

A: Hint:
Homothety in $T$ which takes smaller circle to bigger will do. It takes $K$ to $M$ and line $AB$ to parallel line through $M$ since $K$ is on $AB$. Thus this new line is also tangent to bigger circle, since $AB$ is tangent to smaller. Now it should not be difficult to see that $AMB$ is isosceles (remember tangent-chord property).


text:
Q: SendToBack TlistItemImage at design time or runtime in fireMonkey In TlistView Dynamic appearance I added a few object appearanced to the item.
I have a TextObjectAppearence and an ImageObjectAppearence.
I want to set the image to be a background for the text meaning the text should be on top of the image.
I tried right-clicking on the image object and selecting SendToBack but it doesn't seem to work.
At run-time, there's also not any way to call ListItemImage.sendtoback etc.
what is the right way of doing it?
I've attached a screenshot of the two items overlapping...

A: The only way I found is to open fmx file in text mode and to move the various objects in the order needed (first is the deeper)


text:
Q: invalid or incomplete html syntax issue when you find the "hard" stuff easy and the easy stuff hard!
Not sure why I'm asking for help with what looks like a very simple html and/or css problem but here I am.
Please see screenshot for a visual on the problem. My electronics seem  to be all over the place even though i've checked by divs and html syntax, that also goes for my footer. The css i believe is correct but perhaps i'm missing a div somewhere. I need a fresh pair of eyes to see something I clearly don't.
so i've added my getItem function()

function getItem(){
   global $con;

    //limit to just getting 6 random products per page
    $get_item = "select * from items order by RAND() LIMIT 0,6";
    $run_item = mysqli_query($con,$get_item);

    //using while loop to get multiple data from items table

    while($row_item = mysqli_fetch_array($run_item)){

        $item_id = $row_item['item_id'];
        $item_cat = $row_item['item_cat'];
        $item_brand = $row_item['item_brand'];
        $item_title = $row_item['item_title'];
        $item_price = $row_item['item_price'];
        $item_image = $row_item['item_image'];

        echo "

$item_title

            ";
    }

}

?>

screenshot of the issue

/* http://meyerweb.com/eric/tools/css/reset/
   v2.0 | 20110126
   License: none (public domain)
*/

html, body, div, span, applet, object, iframe,
h1, h2, h3, h4, h5, h6, p, blockquote, pre,
a, abbr, acronym, address, big, cite, code,
del, dfn, em, img, ins, kbd, q, s, samp,
small, strike, strong, sub, sup, tt, var,
b, u, i, center,
dl, dt, dd, ol, ul, li,
fieldset, form, label, legend,
table, caption, tbody, tfoot, thead, tr, th, td,
article, aside, canvas, details, embed,
figure, figcaption, footer, header, hgroup,
menu, nav, output, ruby, section, summary,
time, mark, audio, video {
 margin: 0;
 padding: 0;
 border: 0;
 vertical-align: baseline;
}
/* HTML5 display-role reset for older browsers */
article, aside, details, figcaption, figure,
footer, header, hgroup, menu, nav, section {
 display: block;
}

body {background:skyblue;}

.wrapper_main{
width:1000px;
height:auto;
margin:auto;
background:black;
}

.wrapper_header{
width:1000px;
height:100px;
margin:auto;

}

#logo {float:left;}

#banner {float:right;}

.menubar {
width:1000px;
height:50px;
background:gray;
color:white;

}

#indexmenu {
padding:0;
margin:0;
line-height:40px;
float:left;
}

#indexmenu li {
list-style:none;
display:inline;
}

#indexmenu a {
text-decoration:none;
color:white;
padding:8px;
margin:5px;
font-size:18px;
font-family:COMIC SANS MS;
}

#indexmenu a:hover {color:orange; font-weight:bolder; text-decoration:underline;}

#form {float:right; padding-right:8px; line-height:50px;}

.content_wrapper {
width:1000px;
margin:auto;
background:pink;

}

#content_area {
width:800px;
float:right;
background:pink;
}

#sidebar {
width:200px;
background:black;
float:left;
}

#sidebar_title {
background:white;
color:black;
font-size:22px;
font-family:arial;
padding:10px;
text-align:center;
}

#cats {
 text-align:center;
}

#cats li {list-style:none; margin:5px;}

#cats a {color:white; padding:8px; margin:5px; text-align:center; font-size:20px; text-decoration:none; font-family:Comic Sans Ms;}

#cats a:hover {color:orange; font-weight:bolder; text-decoration:underline;}

#items_box {
width:780px;
text-align:center;
margin-left:30px;
margin-bottom:10px;
}

 #single_item {float:left; margin-left:30px; padding:10px;}

 #single_item img {border:2px solid black;}

 #shopping_cart {width:800px; height:50px; background:black; color:white;}

#footer {
width:1000px;
height:100px;
background:gray;
clear:both;

}
<!DOCTYPE>
<?php
session_start();
include("functions/functions.php");

?>

  <title>My Online Shop</title>

 <link rel="stylesheet" href="styles/style.css" media="all" />

Home

All Products

My Account

Sign Up

Shopping Cart

Contact Us

    <form method="get" action="results.php" enctype="multipart/form-data">
     <input type="text" name="user_query" placeholder="Search a Product"/ >
     <input type="submit" name="search" value="Search" />
    </form>

Categories

    <?php getCategories(); ?>

Brands

     <?php getBrandsName(); ?>

                <?php getItem(); ?>

© 2018

A: Just a few first things regarding the HTML:
Change <!DOCTYPE> to <!DOCTYPE html>
in lin 38 change
<input type="text" name="user_query" placeholder="Search a Product"/ > to <input type="text" name="user_query" placeholder="Search a Product" />
you also have multiple usage of the id cats -> id="cats" . In HTML you can only have one ID per page. It has to unique.

and there is a
 missing in the php function:
after that line  add this closing element ->

A: In addition to Simon's answer, it appears that you've missed clearing some floats. From what I can tell, #sidebar and #content_area have been left uncleared within #content_area. Adding a clear fix at the bottom of #content_area should fix things up. It's hard to tell with the content inside #content_area since you're developing locally and we don't have access to inspect that code.


text:
Q: YES/NO Column No Option for Require that this column contains information: I want to create a column with Yes/No option but I want it to be required that his has to be filled.
However, I dont see the option for "Require that this column contains information: "
I can only find if a use the choice option when  creating a column
thank you

A: This is how it is designed. Yes No column gives you single Checkbox. When Selected it is 'Yes' and when not selected it is 'No'. So either way it is mandatory. If user has not selected it means he wanted to select No.  You can also set default value which controls by default it would be selected or not.

Hope this helps...Happy coding..!!

A: It's the default behavior.
When create a Yes/No column, we need to select the default value which only has Yes and No option. If user not selects any value when he creates an item, the column will be populated with default value.


text:
Q: What should my path if I am using python venv? I use python 3.6.9 and asterisk 16.16.0 in Ubuntu 18.04.
If you know about AGI then you probably know about this line
#!/usr/bin/python
or this
#!/usr/bin/env python
if not then don't worry its tells the system to run this script in the Python interpreter.
So as far you know what I can do. but now my question is if I am use virtual environment for python using help of venv package and want defines path of that python environment in my AGI then what should I define.
My virtual environment store in following directory: /home/test/Documents/environments/test_env.

A: When you are running ANY agi script in asterisk it will run under asterisk user.
Asterisk user on most systems is limited user and may have no python environment at all.
Best way is create virtual environment for your python and use full path for your python INSIDE venv like /opt/my_virtual_env/bin/python3 in all agi scripts.
Ensure that those path is readable by asterisk user or owned by asterisk user

A: Try adding this path to the $PATH variable
/home/test/Documents/environments/test_env/bin
This directory contains scripts like activate, deactivate etc. which are used for activating and deactivating the virtual env.
Regarding the shebang, #!/usr/bin/env python should work properly if the virtual env is activated.
Hope this is what you were looking for.


text:
Q: Take pictures from a service while camera is in use by ARCore I am playing with the Android HelloAR example. Being an AR app, the rear camera is opened and the captured video is presented on-screen to the user.
I want to, from a service, take pictures at some set interval (e.g. 30fps). I don't want video and I don't want the user to have to do anything (e.g. press a button). Further, I do not want to have to do anything other than start/stop the service from the HelloAR app. The service must be totally self-contained so that it will work in a library that I can import into other Android-based AR apps.
Is it possible for my HelloAR app and a service to both have access to the camera simultaneously? If not, is there another way to take a picture or grab a raw frame from the existing/open camera?

A: To open the front camera:
Set<Session.Feature> features  = new HashSet<Session.Feature>();
features.add(Session.Feature.FRONT_CAMERA);
Session = new Session(this,features);

To capture the image from Frame in onDrawFrame(GL10 gl) method you can do:
Frame frame = session.update();
frame.acquireCameraImage();


text:
Q: Java - Selenium PhantomJS RemoteDriver with proxy settings is not working I would like to use Selenium's RemoteDriver with PhantomJS with proxies + multi threading. My problem is that the RemoteDriver is not using the given proxy in my setup.
I tried the following 2 setups, both times I can see the correct proxy in the PhantomJS response, but it is still using my local IP.
In the CLI I start PhantomJS with: phantomjs --webdriver=4444
First setup:
org.openqa.selenium.Proxy proxy = new org.openqa.selenium.Proxy();
proxy.setHttpProxy(proxyHost);
DesiredCapabilities cap = new DesiredCapabilities().phantomjs();
cap.setCapability(CapabilityType.PROXY, proxy);

try {
    this.driver = new RemoteWebDriver(new URL("http://localhost:4444/wd/hub"), cap);
} catch (MalformedURLException e) {
    e.printStackTrace();
}
this.driver.get("http://whatismyipaddress.com/");

As response PhantonJS says:

[INFO  - 2014-12-26T10:29:42.902Z] Session
  [1ade9c30-8cea-11e4-952c-61f83d60a6ec] - CONSTRUCTOR - Desired
  Capabilities:
  {"platform":"ANY","browserName":"phantomjs","proxy":{"httpProxy":"173.234.249.114:3128","noProxy":null,"socksUsername":null,"ftpProxy":null,"socksPassword":null,"sslProxy":null,"proxyAutoconfigUrl":null,"proxyType":"MANUAL","class":"org.openqa.selenium.Proxy","autodetect":false,"socksProxy":null,"hCode":1338671111},"version":""}
  [INFO  - 2014-12-26T10:29:42.902Z] Session
  [1ade9c30-8cea-11e4-952c-61f83d60a6ec] - CONSTRUCTOR - Negotiated
  Capabilities:
  {"browserName":"phantomjs","version":"1.9.0","driverName":"ghostdriver","driverVersion":"1.0.3","platform":"linux-unknown-64bit","javascriptEnabled":true,"takesScreenshot":true,"handlesAlerts":false,"databaseEnabled":false,"locationContextEnabled":false,"applicationCacheEnabled":false,"browserConnectionEnabled":false,"cssSelectorsEnabled":true,"webStorageEnabled":false,"rotatable":false,"acceptSslCerts":false,"nativeEvents":true,"proxy":{"httpProxy":"173.234.249.114:3128","noProxy":null,"socksUsername":null,"ftpProxy":null,"socksPassword":null,"sslProxy":null,"proxyAutoconfigUrl":null,"proxyType":"MANUAL","class":"org.openqa.selenium.Proxy","autodetect":false,"socksProxy":null,"hCode":1338671111}}
  [INFO  - 2014-12-26T10:29:42.902Z] SessionManagerReqHand -
  _postNewSessionCommand - New Session Created: 1ade9c30-8cea-11e4-952c-61f83d60a6ec

Second setup:
org.openqa.selenium.Proxy proxy = new org.openqa.selenium.Proxy();
proxy.setHttpProxy(proxyHost);
DesiredCapabilities cap = new DesiredCapabilities().phantomjs();
ArrayList<String> cliArgsCap = new ArrayList<String>();
cliArgsCap.add("--proxy=proxy");
cliArgsCap.add("--proxy-type=http");
cap.setCapability(PhantomJSDriverService.PHANTOMJS_CLI_ARGS, proxy);

try {
    this.driver = new RemoteWebDriver(new URL("http://localhost:4444/wd/hub"), cap);
} catch (MalformedURLException e) {
    System.out.println("nope");
    e.printStackTrace();
}
this.driver.get("http://whatismyipaddress.com/");

As response PhantomJS says:

[INFO  - 2014-12-26T10:36:38.259Z] Session
  [12710f00-8ceb-11e4-952c-61f83d60a6ec] - CONSTRUCTOR - Desired
  Capabilities:
  {"platform":"ANY","phantomjs.cli.args":{"httpProxy":"173.234.249.114:3128","noProxy":null,"socksUsername":null,"ftpProxy":null,"socksPassword":null,"sslProxy":null,"proxyAutoconfigUrl":null,"proxyType":"MANUAL","class":"org.openqa.selenium.Proxy","autodetect":false,"socksProxy":null,"hCode":2130507747},"browserName":"phantomjs","version":""}
  [INFO  - 2014-12-26T10:36:38.259Z] Session
  [12710f00-8ceb-11e4-952c-61f83d60a6ec] - CONSTRUCTOR - Negotiated
  Capabilities:
  {"browserName":"phantomjs","version":"1.9.0","driverName":"ghostdriver","driverVersion":"1.0.3","platform":"linux-unknown-64bit","javascriptEnabled":true,"takesScreenshot":true,"handlesAlerts":false,"databaseEnabled":false,"locationContextEnabled":false,"applicationCacheEnabled":false,"browserConnectionEnabled":false,"cssSelectorsEnabled":true,"webStorageEnabled":false,"rotatable":false,"acceptSslCerts":false,"nativeEvents":true,"proxy":{"proxyType":"direct"}}
  [INFO  - 2014-12-26T10:36:38.259Z] SessionManagerReqHand -
  _postNewSessionCommand - New Session Created: 12710f00-8ceb-11e4-952c-61f83d60a6ec

As you can see both times the correct proxy address is used ("httpProxy":"173.234.249.114:3128"), but whatismyipaddress.com is reporting my own address.
When I use the PhantomJSDriver from GhostDriver, then I can use the regular org.openqa.selenium.Proxy, but I'm not able to accomplish multi threading as described here. With a PhantomJS process in the CLI and RemoteDriver at least multi threading works well.
Thanks for any advice! And sorry for the long text :)
--- UPDATE ---

Just found out that if I start PhontomJS directly in the CLI with the --proxy then it uses the given proxy, when I connect with RemoteDriver. One option would for me would be now simply to start multiple PhantonJS processes manually with a fixed proxy.


text:
Q: Java Spring app run DynamoDBEmbedded for integration testing? Is it possible to run an embedded instance of DynamoDB within a Spring application to be used by integration tests similar to what embedded-redis allows? https://github.com/kstyrc/embedded-redis
A sample blob by AWS seems to indicate this is possible: https://github.com/awslabs/aws-dynamodb-examples/blob/master/src/test/java/com/amazonaws/services/dynamodbv2/local/embedded/DynamoDBEmbeddedTest.java
However, the documentation is scant and when attempting to set up the Embedded DynamoDB in the way shown I get the following error:
AmazonDynamoDB ddb = DynamoDBEmbedded.create().amazonDynamoDB();

Throws:
Caused by: java.lang.NullPointerException
    at com.amazonaws.services.dynamodbv2.local.shared.access.sqlite.SQLiteDBAccess.initializeMetadataTables(SQLiteDBAccess.java:389)
    at com.amazonaws.services.dynamodbv2.local.shared.access.sqlite.SQLiteDBAccess.<init>(SQLiteDBAccess.java:225)
    at com.amazonaws.services.dynamodbv2.local.shared.access.sqlite.SQLiteDBAccess.<init>(SQLiteDBAccess.java:194)
    at com.amazonaws.services.dynamodbv2.local.embedded.DynamoDBEmbedded.create(DynamoDBEmbedded.java:45)
    at com.amazonaws.services.dynamodbv2.local.embedded.DynamoDBEmbedded.create(DynamoDBEmbedded.java:35)
    at com.wdpr.keyring.entitlements.EmbeddedDynamoDBConfig.embeddedDynamoDB(EmbeddedDynamoDBConfig.java:26)

Essentially for the Spring application I would be registering the AmazonDynamoDB instance created by DynamoDBEmbedded.create().amazonDynamoDB(); as my bean to be used in the TEST application context like so:
@TestConfiguration
public class EmbeddedDynamoDBConfig {

    @Bean
    AmazonDynamoDB embeddedDynamoDB() {
        return DynamoDBEmbedded.create().amazonDynamoDB();
    }
}

If this is not possible, what are some other potential solutions?

A: As you wrote, but you need to copy native libs and set library path before that.
These answers worked for me: https://stackoverflow.com/a/39086207 and https://stackoverflow.com/a/39086207. There are both Gradle and Maven samples there. Maven sample includes Java code you need. As I wrote above, missing item is setting library.path as JUnit Rule did not work for me for Bean creation.
@TestConfiguration
public class EmbeddedDynamoDBConfig {
    public EmbeddedDynamoDBConfig() {
        // adjust this path as needed
        System.setProperty("sqlite4java.library.path", "build/libs-native");
    }

    @Bean
    @Primary
    public AmazonDynamoDB amazonDynamoDB() {
        return DynamoDBEmbedded.create().amazonDynamoDB();
    }
}

Note however that STS does not handle the Gradle task automatically. I had to run Gradle by hands and then only use STS's JUnit run. If you find a solution, please share. Did not test Maven.
Right now I seem to have some access issue for automated runs in console: com.amazonaws.services.dynamodbv2.model.AmazonDynamoDBException: The security token included in the request is invalid. (Service: AmazonDynamoDBv2; Status Code: 400; Error Code: UnrecognizedClientException; Request ID: ...). Not yet sure how to fix.


text:
Q: Howler.JS + Angular - path for playing sound file I'm trying to play mp3 file in cordova + ionic hybrid app.
Sound is stored in:
www/sounds/dubstep/sound.mp3

And i'm trying to play file from service placed in /www/scripts/services/global.js using following code:
var sound = new Howl({
     src: ['sounds/dubstep/sound.mp3'],
     onend: function() {
         console.log('Finished!');
     },
     onloaderror: function() {
        console.log('Error!');
    },
});

sound.play();

But it is always throwing onloaderror.
How I should set path in right way?
Thanks for any help.

A: According to github documentation you should be using urls instead of src:
var sound = new Howl({
    urls: ['sounds/dubstep/sound.mp3'],
    onend: function() {
        console.log('Finished!');
    },
    onloaderror: function() {
        console.log('Error!');
    },
});

Src: https://github.com/goldfire/howler.js/


text:
Q: How to find out correlation between Attributes in R I am new at R.
I have a large data set which has many numeric and non numeric columns.
I am trying to find out which of the columns are highly correlated and this  correlation is meaningfull or not.
First I want to find out correlation between numeric values and then categorical values. It should be separate from each other.
What should I do to find out correlation?
And how to determine errors or unusual datas in dataset?
This is just an example dataset ;
 > df1 <- LungCapData22
 > sapply(df1,class)
 LungCap       Age    Height     Smoke    Gender Caesarean
"numeric" "integer" "numeric"  "factor"  "factor"  "factor"

      LungCap Age Height Smoke Gender Caesarean
1    6.475   6   62.1    no   male        no
2    10.125  18   74.7   yes female        no
3     9.550  16   69.7    no female       yes
4    11.125  14   71.0    no   male        no