text:
Q: 3d convolution tensorflow float64 I'm working on some convolutional calculation on the Tensorflow and got some strange errors with the Double Precision numbers.
I needed to calculate those tensors in float64 because of the precision issues.
The conv3d works fine with me on float32, but on the Double precision, it's only works on CPU and for the GPU the error is saying
InvalidArgumentError (see above for traceback): Cannot assign a device for operation 'Conv3D': Could not satisfy explicit device specification '/device:GPU:0' because no supported kernel for GPU devices is available.
Registered kernels:
  device='CPU'; T in [DT_HALF]
  device='CPU'; T in [DT_FLOAT]
  device='CPU'; T in [DT_DOUBLE]
  device='GPU'; T in [DT_HALF]
  device='GPU'; T in [DT_FLOAT]

 [[Node: Conv3D = Conv3D[T=DT_DOUBLE, data_format="NDHWC", dilations=[1, 1, 1, 1, 1], padding="SAME", strides=[1, 1, 1, 1, 1], _device="/device:GPU:0"](Const, Const_1)]]

Below is my test code.
import tensorflow as tf
import numpy as np

with tf.device('/device:GPU:0'):

    a = tf.constant(2 * np.ones([1, 200, 200, 200, 9], dtype=np.float64), dtype=tf.float64)

    b = tf.constant(np.ones([3, 3, 3, 9, 9], dtype=np.float64), dtype=tf.float64)

    sess = tf.Session()

    init = tf.global_variables_initializer()

    sess.run(init)

    c = tf.nn.conv3d(a, b, strides=[1, 1, 1, 1, 1], padding='SAME')
    print(a)
    print(b)
    print(c)
    for i in range(1000):
        print(sess.run(c))

is there any way to use gpus for these ops?

A: Support for double precision on a GPU is hardware dependent.  A quick search for your make and model and "support for double precision" should get you an answer whether your GPU can support double precision math.
A quick search for my GPU (gtx 1060) and its support for double precision resulted in this link:
https://devtalk.nvidia.com/default/topic/995849/does-the-gtx1060-support-double-precision-/
For the gtx 1060, the throughput for double precision math is 1/32 that of single precision math.  So even if your GPU supports it, the performance many not match your expectations.


text:
Q: Django: how to order query set by OneToOneField's date? I have two classes:
class Foo(models.Model):
    date = models.DateTimeField(auto_now_add = True)
    ...

class Bar(models.Model):
    foo = models.OneToOneField(
        Foo,
        on_delete = models.CASCADE,
        primary_key = True
    )
    ...

How can I order Bar's objects like this:
query_set = Bar.objects.all().order_by('-foo.date')

A: You can access foreign key value by __
Something like this
query_set = Bar.objects.all().order_by('-foo__date')

redpajama_set_name: RedPajamaStackExchange


text:
Q: Verifying codecademy course completion Is there any way to verify that someone who claims they have completed a codecademy course has actually done so? I.e. if someone with the email name@example.com says that they have completed the PHP track on codecademy, is there a way this can be verified? I would imagine that there would be an API for this, something like http://api.codecademy.com/verifyCompletion?email=name@example.com&track=PHP and this would answer true of false depending on if that course has been completed by this person. But can't find any information related to this. Does anyone know?
Thanks!


text:
Q: 3d plot of young's modulus for anisotropic material can anyone can help me in plotting 3d plot of young's modulus for anisotropic material. For input i have 6*6 stiffness tensor matrix and hydrostatic pressure value.
I am trying with the following script, but its not helping.
The code is for cubic system for which system is symmetric. But in my case I have triclinic system, in which every element of tensor matrix is non zero. So how should i incorporate this thing for my system.
(*tensile direction*)
n = {Cos[phi]*Sin[theta], Sin[phi]*Sin[theta], Cos[theta]};
(*Basic tensors*)
I2 = IdentityMatrix@3;
IdI = TensorProduct[I2, I2];
I4 = TensorTranspose[IdI, {1, 3, 2, 4}];
IS = (I4 + TensorTranspose[I4, {1, 2, 4, 3}])/2;
(*Projectors of cubic materials*)
Pc1 = 1/3*IdI;
Dc = ConstantArray[0, {3, 3, 3, 3}];
Dc[[1, 1, 1, 1]] = 1;
Dc[[2, 2, 2, 2]] = 1;
Dc[[3, 3, 3, 3]] = 1;
Pc2 = Dc - Pc1;
Pc3 = IS - Pc1 - Pc2;
(*Spectral represention of cubic compliance*)
comp = 1/l1*Pc1 + 1/l2*Pc2 + 1/l3*Pc3;
l1 = 10;
l2 = 3;
l3 = 8;
(*Young's modulues*)
Y = (Total[comp*TensorProduct[n, n, n, n], Infinity])^(-1) //
Simplify;
(*Plot*)
SphericalPlot3D[Y, {theta, 0, Pi}, {phi, 0, 2 Pi}]


text:
Q: Creating divs that have a width of the top div in a foreach so I have a goal but I have no idea if it's possible or not:
Here's an image of what i got: https://screencast.com/t/88ImEmMif
And code:

                    <?php
                    $links = array("https://google.com","foo", "bar", "hello", "world","google.com","google.com/adwords/","foo", "bar", "hello", "world","https://google.com/gmail","https://google.com/adwords/");
                    foreach($links as $link) {

                        echo '
'.$link.'
';

                    }
                    ?>

And here is what I'm looking to do: https://screencast.com/t/ze5fCya3wpbJ
So each of the boxes will have the same width in col's depending on the length in the box.

A: You could give a try to flex setting a fixed height:
example using lorem ipsum text. (your pHp is not the HTML output)

div {/* your .parent */
  display: flex;
  height: 4em;/* makes about 2 lines before wrapping to next */
  flex-direction: column;
  flex-wrap: wrap;
  width: 500px;
  margin: auto;
}

b {/* your .child */
  border: solid 1px turquoise;
  margin: 2px;
  padding:2px;
}

  lorem
  Pellentesque
  habitant
  morbi
  tristique
  senectus
  et
  netus
  et
  malesuada
  fames
  ac
  turpis
  egestas.

A: An alternative would be using FlexBox on the outer div, applying the styles flex-wrap: wrap; and justify-content: space-between; to make them evenly spaced and distributed inside the outer div. Thanks to FlexBox each of the inner contents will have their own width.

.box {
  width: 600px;
  margin:0 auto;
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
}

p {
  margin: 0 0 5px;
  padding: 3px 5px;
  border: 1px solid black;
}

Bulbasaur

Ivysaur

Venusaur

Charmander

Charmeleon

Ash

Charizard

Squirtle

Wartortle

Blastoise

Ekans

Pikachu

Paras

Abra


text:
Q: Python virtualenv requirements.txt by default includes wheel I just re-installed python & virtualenv after accidentally getting everything messy. I noticed that my requirements.txt in my newly created environment automatically includes wheel==0.24.0. Is this normal, and what is it? I understand that virtualenv should create new environments without any system-installed packages.

A: I came across this issue when setting up virtualenv in windows.
To avoid wheel from being installed you can use the --no-wheel option.
virtualenv venv --no-wheel
To my understanding wheel is used handle a compressed format of a python package (.whl) that can be used by pip to speed up the install time. https://wheel.readthedocs.org/en/latest/

A: Probably one of the itens listed in your requirements.txt needs wheel package installed to work.
Although it's a common (and good) pratice list the fundamental python packages of a project inside requirements.txt, not all of the packages the eventually will be installed are there.
Your pip log may helps you to point what package required wheel to be installed.


text:
Q: Is there any way to filter objects using _pickBy() for float numbers I am trying to filter one Object and filtering to display only the version greater than 9.8 by using _pickBy lodash method. But it is not working as expected. My code is below,
let test_obj= {
 "version-1":{
      "path":"abcd",
      "version":"9.1"
   },
   "version-2":{
      "path":"efgh",
      "version":"9.9.1"
   },
   "version-3":{
      "path":"bbbbbb",
      "version":"9.10.0"
   },
   "version-4":{
      "path":"cccccc",
      "version":"9.9.0"
   },
   "version-5":{
      "path":"kkkkkkk",
      "version":"9.8"
   }
}

let output = _.pickBy(test_obj, (v,k) => v.version === "" || parseFloat(v.version) >= parseFloat(9.8));

The output for the above code is,
{
       "version-2":{
          "path":"efgh",
          "version":"9.9.1"
       },
       "version-4":{
          "path":"cccccc",
          "version":"9.9.0"
       },
       "version-5":{
          "path":"kkkkkkk",
          "version":"9.8"
       }
    }

JS Fiddle : https://jsfiddle.net/ufzh7631/
It should add "version-3" as well, because it is greater than 9.8. But it is omitting 9.10.0.
Is there any way to achieve this. Any help will be most appreciated.

A: You could use localeCompare with numeric: true in the options parameter
v.version.localeCompare("9.8", undefined, { 'numeric': true }) >= 0

This works even when there are more than 1 decimal points in the version like 9.8.1

let test_obj = {
  "version-1": {
    "path": "abcd",
    "version": "9.1"
  },
  "version-2": {
    "path": "efgh",
    "version": "9.9.1"
  },
  "version-3": {
    "path": "bbbbbb",
    "version": "9.10.0"
  },
  "version-4": {
    "path": "cccccc",
    "version": "9.9.0"
  },
  "version-5": {
    "path": "kkkkkkk",
    "version": "9.8"
  }
}

let output = _.pickBy(
  test_obj,
  v => v.version === "" || v.version.localeCompare("9.8", undefined, { 'numeric': true }) >= 0);

console.log(output)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.20/lodash.min.js" integrity="sha512-90vH1Z83AJY9DmlWa8WkjkV79yfS2n2Oxhsi2dZbIv0nC4E6m5AbH8Nh156kkM7JePmqD6tcZsfad1ueoaovww==" crossorigin="anonymous"></script>


text:
Q: Prove whether $(5, X^2 + 3) \subseteq \mathbb{Z}[X]$ is a maximum/prime ideal. Prove whether $(5, X^2 + 3) \subseteq \mathbb{Z}[X]$ is a maximum/prime ideal.
My attempt:
I have a hunch that it is prime
I will try to use the following theorem
$$
I \subseteq R \text{ is an ideal} \iff R/I \text{ is a domain}
$$
with $R$ being commutative. From the third the third isomorphism theorem we can conclude that
\begin{align*}
\mathbb{Z}[X]/(5,X^2 + 3) &\cong \frac{\mathbb{Z}[X]/(X^2 + 3)}{(5,X^2 + 3)/(X^2 + 3)} \\
&\cong \frac{\mathbb{Z}[X]/(X^2 + 3)}{(5)}.
\end{align*}
From here I would like to prove that $\mathbb{Z}[X]/(X^2 + 3) \cong \mathbb{Z}[i\sqrt{3}]$. Define $z = i\sqrt{3}$. The evaluation homomorphism is now given by
$$
\Phi_z: \mathbb{Z}[X] \to \mathbb{Z}[i\sqrt{3}], f \mapsto f(z)
$$
It is clear that $\Phi_z$ is surjective, because $f(aX + b) = ai\sqrt{3} + b$ for arbitrary $a,b \in \mathbb{Z}$. From here I would like to prove that $\text{Ker}(\Phi_z) = (X^2 + 3)$. It is clear that $\text{Ker}(\Phi_z) \supseteq (X^2 + 3)$ because $\Phi_z(X^2 + 3) = (-3 + 3) = 0$.
Now take $f \in \text{Ker}(\Phi_z)$. We will devide with remainders with X^2 + 3. We see that $f = q(X^2 + 3) + r$ with $q,r \in \mathbb{Z}[X]$ and $r = aX + b$ or $r = 0$. If $r=0$, then we're finished. If $r = aX + b$ we see
\begin{align*}
0 =\Phi_z(f) &= \Phi_z(q)\Phi_z(X^2 + 3) + \Phi_z(r) \\
&= \Phi_z(r) \\
&= ai\sqrt{3} + b.
\end{align*}
Since $a,b \in \mathbb{Z}$, we must have $a = b = 0$. So $f \in (X^2 + 3)$. Now use the first isomorphism theorem
$$
\mathbb{Z}[X]/(X^2 + 3) \cong \mathbb{Z}[i\sqrt{3}].
$$
The only thing left to do is, proving whether $\mathbb{Z}[i\sqrt{3}]/(5)$ is a domain. From here I have no clue how to pick things up. Any hints/tips?

A: It's probably easier to do it the other way $$\mathbb Z[x]/(x^2+3,5)\simeq \mathbb Z_5[x]/(x^2+3) $$
where $\mathbb Z_5$ is the integers modulo $5$. Since $x^2+3$ is irreducible over $\mathbb Z_5[x]$ (just check that it has no roots), $(x^2+3)$ is a prime ideal and in fact, maximal ideal in $\mathbb Z_5[x]$ since it is a principal ideal domain. Therefore $\mathbb Z_5[x]/(x^2+3) $ is a field and therefore $(x^2+3,5)$ is a maximal ideal in $\mathbb Z[x]$ (and so prime as well).


text:
Q: How do I return the index of value using a for loop and else statement? // This function returns the index of value, or -1 if not found
Function Integer findValue(Integer nums[], Integer size, Integer value)
Declare Integer index

For index = 0 To size − 1
   If nums[index] == value Then
      Return index
    Else
Return -1
   End If
End For
End Function

A: In Python, there is already a built-in function for lists to get the index list.index. It returns the index of the element passed if found in list


text:
Q: heroku django import error no module named _collections It's worth noting that I'm using a custom buildpack to enable coffeescript compilation with node.js.
After a change that included a migration, I got the below error upon running the migration
Running `./manage.py migrate talent` attached to terminal... up, run.3366
Traceback (most recent call last):
  File "./manage.py", line 8, in <module>
    from django.core.management import execute_from_command_line
  File "/app/lib/python2.7/site-packages/django/core/management/__init__.py", line 1, in <module>
    import collections
  File "/usr/local/lib/python2.7/collections.py", line 8, in <module>
    from _collections import deque, defaultdict
ImportError: No module named _collections

After poking around a bit in a heroku run bash shell session I found that the same error could be triggered by opening a python repl and running import collections.

A: Further poking revealed that the error could be suppressed by adding /usr/local/lib/python2.7/:/usr/local/lib/python2.7/lib-dynload/ to $PYTHONPATH. I first tried to to this in the bin/release file of the buildpack, but I also had a PYTHONPATH config variable which apparently overrides the buildpack setting of the environment (as it probably should).
Anyway fixing the $PYTHONPATH made everything work again, but this feels awkward, like a symptom that something else has gone wrong. Hopefully someone with more Heroku knowledge than me can shed some light.


text:
Q: Regex in ANTLR4 I want to generate strings like these:
tablename(attr1, attr2)
tablename(attr1, attr2, attr3)
tablename(attr1, attr2, attr3, attr4)

The problem is that with the wildcards operators (*,?,+) I cannot control the cardinality I want, because I need at least two.
So, strings like this one are not accepted:
tablename(attr1)
tablename()

Moreover, I want to reproduce also the commas but not for the last attribute.
Is there a way to do it ANTLR4?

A: Formulate the possible variantions explicitly. For instance:
table: id OPEN_PAR attribute CLOSE_PAR
       | id OPEN_PAR attribute COMMA attribute CLOSE_PAR
       | id OPEN_PAR attribute COMMA attribute COMMA attribute CLOSE_PAR
       | id OPEN_PAR attribute COMMA attribute COMMA attribute COMMA attribute CLOSE_PAR
       ... etc.
;


text:
Q: Calling overridden method in super module in Ruby In the following code, Parent#just_do overrides GrandParent#just_do. In the Me class, how do I call GrandParent#just_do?
module GrandParent
  def just_do
    puts "GrandParent"
  end
end

module Parent
  def self.included(base)
    base.extend ClassMethods
  end

  module ClassMethods
    include GrandParent

    def just_do
      puts "Parent"
    end
  end
end

class Me
  include Parent

  def self.just_do
    super # this calls Parent#just_do
  end
end

A: You could work with the method object directly.
class Me
  include Parent

  def self.just_do
    method(:just_do).super_method.super_method.call
  end
end

A: You can't really un-override something. In this particular case you could re-import it, but that could have other side-effects.
It's probably best for the "Parent" to preserve the original because it may need to be called:
module GrandParent
  def just_do
    puts "GrandParent"
  end
end

module Parent
  def self.included(base)
    base.extend ClassMethods
  end

  module ClassMethods
    include GrandParent

    # Creates an alias to the original method
    alias_method :grandpa_just_do, :just_do
    def just_do
      puts "Parent"
    end
  end
end

class Me
  include Parent

  def self.just_do
    # Call using the alias created previously
    grandpa_just_do
  end
end

Me.just_do


text:
Q: Получить файл из сообщения Как проверить наличие и получить файл из обновления? Пишу на джаве лонг поллинг бота. Библиотека rubenlagus/TelegramBots. Заранее спасибо.

A: Нашел решение в чате разработчика библиотеки
Получение файла
 GetFile getFileRequest = new GetFile();

getFileRequest.setFileId(update.getMessage().getDocument().getFileId());

 org.telegram.telegrambots.api.objects.File telegramFile =
bot.execute(getFileRequest);

File testFile = bot.downloadFile(telegramFile);

Проверка на наличие файла
if (update.hasMessage() && update.getMessage().hasDocument())


text:
Q: Toggling the menu icon I am trying to trigger the menu icon off when clicked, and trigger on an 'x' icon. Likewise, I need the reverse of this to happen. Trigger the 'x' icon off when clicked, and the menu icon back on.
When nav-button-menuOpen is clicked, the three divs inside go from opacity: 1; to opacity: 0; and the button fades away like it's supposed to. Then the span inside nav-button-menuClose is supposed to go from opacity: 0; to opacity: 1;. I can see the class being added in the browser, but the animation on the span doesn't change the opacity property.

const mobileMenuOpenAndClose = () => {
    const menuOpenButton = document.querySelector('.nav-button-menuOpen');
    const menuCloseButton= document.querySelector('.nav-button-menuClose');
    const navMobileMenu = document.querySelector('.nav-mobileMenu');
    const navMobileMenuLinks = document.querySelectorAll('.nav-mobileMenu-links');

    menuOpenButton.addEventListener('click', () => {
      console.log('menuButtonOpen clicked');
      menuOpenButton.classList.toggle('nav-button-toggle');
      menuCloseButton.classList.toggle('nav-button-toggle');
    });

    menuCloseButton.addEventListener('click', () => {
      console.log('menuButtonClose clicked')
      menuCloseButton.classList.toggle('nav-button-toggle');
      menuOpenButton.classList.toggle('nav-button-toggle');
    });
};

mobileMenuOpenAndClose();
/* Hamburger Menu */
nav .nav-button-menuOpen {
  justify-self: end;
  cursor: pointer;
  display: inline-block;
  opacity: 1;
}
nav .nav-button-menuOpen div {
  width: 30px;
  height: 30px;
  height: 3px;
  margin: 5px 0;
  background-color: var(--color-black);
  transition: all;
}
nav .nav-button-menuClose {
  justify-self: end;
  cursor: pointer;
  display: inline-block;
  opacity: 0;
}
nav .nav-button-menuClose span {
  color: var(--color-black);
  font-size: 1rem;
  transition: all;
}
nav .nav-button-toggle .menuOpen-line  {
  opacity: 0;
}
nav .nav-button-toggle .nav-button-menuClose {
    opacity: 1;
}

  x

A: This is because you are adding nav-button-toggle class to the .nav-button-menuClose element, but in your css selector you trying apply opacity if this element's parent has nav-button-toggle class:
nav .nav-button-toggle .nav-button-menuClose {
(basically you have an extra space between classes in this selector)

const mobileMenuOpenAndClose = () => {
    const menuOpenButton = document.querySelector('.nav-button-menuOpen');
    const menuCloseButton= document.querySelector('.nav-button-menuClose');
    const navMobileMenu = document.querySelector('.nav-mobileMenu');
    const navMobileMenuLinks = document.querySelectorAll('.nav-mobileMenu-links');

    menuOpenButton.addEventListener('click', () => {
      console.log('menuButtonOpen clicked');
      menuOpenButton.classList.toggle('nav-button-toggle');
      menuCloseButton.classList.toggle('nav-button-toggle');
    });

    menuCloseButton.addEventListener('click', () => {
      console.log('menuButtonClose clicked')
      menuCloseButton.classList.toggle('nav-button-toggle');
      menuOpenButton.classList.toggle('nav-button-toggle');
    });
};

mobileMenuOpenAndClose();
/* Hamburger Menu */
nav .nav-button-menuOpen {
  justify-self: end;
  cursor: pointer;
  display: inline-block;
  opacity: 1;
}
nav .nav-button-menuOpen div {
  width: 30px;
  height: 30px;
  height: 3px;
  margin: 5px 0;
  background-color: var(--color-black);
  transition: all;
}
nav .nav-button-menuClose {
  justify-self: end;
  cursor: pointer;
  display: inline-block;
  opacity: 0;
}
nav .nav-button-menuClose span {
  color: var(--color-black);
  font-size: 1rem;
  transition: all;
}
nav .nav-button-toggle .menuOpen-line  {
  opacity: 0;
}
nav .nav-button-toggle.nav-button-menuClose {
  opacity: 1;
}

menu1

menu2

menu3

  x

As of animation, since you are only changing opacity, there nothing else to animate as there are no other changes applied to the style between the states.

A: Writing the css with the space in the middle like this: .nav-button-toggle .nav-button-menuClose applys the style to the elements children. Write .nav-button-toggle.nav-button-menuClose without the space in the middle to apply it to itself.

const mobileMenuOpenAndClose = () => {
    const menuOpenButton = document.querySelector('.nav-button-menuOpen');
    const menuCloseButton= document.querySelector('.nav-button-menuClose');
    const navMobileMenu = document.querySelector('.nav-mobileMenu');
    const navMobileMenuLinks = document.querySelectorAll('.nav-mobileMenu-links');

    menuOpenButton.addEventListener('click', () => {
      console.log('menuButtonOpen clicked');
      menuOpenButton.classList.toggle('nav-button-toggle');
      menuCloseButton.classList.toggle('nav-button-toggle');
    });

    menuCloseButton.addEventListener('click', () => {
      console.log('menuButtonClose clicked')
      menuCloseButton.classList.toggle('nav-button-toggle');
      menuOpenButton.classList.toggle('nav-button-toggle');
    });
};

mobileMenuOpenAndClose();
/* Hamburger Menu */
nav .nav-button-menuOpen {
  justify-self: end;
  cursor: pointer;
  display: inline-block;
  opacity: 1;
}
nav .nav-button-menuOpen div {
  width: 30px;
  height: 30px;
  height: 3px;
  margin: 5px 0;
  background-color: black;
  transition: all;
}
nav .nav-button-menuClose {
  justify-self: end;
  cursor: pointer;
  display: inline-block;
  opacity: 0;
}
nav .nav-button-menuClose span {
  color: black;
  font-size: 1rem;
  transition: all;
}
nav .nav-button-toggle .menuOpen-line  {
  opacity: 0;
}
nav .nav-button-toggle.nav-button-menuClose {
    opacity: 1;
}

  x

For the animation part I would recommand you to use the CSS @keyframes Rule (https://www.w3schools.com/cssref/css3_pr_animation-keyframes.asp) instead of transiton. This way you can easily apply a hide class with display: none; to the hidden elements, and if you remove the class, the animation gets triggered.

const mobileMenuOpenAndClose = () => {
    const menuOpenButton = document.querySelector('.nav-button-menuOpen');
    const menuCloseButton= document.querySelector('.nav-button-menuClose');
    const navMobileMenu = document.querySelector('.nav-mobileMenu');
    const navMobileMenuLinks = document.querySelectorAll('.nav-mobileMenu-links');

    menuOpenButton.addEventListener('click', () => {
      console.log('menuButtonOpen clicked');
      menuOpenButton.classList.toggle('hidden');
      menuCloseButton.classList.toggle('hidden');
    });

    menuCloseButton.addEventListener('click', () => {
      console.log('menuButtonClose clicked')
      menuCloseButton.classList.toggle('hidden');
      menuOpenButton.classList.toggle('hidden');
    });
};

mobileMenuOpenAndClose();
/* Hamburger Menu */
.nav-button-menuOpen {
  cursor: pointer;
  display: inline-block;
  animation: fadeIn 0.2s;
}
.nav-button-menuOpen div {
  width: 30px;
  height: 30px;
  height: 3px;
  margin: 5px 0;
  background-color: black;
}
.nav-button-menuClose {
  cursor: pointer;
  display: inline-block;
  animation: fadeIn 0.2s;
  width: 30px;
  height: 30px;
  display: flex;
  align-items: center;
  justify-content: center;
}

@keyframes fadeIn {
  from { opacity: 0 }
  to { opacity: 100 }
}

.nav-button-menuClose span {
  color: black;
  font-size: 2rem;
}

.hidden {
  display: none
}

  x

A: You can achieve with single .nav-menu-toggle element to open and close menu with single click event of JavaScript.

document.querySelector('.nav-menu-toggle').addEventListener('click', (t) => {
    t.target.classList.toggle('active');
});
/* Hamburger Menu */
:root{
    --color-black : #000
}
nav{
    background-color: #f2f2f2;
    padding: 20px;
}
nav .nav-menu-toggle {
    width: 30px;
    height: 30px;
    display: block;
    cursor: pointer;
    overflow: hidden;
}
nav .nav-menu-toggle div{
    width: 100%;
    height: 3px;
    margin-bottom: 10px;
    background-color: #000;
    transition: 0.5s transform cubic-bezier(0.075, 0.82, 0.165, 1);
    pointer-events: none;
}
nav .nav-menu-toggle.active div{
    background-color: #ff0000;
}
nav .nav-menu-toggle.active div:nth-child(1){
    transform: rotate(-45deg);
    transform-origin: 110% 9px;
}
nav .nav-menu-toggle.active div:nth-child(2){
    transform: scale(0);
}
nav .nav-menu-toggle.active div:nth-child(3){
    transform: rotate(45deg);
    transform-origin: 95% -4.5px;
}


text:
Q: How to solve unknown expected error in iphone app I am assigning a value to var with calculations but it shows syntax error i have seen all the brackets still it gives error here is my code .

appDelegate.Same_Vaccination_Cost_Treatment_Annually_With_Guarantee=((appDelegate.Same_Vaccination_Cost_Treatment_Annually_No_Guarantee
  - 5000) / appDelegate.Same_Vaccination_Cost_Treatment_Annually_No_Guarantee) *
  ((appDelegate.Cost_Treatment_SevereEI *
  appDelegate.Same_Vaccination_SevereEI_Annually) +
  (appDelegate.Cost_Treatment_ModerateEI *
  appDelegate.Same_Vaccination_ModerateEI_Annually) +
  (appDelegate.Cost_Treatment_MildEI *
  appDelegate.Same_Vaccination_MildEI_Annually)))) *
  appDelegate.Same_Vaccination_Horses_Per_Premise;

A: As per Your code:-
    float Same_Vaccination_Cost_Treatment_Annually_With_Guarantee;
    float Cost_Treatment_SevereEI;
    float Same_Vaccination_SevereEI_Annually;
    float Cost_Treatment_MildEI;
    float Same_Vaccination_MildEI_Annually;
    float Same_Vaccination_Horses_Per_Premise;
    float Same_Vaccination_Cost_Treatment_Annually_No_Guarantee;
    float Cost_Treatment_ModerateEI;
    float Same_Vaccination_ModerateEI_Annually;

Same_Vaccination_Cost_Treatment_Annually_With_Guarantee=(((Same_Vaccination_Cost_Treatment_Annually_No_Guarantee - 5000) / Same_Vaccination_Cost_Treatment_Annually_No_Guarantee) * (((Cost_Treatment_SevereEI * Same_Vaccination_SevereEI_Annually) + (Cost_Treatment_ModerateEI * Same_Vaccination_ModerateEI_Annually) + (Cost_Treatment_MildEI * Same_Vaccination_MildEI_Annually)) * Same_Vaccination_Horses_Per_Premise));

and you can also put Method like:-
Same_Vaccination_Cost_Treatment_Annually_With_Guarantee=((Same_Vaccination_Cost_Treatment_Annually_No_Guarantee - 5000) / Same_Vaccination_Cost_Treatment_Annually_No_Guarantee) * ((Cost_Treatment_SevereEI * Same_Vaccination_SevereEI_Annually) + (Cost_Treatment_ModerateEI * Same_Vaccination_ModerateEI_Annually) + (Cost_Treatment_MildEI * Same_Vaccination_MildEI_Annually)) * Same_Vaccination_Horses_Per_Premise;

A: If you are using exactly same
    appDelegate.Same_Vaccination_Cost_Treatment_Annually_With_Guarantee=((appDelegate.Same_Vaccination_Cost_Treatment_Annually_No_Guarantee - 5000) / appDelegate.Same_Vaccination_Cost_Treatment_Annually_No_Guarantee) * ((appDelegate.Cost_Treatment_SevereEI * appDelegate.Same_Vaccination_SevereEI_Annually) + (appDelegate.Cost_Treatment_ModerateEI * appDelegate.Same_Vaccination_ModerateEI_Annually) + (appDelegate.Cost_Treatment_MildEI * appDelegate.Same_Vaccination_MildEI_Annually)))) * appDelegate.Same_Vaccination_Horses_Per_Premise;

then you have 2 braces extra
try
    appDelegate.Same_Vaccination_Cost_Treatment_Annually_With_Guarantee=((appDelegate.Same_Vaccination_Cost_Treatment_Annually_No_Guarantee - 5000) / appDelegate.Same_Vaccination_Cost_Treatment_Annually_No_Guarantee) * ((appDelegate.Cost_Treatment_SevereEI * appDelegate.Same_Vaccination_SevereEI_Annually) + (appDelegate.Cost_Treatment_ModerateEI * appDelegate.Same_Vaccination_ModerateEI_Annually) + (appDelegate.Cost_Treatment_MildEI * appDelegate.Same_Vaccination_MildEI_Annually)) * appDelegate.Same_Vaccination_Horses_Per_Premise;

A: appDelegate.Same_Vaccination_Cost_Treatment_Annually_With_Guarantee=((appDelegate.Same_Vaccination_Cost_Treatment_Annually_No_Guarantee - 5000) / appDelegate.Same_Vaccination_Cost_Treatment_Annually_No_Guarantee) * ((appDelegate.Cost_Treatment_SevereEI * appDelegate.Same_Vaccination_SevereEI_Annually) + (appDelegate.Cost_Treatment_ModerateEI * appDelegate.Same_Vaccination_ModerateEI_Annually) + (appDelegate.Cost_Treatment_MildEI * appDelegate.Same_Vaccination_MildEI_Annually)) * appDelegate.Same_Vaccination_Horses_Per_Premise;
This will work. You were using too many brackets.


text:
Q: Get total hours, minutes with relativdelta How with relativdelta get total played time for Ronaldo and Messi?
Eg.
ronaldo = relativedelta(years=0, months=0, days=0, hours=0, minutes=92)
messi = relativedelta(years=0, months=0, days=0, hours=0, minutes=91)

total = 3 hours 05 minutes

A: You can simply add them together:
>>> from dateutil.relativedelta import *
>>>
>>> r1 = relativedelta(minutes=91)
>>> r2 = relativedelta(minutes=92)
>>> r1 + r2
relativedelta(hours=+3, minutes=+3)


text:
Q: AWS:::sam local invoke "HelloWorldFunction" I have successfully executed sam init and sam build. and my folder structure is:
enter image description here
While issuing sam local invoke "HelloWorldFunction" I am getting below error:::handle = win32file.CreateFile(
pywintypes.error: (2, 'CreateFile', 'The system cannot find the file specified.')
Any solution please?

A: Typically this means Docker isn't running. Check that Docker is working.


text:
Q: Passing map type argument in function in Erlang complains error Here's my code snippet.
%% test.erl
-export([count_characters/1]).

count_characters(Str) ->
  count_characters(Str, #{}).

count_characters([H|T], #{H := N} = X) ->
  count_characters(T, X#{H := N+1});
count_characters([H|T], X) ->
  count_characters(T, X#{H => 1});
count_characters([], X) ->
  X.

%% ErShell
1> c(test).
test.erl:19: illegal use of variable 'H' in map
test.erl:20: illegal use of variable 'H' in map
test.erl:20: variable 'N' is unbound
test.erl:22: illegal use of variable 'H' in map
error

I just don't know why it complains such error, since the following code just worked out fine:
%% test2.erl
birthday(#{age := N} = Person) ->
    Person#{age := N+1}.

%% ErShell
1> c(test2).
2> test2:birthday(#{age => 333}).
#{age => 334}

Thanks in advance.

A: The reason is simple: map hasn't been fully implemented yet. Take a look at: http://learnyousomeerlang.com/maps
Also, you might think of alternative implementations, using the stuff that's already possible with maps:
count_characters(Str) -> count_characters(Str, #{}).

count_characters([H|T], Map) ->
    N = maps:get(H, Map, 0),
    count_characters(T, maps:put(H, N + 1, Map));
count_characters([], Map) -> Map.

A: As of today (2021), the feature is still not implemented.
However, for larger keys it is recommended to use the update function for reasons of efficiency:
count_characters([H|T], Map) ->
    case N = maps:get(H, Map, 0) of
       0 -> count_chars(T, Map#{H => 1});
       _ -> count_chars(T, Map#{H := N+1}) % update function maps:udpate(...)
    end;


text:
Q: Does `git submodule update` actually mean `git restore submodule to last commited state`? I have read some of the better question and answers regarding git submodule update. I am still a little confused about an aspect and want to clarify.
The term "update" in git submodule update triggered me to the assumption that, since a subumodule being another project/repo which might evolve, that an we are talking about importing those changes into the local copy of the submodule.
Can an answer to this question please clarify that if instead the action caused by calling git submodule update is not the action before, but instead would mean git submodule restore_submodule_to_commit_state_of_which_was_commited_in_the_superproject?


text:
Q: Which DropBox installer do I have to download for use on Lubuntu? Which one should I use - Ubuntu or Debian?
The Debian one I guess since Lubuntu doesn't use nautilus. Not sure though.

A: You should use the one for Ubuntu, since Lubuntu actually is Ubuntu, only with a different set of default applications.


text:
Q: Trying to delay in python I try to add a delay in my code (Im using python v 2.7.2), like this:
import time
time.sleep(2)
print "Hi"

But this error pops up:
Internal error: ReferenceError: _select is not defined

Please help, this would really make my code much cooler :)

A: This error is a result of you running your code in CodeAcademy Labs. It appears from some research this error happens when you are compiling on a different system than the actual interpreter is run on, for some reason.
If you can, run your program on a Python install on your actual system instead of one online and it should work as it did for me.


text:
Q: Python: delete all variables except one for loops without contaminations %reset
%reset -f

and
%reset_selective a
%reset_selective -f a

are usefull Python alternative to the Matlab command "clear all", in which "-f" means "force without asking for confirmation" and "_selective" could be used in conjunction with
who_ls

to selectively delete variables in workspace as clearly shown here https://ipython.org/ipython-doc/3/interactive/magics.html .
Now I am managing loops in which I am going to define a large number of variables, for example
for j in range(1000):
    a = crazy_function1()
    b = crazy_function2()
    ...
    m = crazy_function18()
    n = crazy_function19()
    ...
    z = crazy_functionN()

and at the end of each cycle I want to delete ALL variables EXCEPT the standard variables of the Python workspace and some of the variables I introduced (in this example only m and n). This would avoid contaminations and memory burdening hence it will make the code more efficient and safe.
I saw that "who_ls" result looks like a list, hence I thought at a loop that delete all variables that are not equal to m or n
for j in range(1000):
    a = crazy_function1()
    b = crazy_function2()
    ...
    m = crazy_function18()
    n = crazy_function19()
    ...
    z = crazy_functionN()
    if who_ls[j] != m or who_ls[j] != n:
         %reset_selective -f who_ls[j]

but it doesn't work as who_ls looks as a list but it doesn't work as a list. How would you modify the last lines of code?
Is there anything like
 %reset_selective -f, except variables(m, n)

?

A: The normal approach to limiting the scope of variables is to use them in a function.  When the function is done, its locals disappear.
In [71]: def foo():
    ...:     a=1
    ...:     b=2
    ...:     c=[1,2,3]
    ...:     d=np.arange(12)
    ...:     print(locals())
    ...:     del(a,b,c)
    ...:     print(locals())
    ...:
In [72]: foo()
{'d': array([ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11]), 'c': [1, 2, 3], 'a': 1, 'b': 2}
{'d': array([ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11])}

==================
%who_ls returns a list, and can be used on the RHS, as in
xx = %who_ls

and then that list can be iterated.  But note that this is a list of variable names, not the variables themselves.
for x in xx:
    if len(x)==1:
        print(x)
        # del(x)  does not work

shows all names of length 1.
======================
A simple way to use %reset_selective is to give the temporary variables a distinctive name, such as a prefix that regex can easily find.  For example
In [198]: temp_a, temp_b, temp_c, x, y = 1,'one string',np.arange(10), 10, [1,23]
In [199]: who_ls
Out[199]: ['np', 'temp_a', 'temp_b', 'temp_c', 'x', 'y']
In [200]: %reset_selective -f temp
In [201]: who_ls
Out[201]: ['np', 'x', 'y']

====================
Here's an example of doing this deletion from a list of names.  Keep in mind that there is a difference between the actual variable that we are trying to delete, and its name.
Make some variables, and list of names to delete
In [221]: temp_a, temp_b, temp_c, x, y = 1,'one string',np.arange(10), 10, [1,23]
In [222]: dellist=['temp_a', 'temp_c','x']

Get the shell, and the user_ns.  who_ls uses the keys from self.shell.user_ns.
In [223]: ip=get_ipython()
In [224]: user_ns=ip.user_ns

In [225]: %who_ls
Out[225]: ['dellist', 'i', 'ip', 'np', 'temp_a', 'temp_b', 'temp_c', 'user_ns', 'x', 'y']

In [226]: for i in dellist:
     ...:     del(user_ns[i])
     ...:
In [227]: %who_ls
Out[227]: ['dellist', 'i', 'ip', 'np', 'temp_b', 'user_ns', 'y']

So we have to look up the names in the user_ns dictionary in order to delete them.  Note that this deletion code creates some variables, dellist, i, ip, user_ns.
==============
How many variables are you worried about?  How big are they?  Scalars, lists, numpy arrays.  A dozen or so scalars that can be named with letters  don't take up much memory.  And if there's any pattern in the generation of the variables, it may make more sense to collect them in a list or dictionary, rather than trying to give each a unique name.
In general it is better to use functions to limit the scope of variables, rather than use del() or %reset.  Occasionally if dealing with very large arrays, the kind that take a meg of memory and can create memory errors, I may use del or just a=None to remove them.  But ordinary variables don't need special attention (not even in an ipython session that hangs around for several days).

A: I was looking help for the same task and I noticed the comment from hpaulj, about that %who_ls return a list of names then I remembered a little about metaprogrammin in R with the command eval(parser(text = text)), then I looked for and equivalent of the previous command in python to delete all the variables in lst_arch using the names of the variables (R's eval(parse(text=text)) equivalent in Python)
    a = 1
    b = 1

    lst_arch = %who_ls
    lst_arch.append('lst_arch')
    lst_arch.append('x')

    for x in lst_arch:
        exec(f'del(' + x + ')')

If we want to filter certain variables from lst_arch, we can use regular expression or something like that to delete just those variables we want to delete.


text:
Q: How to make sure that TFLite Interpreter is only using int8 operations? I've been studying quantization using Tensorflow's TFLite. As far as I understand it is possible to quantize my model weights (so that they will be stored using 4x less memory) but it doesn't necessary implies that the model won't convert it back to floats to run it. I've also understood that to run my model only using int I need to set the following parameters:
converter.target_spec.supported_ops = [tf.lite.OpsSet.TFLITE_BUILTINS_INT8]
converter.inference_input_type = tf.uint8
converter.inference_output_type = tf.uint8

I'd like to know what are the diference in the tf.lite.Interpreter between a loaded model in which those parameters were set and one in which they weren't. I tried to investigate .get_tensor_details() for that but I didn't notice any difference.

A: Depending on your requirements (performance, memory and runtime), post training quantization can be done in two ways.
Approach #1: Post training weight quantization (quantizes weights only)
In this case only weights are quantized to int8 but activations remain as they were. Inference input and output are floating-point.
converter = tf.lite.TFLiteConverter.from_keras_model(model)
converter.experimental_new_converter = True
# Post training quantization
converter.optimizations = [tf.lite.Optimize.OPTIMIZE_FOR_SIZE]
tflite_quant_model = converter.convert()
tflite_model_quant_file = tflite_models_dir/"lstm_model_quant.tflite"
tflite_model_quant_file.write_bytes(tflite_quant_model)

Approach #2: Full integer quantization (Quantizes weights and activations)
In this case weights and activations are quantized to int8. First we need to follow the approach #1 to quantize weight and then implement following code to do full integer quantization. This uses quantized input and output, making it compatible with more accelerators, such as the Coral Edge TPU. Inference input and output are integers.
converter.target_spec.supported_ops = [tf.lite.OpsSet.TFLITE_BUILTINS_INT8]
converter.inference_input_type = tf.uint8
converter.inference_output_type = tf.uint8

tflite_model_quant = converter.convert()
tflite_model_quant_file = tflite_models_dir/"lstm_model_quant_io.tflite"
tflite_model_quant_file.write_bytes(tflite_model_quant)

More details on weight quantization are here and you can find more details on full integer quantization here.


text:
Q: DefaultIfEmpty - LINQ to SQL vs In Memory For unit testing we use in memory collections to verify the logic of our LINQ queries. But, in the below scenario I'm seeing differences between the results from LINQ to SQL vs In Memory.
For this example we have three tables Customer, Order, Item. I would like the count of all items ordered by a customer. I would like to show customers who have not ordered any items as well. In SQL this would be an outer join. In LINQ to SQL I wrote this...
var itemCounts =
   from c in Customer
   from o in Order.Where(oo=>o.CustomerId==c.CustomerId).DefaultIfEmpty()
   from i in Item.Where(ii=>i.OrderId==o.OrderId).DefaultIfEmpty()
   group i by new { i.ItemId, c.CustomerId } into ig
   select new ItemCountResult {
     CustomerId = ig.Key.CustomerId,
     Count = ig.Count()
   };

This works fine when we are going against the database. We get customers with and without orders along with counts. When we substitute in memory collections for unit testing we see an object reference not set exception. I've narrowed it down to the line "i.OrderId==o.OrderId" specifically o is null.
Based on how "DefaultIfEmpty" works, this is actually the behavior I would expect. DefaultIfEmpty returns a single element enumerable of null.
So how do I fix this code to work in both scenarios?
UPDATE:
While I was simplifying the problem I lost some important pieces of information. So let me restate the problem.
A Customer has 0-n Orders.
A Order has 1-n Items.
A Item has 1-n Order.
I need the list of Items along with the number of customers that ordered that item. If 0 customers ordered the item I want it to still be returned but with a count of 0.
The problem is the many-to-many between Order and Item which prevents me from using the join-into syntax.
I currently have something like this (hopefully without mistypes this time):
var counts =
  from i in Items
  from oi in OrderItems.Where(z=>z.ItemId==i.ItemId).DefaultIfEmpty()
  from o in Orders.Where(z=>z.OrderId==oi.OrderId).DefaultIfEmpty()
  from c in Customers.Where(z=>z.CustomerId==o.CustomerId).DefaultIfEmpty()
  group c by new { i.ItemId, c.CustomerId } into cg
  select new CountResult {
    CustomerId = cg.Key.CustomerId,
    Count = cg.Count()
  };

A: Your query is pooched to start with. This:
from ...
from o in Order.Where(oo=>o.CustomerId==c.CustomerId).DefaultIfEmpty()
from i in Item.Where(ii=>i.OrderId==o.OrderId).DefaultIfEmpty()

... is trying to use o before it's really in scope. I'm surprised that works at all. It looks like you want:
from ...
from o in Order.Where(oo => oo.CustomerId == c.CustomerId).DefaultIfEmpty()
from i in Item.Where(ii => ii.OrderId == o.OrderId).DefaultIfEmpty()

However, that still has the same problem - o will be null if there are no customers for c.CustomerId. The SQL translation may well not exhibit the same behaviour, but it's frankly a little odd to start with IMO.
Try this instead, assuming you have the right relationship set up:
from c in Customer
join i in Items on c.CustomerId equals i.Order.OrderId into items
select new { CustomerId = c.CustomerId, Count = items.Count() };

Here's another alternative, back to using explicit joins:
from c in Customer
join oi in (from o in Orders
            join i in Items on o.OrderId equals i.OrderId
            select new { o, i })
on c.CustomerId equals oi.o.CustomerId into ordersForCustomer
select new { CustomerId = c.CustomerId, Count = ordersForCustomer.Count() };


text:
Q: How can I select multiple rows within dataTable in JSF I am facing some problem to select multiple rows of h:dataTable. My code is below:
<h:dataTable value="#{reportBean.lstchalan}"  var="chalan" >
 <h:column  >
      <f:facet name="header">
            <h:outputText value="Select" />
        </f:facet>
         <h:selectBooleanCheckbox value="#{reportBean.checked[chalan.issueNo]}" />

</h:column>
...
</h:dataTable>
<h:commandButton value="submit" action="#{reportBean.submit()}" />

and Below is my backing bean:
  public class ReportBean {
  List<ChalanVo> checkedItems = new ArrayList<ChalanVo>();
  private Map<String, Boolean> checked = new HashMap<String, Boolean>();
  ........
  public List<ChalanVo> getCheckedItems() {
    return checkedItems;
  }

  public void setCheckedItems(List<ChalanVo> checkedItems) {
    this.checkedItems = checkedItems;
 }
 public Map<String, Boolean> getChecked() {
    return checked;
 }

 public void setChecked(Map<String, Boolean> checked) {
    this.checked = checked;
 }
 public String submit() {

checkedItems = new ArrayList<ChalanVo>();
    for (ChalanVo dataItem : lstchalan) {
        if (checked.get(dataItem.getIssueNo())) {
            checkedItems.add(dataItem);
            checked.remove(dataItem.getIssueNo());
        }
    }}
}

But I am getting an exception when execute the line for (ChalanVo dataItem : lstchalan) .  lstchalan is giving null.Could you please help me to understand where I am doing wrong?

A: Here is a working, simplified example:
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import javax.faces.view.ViewScoped;
import javax.inject.Named;

@Named("test")
@ViewScoped
public class TestBean implements Serializable{

    private static final long serialVersionUID = -1064219566884774973L;

    private List<ChalanVo> lstChalans;
    private Map<ChalanVo, Boolean> checkedItems = new HashMap<TestBean.ChalanVo, Boolean>();

    public TestBean() {
        lstChalans = new ArrayList<TestBean.ChalanVo>();
        lstChalans.add(new ChalanVo("test1"));
        lstChalans.add(new ChalanVo("test2"));
        lstChalans.add(new ChalanVo("test3"));
    }

    public List<ChalanVo> getLstChalans() {
        return lstChalans;
    }

    public void setLstChalans(List<ChalanVo> lstChalans) {
        this.lstChalans = lstChalans;
    }

    public Map<ChalanVo, Boolean>  getCheckedItems() {
        return checkedItems;
    }

    public void setCheckedItems(Map<ChalanVo, Boolean>  checkedItems) {
        this.checkedItems = checkedItems;
    }

    public void save() {
        System.out.println("save");
        for (Entry<ChalanVo, Boolean> e : checkedItems.entrySet()) {
            if (e.getValue()) {
                System.out.println("checked: " + e.getKey().getIssueNo());
            }
        }
    }

    public class ChalanVo {
        private String issueNo;

        public ChalanVo(String issueNo) {
            setIssueNo(issueNo);
        }

        public String getIssueNo() {
            return issueNo;
        }

        public void setIssueNo(String issueNo) {
            this.issueNo = issueNo;
        }
    }
}

With this xhtml:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
   "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:h="http://xmlns.jcp.org/jsf/html"
      xmlns:f="http://xmlns.jcp.org/jsf/core">
<h:head />
<h:body>
        <h:form>
            <h:dataTable value="#{test.lstChalans}" var="chalan">
                <h:column>
                    <f:facet name="header">
                        <h:outputText value="Select" />
                    </f:facet>
                    <h:selectBooleanCheckbox value="#{test.checkedItems[chalan]}"  />
                </h:column>
                <h:column>
                    <f:facet name="header">
                        <h:outputText value="Issue No" />
                    </f:facet>
                    <h:outputText value="#{chalan.issueNo}"/>
                </h:column>
            </h:dataTable>

            <h:commandButton action="#{test.save()}" value="Submit" />
        </h:form>
</h:body>
</html>

The save() method is able to list the selected items. I think your NullPointerException is unrelated to the checkbox thing. But anyway, you can do the selection like this.


text:
Q: Swift 5.1 Combine Observable/Environment variable not updating when didSet I am trying to figure out why my session is not updating despite didSet firing and presumably updating User.
I've removed superfluous comments and style from the snippets but this is what I am trying currently.
//  SessionStore.swift

class User {
    var uid: String
    var phoneNumber: String
    init(uid: String, phoneNumber: String) {
        self.uid = uid
        self.phoneNumber = phoneNumber
    }

}
class SessionStore : ObservableObject {
    var didChange = PassthroughSubject<SessionStore, Never>()
    var session: User? { didSet { self.didChange.send(self); print("didSet()") }}
    var handle: AuthStateDidChangeListenerHandle?
    func listen () {
        // monitor authentication changes using firebase
        handle = Auth.auth().addStateDidChangeListener { (auth, user) in
            if let user = user {
                self.session = User(
                    uid: user.uid,
                    phoneNumber: ""
                )
            } else {
                self.session = nil
            }
        }
    }
    func register(
        phoneNumber: String,
        handler: @escaping AuthDataResultCallback
        ){

        PhoneAuthProvider.provider(auth: Auth.auth())
        PhoneAuthProvider.provider().verifyPhoneNumber(phoneNumber, uiDelegate: nil) { (verificationID, error) in
          if let error = error {
            return
          }
            UserDefaults.standard.set(verificationID, forKey: "authVerificationID")
            let verificationID = UserDefaults.standard.string(forKey: "authVerificationID")
            let verificationCode = "123456"
            let credential = PhoneAuthProvider.provider().credential(
                withVerificationID: verificationID!,
                verificationCode: verificationCode
            )
            Auth.auth().signIn(with: credential) { (authResult, error) in
                if let error = error {
                    print(error)
                    return
                }
                self.listen()
                return
            }

        }
    }
}

and
struct Login: View {
    @EnvironmentObject var session: SessionStore
    @State var phoneNumber: String = ""
    @State var loading = false
    @State var error = false
    func getUser () {
        session.listen()
    }
    var body: some View {
        Group {
            // If  the user is logged in
            if(session.session != nil) {
                Score()
            // If the user is NOT logged in
            } else {
                VStack {
                    Text("Register!")
                    TextField("Phone Number", text: $phoneNumber)
                    MyButton(...).gesture(TapGesture().onEnded {
                        self.session.register(
                            phoneNumber: self.phoneNumber
                         ){
                             (result, error) in
                             if(error != nil) {
                                 self.error = true
                             } else {
                                 self.phoneNumber = ""
                                 self.getUser()
                             }
                         })
                    }
                }
            }
        }.onAppear(perform: getUser)
    }
}

A: Scratchy (only based on your snapshot)...
Instead of this
class SessionStore : ObservableObject {
    var didChange = PassthroughSubject<SessionStore, Never>()
    var session: User? { didSet { self.didChange.send(self); print("didSet()") }}

use this
class SessionStore : ObservableObject {
    @Published var session: User?

as far as I see from snapshot no more changes should be needed, might be some type alignment in other parts.


text:
Q: different ways of logging in a user in a Java EE 6 web app I am wondering what all options or ways do we have in a Java EE 6 web app, to log in users? With this I mean, saving their data (id, username, ...) while they are using the app.
I know this data is stored in a session while thy are using the site, sometimes in cookies or even the URL.
But what I would like to know is:

*

*What is the most common approach in a Java EE 6?

*What would be the most recommendable way?

*What do you practice and what do you prefer?

*What other options do we have?

*What would be the safest?

A:
What would be the most recommendable way?

On Java EE 6, that would (in my opinion) be using container managed security with a Realm pointing to a SQL database.

What do you practice and what do you preffer?

Before Java EE 6, I used to prefer a homegrown login mechanism because I'd like to have full control over the login. Most containers namely doesn't allow filtering j_security_check requests. Since Java EE 6 it's possible to do a programmatic login with the new HttpServletRequest#login() method, so that disadvantage has gone.

What other options do we have?

Well, I already mentioned two major ways. Apart from some frameworks like Spring Security, there are not really other options. The container managed security in turn offers several ways to do the login such as HTTP BASIC authentication (which just shows a browser-builtin JavaScript-like login popup), form based authentication (using a HTML form submitting to j_security_check) and the new programmatic login.

What would be the safest?

All are equally safe. The safefy in practice depends on your own code and configuration settigns.

A: try to use some framework, like spring (spring mvc will automatically inject the session data which include log in info).


text:
Q: SQL trigger that creates another table Is there a way to make a trigger, that creates a new table when a row is inserted in the trigger table, where the name of the new table is what was inserted in a specific column in the table with the trigger?
Something like this?
CREATE TRIGGER playlists.insert_trigger ON playlists AFTER INSERT AS  name = SELECT name FROM playlists WHERE id = max(id) CREATE TABLE name (id int, song varchar(255));

A: Table creation is an operation which causes implicit commit.
Statements That Cause an Implicit Commit
So this operation is not possible in the trigger.


text:
Q: Angular load everything on startup So I am trying to figure our how I can load everything in the angular app on startup then reference it from cache when it is needed. Basically, I have an app that has around 40+ pages with some text and images on each page. I want to basically have a loading screen at the beginning of the app that loads in everything so once they load they don't need internet anymore. The computers that will be serving this app are slow and often loose internet that is why.
Now angular is a Single page app framework. Would it be enough to just use ng-src for images(I think it caches them).
I'm not sure and no-one seems to want to load everything first most people are looking to load it asynchronously and I can't do that


text:
Q: Using VB.net DataGrid view to interact with SQL DB. Update/Delete/Add Setup Information
I have "Form1" with a DataGrid View ("DataGridView1") which populates with Data from an SQL server table.
It's a simple table, with about 10 records.
The table used is "jamesTestVBlol"
The dataset is named "DataSetJames.xsd"
I believe the table adaptor is called "JamesTestVBlolTableAdaptor"
Question
Is there a way, I can update a record and send these changes back to the server.
e.g. Column 1, record 1 I would like to change to "TEST" and update this table on the server.
The only code I have is:
Public Class Form1

  Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    'TODO: This line of code loads data into the 'DataSetJames.jamesTestVBlol' table.' You can move, or remove it, as needed.
    Me.JamesTestVBlolTableAdapter.Fill(Me.DataSetJames.jamesTestVBlol)
  End Sub

End Class

Could anyone help me with where I need to look?
I've tried to read several online tutorials, but generally they are above my head.
Thanks,
James.


text:
Q: python flask ImportError: No module named views.login I have a app named flaskr. When I want to import views.login` from views. it gives me error:
   File "C:\Projects\flaskr\flaskr.py", line 28, in <module>
     from flaskr.views.login import login
ImportError: No module named views.login

Before I put all the methods inside the flaskr.py file. I want to move each functions to different views, like login, show_entries, log_out, just like MVC has different views.
flaskr.py
from sqlite3 import dbapi2 as sqlite3
from flask import Flask, request, session, g, redirect, url_for, abort, render_template, flash
import os

app = Flask(__name__)
app.config.from_object(__name__)

from flaskr.views.login import login
app.register_blueprint(login)

if __name__ == '__main__':
    app.run(debug = True)

login.py
from flask import Flask, request, session, g, redirect, url_for, abort, render_template, flash
from jinja2 import TemplateNotFound

login = Blueprint('login', __name__,template_folder='../template')

@app.route('/login')
def login():
    return render_template('login.html')

A: Create folder named app or whatever.
Create __init__.py file in app:
from sqlite3 import dbapi2 as sqlite3
from flask import Flask, request, session, g, redirect, url_for, abort, render_template, flash
import os

app = Flask(__name__)
app.config.from_object(__name__)

from app import views

app.register_blueprint(views.login)

Move app.run method into separate start.py file in root directory
from app import app

if __name__ == '__main__':
    app.run(debug = True)

Create folder views in app/. Create __init__.py in views
Now you could have structure like this:
your_project_name/
    |app/
    |__init__.py
        |views/
            |__init__.py
            |login.py
    start.py

Sorry, if there are have mistakes.


text:
Q: What should I do if I realize the premise of a question was faulty, but I already have answers? The question in question is this: SSHing git@github.com shows wrong/old SSH key.
I had assumed wrongly that the SSH key fingerprint displayed when you're SSHing into GitHub for example, should match your own Public RSA key. After reading the answers, I realized it was simply GitHub's own Public key's fingerprint (so as to authenticate the host you're trying to connect to).
Since the question is wrongly framed, I can't really accept any answer (which would lower my accept-percentage BTW, so it's not like I don't want to give away reputation). I can't delete it either as it says "Sorry, this question has one more answers; flag it for moderator attention instead", even though its my question; I guess this is because, as it says in How can I delete my own question with a low score but with answers? I'd have wasted reader's time.
I don't want to lose reputation, nor do I want to turn Stack Overflow into a big pile of junk.
What should I do, without losing reputation (if possible)?

A: What said from Mr Lister is correct, but I would point out that Miguel's answer actually answers your question, when it says:

But maybe it is not a problem, as Step 5: Test everything out of your link says that you may see this warning:
# The authenticity of host 'github.com (207.97.227.239)' can't be established.
# RSA key fingerprint is 16:27:ac:a5:76:28:2d:36:63:1b:56:4d:eb:df:a6:48.
# Are you sure you want to continue connecting (yes/no)?

and you shouldn't worry, this is supposed to happen. Just verify that the fingerprint matches the one here and type "yes".

I cannot say if Stack Overflow's moderators delete questions in such cases, when there is an answer, and the question doesn't have a negative score. You could try by flagging it for moderation attention, saying that you discovered you made a false assumption, and the question would not help any future reader (which means the question is not relevant for you, nor for future readers). It could be deleted, if they think the question effectively doesn't help any future reader.
I had some of my questions deleted from Meta Stack Overflow. Once, I have explained the question was not anymore relevant as I was reporting something true for an old version of Safari (the browser) that was not anymore used from me, or any other user; in another occasion, I explained the feature request seemed only relevant for me, and no other users seemed interested in it.
I guess the important is to give a detailed explanation, not a too generic explanation.

A: Flag it for moderator attention mentioning that "Answer should be deleted because it doesn't make sense and is therefore not suitable for the Q&A format".
You do have one upvote on the question currently, so you'd lose 5 rep if it really gets deleted. You can vote to close instead, but if it does get closed, it might get deleted later on, with the same result.
Mind you, deleting too many questions is frowned upon by the system and may result in question banning in the long run.

A: Your question could still be valuable to someone else who has the same incorrect assumption you did. If you thought this, it's almost certain someone else does. You could answer your own question with the edit you added at the bottom and accept it as the answer.


text:
Q: When to use timed cookies over a timed interval in a database I'm coming here today to ask the professionals when/how do you(s) make the decision to use a Cookie Expire time over a Timed Access specified by a time and using the clients $_SESSION['REMOTE_ADDR'];?
Just taking a chunk from the php manual about setcookie(); follows:
setcookie("TestCookie", $value, time()+3600);  /* expire in 1 hour */

According to the manual, this cookie will expire in one hour.. But as we know, cookies can be modified by the client using a range of tools, so if the client (bad person) caught on that the cookie is set to expire, which will either allow access to something, or deny access to something until another event is triggered?
Whereas, something more is to use the time(); function within MySQL and create a Timed row in the Schema table with the clients Public IP address as the identifier.
But the client can browse to the website using a proxy browser/mobile device with a different IP address.
They both use the same concept, of either allowing/denying access after the interval has passed, but can both be bypassed if the client knows their stuff.
So I come back to my overall question, when/how is it possible to tell when it's acceptable to use a timed interval set by a cookie or a database?

A: I believe you should use combination of both - database to store the data and client's cookies to identify row in the database table.
Using IP address for identification is not very reliable because:

*

*More clients may have the same IP

*Client's IP address might change randomly (i.e. wifi / gsm connection on the smartphones)

You can also use sessions which are probably faster and easier way to store user's information, and if you don't want to manage cookies by yourself, it's a way to go.


text:
Q: What is best way to securely store a password in the properties.settings file?
Possible Duplicate:
Encrypting passwords in WinForms app.config, .NET

I want to be able store username/password pair for a login box.  Each time the application is loaded, the saved credentials are loaded from the Properties.Settings file and then the login box is populated with these values.
I know there is always the chance that the password could be hacked, but anything must be better than storing clear-text in the properties.settings file.
I've been looking at using SecureString, but all that appears to do is prevent the password from being stored in cleartext in memory.
Any ideas the best way to handle this?

A: I don't understand why hashes are mentioned; if they are designed to be irreversible, how could they be used to pre-populate the fields?
When I did something similar to this a while ago, I did the following:
AES_encrypt ( username + saltString1 + password + saltString2 )

Store the result of that and store the AES key.
To populate the fields:

*

*recall the data and the key

*decrypt the data, using the key

*split the string about saltString1

*the first value of the split is the username

*the second value is password + saltString2

*

*substring using saltString2 and you have your password

A: You can store just hash of password, instead saving plain text. Then, when you are comparing password stored in user database and password entered, you are comparing hashes instead of open text. Look in System.Security.Cryptography ...

A: If you want the login box to be prepopulated with the password, then it has to be stored in clear text somewhere, whether as a literal string in the source, a database, a config or settings file, or as a string in a compiled resource.
Also note that extracting a password from a masked password field can be as simple as sending a message to the textbox.
You might consider encrypting the password, or generating an MD5 hash and storing that. When the user logs in, use the same process as you used on the original password and compare the result to see if the correct password was entered, but that won't let you prepopulate the login box.
On the other hand, what's the point in requiring a password if you're going to populate the dialog? You may as well just show a form that says "press enter to log in" with no fields at all.


text:
Q: Need some guidance regarding a licensing script (BoxBilling) I'm pretty new to the BoxBilling Licensing and to be fair, their not really providing any support!
I have this code to check a license which is working correctly however, if the license is invalid, it simply shows the word "Array" and if it is valid, shows nothing at all.
I need to know how I can set a different message rather than "Array" if the license is invalid and how I can basically kill the page (via die() or something similar).
Thanks in advance for your help guys!
<?php
include("config.php");
include("opendb.php");

function getLicenseDetails($key)
{
$systeminfo = mysql_query("SELECT * from `systeminfo`");
$systeminfo = mysql_fetch_array($systeminfo);
$url = 'http://clients.pbtechsupport.com/index.php/api/guest/servicelicense/check';
$params = array();
$params['license']  = $systeminfo[licensekey];
$params['host']     = 'localhost';
$params['path']     = dirname(__FILE__);
$params['version']  = '1.0';

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_VERBOSE, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 20);
curl_setopt($ch, CURLOPT_TIMEOUT, 20);
curl_setopt($ch, CURLOPT_POST,              true);
curl_setopt($ch, CURLOPT_POSTFIELDS,        json_encode($params));
$result = curl_exec($ch);

$code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if($code != 200) {
    error_log('CURLINFO_HTTP_CODE: '.$code);
}

return json_decode($result, true);
}

$json = getLicenseDetails('test');
if(!$json['valid']) {
print $json['error'];
}
include("closedb.php");
?>

A: print_r($json['error']) to see what's in the array, then use its contents to output something more intelligent based on that. They presumably are returning information about the particular error encountered in their JSON.
Based on your comment, doing print $json['error']['message']; will display the error encountered. You could also do if($json['error']['code'] == 1006) { print 'Your own custom error about the license here.'; } if you'd prefer not to use their own text.


text:
Q: extracting numbers of certain length from list I have a list of thousands of elements - some elements contain years - which are strings of 4 numbers - others contain random numbers that I need to get rid of.
I need to extract from the list only numbers that are 4 in length, and remove all other numbers. In the end I need a data frame of 20 rows - and columns containing the years that are nested in the list.  For example, in the sample below I need a table that looks like this.
> sample_years
   element year year.1 year.2 year.3
1        1   NA     NA     NA     NA
2        2   NA   1918     NA     NA
3        3   NA     NA     NA     NA
4        4   NA     NA     NA     NA
5        5   NA   1912   1913     NA
6        6   NA   1893   1898   1925
7        7   NA   1820   1830   1899
8        8   NA     NA     NA     NA
9        9   NA   1808   1810   1854
10      10   NA     NA     NA     NA
11      11   NA     NA     NA     NA
12      12   NA   1885     NA     NA
13      13   NA   1900     NA     NA
14      14   NA   1926   1933     NA
15      15   NA     NA     NA     NA
16      16   NA     NA     NA     NA
17      17   NA   1870     NA     NA
18      18   NA     NA   1923     NA
19      19   NA     NA     NA     NA
20      20   NA     NA     NA     NA

> dput(sample)
list(c("", "2"), c("", "1918"), "", "", c("", "1912", "1913"),
    c("", "1893", "1898", "1925", "1993"), c("", "1820", "1830",
    "1899", "1900"), "", c("", "1808", "1810", "1854", "1905",
    "1907"), "", "", c("", "1885"), c("", "1900"), c("", "1926",
    "1933"), "", "", c("", "1870"), c("", "1", "1923"), "", "")

A: We can use rbind.fill from plyr package to bind the list, and then grepl to handle your condition,
df <- rbind.fill(lapply(lst1,function(i)as.data.frame(t(i))))
df[!apply(df, 1:2, function(i) grepl('[0-9]{4}', i))] <- NA
head(df)
#    V1   V2   V3   V4   V5   V6
#1 <NA> <NA> <NA> <NA> <NA> <NA>
#2 <NA> 1918 <NA> <NA> <NA> <NA>
#3 <NA> <NA> <NA> <NA> <NA> <NA>
#4 <NA> <NA> <NA> <NA> <NA> <NA>
#5 <NA> 1912 1913 <NA> <NA> <NA>
#6 <NA> 1893 1898 1925 1993 <NA>

A: I think sapplyis what you are looking for. For your list named sample:
sapply(sample, function(i) sum(i != ""))

You can then extract the elements of the list that fit your criterion as follows:
myNewSample <- sample[which(sapply(sample, function(i) sum(i != ""))) == 4]

On a sidenote, it is not advisable to use "sample" as the name of your list object as it is a fairly important function in R. See ?sample.


text:
Q: Book about Human-eating Alien Lizards I am looking for a book that I read in the early 2000's in middle school.
The main character was a teen girl. I don't remember how she got to where she was but she ends up finding out that everyone around her are lizard-type, alien creatures who disguise themselves as her friends and family. They are only being nice to her in order to fatten her up enough to eat.
It reminds me of Coraline in some ways.


text:
Q: Mask is not extending to scrollable portion I have  set
.x-mask {
   height:100% !important;
}

But the parent window is scrollable. So when I scroll the window, the bottom portion does not have mask. Any way to solve this issue?
I am using extjs.

A: Your CSS isn't written correctly:
.x-mask {
 height:100%;
}

If this doesn't fix your problem you would have to supply us with more code and/or a link to your website or a fiddle showing the issue.

A: x-mask {
 position:fixed;
 height:100%;
 width:100%;
}


text:
Q: ElanTech touchpad both keys simultaneously don't work I have a huge problem with ElanTech touchpad. Without the ElanTech driver both the keys can be used at the same time(R+L). This is usefull in games like Mafia2 (can't play without it). When I install their driver I get the gestures, scrolling etc. but I can't use both keys at the same time. It is a common problem.
Acer Aspire v3-571G Windows 7 x64
This didn't work at all: Synaptics  15.3.41.5
Is there any universal driver which will give me at least scrolling and simultaneous keys usage?

A: I have downloaded Mouse Generic form Apcom. It is awesome, works fine and finally did, wrong, but did do good, well.


text:
Q: Node puppeteer stream not recording audio I'm trying to record video and audio using puppeteer stream, but it's getting written only the video to the output file:
async function videoRecorder() {
  require("puppeteer-stream");
  const puppeteer = require("puppeteer");
  const fs = require("fs");

  const filename = `./recordings/test.mp4`;

  const file = fs.createWriteStream(filename);

  const browser = await puppeteer.launch({
    executablePath:
      "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",
    headless: true,
    defaultViewport: null,
    devtools: false,
    args: [
      "--window-size=1920,1080",
      "--window-position=1921,0",
      "--autoplay-policy=no-user-gesture-required",
    ],
    ignoreDefaultArgs: ["--mute-audio"],
  });

  const page = await browser.newPage();

  await page.goto(pathToPageWithVideo, {
    waitUntil: "load",
  });

  const stream = await page.getStream({
    audio: true,
    video: true,
  });

  stream.pipe(file);

  setTimeout(async () => {
    await stream.destroy();
    file.close();
    console.log("finished");
  }, 10000);
}

I've tried many other ways of recording video and audio but this is the one I got closer, since my main purpose is to get the audio only, I'm open to more suggestions.
Thanks

A: Solved by saving as .webm instead of .mp4.
Reference: https://github.com/Flam3rboy/puppeteer-stream/issues/1


text:
Q: Show that there exist a constant c>0 Show that there exist a constant $c>0$ such that for all $x \in [1,\infty)$
$$  \sum_{n>=x}^{\infty} 1/n^2 < c/x. $$

A: Note that for $x\ge 1$
$$\sum_{n>=x}^{\infty} 1/n^2 <\int _x^{\infty} \frac {1}{t^2}dt= \frac{1}{x} <2/x$$
Thus $c=2$ does the trick.

A: If $x$ is an integer bigger than $1$, you can bound the sum by
$$\int_{x-1}^\infty  \frac{1}{ y^2 } \; d y.$$
If $x=1$, you have to tweak it a bit.  Then if $x$ is not an integer, you have a different little tweak.


text:
Q: Replacing an Excel connection range with an Add-In I've having a bit of a nightmare with an Excel Add-In I've written. The customers workbook used to be populated from a SQL connection and has loads of formulas setup around named tables etc. I'm trying to populate some the same tables that connection populated (using the existing headers and footers) with the data from a WCF service while maintaining formatting and formulas (ie: not break anything).
Getting the data in is fine. The problem I'm hitting is this: The data being replaced may be more or less data than currently exists in the named range. I can't seem to find a way of removing the exising rows and replacing them with my new data and having the named range resize to the new data.
Many thanks in advance.
Range range = activeWorksheet.get_Range("Name", MissingValue);
range.Clear();
object[,] data = new object[result.Length, 26];
range.get_Resize(result.Length, 26);
... fill data....
range.Value2 = data;

A: Ok, managed to solve it with the code below. Also removed the "range.Clear()" call which stopped the formatting from being removed.
 Range range = activeWorksheet.get_Range("Name", MissingValue);
 int totalMissingRows = 0;
            if (range.Rows.Count < result.Length)
            {
                totalMissingRows = result.Length - range.Rows.Count;
                for (int i = 0, l = totalMissingRows; i < l; i++)
                {

                    Excel.Range rng = range;
                    rng = (Excel.Range)rng.Cells[rng.Rows.Count, 1];
                    rng = rng.EntireRow;
                    rng.Insert(Excel.XlInsertShiftDirection.xlShiftDown, MissingValue);
                }
            }

            //delete extra lines
            //remove left over data
            for (int i = result.Length, l = range.Rows.Count; i < l; i++) { range.Cells[range.Rows.Count, 1].EntireRow.Delete(null); }

A: Since, you are already getting an array of data, why not directly write it to the excel like this:
int startRow, startCol;
var startCell = (Range)worksheet.Cells[startRow, startCol];
var endCell = (Range)worksheet.Cells[startRow + result.Length, startCol + 26];
var writeRange = worksheet.get_Range(startCell, endCell);
writeRange.Value2 = data;
Here, I have used the lengths of your array as per your question and data is the 2d array of data.


text:
Q: How do I animate, Moving an ImageView on a circular path with certain radius in android? Please Find the attachment for my image.
https://docs.google.com/file/d/0B_c-SDSO63obS0ZyQ1dsOXdUQmc/edit?usp=sharing
My task is, animate that GONG type of image up to some time with clock wise and anti clock wise.
For that i did some coding in animation but i didn't succeed. I am using both translate and rotate.
     <translate
        android:fromXDelta="0%p"
        android:toXDelta="75%p"
        android:duration="1500" />

and rotate functions,
      <rotate android:fromDegrees="0"
    android:toDegrees="360"
    android:pivotX="50%"
    android:pivotY="50%"
    android:duration="600"
    android:repeatMode="restart"
    android:repeatCount="infinite"
    android:interpolator="@android:anim/cycle_interpolator"/>

Actually my idea is in a specific time i want to move with specific angle. But i don't know the correct way to solve this task.
Please help me. sorry for my English.
All answers are acceptable
Thanks
Shankar

A: You have divided a circle in 12 parts in that image and that equals to 30 degrees per segment.
you have to rotate it  like this to look proper
 rotateDegree=[steps]*30;

use AlarmManager to trigger animation in specific time
EDIT:
to move your image in circular path with a radius you have to give a different pivot x and y
you can find it by tryng with
 pivotX= 0 and pivotY=(negative value)

I hope this helps.


text:
Q: Defining a single cell value for use in automated calculation I am trying to define a formule in my VBA coding to take into account a certain value from a specific worksheet inside my workbook.
Could somenody have a look at my code and tell me what I am doing wrong?
' Macro used to create the labour demand
'
' define variables and tables

Dim wb As Workbook
Set wb = Application.ActiveWorkbook
Dim LabourDemand As Worksheet
Set LabourDemand = Sheets("Labour Demand")
Dim LaborPerFTE As Double
Set LaborPerFTE = Application.ActiveWorkbook.Worksheets("FTE Calculation").Range("C34").Value

' define connection string

Dim connectionString As String
connectionString = "ODBC;DSN=Excel Files;DBQ=" & Application.ActiveWorkbook.FullName & ";DefaultDir=" & Application.ActiveWorkbook.Path & ";Dri"

' clear out the old table

LabourDemand.Cells.Clear

And then this value should be used for calculations as follows
'create new table

    With LabourDemand.ListObjects.Add(SourceType:=0, Source:=Array(Array( _
        connectionString), Array("verId=1046;MaxBufferSize=2048;PageTimeout=5;")), _
        Destination:=LabourDemand.Range("$A$1")).QueryTable
        .CommandType = 2
        .CommandText = "SELECT `'Merged demand$'`.Category, `'Merged demand$'`.`Test Name`, `'Labor and equipment times$'`.`Equipment used`, `'Merged demand$'`.SampleDemandN, `'Merged demand$'`.SampleDemandN1, `'Merged demand$'`.SampleDemandN2, `'Merged demand$'`.SampleDemandN3, `'Labor and equipment times$'`.`Typical Batch Size`, `'Labor and equipment times$'`.typical, `'Labor and equipment times$'`.`Minimum batch size`, `'Labor and equipment times$'`.`1`, `'Labor and equipment times$'`.`Maximum batch size`, `'Labor and equipment times$'`.Max " _
        & " ,'=(([@[SampleDemandN]]/[@[Typical Batch Size]])*[@typical])/LaborPerFTE' as 'Labour needed for N (Typical)'" _
        & " ,'=(([@[SampleDemandN]]/[@[Maximum batch size]])*[@Max])/LaborPerFTE' as 'Labour needed for N (MAX)'" _
        & " ,'=(([@[SampleDemandN]]/[@[Minimum batch size]])*[@1])/LaborPerFTE' as 'Labour needed for N (MIN)'" _
        & " ,'=([@[SampleDemandN1]]/[@[Typical Batch Size]])*[@typical]' as 'Labour needed for N+1 (Typical)'" _
        & " ,'=([@[SampleDemandN1]]/[@[Maximum batch size]])*[@Max]' as 'Labour needed for N+1 (MAX)'" _
        & " ,'=([@[SampleDemandN1]]/[@[Minimum batch size]])*[@1]' as 'Labour needed for N+1 (MIN)'" _
        & " ,'=([@[SampleDemandN2]]/[@[Typical Batch Size]])*[@typical]' as 'Labour needed for N+2 (Typical)'" _
        & " ,'=([@[SampleDemandN2]]/[@[Maximum batch size]])*[@Max]' as 'Labour needed for N+2 (MAX)'" _
        & " ,'=([@[SampleDemandN2]]/[@[Minimum batch size]])*[@1]' as 'Labour needed for N+2 (MIN)'" _
        & " ,'=([@[SampleDemandN3]]/[@[Typical Batch Size]])*[@typical]' as 'Labour needed for N+3 (Typical)'" _
        & " ,'=([@[SampleDemandN3]]/[@[Maximum batch size]])*[@Max]' as 'Labour needed for N+3 (MAX)'" _
        & " ,'=([@[SampleDemandN3]]/[@[Minimum batch size]])*[@1]' as 'Labour needed for N+3 (MIN)'" _
        & " FROM `'Labor and equipment times$'` `'Labor and equipment times$'`, `'Merged demand$'` `'Merged demand$'`" _
        & " WHERE `'Merged demand$'`.`Test Name` = `'Labor and equipment times$'`.`Test Name` AND ((`'Labor and equipment times$'`.`Equipment used`='Manual labor'))"
        .RowNumbers = False
        .FillAdjacentFormulas = False
        .PreserveFormatting = True
        .RefreshOnFileOpen = False
        .BackgroundQuery = True
        .RefreshStyle = xlInsertDeleteCells
        .SavePassword = False
        .SaveData = True
        .AdjustColumnWidth = True
        .RefreshPeriod = 0
        .PreserveColumnInfo = True
        .ListObject.DisplayName = "LabourDemand"
        .Refresh BackgroundQuery:=False
    End With

' calculation of the values
    Dim LastRow As Long
    LastRow = Cells(Rows.Count, "A").End(xlUp).Row

    For Each cell In Range(Cells(1, 14), Cells(LastRow, 25))
    cell.FormulaR1C1 = cell.Formula
    Next cell

End Sub

Any help is welcome.
And as a final question how can I adapt the calculation part so it runs on the correct worksheet so that I do not need to have it as active worksheet in my active workbook.

A: Change the below line
LastRow = Cells(Rows.Count, "A").End(xlUp).Row

For Each cell In Range(Cells(1, 14), Cells(LastRow, 25))
cell.FormulaR1C1 = cell.Formula
Next cell

To...
with LabourDemand
    LastRow = .Cells(.Rows.Count, "A").End(xlUp).Row

    For Each cell In .Range(.Cells(1, 14), .Cells(LastRow, 25))
        cell.FormulaR1C1 = cell.Formula
    Next cell
end with


text:
Q: How to grasp the data type Pair in dolphindb? According to the manual of dolphindb,the range is upper bound exclusive of Pair,but when I test this data type:
print a[1:3];
for(s in 1:3){print s};
print  3 in 1:3;

Output:
[1,2]
1
2
1

I think "upper bound exclusive" means open interval at the upper bound, why does 3 in 1:3 return 1?  How to grasp it?

A: In DolphinDB, pair itself is just a special vector that contains two elements with identical type. So when you evaluate the expression 3 in 1:3, just check if 3 in vector [1,3]. Of course it returns 1 (true).
When a pair is used as an index of a vector, the upper bound is exclusive.


text:
Q: redirected Autocomplete Jquery I have a script with autocomplete that I wanted if the user typed a word that does not have in the script it was redirected to a specific url example warning.html but I am not able to do that, if you can help me from now thank you.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>jQuery UI Autocomplete Testt</title>
<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css" rel="stylesheet" type="text/css"/>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script>
<script>
 $(document).ready(function() {
  var data = [
   {label: 'Google', value: 'http://google.com'},
   {label: 'Yahoo', value: 'http://yahoo.com'},
   {label: 'BMW', value: 'http://bmw.com'},
   {label: 'Bing', value: 'http://bing.com'}
  ];

     $("input#autocomplete").autocomplete({
   source: data,
   focus: function (event, ui) {
    $(event.target).val(ui.item.label);
    return false;
   },
   select: function (event, ui) {
    $(event.target).val(ui.item.label);
    window.location = ui.item.value;
    return false;
   }
  });
   });
  </script>
</head>
<body>
<input id="autocomplete" />
</body>
</html>

A: You are using jqueryui 1.8. I am using 1.9 in the example below. Because, 1.9 has the response function, which can check the length.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>jQuery UI Autocomplete Testt</title>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.9.2/themes/base/jquery-ui.css">
<script src="http://code.jquery.com/jquery-1.8.3.js"></script>
<script src="http://code.jquery.com/ui/1.9.2/jquery-ui.js"></script>
<script>
    $(document).ready(function() {
        var data = [
            {label: 'Google', value: 'http://google.com'},
            {label: 'Yahoo', value: 'http://yahoo.com'},
            {label: 'BMW', value: 'http://bmw.com'},
            {label: 'Bing', value: 'http://bing.com'}
        ];

        $("input#autocomplete").autocomplete({
            source: data,
            focus: function (event, ui) {
                $(event.target).val(ui.item.label);
                return false;
            },
            select: function (event, ui) {
                $(event.target).val(ui.item.label);
                window.location = ui.item.value;
                return false;
            },
            response: function(event, ui) {
            if (ui.content.length === 0) {
                console.log('action here');
            }
        }
        });
    });
  </script>
</head>
<body>
<input id="autocomplete" />
</body>
</html>


text:
Q: How to Query Grandchildren and there sub children in Wordpress I've been researching for a query that would display ul list of grandchildren pages and within each a another ul of the children pages. I think it would be going 3 & 4 levels deep? What I have right now as far as pages are:
Parent

*

*Child 1

--Grandchild 1
---Grandchild 1 child 1
--Grandchild 2
---Grandchild 2 child 1

*

*Child 2

--Grandchild 1
---Grandchild 1 child 1
--Grandchild 2
---Grandchild 2 child 1

*

*Child 3

--Grandchild 1
---Grandchild 1 child 1
--Grandchild 2
---Grandchild 2 child 1
Then basically when you are on a child, grandchild or granchild child it would display a menu list of all pages/links of the Child (but not the child itself in the menu).
I found how many things on parent and children, and even something with the grandchild, but nothing beyond the grandchild that would work? Any ideas or reference on how I can achieve this?

A: A couple of ways to do this:
First the simplest, just hide the top menu with CSS, display only the ones that are selected.
A bit of code I had luck with myself http://www.ordinarycoder.com/wordpress-wp_nav_menu-show-a-submenu-only/
And there's a duplicate question if you can find anything of use here: WordPress wp_nav_menu specific sub menu only

A: I had no luck after trying the references from: http://codex.wordpress.org/Function_Reference/wp_list_pages#List_Sub-Pages
The closet thing I found from another resource in what I need to do is reliant on page ID:
<?php
$parent = 64;
$args=array(
 'child_of' => $parent
);
$pages = get_pages($args);
if ($pages) {
  $pageids = array();
  foreach ($pages as $page) {
  $pageids[]= $page->ID;
}
wp_list_pages($args);
}
?>

Though it will work, I am using templates that may be used throughout different pages. So if a grandchild or one of it's children is the page shown I need to show the whole list of the grandchild's parent (or in reality child 1, child 2 or child 3).
After many attempts I finally figured it out. I did go back and decided to make nav menus and by using if statements like this where I want the nav menu to appear.
<?php
   if ( is_page( 'child-1' ) || in_array( 3, get_post_ancestors($post->ID) ) ) {
     menu2_nav();
   } elseif ( is_page( 'child-2' ) || in_array( 4, get_post_ancestors($post->ID) ) ) {
     menu3_nav();
   } else {
   }
 ?>

So no matter if child 1 or child 2 uses the same template, example template-green, the correct nav menu will appear depending on the parent page listed. Also, if you're on a child page, or sub pages within that child no matter how deep the selected nav menu would show. The same code would be used on multiple templates such as template-blue, template-red, etc.


text:
Q: My program is taking very long to print out results over 25, is there a way to make this more efficient when I run? These are the lines I'm using, it produces a list of the possible combinations of the sum to an integer typed in and then states the amount of combinations.
import itertools

val = int(input())
r = range(val)[1:]
res = []
for i in range(len(r)+1):
    res += [list(x) for x in itertools.combinations(r, i) if sum(list(x)) == val]
print("Solution : %s " % res)
print("Combinations : %s" % len(res))

A: It looks like you are calculating every single possible combination, and then keeping only the combinations that satisfy your sum condition. The combination pool it is searching through grows at a rate 2^(n-1) which you can see by commenting out the condition part:
import itertools
import time

startTime = time.time()

val = 21
r = range(val)[1:]
res = []
for i in range(len(r)+1):
    res += [list(x) for x in itertools.combinations(r, i)]# if sum(list(x)) == val]
#print("Solution : %s " % res)
print("Combinations : %s" % len(res))

print(time.time() - startTime, 'seconds')

Try this:
def a(lst, target, with_replacement=False):
    def _a(idx, l, r, t, w):
        if t == sum(l): r.append(l)
        elif t < sum(l): return
        for u in range(idx, len(lst)):
            _a(u if w else (u + 1), l + [lst[u]], r, t, w)
        return r
    return _a(0, [], [], target, with_replacement)

val = 50
s = range(1, val)
solutions = a(s, val)
print(solutions)
print(len(solutions))

which is modified from code by thefourtheye:
Finding Combinations to the provided Sum value
timing it:
original code:
val = 24, t = 6.5917372703552253 seconds
val = 25, t = 13.705767631530762 seconds
val = 26, t = 27.934977531433105 seconds
val = 50, t = 459889248.39282094 seconds

above method:
val = 24, t = 0.0084612369537353 seconds
val = 25, t = 0.0069310665130615 seconds
val = 26, t = 0.0085859298706054 seconds
val = 50, t = 0.4947729110717773 seconds

A: There are probably many ways to improve the speed. I tried (and noticed that it makes a big difference) a simple one: getting rid of the repeated conversions between generators and lists. Here's your code, modified:
import time
import itertools

#val = int(input("val:"))
#r = range(val)[1:]

def simple_time_func(func):
    def wrapper(*args, **kwargs):
        start = time.time()
        r = func(*args, **kwargs)
        print("{} took {:.3f} seconds.".format(func.__name__, time.time() - start))
        return r
    return wrapper

@simple_time_func
def original(val, r):
    res = list()
    for i in range(len(r) + 1):
        res += [list(x) for x in itertools.combinations(r, i) if sum(list(x)) == val]
    return res

@simple_time_func
def improved0(val, r):
    res = list()
    for i in range(len(r) + 1):
        res += [x for x in itertools.combinations(r, i) if sum(x) == val]
    return res

for val in range(21, 28):
    r = range(val)[1:]
    print("\nval: {}".format(val))
    for func in (original, improved0):
        res = func(val, r)
        #print("    Solution : %s " % res)
        #print("    Combinations : %s" % len(res))

Notes:

*

*I took the expensive portion (the for loop) and encapsulated it in a function (original) in order to time it

*I placed the improved loop in another function (called it improved0)

*The rest of the code (unfortunately, also the most of it) is simply for performance testing

Output:

(py35x64_test) c:\Work\Dev\StackOverflow\q46853086>"c:\Work\Dev\VEnvs\py35x64_test\Scripts\python.exe" a.py

val: 21
original took 0.573 seconds.
improved0 took 0.325 seconds.

val: 22
original took 1.185 seconds.
improved0 took 0.633 seconds.

val: 23
original took 2.388 seconds.
improved0 took 1.300 seconds.

val: 24
original took 4.880 seconds.
improved0 took 2.609 seconds.

val: 25
original took 9.796 seconds.
improved0 took 5.243 seconds.

val: 26
original took 19.701 seconds.
improved0 took 10.489 seconds.

val: 27
original took 39.314 seconds.
improved0 took 21.559 seconds.

As the output shows, this apparently insignificant change almost cuts the time in half.
Next step consists of real optimization (as the computational complexity still looks exponential), regarding efficient usage of mathematical and programming skills, to improve the speed even more (unfortunately I'm running out of time).


text:
Q: 2 iPhones with iMessage and getting messages from one phone to the other I have a personal iPhone XR. A couple of weeks ago my boss wanted to get business cells for a few of us (I'm a customer facing landscape designer) so we could ignore work calls when we wanted to.  As a Mac/apple user for years but I'm no power user or anything, we selected 2020 iPhone SE.

*

*I want to push my personal texts through to my work phone so that during the day I can set my personal phone aside and not worry about it.

*I have both devices signed in to the same Apple ID and I think I set
it up right.

*Some things push through and some things don't.

Mostly what I've missed is group texts that include android users. At first I thought it was because it's only pushing iMessages through and not true SMS, but I miss texts from some android users but not all. Also I get regular SMS pushed through to my laptop and iPad....so that doesn't seem to line up.

Is there a general fix for having two phones, and allowing the personal one to forward everything to the work phone and being able to switch that on and off cleanly once a day?

A: SMS does not do group messages (well it might be up to the provider)
In the UK the phone providers will charge extra for MMS which do do group messages but not directly supported by Messages by default.
This is one reason to use WhatsApp, Signal etc.


text:
Q: Execute Java main method on a different thread with Maven I am converting my Ant project to a Maven project.
In Ant I am invoking a Java class but in a different thread using fork="yes" option in Ant.
Now I am trying to find a similar task in Maven.
I have code like the following, but I'm not sure if it is correct or not. It is calling my main class as expected, but it is running in the same thread/JVM.
<plugin>
    <groupId>org.codehaus.mojo</groupId>
    <artifactId>exec-maven-plugin</artifactId>
    <version>1.2.1</version>
    <executions>
        <execution>
            <phase>compile</phase>
            <goals>
                <goal>java</goal>
            </goals>
        </execution>
    </executions>
    <configuration>
        <mainClass>com.App</mainClass>
        <arguments>
            <argument>-s src/main/resources</argument>
        </arguments>
    </configuration>
</plugin>

Here com.App is a class which has a main method.
I need to run this in a different thread because the App.main() method contains a call to system.exit(), so the control is not coming back. As I am not authorized to change the App class, I have to call that in a different thread.

A: Try exec goal instead of java. The exec goal spawn a new process while java goal does not. See exec maven plugin doc.

A: just use the exec goal instead of the java goal and use JAVA_HOME/bin/java as the executable. This should do ;)


text:
Q: Script doesn't seem to be working, and I cannot understand why script dont work
I am incredibly new to scripting, and I was just fooling around in ROBLOX studio and I made a script that was INTENDED to put an item stored in ReplicatedStorage into a specific players StarterPack, but no matter what I change it does not want to work.
Could anyone explain why?
local playerName = "plr name"

local toolName = "tool name"

game.Players.PlayerAdded:Connect(function(player)
if player.Name == playerName then
local tool = game.ReplicatedStorage:FindFirstChild(toolName)
player.StarterPack:AddItem(tool)
end
end)

A: You are using an :AddItem() function which doesn't work. You must first clone the tool and add it into the players inventory.
Check the documentation on StarterPack if you are having issues: https://create.roblox.com/docs/reference/engine/classes/StarterPack
Try this:
local playerName = "plr name"
local toolName = "tool name"
local tool = game.ReplicatedStorage:FindFirstChild(toolName)

game.Players.PlayerAdded:Connect(function(player)
    if player.Name == playerName then
            local newTool = tool:Clone()
            newTool.Parent = player.Backpack
        end)
 end`

The StarterPack is used to determine a set of Tools that all players will spawn with. If a developer wants to ensure that certain Tools are available to specific players, then they will need to parent the Tools directly to the player's Backpack instead.

A: Your code is mostly fine, but you didn't close your PlayerAdded function, and the StarterPack doesn't have an AddItem function.
If you are having issues, you can always check the documentation for the StarterPack. One issue that I think you'll run into is that putting a tool into the StarterPack will give it to all players, not just the one who matches the name.

The StarterPack is used to determine a set of Tools that all players will spawn with. If a developer wants to ensure that certain Tools are available to specific players, then they will need to parent the Tools directly to the player's Backpack instead.

So instead let's clone the tool into the player's Backpack. But since the backpack gets cleared every time the player respawns, let's move this code into the CharacterAdded event, so it fires every time the character loads into the Workspace.
local playerName = "plr name"
local toolName = "tool name"
local tool = game.ReplicatedStorage:FindFirstChild(toolName)

game.Players.PlayerAdded:Connect(function(player)
    if player.Name == playerName then
        player.CharacterAdded:Connect(function()
            local newTool = tool:Clone()
            newTool.Parent = player.Backpack
        end)
    end
end)