text:
Q: How to upscale my low res image to high res image using any software? I have a low-res image in the attachments section, would anybody explain me technique to make it high-res image ? It would be really helpful if you could show me how can I improve resolution, quality and bring out the elements from the image clearly.

A: As far as I know there is no way to change the resolution upwards simply because your image lacks the data to do so. There is no program that would 'calculate' the pixels to more then there are. Ether find the source of the image and take a larger picture or have a higher resolution rendered. You could -trace- the image in illustrator and abandon the exact composition of the artwork.

A: I know "Vector Magic" Paid software. Give it a try.

A: I also suggest tracing the image in illustrator and that way you will create a new image with higher pixel counts. It is not possible to "add" any pixels in your current image as it originally does not have additional pixels.
Also, please specify if you want to improve resolution while enlarging the picture or you wish to use it as the same size? This will help in getting a to the point answer.


text:
Q: Responsive navbar menu (hamburger menu) doesn't open by clicking Got a navbar but the problem is when I open (click) it on mobile phone or in responsive environment (when the hamburger menu shows up), it does not open by clicking on it, the links are not showing. Below is the code that I'm using for it. Used the necessary links but not working. Everything is fine, the only problem that is occurring is with that hamburger menu.

$('.navTrigger').click(function() {
  $(this).toggleClass('active');
  console.log("Clicked menu");
  $("#mainListDiv").toggleClass("show_list");
  $("#mainListDiv").fadeIn();

});

$(window).scroll(function() {
  if ($(document).scrollTop() > 50) {
    $('.nav').addClass('affix');
    console.log("OK");
  } else {
    $('.nav').removeClass('affix');
  }
});
.nav {
  width: 100%;
  height: 65px;
  position: fixed;
  line-height: 65px;
  text-align: center;
  z-index: 1;
}

.nav div.logo {
  float: left;
  width: auto;
  height: auto;
  padding-left: 0.9rem;
}

.nav div.logo a {
  text-decoration: none;
  color: #fff;
}

.nav div.logo a:hover {
  color: #00E676;
}

.nav div.main_list {
  height: 65px;
  float: right;
}

.nav div.main_list ul {
  width: 100%;
  height: 65px;
  display: flex;
  list-style: none;
  margin: 0;
  padding: 0;
}

.nav div.main_list ul li {
  width: auto;
  height: 65px;
  padding: 2px;
  padding-right: 0.9rem;
}

.nav div.main_list ul li a {
  text-decoration: none;
  color: #fff;
  line-height: 65px;
  font-size: 80%;
  font-weight: bold;
}

.nav div.main_list ul li a:hover {
  color: #00b3ee;
}

/* Home section */

.home {
  width: 100%;
  height: 100vh;
  background-position: center top;
  background-size: cover;
}

.navTrigger {
  display: none;
}

.nav {
  padding-top: 20px;
  padding-bottom: 20px;
  -webkit-transition: all 0.4s ease;
  transition: all 0.4s ease;
  z-index: 1;
}

/* Media query section */
@media screen and (min-width: 768px) and (max-width: 1024px) {
  .container {
    margin: 0;
  }
}

@media screen and (max-width:768px) {
  .navTrigger {
    display: block;
  }
  .nav div.logo {
    margin-left: 15px;
  }
  .nav div.main_list {
    width: 100%;
    height: 0;
    overflow: hidden;
  }
  .nav div.show_list {
    height: auto;
    display: none;
  }
  .nav div.main_list ul {
    flex-direction: column;
    width: 100%;
    height: 100vh;
    right: 0;
    left: 0;
    bottom: 0;
    background-color: #111;
    /*same background color of navbar*/
    background-position: center top;
  }
  .nav div.main_list ul li {
    width: 100%;
    text-align: right;
  }
  .nav div.main_list ul li a {
    text-align: center;
    width: 100%;
    font-size: 3rem;
    padding: 20px;
  }
  .nav div.media_button {
    display: block;
  }
}

.navTrigger {
  cursor: pointer;
  width: 30px;
  height: 25px;
  margin: auto;
  position: absolute;
  right: 30px;
  top: 0;
  bottom: 0;
}

.navTrigger i {
  background-color: #fff;
  border-radius: 2px;
  content: '';
  display: block;
  width: 100%;
  height: 4px;
}

.navTrigger i:nth-child(1) {
  -webkit-animation: outT 0.8s backwards;
  animation: outT 0.8s backwards;
  -webkit-animation-direction: reverse;
  animation-direction: reverse;
}

.navTrigger i:nth-child(2) {
  margin: 5px 0;
  -webkit-animation: outM 0.8s backwards;
  animation: outM 0.8s backwards;
  -webkit-animation-direction: reverse;
  animation-direction: reverse;
}

.navTrigger i:nth-child(3) {
  -webkit-animation: outBtm 0.8s backwards;
  animation: outBtm 0.8s backwards;
  -webkit-animation-direction: reverse;
  animation-direction: reverse;
}

.navTrigger.active i:nth-child(1) {
  -webkit-animation: inT 0.8s forwards;
  animation: inT 0.8s forwards;
}

.navTrigger.active i:nth-child(2) {
  -webkit-animation: inM 0.8s forwards;
  animation: inM 0.8s forwards;
}

.navTrigger.active i:nth-child(3) {
  -webkit-animation: inBtm 0.8s forwards;
  animation: inBtm 0.8s forwards;
}

@-webkit-keyframes inM {
  50% {
    -webkit-transform: rotate(0deg);
  }
  100% {
    -webkit-transform: rotate(45deg);
  }
}

@keyframes inM {
  50% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(45deg);
  }
}

@-webkit-keyframes outM {
  50% {
    -webkit-transform: rotate(0deg);
  }
  100% {
    -webkit-transform: rotate(45deg);
  }
}

@keyframes outM {
  50% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(45deg);
  }
}

@-webkit-keyframes inT {
  0% {
    -webkit-transform: translateY(0px) rotate(0deg);
  }
  50% {
    -webkit-transform: translateY(9px) rotate(0deg);
  }
  100% {
    -webkit-transform: translateY(9px) rotate(135deg);
  }
}

@keyframes inT {
  0% {
    transform: translateY(0px) rotate(0deg);
  }
  50% {
    transform: translateY(9px) rotate(0deg);
  }
  100% {
    transform: translateY(9px) rotate(135deg);
  }
}

@-webkit-keyframes outT {
  0% {
    -webkit-transform: translateY(0px) rotate(0deg);
  }
  50% {
    -webkit-transform: translateY(9px) rotate(0deg);
  }
  100% {
    -webkit-transform: translateY(9px) rotate(135deg);
  }
}

@keyframes outT {
  0% {
    transform: translateY(0px) rotate(0deg);
  }
  50% {
    transform: translateY(9px) rotate(0deg);
  }
  100% {
    transform: translateY(9px) rotate(135deg);
  }
}

@-webkit-keyframes inBtm {
  0% {
    -webkit-transform: translateY(0px) rotate(0deg);
  }
  50% {
    -webkit-transform: translateY(-9px) rotate(0deg);
  }
  100% {
    -webkit-transform: translateY(-9px) rotate(135deg);
  }
}

@keyframes inBtm {
  0% {
    transform: translateY(0px) rotate(0deg);
  }
  50% {
    transform: translateY(-9px) rotate(0deg);
  }
  100% {
    transform: translateY(-9px) rotate(135deg);
  }
}

@-webkit-keyframes outBtm {
  0% {
    -webkit-transform: translateY(0px) rotate(0deg);
  }
  50% {
    -webkit-transform: translateY(-9px) rotate(0deg);
  }
  100% {
    -webkit-transform: translateY(-9px) rotate(135deg);
  }
}

@keyframes outBtm {
  0% {
    transform: translateY(0px) rotate(0deg);
  }
  50% {
    transform: translateY(-9px) rotate(0deg);
  }
  100% {
    transform: translateY(-9px) rotate(135deg);
  }
}

.affix {
  padding: 0;
  background-color: #111;
}

.myH2 {
  text-align: center;
  font-size: 4rem;
}

.myP {
  text-align: justify;
  padding-left: 15%;
  padding-right: 15%;
  font-size: 20px;
}

@media all and (max-width:700px) {
  .myP {
    padding: 2%;
  }
}

HOME

ABOUT US

OUR SERVICES

JOBS

CONTACT US

HOME

ABOUT US

OUR SERVICES

JOBS AT HEGTAVIC

CONTACT US

A: I have tried your code and modified in fallowing way. It is working fine.
$(document).ready(function(){
  $('.navTrigger').on('click',function (){
    $(this).toggleClass('active');
    console.log("Clicked menu");
    $("#mainListDiv").toggleClass("show_list");
    $("#mainListDiv").fadeIn();

  });
});

redpajama_set_name: RedPajamaStackExchange


text:
Q: Multiple duplicate dialog box on drag in IE11 when connected through VDI I am using the test code given below and facing issue with the javascript alert box (or any dialog box) in Internet explorer 11 in VDI. If the user drags or moves the alert box, it creates a duplicate of that box. Thus, doing so continuously opens multiple alert box. I am not facing this issue in IE8.
Note: I am facing this issue only while working on Client network connected through VDI. This issue is not reproducible when running it on eclipse in my local and using same IE11 version as on client network.
Is this issue related to network slowness. Please help me to fix this issue.
Login.jsp
<html>
<head>
<script>
function validateForm() {
var x = document.forms["Login"]["fname"].value;
if (x == null || x == "") {
    alert("Name cannot be empty...");
    return false;
}
}
</script>
</head>
<body>
<form name="Login" action="AfterLogin.jsp"
onsubmit="return validateForm()" method="post">
Name: <input type="text" name="fname">
<input type="submit" value="Submit">
</form>
</body>
</html>

AfterLogin.jsp
<html>
<body>
<%
String name=request.getParameter("fname");
if(name.equals("test"))
{
%>
<script>
alert("Login success...");
</script>
<%
}
else
{
%>
<script>
alert("Login fail...");
</script>
<%
}
%>
</body>
</html>

The duplicate alert box opens for "Login success..." and "Login fail..." alert box. If you continuosly drag this alert it will open mutiple alert box. This issue is not happenning for "Name cannot be empty..." alert box.
Screenshot


text:
Q: Computation failed in `stat_signif()`: data are essentially constant I am trying to make a boxplot and I want to see the group comparisons however for some reason it is not showing up
library(ggbeeswarm)
library(ggpubr)
library(ggplot2)
ggplot(data = data2, aes(wcc_group, 2750.3)) +
geom_boxplot() +
geom_quasirandom(aes(colour = as.factor(X28_day_mortality) , shape = sex, fill =
as.factor(X28_day_mortality)), groupOnX = FALSE) +
labs(x = "WCC Group", y = "Apolipoprotein A-I", title = "Expression of Apolipoprotein A-I in WCC
Groups", fill = "Mortality", shape = "Sex", colour = "Mortality") +  stat_compare_means(method =
"t.test", comparisons = list(c("Low", "Medium"), c("Low", "High"), c("Medium", "High") ), aes(label =
..p.signif..)) +
 scale_colour_manual(values =c("red", "black")) +
 scale_fill_manual(values =c("red", "black")) +
 scale_shape_manual(values =c(24,22))

enter image description here
Any reason why this error keeps showing up?

A: When you specify the y-value in your example, you have it as 2750.3, is there a reason for this?
This singular y-value is why the black line is drawn for each of the groups. It is not a boxplot because there is only one value-- can't have a Q1, median, Q3, etc. If you were to have y-values be values for that variable (Apolipoprotein A-I?), then the boxplot will be able to show the distribution of the scores.
The t-test won't work and kicks an error for a similar reason-- there is no variance to calculate the t-test value since the only value for y is 2750.3.
ggplot(data = data2, aes(wcc_group, [enter associated protein var here])) +
geom_boxplot() +
geom_quasirandom(aes(colour = as.factor(X28_day_mortality) , shape = sex, fill =
as.factor(X28_day_mortality)), groupOnX = FALSE) +
labs(x = "WCC Group", y = "Apolipoprotein A-I", title = "Expression of Apolipoprotein A-I in WCC
Groups", fill = "Mortality", shape = "Sex", colour = "Mortality") +  stat_compare_means(method =
"t.test", comparisons = list(c("Low", "Medium"), c("Low", "High"), c("Medium", "High") ), aes(label =
..p.signif..)) +
 scale_colour_manual(values =c("red", "black")) +
 scale_fill_manual(values =c("red", "black")) +
 scale_shape_manual(values =c(24,22))


text:
Q: What does = mean? whats the meaning of this line
<input type=text name="name" value="<?= $name ?>

if we are to declare as PHP shouldn't we write <?php instead of <?=
Thanks

A: using short tags is generally frowned upon nowadays but it's still an option in the php.ini. It's fine, it's just poor coding style and has some repercussions if you use multiple dynamic languages.

A: <?= are PHP short open tags, which can be enabled (or disabled) via the short_open_tag directive in php.ini (quoting) :

This directive also affects the
  shorthand <?= , which is identical
  to <? echo . Use of this shortcut
  requires short_open_tag to be on.

And:

Also if disabled, you must use the
  long form of the PHP open tag (<?php
  ?> ).

This means your portion of code :
<input type=text name="name" value="<?= $name ?>

Is equivalent to this one :
<input type=text name="name" value="<?php echo $name; ?>

But only when short open tags are enabled.
And, as a sidenote : short open tags are not always enabled -- in fact, they are disabled by default, with recent versions of PHP.
Which means it might be wise to not depend on those, at least if you want to deploy your application on servers on which you are not administrator.

A: <?= ... ?> is shorthand for <?php echo ... ?>


text:
Q: JQuery find() opposite I want to find the next form-element, starting from input-object inside.
Find() is a great function to find child objects. But what about the opposite Way to find in parent?
<form id="grabbMe">

<input type="text" value="test">

</form>

A: The opposite of find() is parents().
closest() isn't quite an opposite to find(), although depending on what you're trying to do, it may work for you.
the find() function finds all occurances of the selector within the descendants of the element you specify.
closest() only finds the first occurrence of the selector, going upward through the ancestors of the specified element.
So the correct opposite to find() would be parents(), which will find all ancestors of your element that match the specified selector.

A: You can use jQuery's closest() function to do this.
$('input').closest('form').attr('id');


text:
Q: What are equivalent parameters of adduser debian command in RHEL6? None of this options doesn't exist in RHEL6.
/usr/sbin/adduser --disabled-login --gecos 'GitLab' git

What is equivalent parameters for disabling account (no locking, it's different) and adding gecos in Red Hat 6 ?

A: As per the Debian adduser manpage:
   --disabled-login
          Do  not  run passwd to set the password.  The user won't be able
          to use her account until the password is set.

By default, when using useradd, the account is disabled until you set a password on it for the first time, so simply not giving the user a password will accomplish the same thing as adduser --disabled-login.


text:
Q: Critical Sections openMP I would like to know where do we need to set critical sections?
If there are multiple threads with a shared array, and each one want
to write in different place does it need to be in a critical section, even though each
thread write to a different place in the array?
lets say that I have 2 dimensional array M[3][3], initial_array[3] and some double variable
and I want to calculate something and store it at the first column of M.
I can use with a for loop, but I want to use with openMP , so I did:
 omp_set_num_threads(3);
 #pragma omp parallel shared(M,variable)
 {
     int id = omp_get_thread_num();
     double init = initial_array[id]*variable;
     M[id][0] = init;
 }

It works fine, but I know that it can cause to deadlock or for bad running time.
I mean what if I had more threads and even a larger M..
what is the correct way to set critical section?
another thing i want to ask is about the initial_array, is it also need to be shared?

A: This is safe code.
Random access in arrays does not cause any race conditions to other elements in the array. As long as you continue to read and write to unshared elements within the array concurrently, you'll never hit a race condition.
Keep in mind that a read can race with a write depending on the type and size of the element. Your example shows double, and I'd be concerned if you had reads concurrent with write operations on the same element. It is possible for there to be a context switch during a write, but that depends on your arch/platform. Anyways, you aren't doing this but it is worth mentioning.

A: I don't see any problem with regards to concurrency since you are accessing different parts of the memory (different indices of the array), but the only problem I see is performance hit if your cores have dedicated L1 caches.
In this case there will be a performance hit due to cache coherency, where one updates the index, invalidates others, does a write back etc. For small no of threads/cores not an issue but on threads running on large number of cores it sure it. Because the data your threads running on aren't truly independent, they are read as a block of data in cache (if you are accessing M[0][0], then not only M[0][0] is read into the cache but M[0][0] to M[n][col] where n depends upon the cache block size ). And if the block is large, it might contain more of shared data.


text:
Q: Can't parse element from XML result using DOM I am using Google weather api service. I am using DOM.
I have difficulty to get the element value.
thats an example of xml response:
<xml_api_reply version="1">
 <weather module_id="0" tab_id="0" mobile_row="0" mobile_zipped="1" row="0" section="0">
     <forecast_information>
         <city data="New York, NY"/>
         <postal_code data="new york,ny"/>
         <latitude_e6 data=""/>
         <longitude_e6 data=""/>
         <forecast_date data="2010-05-20"/>
         <current_date_time data="2010-05-20 07:44:43 +0000"/>
         <unit_system data="US"/>
     </forecast_information>
    <current_conditions>
        <condition data="Cloudy"/>
        <temp_f data="59"/>
        <temp_c data="15"/>
        <humidity data="Humidity: 80%"/>
        <icon data="/ig/images/weather/cloudy.gif"/>
        <wind_condition data="Wind: N at 0 mph"/>
    </current_conditions>
    <forecast_conditions>
        <day_of_week data="Thu"/>
        <low data="61"/>
        <high data="79"/>
        <icon data="/ig/images/weather/sunny.gif"/>
        <condition data="Sunny"/>
        </forecast_conditions>
    <forecast_conditions>
        <day_of_week data="Fri"/>
        <low data="60"/>
        <high data="83"/>
        <icon data="/ig/images/weather/partly_cloudy.gif"/>
        <condition data="Partly Cloudy"/>
    </forecast_conditions>
</weather>

Now let's say I want to retrieve the value of the condition data which is under the tag
(in this example i am trying to get the value="Cloudy"
this is what I do:
 void buildForecasts(String raw) throws Exception
{
    DocumentBuilder builder = DocumentBuilderFactory.newInstance()
            .newDocumentBuilder();
    Document doc = builder.parse(new InputSource(new StringReader(raw)));

    NodeList temps = doc.getElementsByTagName("current_conditions");

    for (int i = 0; i < temps.getLength(); i++)
    {
        Element temp = (Element) temps.item(i);
        String temp1 =temp.getAttribute("condition")
    }

}

it doesnt realy work for me. anyone has any idea?
thanks,
ray.

A: The temps list contains elements with name "current_conditions" (i.e. the node <current_conditions> in the XML). You need to get the sub-element named "condition" (i.e. the node <condition data="Cloudy"/> in the XML), and then get its data attribute.
for (int i = 0; i < temps.getLength(); i++)
{
    Element currentConditionsElement = (Element) temps.item(i);
    NodeList conditionList = currentConditionsElement.getElementsByTagName("condition");
    Element conditionElement = (Element) conditionList.item(0);
    String dataAttribute = conditionElement.getAttribute("data");
}

A: If you are using API level 8 (Android 2.2) then you can probably simplify things by using  XPath.


text:
Q: Proving the Product Rule for exponents with the same base For all $ a, b \text{ and } c \in \mathbb{R}$ and $a>1$, Prove that $a^b\cdot a^c=a^{b+c}$
I have come across this question and its  bugging me. Its a basic property that we learn in HS  and I was hoping someone can enlighten me

A: We give a formal argument. It will not be entirely easy.
Let's assume that we have defined the exponential function $\exp(t)=e^t$ in one of the many ways it can be done, and proved that its derivative is $e^t$. We define $a^x$ as $\exp(x\ln a)$.
For simplicity, write $k$ instead of $\ln a$. We want to prove that $\exp(ku)\exp(kv)=\exp(k(u+v))
$.
Keep $u$ fixed, and let
$$f(v)=\frac{\exp(k(u+v))}{\exp(kv)}.\tag{1}$$
Differentiate with respect to $v$. We get by the Quotient Rule and the Chain Rule
that $f'(v)=0$. (If you need details here, they can be supplied.)
So $f(v)$ is a constant function. Which constant?
Set $v=0$. We find that our constant is $\exp(ku)$. Now (1) gives us the result.

A: On way of doing this is to define $a^x$ for real $x$ using the least upper bound property of the real numbers.
$$ a^x = \text{ l.u.b of } \lbrace a^t \mid t< x, t\in \mathbb{Q} \rbrace $$
This means we consider the values for all rational powers which are less than $x$ and define the result of raising to the $x$ power as the smallest real number that is greater than or equal to the elements of this set.
To prove the product rule then we can first look at the meaning of $a^xa^y$ when $x,y\in \mathbb{R}$. Consider the following set,
$$ B=  \lbrace a^r a^t \mid r < x, t < y, r \in \mathbb{Q}, t \in \mathbb{Q} \rbrace $$
We can conclude the following,
$$ a^r < a^x \text{ by the definition of } a^x.$$
$$ a^t < a^y \text{ by the definition of } a^y.$$
$$ \text{ Therefore } a^r a^t < a^x a^y$$
I am going to leave the proof that $a^xa^y$ is the l.u.b of $B$ to the thoughtful reader.
We can now look at $a^{x+y}$, this is by definition
$$ a^{x+y} = \text{l.u.b of } \lbrace a^s \mid s < x+ y, s \in \mathbb{Q} \rbrace =  \text{ l.u.b of } \lbrace a^{r+t} \mid r < x, t <  y, r \in \mathbb{Q}, t \in \mathbb{Q} \rbrace. $$
Using our knowledge of the power rule for rational number (which is a different proof) we notice that this new set is really just $B$. Therefore $a^{x+y}$ is just the l.u.b of $B$. A set cannot have two distinct least upper bounds therefore $a^{x+y}=a^xa^y$.
Notice that there is no need to appeal to the exponential function (which is far easier) to establish the existence and properties of the real powers. All that is necessary is the defining property of the real numbers which distinguishes them from the rationals (the least upper bound property).
For rational powers we have to take a different approach. We first define rational powers using $n$th roots. If $m,n \in \mathbb{Z}$ then define,
$$ a^{m/n} \equiv \sqrt[n]{a^m} .$$
Now suppose we multiply two expressions with different rational powers,
$$ a^{m/n} a^{p/q} = \sqrt[n]{a^m} \sqrt[q]{a^p} .$$
We will label the left hand side with the variable $K$ giving us,
$$ K = \sqrt[n]{a^m} \sqrt[q]{a^p} .$$
Taking the $n\cdot q$ power of both sides (remember $n$ and $q$ are integers so this is well defined) we get,
$$ K^{nq} = \left(\sqrt[n]{a^m} \sqrt[q]{a^p}\right)^{nq}$$
$$ K^{nq} = \left(\sqrt[n]{a^m} \right)^{nq} \left( \sqrt[q]{a^p}\right)^{nq}$$
$$ K^{nq} = \left[ \left( \sqrt[n]{a^m} \right)^n\right]^{q} \left[ \left(\sqrt[q]{a^p} \right)^q \right]^{n}$$
$$ K^{nq} = \left(a^m \right)^{q} \left( a^p\right)^{n}$$
$$ K^{nq} = a^{mq} a^{pn} $$
$$ K^{nq} = a^{mq+pn} $$
Take note that in every step above I only either used the rules of exponents for integers or the definition of $n$'th roots.
Now we will remove the power from $K$ using radicals.
$$ K = \sqrt[nq]{a^{mq+pn}} $$
Recalling the definition of rational powers we rewrite the right hand side as,
$$ K = a^{\frac{mq+pn}{nq}} = a^{\frac{m}{n} + \frac{p}{q}}$$
Replacing $K$ with its value we have,
$$a^{m/n} a^{p/q} = a^{\frac{m}{n} + \frac{p}{q}}$$
and therefore we have established the product rule for exponents.


text:
Q: How to create .XAP extension file for windows phone I have created a new Windows 8 JavaScript project using phoneGap,
My question is
how can i get .XAP extension file in Bin folder
as this is mandatory to run my application on windows device.
And also tell me one thing there is any other solution to make this .XAP extension file.
Because of using javascript i am not getting .XAP extension file.

A: First of all you need to check that you are configured for windows 8 or windows phone 8.
If you compile it as Windows Phone Project then you can get XAP from your project.  Bin>>Debug>>Your project.XAP

A: You must either compile it, as a Windows Phone project, using Visual Studio. Or alternatively use the Adobe PhoneGap Build service, which allows you to send your code to the 'cloud' as a zip file. It will them build your app, returning IPA, APK, XAP and other native bundles.


text:
Q: How to get output of git commands into Python variables Is it possible to collect output of a git command into a Python variable?
Lets a simple command like git status which gives the list of files changed on the repo. Lets say the output of git status is following
A.cpp
B.hpp
C.cpp

Is it possible to get the above output of git status into a Python list?
I read the some git commands do not pipe the output and rather just print? Is it true even today? If a git command was piping the output, how can one collect it a Python list or variable?
Can GitPython help here?

A: You can use:
GitPython
Or 'native way':
from subprocess import Popen, PIPE
cmd = 'git diff --name-only'
p = Popen(cmd, stdout=PIPE, stderr=PIPE)
stdout, stderr = p.communicate()
files_changed_list = stdout.decode("utf-8").splitlines()

A: You could also use Python's os module.
import os

os.system("git diff --name-only | tee status")

would put the names of the changed files into a file called status.
Erm I think the other answer is better though.


text:
Q: ORACLE SQL Keep Data Show Even On Another Table Column Parameter Not Existed I want to display data with another table with parameter DESCRIPTIONID.
Now I want to keep data shown even on another table is null/empty(not existed DESCRIPTIONID).
Below query work if both table have an DESCRIPTIONID.
SELECT D.DESCRIPTIONID, D.DESCRIPTION, D.PROFILEID_FK, D.ACTIVE, P.PROFILEID, P.PROFILE_NAME FROM WA_BT_TBL_DESCRIPTION D, WA_BT_TBL_PROFILE P WHERE D.PROFILEID_FK = P.PROFILEID AND D.PROFILEID_FK = 'PF0001' AND D.ACTIVE = 'Y' ORDER BY D.DATEADDED ASC

And here the query I want to improve:
SELECT
DISTINCT
D.DESCRIPTIONID,
D.DESCRIPTION,
Y.TIME
FROM
WA_BT_TBL_DESCRIPTION D,
WA_BT_TBL_DAY Y
WHERE
D.DESCRIPTIONID = Y.DESCRIPTIONID_FK AND
D.PROFILEID_FK = Y.PROFILEID_FK AND
D.PROFILEID_FK = 'PF0001'
ORDER BY Y.TIME ASC

Let's see on SQL Fiddle
Please try both query on SQL Fiddle.
As you can see I want "Break Time II" keep show.
Finally I want the query show like below:
DESCRIPTIONID   DESCRIPTION          TIME
DS0003          Break Time I         10:00
DS0001          Operator Clock Time  15:30
DS0002          Working Time I       17:00
DS0024          Break Time II             <-- keep show this row(null/empty)

A: Use outer join.
In the older and harder to understand syntax (the one you used), like this (note the (+) on the conditions):
SELECT
DISTINCT
  D.DESCRIPTIONID,
  D.DESCRIPTION,
  Y.TIME
FROM
  WA_BT_TBL_DESCRIPTION D,
  WA_BT_TBL_DAY Y
WHERE
  D.DESCRIPTIONID = Y.DESCRIPTIONID_FK(+) AND
  D.PROFILEID_FK = Y.PROFILEID_FK(+) AND
  D.PROFILEID_FK = 'PF0001'
ORDER BY Y.TIME ASC

In the more encouraged one (explicitly writing LEFT JOIN...ON):
SELECT
  DISTINCT
  D.DESCRIPTIONID,
  D.DESCRIPTION,
  Y.TIME
FROM
  WA_BT_TBL_DESCRIPTION D LEFT JOIN
  WA_BT_TBL_DAY Y ON D.DESCRIPTIONID = Y.DESCRIPTIONID_FK AND
  D.PROFILEID_FK = Y.PROFILEID_FK AND
  D.PROFILEID_FK = 'PF0001'

ORDER BY Y.TIME ASC

A: Few things, don't you the old style JOIN they are very outdated, You will need to just a LEFT OUTER JOIN. The WHERE clause on your query is limiting the return to results that exists in both tables :
WHERE
D.DESCRIPTIONID = Y.DESCRIPTIONID_FK

This is essentially an INNER JOIN.
Try this:
SELECT
  D.DESCRIPTIONID,
  D.DESCRIPTION,
  Y.TIME
FROM
WA_BT_TBL_DESCRIPTION D
LEFT OUTER JOIN WA_BT_TBL_DAY Y ON D.DESCRIPTIONID = Y.DESCRIPTIONID_FK
WHERE
D.PROFILEID_FK = 'PF0001'
ORDER BY Y.TIME ASC

There is a post HERE which explains the different types of joins really well


text:
Q: redirecting a page and displaying a message through javascript I have an HTML page which provides input fields for email ID and password, I use these values to connect with my backend SQL server through node js express application .
I have an app.post() method to connect with SQL.
app.post('/user', function (req, res, body) {
uid = req.body.user1;
pwd = req.body.user2;

    config = 'Server={ip of server};Database=Dbname;Uid=domain\\user' + uid + ';Pwd=' + pwd;

    var dbConn = new sql.Connection(config);
    dbConn.connect().then(function () {                                         //using promises instead of callbacks(onceconnect() is done), then go to then()

        var request = new sql.Request(dbConn);
         console.log('DONE');
    res.status(500).json({ status: 'done' })

    }).catch(function (err) {

        console.log("INVALID");
    res.status(500).json({ status: 'invalid' })
});

What I want to achieve is -

*

*If the credentials are valid, displaying an alert 'DONE' at client side.

*If the credentials are invalid, displaying an alert 'INVALID' at client side.

Currently, if everything is valid, there is DONE at /user.
If the ID and Password do not match, there is INVALID at /user.
My client side code is
<!DOCTYPE html>
<html>

 <body>

<form id ="target" action="/user" method="post">
    UserID : <input id="uid" type="text" name="user1" />                        <!text fields for date input>
    Password  : <input id="pwd" type="password" name="user2" />

    <input id="Submit1" type="submit" value="LOGIN"/>       <!--<!submit button>-->
    <input id="Button" type="button" value="show graphs" onclick="btntest_onclick()" />
</form>

$.post("/user", function (data) {
    $("#target").html(data)
    alert( "Data Loaded: " + data );
});

<script type="text/javascript">
    function btntest_onclick() {

    setTimeout(function () {

       window.location.href = "/../";
    },500);
}
</script>
</body>
</html>

I am unable to use $.post() on client to retrieve data back from user- gives 500 error.
How do I proceed? Please help me.

A: I could solve this by using the jquery ajax callback that returns back data to the client.
$("#target").submit(function (event) {

    var formData = {
        'uid': $('input[name=uid]').val(),
        'pwd': $('input[name=pwd]').val()
    };

    $.ajax({
        type: 'POST', // define the type of HTTP verb we want to use (POST for our form)
        url: '/user', // the url where we want to POST
        data: formData, // our data object
        dataType: 'json', // what type of data do we expect back from the server
        encode: true
    })
     .error(function (data) {

         // log data to the console so we can see
         alert(data.responseText);
     })
    .done(function (data) {

        // log data to the console so we can see
        console.log(data);

        // here we will handle errors and validation messages
    });
    event.preventDefault();

});


text:
Q: How to call object's method from another object in Java? I have 2 classes:
MainActivity.java
public class MainActivity extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        new MyAsyncTask().execute("string");
    }

    public void setSomething(int param) {
        // ... some code here ...
    }
}

and
MyAsyncTask.java
public class MyAsyncTask extends AsyncTask<String, Void, String> {
    @Override
    protected String doInBackground(String... str) {
        return "Someting here";
    }

    @Override
    protected void onPostExecute(String jsonStr) {
         // how to call setSomething(param) from here?
    }
}

How to call setSomething(param) from MyAsyncTask?

A: In general, the way to call it is to have a reference to an object of type MainActivity and to call this method on it. Whether that's a good idea in this particular Android scenario, is another question.

A: Pass a reference of MainActivity to MyAsyncTask:
public class MyAsyncTask extends AsyncTask<String, Void, String>
{
    private MainActivity mainActivity;

    public MyAsyncTask(MainActivity mainActivity)
    {
        this.mainActivity = mainActivity;
    }
}

Then, whenever creating an instance of MyAsyncTask inside the class MainActivity, pass this (MainActivity instance) to the constructor:
new MyAsyncTask(this).execute();

A: It may be worth looking into using an async library.
Using a library to help handle async callbacks can be super helpful for this as you can start the spinner, call your api, then stop the spinner in either the onSuccess function, or your success callback method in your class.
This is the one I usually use:
LoopJ's Async HTTP Callback Library
This will handle GET and POST requests with a lot of cool features such as custom timeouts, JSON format, onSuccess() and onFailure() methods, etc. There's a lot of working examples of this library too!


text:
Q: Wordpress REST API is sending HTML having script instead of JSON I am sending request to WordPress REST API endpoint -
https://example.com/wp-json/wp/v2/comments.
But it is not sending JSON as response.
Instead, it is sending HTML having script tag as follows -
<html>
  <body>
    <script>
      document.cookie =
        "_test=<cookie value> ; expires=<expiary date>; path=/";
      document.location.href =
        "https://example.com/wp-json/wp/v2/comments";
    </script>
  </body>
</html>

Here, 1) a cookie named _test is getting created, 2) After that, it is redirecting to the requested URL with document.location.href.
So, when I am trying to parse the response using JSON.parse method, then it is failing, as it is in HTML format.
But, when I am entering the endpoint URL in browser search bar, then  document.location.href method inside the script of the response is helping to redirect to the expected JSON.
My expected response should be like this
[{"id":1,"post":1,"parent":0,"author":0,"author_name":"A WordPress Commenter","author_url":"https:\/\/wordpress.org\/","date":"2022-07-22T16:38:55","date_gmt":"2022-07-22T16:38:55","content":{"rendered":"Comment 1"}}, /*...*/]

Now, how to get response as JSON directly, instead of HTML?

A: Your question is confusing. In your code you are using JavaScript to redirect the page to the json data, not fetch the information.
Try this and check your console. You should be able to take it from there.
const url = "https://example.com/wp-json/wp/v2/comments";
const comments = getComments( url );

// My function
async function getComments( url ) {
    // Try to fetch the url
    await fetch( url )
        .then( function ( response ) {
        console.log( response );

        // Get the status
        console.log( "Status code: " + response.status );

        // The API call was unsuccessful
        if ( response.status > 299 ) {
            throw new Error( finalError );

        // The API call was successful
        } else {
            return response.json();
        }
        })
        .then( function ( data ) {
        // This is the response data as a text string
        console.log( data );

        // Make sure we have data
        if ( data.length == 0 ) {
            throw new Error( finalError );
        }

        // Only continue if not null or empty
        if ( data[0] !== null && data[0] !== undefined && data.length > 0 ) {

            // Iter through each item
            for ( let d = 0; d < data.length; d++ ) {

                // Log it
                console.log( data[d] );
            }
        }
        })
        .catch( function handleError( error ) {
            console.log( error );
        }
    );
}


text:
Q: Find volume of remaining solid using surfaces of revolution. A sphere has radius R. A cylindrical hole has been drilled straight through the center of the sphere. What's the volume of the remaining solid if the height of the remaining solid is 6 cm high?

A: Great problem.  The result is surprising.
First, place the sphere's center at the origin, and look at it from the perspective of the positive $z$-axis.
Now, notice that the equation of the circle of radius $R$ that you see is $x^2+y^2=R^2$.  This shows that the radius of a horizontal cross section of the sphere is $x=\sqrt{R^2-y^2}$.  The radius of the cylinder can be found using Pythagorean's theorem.  It is $\sqrt{R^2-9}$.  It follows that the area of a horizontal cross section of the shape is:
$$A(y)=\pi(R^2-y^2)-\pi(R^2-9)=\pi(9-y^2)$$
If we integrate this from $y=-3$ to $y=3$ we find the volume of the shape to be $36\pi$.  Note this answer doesn't depend on the radius of the sphere! (Although I guess that we assume $R\ge 3$ to stay in the world of real numbers).
You can check that our final answer makes sense in the limiting case that $R=3$.  In that case, there is no whole, and the volume of a sphere of radius $3$ is indeed $36\pi$.

A: We imagine the same thing done to a half-sphere. Then we can multiply by $2$ at the end.
Let the radius of the cylinder be $r$. Then by the Pythagorean Theorem, $r^2=R^2-9$.
If we take a horizontal slice at height $x$, the cross-section is a circle of radius $\sqrt{R^2-x^2}$, with a hole of radius $r$. Thus the cross-sectional area is $\pi(R^2-x^2 -r^2)$. This is $9-x^2$. Integrate from $x=0$ to $x=3$. Then double to get the full remaining volume.
Note that the answer depends neither on $r$ nor $R$!


text:
Q: Por qué no se aplica mi clase active a mi NavBar - JQuery Estoy haciendo una página y no se aplica la clase active del todo, vuelve la clase active al que está por defecto ,  ¿por qué pasa esto?  Este es el link de la página llanes
Este es el código, pero aquí si se me ejecuta

$(function() {
            // elementos de la lista
            var menues = $("#navbarSupportedContent .navbar-nav .nav-item");
                // manejador de click sobre todos los elementos
                menues.click(function() {
                    // eliminamos active de todos los elementos
                    menues.removeClass("active");
                    // activamos el elemento clicado.
                    $(this).addClass("active");
                });
        });
.navbar-light .navbar-nav .active>.nav-link, .navbar-light .navbar-nav .nav-link.active, .navbar-light .navbar-nav .nav-link.show, .navbar-light .navbar-nav .show>.nav-link {
 color: #000;
 font-weight: bold;
}

<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">

     <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">

     </button>

           Home (current)

           Quienes Somos

           Semblanza

           Servicios Jurídicos

           Noticias

           Contácto

A: Necesitas apuntar al item que tiene la clase active, en este caso es nav-item, y ya con eso debería de eliminar el actual y aplicarle el active al nuevo.

$(function() {
            // elementos de la lista
            var menues = $(".nav-item");
                // manejador de click sobre todos los elementos
                menues.click(function() {
                    // eliminamos active de todos los elementos
                    menues.removeClass("active");
                    // activamos el elemento clicado.
                    $(this).addClass("active");
                });
        });
.navbar-light .navbar-nav .active>.nav-link, .navbar-light .navbar-nav .nav-link.active, .navbar-light .navbar-nav .nav-link.show, .navbar-light .navbar-nav .show>.nav-link {
 color: #000;
 font-weight: bold;
}

<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">

     <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">

     </button>

           Home (current)

           Quienes Somos

           Semblanza

           Servicios Jurídicos

           Noticias

           Contácto


text:
Q: Cannot connect to dbf file I'm trying to connect to to a foxpro table (.dbf) from a test vb.net form.
I recieve an OleDbException with the message "Cannot open file c:\emp\emptbl.dbf"
Have tried with both of the following connection strings:

Provider=VFPOLEDB.1;Data Source=C:\emp\emptbl.dbf

from the MSDN article here

Provider=vfpoledb;Data Source=C:\emp\emptbl.dbf;Collating Sequence=machine;

from connectionstrings.com
The latter seems to be the type to use when connecting to a single table, but the same exception is thrown regadless of which is used.
I can open and perform the same query okay in visual foxpro 6.0.
Here's my code:
    Dim tbl As DataTable = New DataTable()

        Using con = New OleDbConnection(conString)
            cmd = New OleDbCommand() With {.Connection = con, .CommandType = CommandType.Text}
            Dim sSQL As String = "SELECT * FROM(EMPTBL)"
            cmd.CommandText = sSQL
            Dim adp As OleDbDataAdapter = New OleDbDataAdapter(cmd)
            Dim ds As DataSet = New DataSet()
            con.Open()
            adp.Fill(ds)
            con.Close()
            If (ds.Tables.Count > 0) Then
                tbl = ds.Tables(0)
            End If
        End Using

    Return tbl

A: The OleDB provider should only connect to the PATH where the tables are... not the actual file name.  Once you connect to the PATH, you can query from ANY .Dbf file that is located in it
Provider=VFPOLEDB.1;Data Source=C:\emp
select * from emptbl where ...
You can also look at other connection string settings at
ConnectionStrings.com
UPDATE per comment.
It appears you are getting closer. with your attempt without the () parens.  In VFP, within parens, it interprets that as "look for a variable called EMPTBL", and from its value is the name of the table to query from.  Not something you would need to apply via OleDB connection.
Now, cant open the file is another.  Is it POSSIBLE that another application has the table open and the file is in exclusive use? and thus can not be opened by the .net app too?  Even for grins, if you open VFP, and just do a simple create table in the C:\Emp folder and put a single record in it, then you know no other program will be using it as it is a new file.  Quit out of VFP and try to query THAT table.  There should be no locks, no other program is expecting it, so it should never be opened by anything else and you should be good to go.


text:
Q: Synchronization in php after reading this:
PHP Threads and Synchronization
is my assumption correct that even if I have a singelton pattern, there actually is 1 instance of this class per request? What about flock?
I need to limit a certain functionality/code block in my application to be only executed by one request at a time.
The reason is a bit strange, I need to call a cmd-line tool that reads a txt file I create in php and then writes the result to several txt files. To prevent false/strange results the whole code block create file - run cmd-line- read result should be synchronized.
How could i do that? I tried it with a dummy file an lock it with flock -> does not work.
I also tried a simple boolean field isLocked to stop further execution of a second request.
Also does not work.
The issue is the first request is processed correctly (data inserted into DB) but the second not and both request do not finish, page loads forever.
Ideas? solutions?
EDIT:
$lockFile = fopen("lock", "r");
while (!flock($lockFile, LOCK_EX)) {

    sleep(1000);
}
// do work
flock($lockFile, LOCK_UN);
fclose($lockFile);

Or:
if (myClass::$isLocked) {
  return false;
}
myClass::$isLocked = true
// do work
myClass::$isLocked = false

both versiosn don't work and both requests freeze, eg. next page never loads. I need to kill apache process.

A: Yes, Apache serves the request and then moves on. This means unless you put something in the session, it will cease to exist at the end of the request.
If you want to lock files in you can use flock (as you've indicated) : http://php.net/manual/en/function.flock.php
And if you want to manage state in the DB, you can use transactions (mysql link) : http://dev.mysql.com/doc/refman/5.0/en/ansi-diff-transactions.html


text:
Q: Trouble with AJAX DELETE I'm not sure what I'm doing wrong here? The GET works fine with the same info, but the DELETE keeps giving me a 500 Internal server error, and my server logs say, "StoredProduct.delete is not a function"
For the sake of this post, I'm including the GET route and GET JS below, just to show those are working, so I think my routes are set up correctly?
These are my routes
router.get('/:productID', (req, res, next) => {
  StoredProduct
    .findOne({
      _id: req.params.productID
    })
    .then(product => {
      res.status(201).json(product);
    });
});

router.delete('/:productID', (req, res) => {
  StoredProduct
    .delete(req.params.productID);
  res.status(204).end()
    .catch(err => {
      console.log(err);
      res.status(500).json({
        error: err
      });
    });
});

And this is my JS
  $.ajax({
    type: 'GET',
    url: '/products/' + productID,
    success: function(product) {
      $editProdName.append(`${product.name}`);
      $addPrice1.val(product.prices[0].price);
      $addPrice2.val(product.prices[1].price);
      $addPrice3.val(product.prices[2].price);
      $selectedUnit.val(product.size);
    }
  });

  $('#deleteme').on('click', function(e) {
    e.preventDefault();
    console.log(productID);
    $.ajax({
      type: 'DELETE',
      url: '/products/' + productID,
      success: function(){
        console.log('yippee');
      }
    });
  });

A: Do you use mongoose?
If so try to
StoredProduct.deleteOne({ id: req.params.productID }, function (err) {});

Also from http://api.jquery.com/jquery.ajax/:

Deprecation Notice: The jqXHR.success(), jqXHR.error(), and jqXHR.complete() callbacks are removed as of jQuery 3.0. You can use jqXHR.done(), jqXHR.fail(), and jqXHR.always() instead.

A: You can use mongoose.deleteOne() and search by id and delete:
router.delete('/:productID', (req, res) => {
  StoredProduct
    .deleteOne({ _id: req.params.productID}).then(data =>
  res.status(204).end()).catch(err => {
      console.log(err);
      res.status(500).json({
        error: err
      });
    });
});


text:
Q: Python 3.5: Input function not requiring carriage return, accepts only one character, and character returned only if given condition satisfied I am designing a game in which I require the input function to accept input without requiring the user to press the enter key. Also,once the user enters a single character,the variable in which the input is supposed to be stored must contain that character at once(as if the user had pressed the enter key after entering that character). The character entered must be displayed on screen only if it satisfies a given condition. Please enlighten me on how I can achieve this. Thank you.
NOTE:I am a beginner in Python, hence please do not delve into things that are way beyond my comprehension.My teacher has forbidden us from using classes for our project. I should be able to utilize the characters displayed on screen which I don't find possible using the solutions given for other similar questions.

A: After searching, I found a packaged named msvcrt, and it can be helpful in your situation.
For more information, please check: raw_input in python without pressing enter.
Following is a simple example(it works in Windows). You should open your command line and use python xxx.py to execute the following program.
import msvcrt
import sys

while True:
    c = msvcrt.getch()
    if c == b'\x03': # Ctrl-C
        sys.exit()
    #print(type(c)) # bytes

    #convert from bytes to str
    c = c.decode('utf-8')

    if c =='a': #replace 'a' with whatever you want
        print(c)

It takes the single character input from msvcrt.getch() and assign it to the variable c.
And it prints that character if its string format equals to 'a'.
If you want to exit the program, just press Ctrl-C.
EDIT:
From Python kbhit() problems, it seems msvcrt.getch cannot work in IDLE by nature. But there is a workaround (adjusted from: PyCharm: msvcrt.kbhit() and msvcrt.getch() not working?). If you are using Spyder, click Run -> Configuration per file -> Execute in an external system terminal. And when you later run the script file, a console window will jump up.


text:
Q: action bar icon keep showing back icon i'm literally new in developing android apps. My project using navigation drawer between fragments. i tried to custom the drawer with tutorial http://www.tutecentral.com/android-custom-navigation-drawer/ and got an error. in my application, in action bar, it keeps showing back icon instead the default icon.
this is url for before-after image of actionbar : http://oi58.tinypic.com/2ahsbys.jpg
here is the code i'm confused of (pretty same with the tutorial, tell me if there's something i missed)
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    getSupportActionBar().setHomeButtonEnabled(true);

    mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
            R.drawable.ic_drawer, R.string.navigation_drawer_open,
            R.string.navigation_drawer_close) {
        public void onDrawerClosed(View view) {
            getSupportActionBar().setTitle(mTitle);
            invalidateOptionsMenu(); // creates call to
            // onPrepareOptionsMenu()
        }

        public void onDrawerOpened(View drawerView) {
            getSupportActionBar().setTitle(mDrawerTitle);
            invalidateOptionsMenu(); // creates call to
            // onPrepareOptionsMenu()
        }
    };

if i delete setDisplayHomeAsUpEnabled, the back icon is gone but i can't click somewhere to display the drawer, i have to slide it. please refer me if someone has solved it. many thanks.
*i have changed the R.drawable.ic_drawer to other drawable icons but it had no effects.

A: Try setting a theme for your activity in manifest file and inside styles.xml set your drawable for homeAsUpIndicator for that theme
<style name="CustomTheme" parent="@style/Widget.AppCompat.ActionBar">
     <item name="homeAsUpIndicator">@drawable/ic_drawer</item>
</style>


text:
Q: How to handle BETWEEN clause on a partition key in Cassandra My table is like below
CREATE TABLE T (
  A int PRIMARY KEY,
  B int,
  C int
);

and I need to retrieve data with values of A between 10 and 1122
In SQL we can do this using BETWEEN clause.
As Cassandra doesn't support use of >, < I couldn't able to query it.
Can anyone please help me on this.

A: Cassandra does not allow that query on its own since it requires reading all the data in the table and filtering out data. You need to change your data model to support your query without operations that would not scale and cannot be efficiently distributed. You can actually make this work with the ALLOW FILTERING flag to acknowledge that you are ignoring all wisdom and recommendations. This is more for one off debugging and specialized bulk operations and will cause issues if you use it in your application:
SELECT * FROM T WHERE A > 10 AND A < 1122 ALLOW FILTERING;


text:
Q: How can I override the session ID for a node.js express session (using passport) I'm implementing a passport strategy that calls our internal auth service.  The internal auth service generates the session ID, so I need to make sure the connect session uses that ID instead of the default generated ID.
Is there a way to do this?  Is it possible to provide my own hook function to connect to produce the session id?  I can't imagine it's as simple as setting session.id or anything like that, because I don't have control over when or how connect actually creates the session.
Has anyone solved this problem?

A: This cannot be done with the current implementation of Connect's session middleware, but you can fork the session middleware and change how the session id is generated, namely this line:
https://github.com/senchalabs/connect/blob/master/lib/middleware/session.js#L202
By "fork" I mean copying the file above, changing the assignment of the sessionID and using your new file instead when configuring the session middleware.
UPDATE:
Here's how I would regenerate the session with a custom id (note - this is just an idea, I haven't tested it):
// this is the function you'll be calling in your routes or whatever
req.regenerateSession = function(newSid) {
  // keep old session data
  var oldSessionData = req.session;

  // destroy current session and make a new one with your custom id
  store.destroy(req.sessionID, function() {
    store.generate(req, newSid);

    // copy back the session data
    // since you don't want to lose it probably
    req.session = oldSessionData;
  });
}

// replace the session store generate function to accept a custom sessionID
// https://github.com/senchalabs/connect/blob/master/lib/middleware/session.js#L201
store.generate = function(req, customID) {
  req.sessionID = customID || utils.uid(24);
  req.session = new Session(req);
  req.session.cookie = new Cookie(req, cookie);
}


text:
Q: Memento not update state with undo in Java I have a graph that contains vertices and edges and I have an originator class that contains the graph that should be used to insert vertices or get the list of vertices in the graph
interface vertex
public interface Vertex<V> {
    public V element();
}

interface edge
public interface Edge<E, V> {
    public E element();
    public Vertex<V>[] vertices();
}

interface graph with Inserts a new vertex and other method is hide()
public interface Graph<V, E> {
  public void insertVertex(V vElement);
  public Iterable<Vertex<V>> vertices();
}

ADT Graph implementation that stores a collection of vertices (and edges, but not need)
public class GraphEdgeList<V, E> implements Graph<V, E> {
    private Map<V, Vertex<V>> vertices;

    public GraphEdgeList() {
        this.vertices = new HashMap<>();
    }

    @Override
    public void insertVertex(V vElement) {
     //method to insert new vertex element
     //not need to return nothing
    }

    @Override
    public Iterable<Vertex<V>> vertices() {
    //return a list of vertices in graph
    }
}

class Memento
public class Memento {
    private Graph graph;

    public Memento(Originator originator) {
        graph = originator.getGraph();
    }

    public Graph getGraph() {
        return graph;
    }
}

class Originator
public class Originator<V,E> {
    private Graph<V,E> graph;
    private Caretaker caretaker;

    public Originator(Caretaker caretaker) {
      this.graph = new GraphEdgeList();
      this.caretaker = caretaker;
    }

    public Memento createMemento() {//create new memento
        return new Memento(this);
    }

    public void setMemento(Memento memento) {//set memento
       graph = memento.getGraph();
    }

    public Graph getGraph() {
      return graph;
    }

    public Caretaker getCaretaker() {
     return caretaker;
    }
}

Interface IMemento
public interface IMemento {
    public void save(Originator originator);
    public void restore(Originator originator);
}

class CareTaker implements interface IMemento
public class Caretaker implements IMemento {

    private final Stack<Memento> undoMemento;//stack explicit

    public Caretaker() {
        this.undoMemento = new StackDynamic();
    }

    @Override
    public void save(Originator originator) {
        Memento memento = originator.createMemento();
        undoMemento.push(memento);
    }

    @Override
    public void restore(Originator originator) {
        if (undoMemento.isEmpty() != true) {
            Memento memento = undoMemento.pop();
            originator.setMemento(memento);
       }
    }
}

my doubt starts after saving the state and when trying to do undo the graph does not update to the previous state
public class Main {
    public static void main(String[] args) {
        Caretaker caretaker = new Caretaker();
        Originator<String, String> originator = new Originator(caretaker);

        //create new string and insert in graph
        originator.getGraph.insertVertex("A");
        //caretaker save state
        caretaker.save(originator);

       //create another string and insert in graph
        originator.getGraph.insertVertex("B");
        //caretaker save state
        caretaker.save(originator);
    }
}

but when I do restore de graph still with 2 vertices
caretaker.restore(originator);

any suggestion?

A: You are referencing the same collection of vertices inside the Memento.
Try to change the following classes:
public class Originator<V,E> {
    private Graph<V,E> graph;
    private Caretaker caretaker;

    public Originator(Caretaker caretaker) {
      this.graph = new GraphEdgeList();
      this.caretaker = caretaker;
    }

    public Originator(Originator<V, E> originator) {
         this.graph = new GraphEdgeList((GraphEdgeList) originator.getGraph());
         this.caretaker = originator.getCaretaker();
    }

    public Memento createMemento() {//create new memento
        return new Memento(new Originator(this));
    }

    public void setMemento(Memento memento) {//set memento
       graph = memento.getGraph();
    }

    public Graph getGraph() {
      return graph;
    }

    public Caretaker getCaretaker() {
     return caretaker;
    }
}

See the new constructors.
public class GraphEdgeList<V, E> implements Graph<V, E> {
    private Map<V, Vertex<V>> vertices;

    public GraphEdgeList() {
        this.vertices = new HashMap<>();
    }

    public GraphEdgeList(GraphEdgeList graph) {
         this.vertices = new HashMap<>();
         this.vertices.putAll(graph.getVertices());
    }

    @Override
    public void insertVertex(V vElement) {
        this.vertices.put(vElement, null);
    }

    public Map<V, Vertex<V>> getVertices() {
        return vertices;
    }

    public void setVertices(Map<V, Vertex<V>> vertices) {
        this.vertices = vertices;
    }

    @Override
    public Iterable<Vertex<V>> vertices() {
        return this.vertices.values();
    }

    @Override
    public String toString() {
        return "GraphEdgeList [vertices=" + vertices + "]";
    }
}


text:
Q: Programmatically adding security permissions to files in C# In an asp.net app, I have a task that ftps some xml files down to a local folder on my computer. I then want to read those files but when they're copied to my local folder, they don't have the Network Service user account set up. So, my question is how, in .Net C#, do you programmatically add the "Network Service" account with full control to my xml files.

A: See the FileSecurity class in MSDN
The following code example uses the FileSecurity class to add and then remove an access control list (ACL) entry from a file. You must supply a valid user or group account to run this example.
using System;
using System.IO;
using System.Security.AccessControl;

namespace FileSystemExample
{
    class FileExample
    {
        public static void Main()
        {
            try
            {
                string fileName = "test.xml";

                Console.WriteLine("Adding access control entry for "
                    + fileName);

                // Add the access control entry to the file.
                AddFileSecurity(fileName, @"DomainName\AccountName",
                    FileSystemRights.FullControl, AccessControlType.Allow);

                Console.WriteLine("Removing access control entry from "
                    + fileName);

                // Remove the access control entry from the file.
                RemoveFileSecurity(fileName, @"DomainName\AccountName",
                    FileSystemRights.FullControl, AccessControlType.Allow);

                Console.WriteLine("Done.");
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }
        }

        // Adds an ACL entry on the specified file for the specified account.
        public static void AddFileSecurity(string fileName, string account,
            FileSystemRights rights, AccessControlType controlType)
        {

            // Get a FileSecurity object that represents the
            // current security settings.
            FileSecurity fSecurity = File.GetAccessControl(fileName);

            // Add the FileSystemAccessRule to the security settings.
            fSecurity.AddAccessRule(new FileSystemAccessRule(account,
                rights, controlType));

            // Set the new access settings.
            File.SetAccessControl(fileName, fSecurity);

        }

        // Removes an ACL entry on the specified file for the specified account.
        public static void RemoveFileSecurity(string fileName, string account,
            FileSystemRights rights, AccessControlType controlType)
        {

            // Get a FileSecurity object that represents the
            // current security settings.
            FileSecurity fSecurity = File.GetAccessControl(fileName);

            // Remove the FileSystemAccessRule from the security settings.
            fSecurity.RemoveAccessRule(new FileSystemAccessRule(account,
                rights, controlType));

            // Set the new access settings.
            File.SetAccessControl(fileName, fSecurity);

        }
    }
}

A: try this code if help
    public static bool CheckReadWriteAccces(string filePath, System.Security.AccessControl.FileSystemRights fileSystemRights)
    {
        FileInfo fileInfo = new FileInfo(filePath);

        string str = System.Security.Principal.WindowsIdentity.GetCurrent().Name.ToUpper();
        foreach (System.Security.AccessControl.FileSystemAccessRule rule in fileInfo.GetAccessControl().GetAccessRules(true, true, typeof(System.Security.Principal.NTAccount)))
        {
            if (str == rule.IdentityReference.Value.ToUpper())
                return ((rule.AccessControlType == System.Security.AccessControl.AccessControlType.Allow) && (fileSystemRights == (rule.FileSystemRights & fileSystemRights)));
        }

        return false;
    }

    /// <summary>
    /// Make a file writteble
    /// </summary>
    /// <param name="path">File name to change</param>
    public static void MakeWritable(string path)
    {
        if (!File.Exists(path))
            return;
        File.SetAttributes(path, File.GetAttributes(path) & ~FileAttributes.ReadOnly);
    }

A: The answer lies in the FileSecurity Class.
http://msdn.microsoft.com/en-us/library/system.security.accesscontrol.filesecurity.aspx


text:
Q: Reversing only the order of a Sentence in C I have been trying to reverse the order of a sentence containing a string using pointers. My code snippet:
int main()
{
char c[50];
char *ptr;
int i=0,len;
gets(c);
ptr=c;
len=strlen(c);
for(i=len-1;i>=0;i--)
  printf("%c",*(ptr+i));
return 0;
}

This code generates a reverse of the string I enter correctly. Like for example:
Input: how are you
output: uoy era woh
But what I kept in mind was entirely different, I just wanted the order of the words in the sentence to reverse and not the exact words to reverse.
For example, for the same input "how are you" I want the output to be "you are how". Ive been breaking my head for quite some time now. Is there something that Im missing???
Re-EDIT: I want to do the reverse concept using pointers and pointers only!!! thats why i posted as a new question!!!
As suggested by another user, I tried using the strtok() function too and my output works kinda fine but is throwing garbage values.... Kindly help to this context::
#include <stdio.h>
#include <stdlib.h>

int main()
{
char c[50],d[50];
char *ptr,*aptr,*tok;
int i=0,j=0,len;
gets(c);
ptr=c;
aptr=d;
len=strlen(c);
printf("%d\n",len);
for(i=len-1;i>=0;i--,j++)
  *(aptr+j)=(*(ptr+i));
for(i=0;i<len;i++)
 printf("%c",d[i]);
printf("\n");
tok=strtok(aptr," ");
while(tok!=NULL)
{
 printf("%s\n",strrev(tok));
 tok=strtok(NULL,aptr);
}
return 0;
}

and i Finally landed at the most optimized answer!!!!
#include <stdlib.h>

int main()
{
char s[20][20];
int i=0,length=-1;
for(i=0;;i++)
{
    scanf("%s",s[i]);
    length++;
    if(getchar()=='\n')
        break;
}
for(i=length;i>=0;i--)
    printf("%s ",s[i]);
return 0;
}

A: Print string when you just after a spacebar or at the beginning:
for(i=len-1;i>=0;i--)
  if (i==0) || (*(ptr+i-1)==' ') {
    printf("%s ",*(ptr+i));
    if (i!=0)
      *(ptr+i-1)='\0'; // Cutting the next print. Attention: that changes the original string.
  }
return 0;


text:
Q: Can I Pivot a table without a Key in MySQL? I have a table that has data coming in like my example here.  I need to pivot the table but have no key to reference for the column name.  I can do it if there are only two values with Max and Min. However I'm going to eventual end up with 20 columns.  Right now I'm concatenating them all into a table and then Splitting them apart into another.  I was hoping there was a more efficient way of doing this.
 CREATE TABLE  test (
    ID VarChar(50),
    PJQ VarChar(50));

    INSERT INTO test
      (ID, PJQ)
    VALUES
      (1001, 'C982401'),
      (1001, 'F258147'),
      (1000, 'Q985267'),
      (1000, 'R258147'),
      (1000, 'T258476');

And Then I can do this However it only works with two. I'm going to have to do this 20 times.
SELECT ID,
   MAX(PJQ) PJQ1,
   MIN(PJQ) PJQ2
FROM test
GROUP BY ID

I need to be able to do this.
ID      PJQ1     PJQ2      PJQ3
1000    T258476  Q985267   T258476
1001    F258147  C982401

Any help on this problem would be very helpful.  Thanks
Here is a link to Fiddle where I have been trying to figure this out.
Fiddle

A: You can use a subquery that increments a variable for each row, and then use this as the pivot key.
SELECT id,
        MAX(IF(counter = 1, pjq, '')) AS pjq1,
        MAX(IF(counter = 2, pjq, '')) AS pjq2,
        MAX(IF(counter = 3, pjq, '')) AS pjq3,
        ...
        MAX(IF(counter = 20, pjq, '')) AS pjq20
FROM (SELECT id, pjq,
            @counter := IF(id = @last_id, @counter + 1,
                            IF(@last_id := id, 1, 1)) AS counter
      FROM (SELECT id, pjq FROM test ORDER BY id, pjq) AS x
      CROSS JOIN (SELECT @counter := 0, @last_id = null) AS vars
) AS y
GROUP BY id

FIDDLE
This simple query will work as long as you know the maximum number of columns. If it can be an arbitrary number, you'll need to write a stored procedure that creates dynamic SQL, by first getting the maximum count of values per ID, then generates enough MAX(IF...) columns to get them all.


text:
Q: Cookies disabled message with Vaadin running under Tomcat 8 and Apache with proxying I have a web application based on Vaadin and deployed it to my Tomcat 8 web app server. To access the application without port number etc. I installed an Apache web server and configured the VirtualHost to proxy it through. The problem now is, that I always get the following message, if I try to click on a Button etc. in the web application:
Cookies disabled
This application requires cookies to function.
Please enable cookies in your browser and click here or press ESC to try again.

All cookies are enabled and I'm using Chrome browser. Also the cookies from this webpage are retrieved and are valid.
If I access the web application the normal way with the port specification, I can click all content without errors.


text:
Q: getContent() not paging - only returns latest results Within an extension (JSON access), I'm calling getContent() with:
 $items = $this->app['storage']->getContent($contenttype, $options);

 $response = $this->app->json($items);
 return $response;

The options array is:
[
    'limit' => 5,
    'page'  => 3
]

But getContent only returns the latest 5 results, not calculating the offset from the page variable. Is there another setting that I have to change to get it to recognise the paging?

A: Calling getContent you need to specify that you want paging turned on, here's some adding 'paging'=>true to the options should work correctly.


text:
Q: How to design email and username login I have two question about usernames and emails
1. I judge username is a Email if '@' in username, and auth it follow:
email_user = User.objects.get(email__iexact=username)
authenticate(username=email_user.username)

Is that a good way that you recommended? or you may have a better advice?
  I know a AbstractBaseUser can do it, but I think use User is more reasonable.
2. Should I store the user's email within the User.email field?
Imagine if I sign up a new user with:
username: '123'
email: '456@google.com'

and when I signup success, then I find that my email is wrong,
and now another user that email is '456@google.com' can't signup again.
I just want to a email is verified that can associate with the user.
what's your advice?

A: If you want to use email as your unique sign in key, it would save you a lot of trouble in future development of your website if you make a custom User model using AbstractBaseUser. If you want i can post a sample working code
In reference to your second question - You can use Cryptographic signing in Django (https://docs.djangoproject.com/ja/1.9/topics/signing/) to produce a key. Further send this key as a link (eg www.example.com/verify/:some_crypto_key:) and send it as a link to user's email address. This key will contain user id and time stamp. If you receive a request on that link, it means that email is legit. You may find a package that does a similar task maybe.
EDIT:
Implementation (short way) - As the user signups on your website, Immediately ask him/her to verify account using the link you have sent to the given email. If you do not receive a response from that email within a given time (say 20 mins), delete that user entry. This means that you can not let the user access your website until he/she verifies the account.
Flaw - Consider a situation where the user has submitted a wrong email. It is obvious that the user will never be able to verify it but for those 20 mins if co-incidentally the actual user with that same email tries to signup on your website, he won't be able to access. This is very unlikely. Also this user will receive an email from your website saying that user has signed-up on a website (so here you can provide another link, 'if this was not you, please click here' kind of thing)

A: Unless you have a burning desire to write your own custom user model, which will let you replace the username field with the email, I would recommend using something like Django AllAuth.  It includes email verification (as outlined in your question), and can be set to use email as username fairly easily.  It's a well established library with lots of support, and will be more immediately usable than rolling your own.
(That said - rolling your own is an illuminating experience, and RA123's point is the answer you should accept if you're going down that road.)


text:
Q: std::this_thread::sleep_until timing is completely off by about a factor of 2, inexplicably Ok, I really have no idea why this is happening. I'm currently implementing a thread container which runs an infinite loop in a detached manner, limited to a certain speed between each iteration.
Header:
class timeloop
{
public:
    std::thread thread = { };
    bool state = true;

    void (*function_pointer)() = nullptr;

    double ratio = 1.0f;
    std::chrono::nanoseconds elapsed = { };

    timeloop(
        void (*function_pointer)() = nullptr
    );

    void function();
};

Definition:
void timeloop::start()
{
    this->thread = std::thread(
        &loop::function,
        this
    );
}

void timeloop::function()
{
    std::chrono::steady_clock::time_point next;

    std::chrono::steady_clock::time_point start;
    std::chrono::steady_clock::time_point end;

    while (
        this->state
        )
    {
        start = std::chrono::high_resolution_clock::now();
        next = start + std::chrono::nanoseconds(
            (long long) (this->ratio * (double) std::chrono::nanoseconds::period::den)
        );

        if (
            this->function_pointer != nullptr
            )
        {
            this->function_pointer();
        }

        /***************************
            this is the culprit
        ***************************/
        std::this_thread::sleep_until(
            next
        );

        end = std::chrono::high_resolution_clock::now();
        this->elapsed = std::chrono::duration_cast<std::chrono::nanoseconds>(
            end - start
            );
    }
}

Calling code:
timeloop* thread_draw = new timeloop(
    &some_void_function
);
thread_draw->ratio = 1.0 / 128.0;

thread_draw->start();
thread_draw->thread.detach();

The definition code is behaving weirdly, specifically std::this_thread::sleep_until. With this->ratio = 1.0 / 128.0 I'm expecting a framerate of around 128, the computed values of start and next reinforce this, yet it inexplicably hovers at around 60. And yeah, I tried just dividing next by 2, but that actually made it drop to around 40.
Extra code to verify the normal time to sleep for:
auto diff = std::chrono::nanoseconds(
    next - start
).count() / (double) std::chrono::nanoseconds::period::den;
auto equal = diff == this->ratio;

where equal evaluates to true.
Frame rate calculation:
double time = (double) thread_draw->elapsed.count() / (double) std::chrono::nanoseconds::period::den;
double fps = 1.0 / time;

Though I also used external FPS counters to verify (NVIDIA ShadowPlay and RivaTuner/MSI Afterburner), and they were in a range of about +-5 of the calculated value.
And I know it's std::this_thread::sleep_until because once I comment that out, the frame rate jumps up to around 2000. Yeah...
I'm truly baffled at this, especially seeing how I can't find any evidence of anybody else ever having had this problem. And yes, I'm aware that sleep functions aren't perfectly accurate, and there's bound to be hiccups every now and then, but consistently sleeping for pretty much double the scheduled time is just absurd.
Did I perhaps misconfigure a compiler option or something? It's definitely not a performance problem, and I'm reasonably sure it's not a logic error either (seeing how all the calculations check out) [unless I'm abusing chrono somewhere].

A: There are no guarantees on resolution of sleep_until, you are only guaranteed the thread will not be woken before the timepoint. If you are implementing the main game loop, read Fix your timestep.
Using sleep to guarantee timing is a terrible way to do it. You are at mercy of OS scheduler and e.g. Windows has a minimal sleep amount about 10 milliseconds I believe. (If the implementation actually asks the OS to put the thread to sleep and the OS decides to do a context switch.)
The lag might also be caused by VSync in the drawing thread if you are calling glfwSwapBuffers or similar. That would explain why your are limited to 60FPS, but not why commenting sleep solves the problem.
So my guess is the OS's sleep above. I would recommend to remove the sleep and rely on VSync, that's the right frequency you want to draw at anyway. Synchronization with logic threads will be a pain in... but that's always the case.

A: I think your problem is you are not using absolute timing because you keep resetting your absolute time point next relative to the current time now().
Try changing this:
while (
    this->state
    )
{
    start = std::chrono::high_resolution_clock::now();
    next = start + std::chrono::nanoseconds(
        (long long) (this->ratio * (double) std::chrono::nanoseconds::period::den)
    );
// ...

to this
// before the loop
next = std::chrono::high_resolution_clock::now();

while (
    this->state
    )
{
    // keep the timing absolute by adding to the absolute time point
    next = next + std::chrono::nanoseconds(
        (long long) (this->ratio * (double) std::chrono::nanoseconds::period::den)
    );

// ...

That way you call now() only once and then all your subsequent timings are absolutely (as opposed to relatively) calculated from that point.
Edited to add:
Additionally, I would avoid using std::chrono::high_resolution_clock. It is often just an alias of std::chrono::system_clock which is subject to random time alterations as the system clock attempts to remain synchronized with internet time.
Use std::chrono::steady_clock.


text:
Q: How to use ngx-advanced-searchbox in lazy loaded module? I have successfully implemented ngx-advanced-searchbox in main module.
But I am unable to use it inside lazy loaded module.
I am getting following error-
Error: Uncaught (in promise): Error: BrowserModule has already been loaded. If you need access to common directives such as NgIf and NgFor from a lazy loaded module, import CommonModule instead.
Error: BrowserModule has already been loaded. If you need access to common directives such as NgIf and NgFor from a lazy loaded module, import CommonModule instead.
    at new BrowserModule (platform-browser.js:3198)
    at _createClass (core.js:23172)
.
.
.

A: You can only use BrowserModule in one module in your application, usually only in app.module.ts. If you have mulitple modules, you have to import CommonModule in all other modules instead of BrowserModule.
EDIT
You can remove BrowserModule from your import in app.module, and rely on ngx-advanced-searchbox to import it for you.
Here is a similar question


text:
Q: Error Generic detail view must be called with either an object pk or a slug, even with the pk I'm trying to update records of a view which has a foreign key field, due to this I'm getting an error, since I tried to update another model without a foreign key field and it worked very well.
There are other quetions like this, but in my case I'm passing the pk.
urls.py
 urlpatterns = [
        url(r'^info/(?P<studentpk>\d+)/update/$', views.updatestudent.as_view(), name="updatestudent"),

]

views.py
class updatestudent(UpdateView):
    model = Student
    form_class = forms.studentform
    template_name = "temp/updatestudent.html"

    def get_success_url(self):
        return reverse("courses")

updatestudent.html
<form action="" method="post">{% csrf_token %}
    {{ form.as_p }}
    <input type="submit" value="Update" />
</form>

models.py
class Student(models.Model):
    classfk = models.ForeignKey(Class)
    name = models.CharField(max_length=100)
    birth_date = models.DateField('Birthdate')

    def __str__(self):
        return self.name

error
AttributeError: Generic detail view updatestudent must be called with either an object pk or a slug.

A: Django doesn't expect you to use studentpk in the URL pattern. The easiest fix is to use pk instead.
url(r'^info/(?P<pk>\d+)/update/$', views.updatestudent.as_view(), name="updatestudent"),

If you really want to use studentpk, then set pk_url_kwarg in the view.
class updatestudent(UpdateView):
    model = Student
    form_class = forms.studentform
    template_name = "temp/updatestudent.html"

    pk_url_kwarg = 'studentpk'

Note that in Python, the recommended style is to name your class based view UpdateStudent, and your form class StudentForm.


text:
Q: Sass, @media "767px is not a valid css value" I can't run the project, because of this error.

Declaration :
$max767 : only screen and (max-width: 767px);

here is the code that is causing the problem :
@media #{$max767} {
  .fc-left,
  .fc-right,
  .fc-center {
    display: flex;
    float: none;
    justify-content: center;
    margin-bottom: $module-rem;
  }
}

thanks in advance.

A: You should declare $max767 in string format $max767: "(max-width : 767px)"

A: Your syntax is just a little off. This works:
$max767: "only screen and (max-width: 767px)";
@media #{$max767} {
    /* css here */
}


text:
Q: Disable Button When EditText Is Empty Android Studio? I'm new, I don't have any experience. I saw some code to disable the login button. I tried to add it to the code. But I did not succeed. The application stops when the login button is pressed when the fields are empty.
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        binding = ActivityLoginBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        auth = FirebaseAuth.getInstance();

        dialog = new ProgressDialog(this);
        dialog.setMessage("Logging in...");

        if(auth.getCurrentUser() != null) {
            startActivity(new Intent(LoginActivity.this, MainActivity.class));
            finish();
        }

        binding.submitBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String email, pass;

                email = binding.emailBox.getText().toString();
                pass = binding.passwordBox.getText().toString();

                dialog.show();

                auth.signInWithEmailAndPassword(email, pass).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
                    @Override
                    public void onComplete(@NonNull Task<AuthResult> task) {
                        dialog.dismiss();

                        if(task.isSuccessful()) {
                            startActivity(new Intent(LoginActivity.this, MainActivity.class));
                            finish();
                        } else {
                            Toast.makeText(LoginActivity.this, task.getException().getLocalizedMessage(), Toast.LENGTH_SHORT).show();
                        }
                    }
                });
            }
        });

        binding.createNewBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(LoginActivity.this, SignupActivity.class));
            }
        });
    }
}

A: Instead of just checking for the empty fields, you should check for email pattern and for password, you should check if length > 6 otherwise Firebase Auth will throw an exception. Use below code for your submitBtn listener:
        binding.submitBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                String email = binding.emailBox.getText().toString();
                String pass = binding.passwordBox.getText().toString();

                if (email.isEmpty()) {
                    binding.emailBox.setError("Email is required");
                    binding.emailBox.requestFocus();
                    return;
                }

                if (!Patterns.EMAIL_ADDRESS.matcher(email).matches()) {
                    binding.emailBox.setError("Email is not valid");
                    binding.emailBox.requestFocus();
                    return;
                }

                if (pass.isEmpty()) {
                    binding.passwordBox.setError("Password is required");
                    binding.passwordBox.requestFocus();
                    return;
                }

                if (pass.length() < 6) {
                    binding.passwordBox.setError("Password is weak");
                    binding.passwordBox.requestFocus();
                    return;
                }

                dialog.show();

                auth.signInWithEmailAndPassword(email, pass).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
                    @Override
                    public void onComplete(@NonNull Task<AuthResult> task) {
                        dialog.dismiss();

                        if(task.isSuccessful()) {
                            startActivity(new Intent(LoginActivity.this, MainActivity.class));
                            finish();
                        } else {
                            Toast.makeText(LoginActivity.this, task.getException().getLocalizedMessage(), Toast.LENGTH_SHORT).show();
                        }
                    }
                });
            }
        });


text:
Q: Why is `let ref a: Trait = Struct` forbidden? We have a noncopyable type and a trait:
struct Struct;
trait Trait {}
impl Trait for Struct {}

If we create a &Struct and dereference it, we get an rvalue reference that we can use to initialize a by-ref binding:
let a: &Struct = &Struct;
let ref a: Struct = *a;

We can also directly initialize that by ref binding:
let ref a: Struct = Struct;

But if we declare our variable binding to require a reference, only the first code snippet works
let a: &Trait = &Struct;
let ref a: Trait = *a;

Attempting to do this directly
let ref a: Trait = Struct;

Or by going through loops
let a: &Struct = &Struct;
let ref a: Trait = *a;

Or
let ref a: Trait = *&Struct;

Will give us a mismatched types error. Obviously they aren't the same type, but inference works for references.
Is this simply not implemented (yet?) or is there a deeper reason it's disallowed?

A: There's a little bit of unsized subtlety going on here. The key difference between
let a: &Struct = &Struct;
let ref a: Struct = *a;

and
let a: &Trait = &Struct;
let ref a: Trait = *a;

Is that the expression *a produces a value whose size is not known at compile-time. This manifests as an error when we attempt to do:
let ref a: Trait = Struct as Trait;

<anon>:6:24: 6:39 error: cast to unsized type: `Struct` as `Trait`
<anon>:6     let ref a: Trait = Struct as Trait;
                                ^~~~~~~~~~~~~~~
<anon>:6:24: 6:30 help: consider using a box or reference as appropriate
<anon>:6     let ref a: Trait = Struct as Trait;

In general, the compiler can't know the size of a bare trait used as a type, like Trait is used here. This is because any type can implement Trait - so the size of trait can be any size, depending on the type that implements it. So, that explains why let ref a: Trait = Struct and let a: &Struct = &Struct; let ref a: Trait = *a don't work, because casting a Struct to a Trait is an unsized cast.
As for why your working trait code snippet works, looking at the MIR for these two examples, we can see that the compiler is treating the two above assignments slightly differently:
let a: &Struct = &Struct;
let ref a: Struct = *a;

bb0: {
    tmp1 = Struct;
    tmp0 = &tmp1;
    var0 = &(*tmp0);
    var1 = &(*var0);
    return = ();
    goto -> bb1;
}

let a: &Trait = &Struct;
let ref a: Trait = *a;

bb0: {
    tmp2 = Struct;
    tmp1 = &tmp2;
    tmp0 = &(*tmp1);
    var0 = tmp0 as &'static Trait + 'static (Unsize);
    var1 = &(*var0);
    return = ();
    goto -> bb1;
}

We see that the compiler has to do a cast to a trait object &'static Trait + 'static to satisfy the implicit coercion of &Struct to &Trait. From there, the ref pattern is simply var1 = &(*var0);, which in this case is a simple assignment from the trait object var0 to the trait object var1.
This is similar to the MIR generated by this function:
fn stuff() {
    let sized = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0];
    let slice : &[u8] = &sized;
    let ref other_slice = *slice;
}

bb0: {
    var0 = [const 1u8, ..., const 0u8];
    tmp2 = &var0;
    tmp1 = &(*tmp2);
    var1 = tmp1 as &'static [u8] (Unsize);
    var2 = &(*var1);
    return = ();
    goto -> bb1;
}

Since the type [u8] is unsized, it does a similar cast to a slice, which is quite similar in layout to a trait object. Ultimately, the compiler allows the code that doesn't introduce any unsized locals.


text:
Q: "as much as" vs. "as much as is"" In a textbook, I read this sentence:

Stretch your arms as much as is comfortable for you.

But can you say it without the is?

Stretch your arms as much as comfortable for you.

Is there any difference?

A: Yes, both are correct and grammatical. No, there is no difference, except that one is shorter, which is the principal reason for the variation.
The is is mandated by the grammar, leaving some clause structure behind while deleting the degree phrase in

*

*[You] stretch your arms
[to the maximum degree D, such that]
[your stretching your arms to degree D] is comfortable for you.
In the above, the [You] understood is deleted, the bracketed degree phrase becomes as much as, and the bracketed subject complement clause is simply deleted as repetition.
The is that gets left behind, however, is predictable and thus contributes no information; coming immediately after the phrase as much as (which is certainly enough to mark the construction), and resembling as, is often gets deleted.
That's all.
The more in a hurry one is, the less likely one is to dot all the syntactic i's and cross all the t's.

A: No doubt a sentence shouldn't be longer than clarity requires—but what does clarity require? If I encountered the sentence "Stretch arms as comfortable" in a series of instructions written in a clipped telegraphic or outline style, I would interpret it to mean "You should stretch your arms as much as is comfortable for you to do"; but getting from the short form to the long one would take me a little while, and it would involve some risk of misinterpretation.
Obviously, different word omissions have different effects on the flow of a sentence. Anyone accustomed to reading English sentences will recognize the imperative form of the opening words "Stretch your arms" and won't pause at all to supply the absent "You." Likewise, most English readers are so accustomed to completing truncated sentences of the type "Stretch your arms as much as is comfortable for you" that the absence of "to do" at the end of the sentence is no impediment to understanding; indeed, the words "for you" (which the sentence does include) are likewise expendable without any loss of pace.
To my ear, then, the original sentence remains completely and immediately coherent when expressed as "Stretch your arms as much as is comfortable." I read it, I understand it, and I haven't slowed down a bit.
The omission of "is" from the sentence, however, affects me differently: I pause for a couple of beats to identify and restore the missing word before I feel that I fully understand the sense of the sentence. Other readers may take the omission in stride, but I would be surprised to discover that I'm the only one who finds it distracting.
The time loss involved is quite brief, but it's not insignificant, especially if the author hopes to maintain rhythm and pacing across a longer piece of writing. Moreover, if the author tends to drop such arguably nonessential words as the "is" here regularly, easily distracted readers will have to pause more often, which cumulatively can render the prose unduly burdensome to read.
Ultimately, if "Stretch your arms as much as comfortable for you" takes a significant number of readers slightly longer to make sense of than "Stretch your arms as much as is comfortable for you" does—even though the sentence is one word shorter—what has the author gained by dropping the word? Nothing desirable, I think.


text:
Q: Missing getnonfreefonts-sys in MacTex 2015 I've just installed MacTeX 2015 and wanted to install the non-free fonts available with the getnonfreefonts Perl script. As recommended elsewhere in this site (see egreg's first comment), I tried calling getnonfreefonts-sys in order to install the fonts in TEXMFLOCAL, but I can't seem to find the script anywhere in my system. Am I missing a symlink or something to that end?

Update:
Of course, I have already installed getnonfreefonts with the Lua install script. But I am missing the -sys version.


text:
Q: react-native-document-picker: uri is undefined while used document picker react native How to fix it:I want to get absolute path but file uei is undefined when used document picker in react native.
import { StyleSheet, Text, View,Button } from 'react-native'
import React from 'react'
import DocumentPicker from 'react-native-document-picker'
import RNFetchBlob from 'rn-fetch-blob'
import Pdf from 'react-native-open-pdf';

const openPdfex = () => {

 const openFile = () => {

    const res =  DocumentPicker.pick({
          type: [DocumentPicker.types.allFiles],
        });

        console.log("absolute path =====> " ,res.uri);
  }

 return (
    <View>
      <Text>openPdf</Text>
      <Button title='Open PDF' onPress={openFile}></Button>
    </View>
  )
}

A: In the documentation, it states that DocumentPicker.pick() returns a promise and because you did not resolve the promise, you are not able to get back the uri from it.
  const openFile = async () => {
    try {
      const res = DocumentPicker.pick({
        type: [DocumentPicker.types.allFiles],
      });

      console.log('absolute path =====> ', res.uri);
    } catch (error) {
      console.log(error);
    }
  };

Try this and see if it works.

A: Try this one it works
const openFile = async () => {
try {
  const res = await DocumentPicker.pick({
    type: [DocumentPicker.types.allFiles],
  });
  console.log('absolute path =====> ', JSON.stringify(res[0]['uri']));
} catch (error) {
  console.log(error);
}}

A: Use DocumentPicker.pickSingle instead of DocumentPicker.pick


text:
Q: javascript: selectize selects the first item by default

    <link rel="stylesheet" href="css/selectize.css" />

        <select id='selecttest'>
            <option value='1'>One</option>
            <option value='2'>Two</option>
            <option value='3'>Three</option>
            <option value='4'>Four</option>
            <option value='5'>Five</option>
        </select>

The above displays one by default in select box, I don't want it display anything by default. How can I change this?

A: In seletize.js, you have one property called items:null. This will remove the default selected stuff. Also you can use the placeholder for your select field if you want to show anything on default.

    <select id='selecttest' placeholder="select test...">
        <option value='1'>One</option>
        <option value='2'>Two</option>
        <option value='3'>Three</option>
        <option value='4'>Four</option>
        <option value='5'>Five</option>
    </select>

$(function($){
    $('#selecttest').selectize({
        maxItems: 8,
        items: null
    });
 });

Fiddle Demo

A: Add an extra option with value "" in select tag. Something like
<option value="">Select</option>

Check the fiddle here


text:
Q: Background-size: 100% not working on iPhone I can't figure out why the background-size: 100% 100% is working in the Safari browser on my desktop and in all the iphone emulators online, but not on an actual iPhone.
The URL of the site is http://cherrycompanies.com
The CSS I'm using is
#header {
background: url(images/header.png) no-repeat top left;
background-size: 100% 100%;
-webkit-background-size: 100% 100%;
-moz-background-size: 100% 100%;
    -o-background-size: 100% 100%;
margin: auto;

A: And if you replace background-size: 100% 100% with background-size: contain ?


text:
Q: Radio Button Group in Material-UI I have this project built with react and bootstrap.
I wanted to change to material-ui and it worked well until changing the radio button.
Here is the old one i used (worked pretty well).
<label>
    <input type= {that.props.questionType} name={that.props.questionID} value={choice}/>
    {choice}
</label>

Here is the material-ui version.
<RadioButtonGroup >
    <RadioButton
        value={that.props.questionID}
        label={choice}
    />
</RadioButtonGroup>

Here is the map function I use to generate the radio buttons:
var iterator = (
  <RadioButtonGroup selectedValue={that.props.questionID}>
    {that.props.questionChoices.map(choice => <RadioButton value={choice} label={choice} /> )}
  </RadioButtonGroup>
);

A: When creating a RadioButtonGroup, you MUST assign name property (please refer the material-ui documentation).
Also when using a map function you should add a key property to each of the returned elements.
Following snippet has those issues addressed:
var iterator = (
  <RadioButtonGroup
    name="questionChoices"
    valueSelected={that.props.questionID}
    onChange={that.props.handleChange}
  >
    {that.props.questionChoices.map(choice => (
       <RadioButton value={choice} label={choice} key={choice}/>
    )}
  </RadioButtonGroup>
)