text:
Q: Python while loop with string string = "Northeastern Africa"
myString = string.lower()
index = 0
num_index = int(index)

length = len(myString)
num_length = int(length)
num_length = num_length - 1

while myString[num_index] >=  myString[18]:
    print(num_index)
    print(num_length)
    print(myString[num_index])
    print(num_index)
    num_index = num_index +1
    print(myString[0:num_index])
    print(" ")

why does it only print "northeastern" and stops at the next space?  how do i make it go through the full string without stopping at the space in between both words?

A: Your while loop compares each character with the last, a, stopping when it finds a character that isn't equal or higher than a. Your code stops at the space because the latter's position in the ASCII table is 32:
>>> ' ' < 'a'
True
>>> ord(' ')
32
>>> ord('a')
97

You probably wanted to create a loop comparing num_index to num_length instead:
while num_index <= num_length:

If you wanted to loop through all characters in a string, just use a for loop:
for character in myString:
    print(character)

You can use the enumerate() function to add an index:
for index, character in enumerate(myString):
    print(index, character, sep=': ')
    print(myString[:index])

A: because myString[num_index] value is space
check this..
>>> " ">="a"
False


text:
Q: Applying Ito's formula to $D^x(t)=(\partial/\partial x)S(t)$ Let $\gamma:[0,T]\times (0,\infty)\to \mathbb{R}$ be continuous, bounded above, $(\partial/\partial s [\gamma(t,s)])$ is continuous in $(s,t)$. Consider the following process $$dS_{\gamma}^x(t)=S^x_{\gamma}(t)[r(t)dt+\gamma(t,S^x_{\gamma}(t))dW(t)]$$ where $W(t)$ is a one dimensional Brownian motion and $r(t)$ is an adapted process and $S^x_{\gamma}(0)=x$.
Now define the process $D^x(t)=(\partial/\partial x)S^x_{\gamma}(t)$. And this apparently satisfies $$dD^x(t)=D^x(t)\big[r(t)dt+\frac{\partial}{\partial s}\rho(t,S^x_{\gamma}(t))dW(t)\big]\rightarrow(1)$$ where $\rho(t,s):=s\gamma(t,s). $ I am not quite sure how equation (1) can be derived since $\gamma$ depends on $S^x_{\gamma}$. Maybe the idea is to apply Ito's formula to $D^x(t)$ by defining a function $f(t,s):=(\partial/\partial x)s $ and then the ito rule gives us $df=f_tdt+f_sdS^x_{\gamma}(t)+\frac{1}{2}f_{ss}dS^x_{\gamma}(t)dS^x_{\gamma}(t)$. I am not sure if what I am doing is even slightly correct. Any help is appreciated!

A: For your Ito process $S_{\gamma}^x(t)$, we focus on its time-differentiation as we write ${\rm d}S_{\gamma}^x(t)$. Since $x$ is an auxiliary parameter independent from $t$, we have that ${\rm d}$ and $\partial/\partial x$ commute with each other, i.e.,
$$
\frac{\partial}{\partial x}{\rm d}S_{\gamma}^x(t)={\rm d}\left(\frac{\partial}{\partial x}S_{\gamma}^x(t)\right)={\rm d}D^x(t).
$$
This is not a magic; it is just as if
$$
\frac{\partial}{\partial x}\left(\frac{\partial}{\partial t}f(x,t)\right)=\frac{\partial}{\partial t}\left(\frac{\partial}{\partial x}f(x,t)\right)
$$
for some differentiable function $f=f(x,t)$.
Therefore, act $\partial/\partial x$ on both sides of
$$
{\rm d}S_{\gamma}^x(t)=S_{\gamma}^x(t)\left(r(t)\,{\rm d}t+\gamma(t,S_{\gamma}^x(t))\,{\rm d}W(t)\right),
$$
and we obtain
\begin{align}
{\rm d}D^x(t)&=\frac{\partial}{\partial x}{\rm d}S_{\gamma}^x(t)\\
&=\frac{\partial}{\partial x}\left(S_{\gamma}^x(t)\left(r(t)\,{\rm d}t+\gamma(t,S_{\gamma}^x(t))\,{\rm d}W(t)\right)\right)\\
&=\frac{\partial}{\partial x}S_{\gamma}^x(t)\left(r(t)\,{\rm d}t+\gamma(t,S_{\gamma}^x(t))\,{\rm d}W(t)\right)\\
&+S_{\gamma}^x(t)\frac{\partial}{\partial x}\left(r(t)\,{\rm d}t+\gamma(t,S_{\gamma}^x(t))\,{\rm d}W(t)\right)\\
&=D^x(t)\left(r(t)\,{\rm d}t+\gamma(t,S_{\gamma}^x(t))\,{\rm d}W(t)\right)\\
&+S_{\gamma}^x(t)\,\frac{\partial}{\partial x}\gamma(t,S_{\gamma}^x(t))\,{\rm d}W(t)\\
&=D^x(t)\left(r(t)\,{\rm d}t+\gamma(t,S_{\gamma}^x(t))\,{\rm d}W(t)\right)\\
&+S_{\gamma}^x(t)\,\frac{\partial\gamma}{\partial s}(t,S_{\gamma}^x(t))\frac{\partial}{\partial x}S_{\gamma}^x(t)\,{\rm d}W(t)\\
&=D^x(t)\left(r(t)\,{\rm d}t+\gamma(t,S_{\gamma}^x(t))\,{\rm d}W(t)\right)\\
&+S_{\gamma}^x(t)\,\frac{\partial\gamma}{\partial s}(t,S_{\gamma}^x(t))\,D^x(t)\,{\rm d}W(t)\\
&=D^x(t)\left(r(t)\,{\rm d}t+\left(\gamma(t,S_{\gamma}^x(t))+S_{\gamma}^x(t)\,\frac{\partial\gamma}{\partial s}(t,S_{\gamma}^x(t))\right){\rm d}W(t)\right).
\end{align}
Note that
\begin{align}
&\gamma(t,S_{\gamma}^x(t))+S_{\gamma}^x(t)\,\frac{\partial\gamma}{\partial s}(t,S_{\gamma}^x(t))\\
&=\left(\gamma(t,s)+s\frac{\partial\gamma}{\partial s}(t,s)\right)\bigg|_{s=S_{\gamma}^x(t)}\\
&=\frac{\partial\rho}{\partial s}(t,s)\bigg|_{s=S_{\gamma}^x(t)}\\
&=\frac{\partial\rho}{\partial s}(t,S_{\gamma}^x(t)).
\end{align}
Hence, we eventually obtain
$$
{\rm d}D^x(t)=D^x(t)\left(r(t)\,{\rm d}t+\frac{\partial\rho}{\partial s}(t,S_{\gamma}^x(t))\,{\rm d}W(t)\right),
$$
as is desired.
In the above derivation, we merely use the commutativity between ${\rm d}$ and $\partial/\partial x$; Ito's formula is not necessary here.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Twig rendering into JSON object I have a twig template that I want to render, store in JSON object, and return as a response to a post request.
$response = json_decode('{"version":1,"status":"success"}', true);
$html = $this->render('DumoBundle:Test:Overlay.html.twig',
     array('left'=>3,'right'=>4));
$response['html'] = $html;
$response= new Response(json_encode($response));
return $response

However, when I print the JSON object to console on the browser side, I see that is is the following:
{"version":1,"status":"success","html":{"headers":{}}}

How can I store all the HTML in the html property of my JSON obejct?


text:
Q: Does the bias amplifier of the RLD amplifier need to be connected to reference electrode of the measurement sensor? I am using the MyoWare AT-04-001 muscle sensor and FSR400 force sensing resistor sensors with the ADS1299 amplifier and ADC and I need to improve the CMRR.
The datasheet mentions that an RC filter must be wired to the bias amplifier and connected to the reference electrode.
Does anyone have an idea how can I wire the MyoWare and FSR sensors to the ADS1299 because I don't have reference electrodes in my case?

A: Your MyoWare AT-04-001 muscle sensor may already have a connection for a reference electrode:

Page 5 of the datasheet you linked to shows how to connect external electrodes to the AT-04-001.
That sensor has all of the electronics needed to amplify the signal and to do "right leg drive" (RLD) as well as to do some preprocessing of the signal.
The output signal is amplified such that the output voltage ranges from 0V to the supply voltage of the module.
Adding amplification to that with the ADS1299 seems like overkill.

I have no experience with this kind of stuff, but from the datasheet it seems that the ADS1299 can completely replace the MyoWare AT-04-001 if you add electrode connectors.  You'll need a PCB but then if you are using the AD1299 at all you will probably already have had to make a board of some kind.

I would suggest testing the MyoWare AT-04-001 with external electrodes and a reference electrode.  I would almost bet that gives you a large improvement right there.
If that doesn't work, then consider using just the AD1299 with three electrodes (middle, end, and reference as described in the Myoware datasheet.)  The AD2199 should have all the gain (amplification) and other things (RLD) you need to build your own EMG.

The right leg drive cannot, of course, be used with the FSR400.  The FSR400 is just a variable resistor and cannot make use of RLD.
If you use RLD with the ADS1299, then you can't use the FSR400 on the same ADS1299 - as I understand it, the RLD applies to all channels, which would have the bias for the EMG messing with the FSR400.  You'll have to figure that out for yourself.


text:
Q: Determining $x_2$ in the solution of the system Task:
Determine $x_2$ in the solution of the system$$
\begin{bmatrix}4&a&0\\6&b&2\\9&c&3\end{bmatrix}\begin{bmatrix}x_1\\x_2\\x_3\end{bmatrix}=\begin{bmatrix}1\\2\\0\end{bmatrix}$$when$$
\left|\begin{matrix}4&a&0\\6&b&2\\9&c&3\end{matrix}\right|=4$$
using Cramer's rule.
Options to choose from:

*

*$-4$

*$4$

*$6$

*$-2$
My answer:
$$\begin{bmatrix}x_1\\x_2\\x_3\end{bmatrix}×4=\begin{bmatrix}1\\2\\0\end{bmatrix}$$
I got $x_2=\dfrac24$ which is not an option to choose. How do I do?

A: $\underline{\text{Cramer's rule:}}$ $x_i=\dfrac{\Delta_i}{\Delta }$ where $\Delta_i$ is the determinant of matrix $A$ with its $i^{th}$ column replaced by vector $b$ and $\Delta$ is the determinant of the matrix $A$.

$$x_2=\dfrac{\left|\begin{matrix}4 &1 &0\\6 &2 &2\\9 &0 &3\end{matrix}\right|}{4}=\dfrac{24}{4}=6$$


text:
Q: Modal "Loading..." dialogs not good UI decision? I've read on Reto Meier's blog that he doesn't recommend the use of modal "Loading..." dialogs in Android applications. Is this a general consensus among developers?
If I have a login screen what should I display when the user tries to sign in? Until now, I have used a "Signing in..." indeterminate progress dialog. Should I use the application's progress bar? Should I use a Toast?
And, in the general case, when should I use dialogs and when not to?

A: It seems that Reto Meier has recently addressed this issue. http://blog.radioactiveyak.com/2010/08/what-you-can-do-with-your-modal-dialogs.html
Basically, the idea in the article is that, generally, modal dialogs are the lazy developer's way of avoiding synchronizations/updates.


text:
Q: How to check super admin for WordPress multisite? I want to check super admin in wp_config.php and I've tried the following code without any result.
if (get_super_admins()) {
    echo 'You are super admin';
}

Kindly help me thanks.

A: Try this:
if ( is_super_admin() ) {
    echo 'You are super admin';
}

It will not work in wp-config.php as a user has not been loaded at this stage. There is essentially no user to check for.
Use it in your theme functions.php file or custom plugin code.


text:
Q: XSL/JScript difference in behaviour between Visual Studio and IE Can anyone tell me why the following XSL happily transforms the XML below in IE9, but the same transform fails under all versions of Visual Studio? If I open the XML file in IE 9, it gets transformed and the output is as expected, but if I attempt the same transform on the XML file in Visual Studio (using the 'Start XSLT' button on the toolbar) I get a JScriptException saying function expected on the line
var node = root.nextNode();

The fix seems to be to change the javascript function to do the following instead:
function test(root, attr)
{
  root.MoveNext();
  var node = root.Current;
  return node.Select("breakfast" + attr);
}

But this then fails the XSLT transform in IE! I can't seem to win!
XSL:
<!--<?xml version="1.0"?>-->
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:msxsl="urn:schemas-microsoft-com:xslt"
xmlns:user="urn:custom-scripts">
<msxsl:script language="JScript" implements-prefix="user">
  <![CDATA[
function test(root, attr)
{
  var node = root.nextNode();
  return node.selectSingleNode("breakfast" + attr);
}
]]>
</msxsl:script>
  <xsl:template match="/">
    <HTML>
      <BODY STYLE="font-family:Arial, helvetica, sans-serif; font-size:12pt;
            background-color:#EEEEEE">
          <xsl:value-of select="user:test(., '-menu')"/>
      </BODY>
    </HTML>
  </xsl:template>
</xsl:stylesheet>

Target XML:
<?xml version='1.0'?>
<?xml-stylesheet type="text/xsl" href="simple.xsl" ?>
<breakfast-menu>
  <food>
    <name>Belgian Waffles</name>
    <price>$5.95</price>
    <description>Two of our famous Belgian Waffles
      with plenty of real maple syrup.</description>
    <calories>650</calories>
  </food>
  <food>
    <name>Homestyle Breakfast</name>
    <price>$6.95</price>
    <description>Two eggs, bacon or sausage, toast,
      and our ever-popular hash browns.</description>
    <calories>950</calories>
  </food>
</breakfast-menu>

A: Well IE uses MSXML as its XSLT processor (I think IE 9 uses MSXML 6) while Visual Studio uses XslCompiledTransform. The APIs exposed by and used with MSXML and XslCompiledTransform differ vastly so don't expect extension function code written against the MSXML API to work with XslCompiledTransform and the .NET API. See http://msdn.microsoft.com/en-us/library/wxaw5z5e.aspx on how XSLT/XPath types are mapped to .NET types when you use extension functions. In your case you pass in a node-set and a string from XSLT, that maps to an XPathNodeIterator and a String in .NET.
Here is a quick attempt to rewrite your extension function for .NET:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:msxsl="urn:schemas-microsoft-com:xslt"
xmlns:user="urn:custom-scripts">
  <msxsl:script language="JScript" implements-prefix="user">
    <![CDATA[
function test(nodeIterator, string)
{
  nodeIterator.MoveNext();
  return nodeIterator.Current.SelectSingleNode("breakfast" + string);
}
]]>
  </msxsl:script>
  <xsl:template match="/">
    <HTML>
      <BODY STYLE="font-family:Arial, helvetica, sans-serif; font-size:12pt;
            background-color:#EEEEEE">
        <xsl:value-of select="user:test(., '-menu')"/>
      </BODY>
    </HTML>
  </xsl:template>
</xsl:stylesheet>

[edit]
Oops, I missed that you already found the .NET code yourself and only want to know how to write code against both XSLT processors. That is difficult. What is your target platform and your aim, do you want to write XSLT for IE but develop with VS? Or do you really need to use the same stylesheet within IE and on the .NET platform?
Here is an attempt to write one extension function for both type of processors:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:msxsl="urn:schemas-microsoft-com:xslt"
xmlns:user="urn:custom-scripts">
  <msxsl:script language="JScript" implements-prefix="user">
    <![CDATA[
function test(nodeSet, string)
{
  if (typeof nodeSet.nextNode !== 'undefined') {
    var node = nodeSet.nextNode();
    return node.selectSingleNode('breakfast' + string);
  }
  else if (typeof nodeSet.MoveNext !== 'undefined') {
    nodeSet.MoveNext();
    return nodeSet.Current.SelectSingleNode("breakfast" + string);
  }
}
]]>
  </msxsl:script>
  <xsl:template match="/">
    <HTML>
      <BODY STYLE="font-family:Arial, helvetica, sans-serif; font-size:12pt;
            background-color:#EEEEEE">
        <xsl:value-of select="user:test(., '-menu')"/>
      </BODY>
    </HTML>
  </xsl:template>
</xsl:stylesheet>

A: You will probably find that the browser embedded into Visual Studio is not IE9. It is most likely to be a version of IE8, or maybe IE7 dependant on which was the stable version when your Visual Studio was released.
I don't really know enough about XLST to explain why it doesn't work, but this may explain the differences in the behaviour you are seeing.

A: I wonder if this answer on SO will be relevant? IE9 selectSingleNode missing from beta, how to overcome this in JavaScript?


text:
Q: nestjs/graphql Nest can't resolve dependencies of the GraphQLModule... HttpAdapterHost at index [0] I have two package with their own package.json
{
  "name": "stock",
  "dependencies": {
    "@apollo/federation": "^0.37.1",
    "@apollo/subgraph": "^2.1.3",
    "@nestjs/apollo": "^10.0.9",
    "@nestjs/axios": "^1.0.0",
    "@nestjs/common": "^8.4.7",
    "@nestjs/core": "^8.4.4",
    "@nestjs/graphql": "^10.0.22",
    "@nestjs/platform-express": "^8.4.4",
    "apollo-server-core": "^3.10.2",
    "apollo-server-express": "^3.10.2",
  }
}

first package stock
@Module({
  imports: [
    GraphQLModule.forRoot<ApolloFederationDriverConfig>({
      driver: ApolloFederationDriver,
      typePaths: [join(__dirname, '..', 'src', 'schema.gql')],
      playground: false,
      plugins: [ApolloServerPluginLandingPageLocalDefault()],
    }),
  ],

})

export class StockModule { }

Second package test has the same package.json
In this package I want to test StockModule features
import { NestFactory } from '@nestjs/core';
import { StockModule } from 'stock'; // stock is defined in package.json
import { Module } from '@nestjs/common';

@Module({
  imports: [
    StockModule,
  ],
})
class TestModule { }

describe('Stock Module ', () => {
  beforeAll(async () => {
    const app = await NestFactory.createApplicationContext(TestModule);
  });
 });

Test are running with jest
When I try to launch the test nest throw me this error:
[Nest] 7278  - 12/02/2022, 11:00:56 AM   ERROR [ExceptionHandler] Nest can't resolve dependencies of the GraphQLModule (?, GqlModuleOptions, AbstractGraphQLDriver, GraphQLTypesLoader). Please make sure that the argument HttpAdapterHost at index [0] is available in the GraphQLModule context.

Potential solutions:
- If HttpAdapterHost is a provider, is it part of the current GraphQLModule?
- If HttpAdapterHost is exported from a separate @Module, is that module imported within GraphQLModule?
  @Module({
    imports: [ /* the Module containing HttpAdapterHost */ ]
  })

The version of @nestjs/* are the same, I even tried to copy the node_modules/@nestjs from stock package to test package and I still have the same issues,


text:
Q: Adding elements of a Scala array in pair-wise fashion Scala 2.12 here, and new to Scala. I am given an Array[Double] which represents the CPU load (%) of all the logical processors on my local system:
val logicalProcessorLoads : Array[Double] = cpu.getProcessorCpuLoadBetweenTicks

For the sake of this question, the # of logical processors is 2x the number of physical processors or "cores" on the machine.
So on a quad-core machine, there would be 8 logical processors, and so the value of this logicalProcessorLoads array at any point in time might be something like:

[ 12.4, 2.2, 10.0, 5.0, 23.7, 18.9, 1.1, 11.2 ]

So to get the CPU load for all 4 cores at any given point in time requires me to iterate through this 8-item array and add each subsequent pair of elements together, hence:

*

*Core #1 CPU load is 12.4 + 2.2 = 14.6%

*Core #2 CPU load is 10.0 + 5.0 = 15.0%

*Core #3 CPU load is 23.7 + 18.9 = 42.6%

*Core #4 CPU load is 1.1 + 11.2 = 12.3%

etc. I'm trying to find the most concise + clean way of doing this pair-wise addition on my array, with the output being a perCoreLoads : Array[Double] with 4-elements in it, each element representing the load for each of my 4 cores. My best attempt so far:
var perCoreLoads : Array[Double] = Array()
for((lpl,i) <- logicalProcessorLoads.zipWithIndex) {
  if(i+1 <= logicalProcessorLoads.size - 1) {
    perCoreLoads :+ (lpl(i) + lpl(i+1))
  }
}

But this seems a little convoluted and I'm sure Scala's got some magic to help me out here. Any ideas?

A: Use grouped with map:
logicalProcessorLoads.grouped(2).map(_.sum).toList

gives:
List(
  14.600000000000001,
  15.0,
  42.599999999999994,
  12.299999999999999
)

To understand it better, look at the intermediate result returned by grouped(2):
List(
  List(12.4, 2.2),
  List(10.0, 5.0),
  List(23.7, 18.9),
  List(1.1, 11.2)
)

those are exactly the summands from the lines in your manually generated table.

A: Sliding with Map Approach
An alternative to @andrey-tyukin answer is to use sliding with map:
logicalProcessorLoads.sliding(2, 2).map(_.sum).toList

gives:
List(
    14.600000000000001,
    15.0,
    42.599999999999994,
    12.299999999999999
)

The intermediate result will also be very similar to grouped, but sliding and grouped are quite different. Sliding will fit this use case as well.

Sliding Approach (slightly descriptive to your example):
val perCoreLoads = for {
  lpl <- logicalProcessorLoads.sliding(2, 2)
} yield lpl(0) + lpl(1)

println(perCoreLoads.toList)

gives:
List(
    14.600000000000001,
    15.0,
    42.599999999999994,
    12.299999999999999
)


text:
Q: Neon Animated Pages not within Paper Material My Neon Animated Pages will not display inside my Paper Material.
Here you can see in my bare-bones example that my neon animated pages will not display inside the paper material. The Paper Material is outlined by a red border. In theory the paper material should have a bottom border and borders along the right and left side that also encompass the blue div. My best guess is that it is a CSS rule in the neon-animated-pages element itself that is overriding the correct behavior. Any help would be appreciated, thanks in advance.

Code for bare-bones exapmle:
    <!DOCTYPE html>

        <meta name="viewport" content="width=device-width, initial-scale=1">

        <link rel="import" href="bower_components/iron-flex-layout/iron-flex-layout.html">
        <link rel="import" href="bower_components/neon-animation/neon-animation.html">
        <link rel="import" href="bower_components/neon-animation/neon-animated-pages.html">
        <link rel="import" href="bower_components/neon-animation/neon-shared-element-animatable-behavior.html">

        <link rel="import" href="bower_components/paper-material/paper-material.html" >

        <test-iron-page></test-iron-page>

<dom-module id="test-iron-page">

    <template>

        <paper-material elevation="2">

Header

            <neon-animated-pages id="nap" selected="0">

I am a div

I am a div

            </neon-animated-pages>

        </paper-material>

    </template>

</dom-module>

A: Specify the height of the paper-material, Here is the working demo with height:300px; for paper-material.

  <title>Template me</title>

  <base href="https://cdn.rawgit.com/download/polymer-cdn/1.0.1/lib/">
  <link rel="import" href="polymer/polymer.html">
  <link rel="import" href="neon-animation/neon-animation.html">
        <link rel="import" href="neon-animation/neon-animated-pages.html">
        <link rel="import" href="neon-animation/neon-shared-element-animatable-behavior.html">

        <link rel="import" href="paper-material/paper-material.html" >
  <link rel="import" href="paper-button/paper-button.html" >

        <test-iron-page></test-iron-page>

<dom-module id="test-iron-page">

    <template>

        <paper-material elevation="2">

Header

            <neon-animated-pages id="nap" selected="0">

I am a div

I am a div

            </neon-animated-pages>

        </paper-material>
<paper-button raised on-tap="_next">Next Page</paper-button>
    </template>

</dom-module>


text:
Q: CDI producer method not working if defining class doesn't declare a scope I'm running some proof of concept in a local Glassfish 4.1.1 (WELD 2.2.2) installation about CDI.
I've created a class bean named TipicalBean which injects an integer produced in a producer method.
The class defining the producer method looks like this
public class ProducerTest {

    @Produces @MyNumber @Dependent public static int getMyNumber() {
        return 100;
    }
}

This doesn't work. Even if I declare the method static
But it does work if if put the @Dependent scope in the class definition, like this:
@Dependent
public class ProducerTest {

In addition, if I declare that producer method in the same class which is injecting it, I can define the @Dependent scope in the producer method declaration, but WELD prints a warning in Glassfish console
WELD-000018: Executing producer field or method [BackedAnnotatedMethod] @Produces
@MyNumber @Dependent public mypackage.TipicalBean.produceMyNumber() on incomplete
declaring bean Managed Bean [class mypackage.TipicalBean] with qualifiers [@Any
@Default] due to circular injection

Why's that? Is that Producer Methods must be defined within ManagedBeans?
As I'm using JavaEE 7, I have not created the beans.xml file.
Thanks

A: From the CDI spec:

A producer method must be a default-access, public, protected or
  private, non-abstract method of a managed bean class or session bean
  class.


text:
Q: WCF Silverlight HTTP AND HTTPS I've got a Silverlight app that I want to call from either https or http.
I've got it working with one or the other but am having problems making it work with both (with a single web.config)
I've found a post on silverlight.net forums that shows how they did it but it is not working for me. http://silverlight.net/forums/t/13275.aspx (the post marked as the answer)
Am I missing something?
If I browse to the https url for the service it gives me the mex description page but if I browse to the http site for the service I get;
"Could not find a base address that matches scheme https for the endpoint with binding BasicHttpBinding. Registered base address schemes are [http]."

A: If you can't even see the service over http, then that would explain why Silverlight cannot connect to the http service.
Make sure that in your service you define both an HTTP and an HTTPS endpoint.  Posting the .config file for your service may be helpful if possible.
Here is a related SO question Can a service have multiple endpoints?
If you can see the service description for both http and https just through the browser, then you can try to get Silverlight to connect to either service.


text:
Q: Form validation is ignored when it is submited with ajax I have this javascript function in my page.
$(document).ready(function(){
    $('input[type="radio"]').click(function(){
        if($(this).attr("value")=="InfiStallStock"){
            $(".e-stock-saldo-box").hide();
            $(".InfiStall ul li .infistallLocation").attr('required');
            $(".Delivery ul input:radio").removeAttr('required');
            $(".Delivery ul input:text").removeAttr('required');
            $(".InfiStall").show();
        }
        if($(this).attr("value")=="DeliveryStock"){
            $(".e-stock-saldo-box").hide();
            $(".InfiStall ul li .infistallLocation").removeAttr('required');
            $(".Delivery ul li input:radio").attr('required');
            $(".Delivery ul input:text").attr('required');
            $(".Delivery").show();
        }
    });
});

            function enableList(element) {
                var select = document.getElementById("select"+element.id.substring(element.id.length-9));
                enableSubmit();
                showUp();
                if(element.checked === true){
                    select.disabled = false;
                    checkSelect(select);
                }else{
                    select.disabled = true;
                    select.selectedIndex = 0;
                }
            }
            function checkSelect(element){
                if(!validate_select(element)){
                    element.setCustomValidity("Pilih Jumlah Estock");
                }else{
                    element.setCustomValidity("");
                }
            }

This javascript functioned to check which option select by user. If user choose one option, then another option which has required input will be ignored/removed, and vice versa.
The javascript is working great in validate the form if I submit the form directly with form action like <form action="submit.php"/>.
However, when I change the way to submit it which is now with ajax, the validation is ignored.
Here is the ajax script to submit the form:
$('#btn_submit').on('click', function(e) {
    e.preventDefault();

    var esquantity = $('.row_selected select').map(function() { return $(this).val(); }).get().join('|');
    var size = $('.row_selected td.size span').map(function() { return $(this).text(); }).get().join('|');

    $.ajax(
    {
        type: "POST",
        url: "../ajax.php",
        data: 'esquantity='+esquantity+ '&size='+ size,
        cache: false,
        success:function(html)
        {
            alert("Succes " + html);
        }
    });

Can anybody help me how to solve this please, so that this form will have some validations even though I submit it with ajax. Thanks!

A: Try -
Writing this below event on the normal button rather than on the submit button
$('#btn_submit').on('click', function(e) {

Which will then require you not to call the
e.preventDefault();

in the function and what you can do then is to call the submit() function explicitly in the ajax call's callback area i.e.
success:function(html)
{
    // call submit function explicitly it should validate all your constraints then
}


text:
Q: rustc shows downstream crates may implement trait pub mod traits {
    pub trait Foo<T> {}
    pub trait Bar<T> {}
    impl<T, U: Foo<T>> Bar<T> for U {}
}
pub struct Test {}
impl<T> traits::Bar<T> for Test {}

fn main() {}

rust playground
it shows :
Compiling playground v0.0.1 (/playground)
error[E0119]: conflicting implementations of trait `traits::Bar<_>` for type `Test`
 --> src/main.rs:8:1
  |
5 |     impl<T, U: Foo<T>> Bar<T> for U {}
  |     ------------------------------- first implementation here
...
8 | impl<T> traits::Bar<T> for Test {}
  | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ conflicting implementation for `Test`
  |
  = note: downstream crates may implement trait `traits::Foo<_>` for type `Test`

For more information about this error, try `rustc --explain E0119`.
error: could not compile `playground` due to previous error

is that a feature or a bug?

A: There is a potential collision:
impl<T, U: Foo<T>> Bar<T> for U {}

This means that all types that implement Foo also implement Bar.
This, however:
impl<T> traits::Bar<T> for Test {}

means that Test implements Bar. The problem here is that Test could implement Foo for T types not yet known in this crate.
Like, if another crate defines a type MyStruct, and implements Foo<MyStruct>:
struct MyStruct {}

impl Foo<MyStruct> for Test {}

that's perfectly fine from the standpoint of the other crate. It creates the ambiguity, though, that the compiler now doesn't know which implementation of Bar<MyStruct> should use:

*

*impl<MyStruct, U: Foo<MyStruct>> Bar<MyStruct> for U {} with U being Test

*impl<T> traits::Bar<T> for Test {} with T being MyStruct
To avoid this ambiguity, the compiler disallows you from writing that code in the first place.


text:
Q: Unresolved reference to DaggerApplicationComponent I can't handle error related to Dagger and it's generation of component.
import android.app.Application
import dagger.Component

@Component(modules = arrayOf(ApplicationModule::class))
interface ApplicationComponent{
    fun inject(app: Application)
}

The place where component is called looks like that
class MyAwesomeApplication : Application(){
    val component: ApplicationComponent by lazy {
        DaggerApplicationComponent.builder().appModule(ApplicationModule(this)).build()
    }

    override fun onCreate() {
        super.onCreate()
        component.inject(this)
    }
}

In gradle build file I have set up:
implementation "com.google.dagger:dagger:$dagger_version"
implementation "com.google.dagger:dagger-android:$dagger_version"
implementation "com.google.dagger:dagger-android-support:$dagger_version"
kapt "com.google.dagger:dagger-android-processor:$dagger_version"

Also the stub generation is turned on and kotlin-kapt has been applied
Any ideas what is wrong there?

A: Your build.gradle should look something like this
apply plugin: 'kotlin-kapt'
…
dependencies {
…
    final dagger_version = '2.17'
    implementation "com.google.dagger:dagger:$dagger_version"
    kapt "com.google.dagger:dagger-compiler:$dagger_version"
    compileOnly 'javax.annotation:javax.annotation-api:1.3.2'
}

I think what you are missing is compileOnly 'javax.annotation:javax.annotation-api:1.3.2'. I have an article for detailed steps to setup Dagger.

A: app.gradle
apply plugin: 'kotlin-kapt'

android {
kapt {
  generateStubs = true
}
}

// Dagger 2
implementation "com.google.dagger:dagger:$dagger2_version"
kapt "com.google.dagger:dagger-compiler:$dagger2_version"

Build -> Rebuild project

A: For me it was a gradle dependency issue. Solved it by adding the following to the app.gradle script:
apply plugin: 'kotlin-kapt'
.
.
dependencies {
    .
    .
    kapt "com.google.dagger:dagger-compiler:$dagger2_version"
    kapt "com.google.dagger:dagger-android-processor:$dagger2_version"
}

Then I cleaned and rebuilt the project.

A: For me its because of dagger version. By using the below version resolved the issue for me.

plugins {
    id 'com.android.application'
    id 'kotlin-android'
    id 'kotlin-kapt'
}

dagger_version = '2.17'
    implementation "com.google.dagger:dagger:$dagger_version"
    kapt "com.google.dagger:dagger-compiler:$dagger_version"


text:
Q: LINQ query optimization? I have a large unsorted list of items.  Some items are important and need to listed first, followed by unimportant items.  The items should be sorted by name in the two groups.  I have a solution, but I believe it can be optimized.  First, it gets a list of important items.  Then a list of everything else, then concatenates the results.  Any suggestions on how to optimize this?
Here is a simplified version of the problem for LINQPad:
var doc = XDocument.Parse(@"
<items>
    <item id='a'>not important4</item>
    <item id='b'>important2</item>
    <item id='c'>not important2</item>
    <item id='d'>not important3</item>
    <item id='e'>important1</item>
    <item id='f'>not important1</item>
</items>");
// identify which items are important
string[] importantItemIDs = new string[] { "b", "e" };
var items = doc.Root.Elements("item");

// get a list of important items (inner join)
var importantList = from itemID in importantItemIDs
            from item in items
            orderby (string) item.Value
            where itemID == (string) item.Attribute("id")
            select item;

// get items that are not important items
var notImportantList = items.Except(importantList).OrderBy(i => (string) i.Value);

// concatenate both sets of results into one list
var fullList = importantList.Concat(notImportantList);
fullList.Select(v => v.Value).Dump();

Here's the correct output:
important1
important2
not important1
not important2
not important3
not important4

A: One approach that immediately comes to mind is to utilize OrderBy as well as ThenBy to avoid querying the original data source multiple times. Something like:
var list = items
       .OrderBy(i => importantItemIDs.Contains(i.Attribute("id") ? 0 : 1)
       .ThenBy(i => i.Value);
       .Select(i => i.Value);

I'm not sure if the ternary operator is necessary there - I forget how OrderBy deals with boolean results. Shouldn't be a major performance concern anyway and is potentially a bit clearer.

A: var prioritized =
        from item in items
        select new {
        Importance = importantItemIDs.Contains((string) item.Attribute)? 1 :2,
        Item = item
        };

var fullList =   from pitem in prioritized
                 orderby pitem.Importance, pitem.Item.Value
                 select pitem.Item.Value;


text:
Q: Send 3 javascript arrays to c# server side code I am fetching an XML format data and assigning it to a treeview. The XML Data has an ID attribute attached to it. On client side I am getting all the selected nodes of the treeview. I am able to fetch the name of the node from the control. Now I want to get that ID attribute so that I can send it as a reference ID. How can I get the ID of the selected nodes in JavaScript?
I am using DevExpressTreeView.

A: window.getSelection().getRangeAt(0).commonAncestorContainer
This help to get the id of selected node.


text:
Q: Batch script to rename files with uppercase in first letter of each word I want to create a batch script to rename files in a folder. I want to uppercase the first letter of each word in files names, for every files extensions. I consider a space, an underscore or a parenthesis as a delimiter between words.
For example:
24 true STORIES.txt -> 24 True Stories.txt
age of empire (full version).exe -> Age Of Empire (Full Version).exe
italian_food_in_30_recipes.pdf -> Italian_Food_In_30_Recipes.pdf
NEW_YORK_CITY.jpeg -> New_York_City.jpeg
the white dog.mp3 -> The White Dog.mp3

I found related posts about this, as @Squashman noticed, but I can't write a full script. Here are my first steps:
@ECHO OFF
SETLOCAL ENABLEDELAYEDEXPANSION

:: Input
SET /P DIR="Path to folder: "

:: Check the last character in the user input path
IF NOT !DIR:~-1! == "\" SET DIR=!DIR!\

:: Scan files in input folder
FOR %%F IN (%DIR%*) DO (
    SET "BASENAME=%%~NXF"
    SET "NAME=%%~NXF"
    SET "F=TRUE"
    SET "NEWNAME="
    SET "DELIM=FALSE"
    SET "UNDERSCORE=_"
    SET "SPACE= "
    SET "PARENTHESIS=("
    CALL :CONVERT
)

:CONVERT

:: Lowercase
FOR %%A IN (a b c d e f g h i j k l m n o p q r s t u v w x y z) DO (
    SET "NAME=!NAME:%%A=%%A!"
   )
)

:: Uppercase
SET "L=!NAME:~0,1!"
IF %F% == TRUE (
  SET "INITIAL=!L!"
  FOR %%I IN (A B C D E F G H I J K L M N O P Q R S T U V W X Y Z) DO SET INITIAL=!INITIAL:%%I=%%I!
  SET NEWNAME=!NEWNAME!!INITIAL!
) ELSE (
  SET NEWNAME=!NEWNAME!!L!
)

:: Detect delimiter
IF "!L!" == "!UNDERSCORE" (
    SET "DELIM=TRUE"
) ELSE (
    SET "DELIM=FALSE"
)
IF "!L!" == "!SPACE!" (
    SET "DELIM=TRUE"
) ELSE (
    SET "DELIM=FALSE"
)
IF !DELIM! == TRUE (
  SET "F=TRUE"
) ELSE (
  SET "F=FALSE"
)

:: Output
SET "NAME=!NAME:~1!"
IF DEFINED NAME GOTO CONVERT
IF NOT %DIR%!BASENAME! == %DIR%!NEWNAME! REN "%DIR%!BASENAME!" "!NEWNAME!"

:: End
EXIT /B

This return me:
24 True Stories.txt -> ok
Age Of Empire (full Version).exe -> not ok
Italian_food_in_30_recipes.pdf -> not ok
New_york_city.jpeg -> not ok
The White Dog.mp3 -> ok

How can I merge/combine severals if conditions (underscore, space, parenthesis...) ?
If I switch their order in script, result isn't the same. I don't find an easy explanation about logical operators to use an or statement like if "!L!" == "!UNDERSCORE!" or "!L!" == "!SPACE!" or "!L!" == "!PARENTHESIS!".

A: I improved my script to detect underscores, spaces and parenthesis as delimiters. It's close to be the expected behaviour.
@ECHO OFF
SETLOCAL ENABLEDELAYEDEXPANSION

:: Input
SET /P DIR="Path to folder: "

:: Check the last character in the user input path
IF NOT !DIR:~-1! == "\" SET DIR=!DIR!\

:: Scan files in input folder
FOR %%F IN (%DIR%*) DO (
    SET "BASENAME=%%~NXF"
    SET "NAME=%%~NXF"
    SET "F=TRUE"
    SET "NEWNAME="
    SET "DELIM=FALSE"
    SET "UNDERSCORE=_"
    SET "SPACE= "
    SET "PARENTHESIS=("
    CALL :CONVERT
)

:CONVERT

:: Lowercase
FOR %%I IN (a b c d e f g h i j k l m n o p q r s t u v w x y z) DO SET "NAME=!NAME:%%I=%%I!"

:: Uppercase
SET "L=!NAME:~0,1!"
IF %F% == TRUE (
    SET "INITIAL=!L!"
    FOR %%I IN (A B C D E F G H I J K L M N O P Q R S T U V W X Y Z) DO SET INITIAL=!INITIAL:%%I=%%I!
    SET NEWNAME=!NEWNAME!!INITIAL!
    SET "DELIM=FALSE"
) ELSE (
    SET NEWNAME=!NEWNAME!!L!
)

:: Detect delimiter
IF "!L!" == "!UNDERSCORE!" SET "DELIM=TRUE"

IF "!L!" == "!SPACE!" SET "DELIM=TRUE"

IF "!L!" == "!PARENTHESIS!" SET "DELIM=TRUE"

IF !DELIM! == TRUE (
    SET "F=TRUE"
) ELSE (
    SET "F=FALSE"
)

:: Output
SET "NAME=!NAME:~1!"
IF DEFINED NAME GOTO CONVERT
IF NOT %DIR%!BASENAME! == %DIR%!NEWNAME! REN "%DIR%!BASENAME!" "!NEWNAME!"

:: End
EXIT /B

When I run this I still have an issue on the last file name:
24 true STORIES.txt -> 24 True Stories.txt
age of empire (full version).exe -> Age Of Empire (Full Version).exe
italian_food_in_30_recipes.pdf -> Italian_Food_In_30_Recipes.pdf
NEW_YORK_CITY.jpeg -> New_York_City.jpeg
the white dog.mp3 -> The White Dog.mp3
The White Dog.mp3 -> The White Dog.mp3a=a

A suffix a=a is added to the last file name, after extension. You will also notice that the last file name is renamed twice. I found this documentation (8.3 Filename bug - a single command can rename the same file twice!) about this behaviour but I dont understand how to solve this bug.
Any ideas ?


text:
Q: Ajuda com Vetor na Logica de programação A ideia é que imprima de acordo com a condição, só que estou perdido na lógica, pois não tem como uma posição do vetor receber os dois valores.
#include <stdio.h>

int main (){

    int N,X[1000],i,band=0;
    scanf("%d",&N);
    for (i=0; i<N ;i++) {
        scanf("%d", &X[i]);
        if(X[i]== 3 && (X[i] == 5))
        {
            band++;
        }
    }

    if(band!=0)
        printf("Vetor certo");
    else
        printf("Vetor errado");

    return 0;

}

A: A condição certa seria ou (representada por ||).
if (X[i]== 3 || X[i] == 5) {
    band++;
}

Ou seja, caso o valor de X[i] seja 3 ou seja 5, a condição será verdadeira.

A: Pelo que posso entender, você apenas confundiu os operadores lógicos "E" com o "OU"
Apenas algumas dicas de boas práticas, evite criar variaveis iniciando com letra maiscúla, e existe um modo de fazer esse exercicio sem definir um valor exato para o tamnho do vetor, caso queira é so avisar!
int main()
{
    int N;
    int X[1000];
    int i;
    int band=0;
    scanf("%d",&N);
    for (i=0; i<N ; i++)
    {
        scanf("%d", &X[i]);
        if(X[i]== 3 || (X[i] == 5))
        {
            band++;
        }
    }

    if(band!=0)
        printf("Vetor certo");
    else

        printf("Vetor errado");

    return 0;
}

A: Código:
if (X[i]== 3 || X[i] == 5) {
    band++;
}


text:
Q: executing sql from vbscript which contains multiple single quotes Executing the above query to create a new db from vbscript. This is the function that I came up with. Any other sql query would work fine with this, except this. I guess I dont know how I can
make vbscript escape the single quotes.
executeQuery("IF  NOT EXISTS (SELECT name FROM master.dbo.sysdatabases WHERE name = 'temp')

CREATE DATABASE temp")
Function executeQuery(query)
Const DB_CONNECT_STRING = "Provider=SQLOLEDB.1;Data Source=localhost;Trusted_Connection=True;persist security info=True;Integrated Security=SSPI;"'
Set myConn = CreateObject("ADODB.Connection")
Set myCommand = CreateObject("ADODB.Command" )
myConn.Open DB_CONNECT_STRING
Set myCommand.ActiveConnection = myConn
'myCommand.CommandText = query
myCommand.CommandText = query
myCommand.Execute
myConn.Close
End Function

'


text:
Q: Can you disprove this counterexample to the diagonal lemma? I was looking at the Diagonal Lemma or Fix point theorem which states in every Theory $T$ every formula with one variable $ B(n) $ has a fix point: $T \vdash G \leftrightarrow B(\# G)$.
Where $\#F$ denotes the Gödel number for $F$ and $n$ is a natural number.
https://plato.stanford.edu/entries/goedel-incompleteness/sup2.html
https://en.wikipedia.org/wiki/Diagonal_lemma
Let $F=\%N$ denote the the inverse of $N=\#F$ (taking a number $N$ from the set of Gödel numbers of syntactically correct formulas and return said formula)
It is easy to see that the formula $A(N) := \lnot \%N$ cannot have a fixpoint, since $A(\#D) = \lnot D \leftrightarrow D$ is a contradiction for all statements $D$.
What part about this counterexample is wrong?

A: The "formula" $\neg\%N$ is not actually a formula in the relevant language, so the diagonal lemma doesn't apply to it. In fact, you've basically written an impossibility proof: that there's no way, inside the language itself, to "unpack" a coded sentence so that it can be operated on via Booleans etc. This turns into Tarski's undefinability theorem.


text:
Q: Spark join *without* shuffle I am trying to optimise my spark application job.
I tried to understand the points from this question: How to avoid shuffles while joining DataFrames on unique keys?

*

*I have made sure that the keys on which join operation has to happen are distributed within the same partition (using my custom partitioner).

*I also cannot do a broadcast join because my data may be come large depending on situation.

*In the answer of above mentioned question, repartitioning only optimises the join but What I need is join WITHOUT A SHUFFLE. I am just fine with the join operation with the help of keys within the partition.
Is it possible? I want to implement something like joinperpartition if similar functionality does not exists.

A:
repartitioning only optimises the join but What I need is join WITHOUT A SHUFFLE

This is not true. Repartition does not only "optimize" the join. Repartition binds a Partitioner to your RDD, which is the key component for a map side join.

I have made sure that the keys on which join operation has to happen are distributed within the same partition

Spark must know about this. Build your DataFrames with the appropriate api's so that they have the same Partitioner, and spark will take care of the rest.

A: just an addition to previously good answers.
If you are joining a big dataframe multiple times throughout your pyspark application then save that table as bucketed tables and read them back in pyspark as dataframe. this way you can avoid multiple shuffles during join as data is already pre-shuffled and sorted.
so when Spark chooses sort merge join on two large dataframe, it will skip the sort and shuffle phase during your join operations. (you can confirm it in spark UI while looking at wholecodegen)
df_data_1.coalesce(1).write.format('orc').bucketBy(20, 'joincolumn').sortBy("sortcolumn").mode("overwrite").saveAsTable('bucketed_table1')

df_data_2.coalesce(1).write.format('orc').bucketBy(20, 'joincolumn').sortBy("sortcolumn").mode("overwrite").saveAsTable('bucketed_table2')

df_bucket_table_1 = spark.table("bucketed_table1");
df_bucket_table_2 = spark.table("bucketed_table2");

spark.conf.set("spark.sql.autoBroadcastJoinThreshold", -1)
spark.conf.set("spark.sql.join.preferSortMergeJoin","true")

 #creating alias for the dataframes:
from pyspark.sql.functions import *

df1 = df_bucket_table_1.alias('df1')
df2 = df_bucket_table_2.alias('df2')

DfInnerJoin = df1.join(df2, df1.joincolumn == df2.joincolumn,'inner').select('df1.*')

The above join will have no shuffling but this is useful only when you have to join same dataframe multiple times throughout the application.


text:
Q: 3 tables joining using left join in mysql I have total 4 tables. The data below is dummy data but the structure is same with my original db.
Table -- ms1    Table -- ms2          Table -- ms3

msoneid         mstwoid               msthreeid
3               11                    79
4               12                    83
5               14                    84
6               17                    85

Master table -- ms

rid                hid                   tie
11                 3                     33
11                 5                     44
12                 12                    55
12                 84                    66
13                 79                    77
13                 17                    88

What I want
hid           tie
3             33
4             0
5             44
6             0
11            0
12            55
14            0
17            88
79            77
83            0
84            66
85            0

My query is
select * from ms where rid in (11,12,13) and this is not giving me the other absent ids which are in other 3 tables obviously because it's not joined.I tried with left join but I messed it up.
Any help/hint/example is highly welcomed. Thanks in advance.

A: Probably a union query would work here
SELECT ms1.msoneid as hid, ms.tie FROM ms1 LEFT JOIN ms ON ms1.msoneid=ms.hid WHERE ms.rid in(11,12,13)
UNION
SELECT ms2.mstwoid as hid, ms.tie FROM ms2 LEFT JOIN ms ON ms2.mstwoid=ms.hid WHERE ms.rid in(11,12,13)
UNION
SELECT ms3.msthreeid as hid, ms.tie FROM ms3 LEFT JOIN ms ON ms3.msthreeid=ms.hid WHERE ms.rid in(11,12,13)

Here's a sql fiddle
To sort the records you could make the series of queries above a sub query.
SELECT * FROM (
  SELECT ms1.msoneid as hid, ms.tie FROM ms1 LEFT JOIN ms ON ms1.msoneid=ms.hid WHERE ms.rid in(11,12,13)
  UNION
  SELECT ms2.mstwoid as hid, ms.tie FROM ms2 LEFT JOIN ms ON ms2.mstwoid=ms.hid WHERE ms.rid in(11,12,13)
  UNION
  SELECT ms3.msthreeid as hid, ms.tie FROM ms3 LEFT JOIN ms ON ms3.msthreeid=ms.hid WHERE ms.rid in(11,12,13)
) as tempTbl
ORDER BY tempTbl.hid;

A: select      alias_master.*
from        ms alias_master
left join   ms1 alias_ms1 on alias_master.rid = alias_ms1.msoneid
left join   ms2 alias_ms2 on alias_master.rid = alias_ms2.mstwoid
left join   ms3 alias_ms3 on alias_master.rid = alias_ms3.msthreeid
where       ms.rid in(11,12,13)

not sure if i get what you mean, but this might help.


text:
Q: How to mock a function called as default argument I have a class containing a timestamp. In the init function the initial timestamp is set to the argument provided, with a default value of 'time.monotonic()'. I also have and update function that sets the timestamp, also using time.monotonic()
When unit-testing this class I want to mock out time.monotonic, to get a predictable result.
However, the call in the default argument is always to the real time.monotonic
ClassWithTimestamp.py:
import time

class ClassWithTimestamp:
    def __init__(self, value={}, timestamp=time.monotonic()):
        self.timestamp = timestamp

    def update(self):
        self.timestamp = time.monotonic()

ClassWithTimestampTest.py:
import unittest
from unittest import mock

import ClassWithTimestamp

class ClassWithTimestampTest(unittest.TestCase):
    def setUp(self):
        ClassWithTimestamp.time.monotonic = mock.Mock(name='now')
        ClassWithTimestamp.time.monotonic.return_value = 1000

    def tearDown(self):
        pass

    def test_init(self):
        sut = ClassWithTimestamp.ClassWithTimestamp()
        self.assertEqual(sut.timestamp, 1000)

    def test_update(self):
        sut = ClassWithTimestamp.ClassWithTimestamp()
        sut.update()
        self.assertEqual(sut.timestamp, 1000)

if __name__ == '__main__':
    unittest.main()

When run:
python3 ClassWithTimestampTest.py -v
test_init (__main__.ClassWithTimestampTest) ... FAIL
test_update (__main__.ClassWithTimestampTest) ... ok

======================================================================
FAIL: test_init (__main__.ClassWithTimestampTest)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "ClassWithTimestampTest.py", line 16, in test_init
    self.assertEqual(sut.timestamp, 1000)
AssertionError: 762811.874163785 != 1000

----------------------------------------------------------------------
Ran 2 tests in 0.001s

FAILED (failures=1)

A: I found this:
"Least Astonishment" and the Mutable Default Argument
It explains my problem, the default argument is called at the time of defining the init function, not executing it.
So my code was buggy to begin with as I intended the timestamp to be set to the construction time.
My revised code is
def __init__(self, value={}, timestamp=None):
    if timestamp:
        self.timestamp = timestamp
    else:
        self.timestamp = time.monotonic()

The problem itself still stands, the only way I see is to overwrite the member of the class after construction with the output of the mocked function.


text:
Q: jQuery's nyroModal with ASP.NET I'm using nyroModal plugin. By simply putting a setup scripts in the head tag and define a class attribute with nyroModal will make that link open as a modal window.
Show

Now, Page1.aspx will open in a modal window. This page has a simple asp:button having a OnClick defined with empty body:
<asp:button ID="btn" runat="server" OnClick="btn_Click"/>

void btn_Click(Object sender,  EventArgs e) {  }

If we click on the above link a window appears with a button and when I click on that button modal windows disappears (or break) and redirected to Page1.aspx.
Any idea, why is this happening?

A: Try adding the following:
jQuery(function ($) { jQuery('.nyroModal').nyroModal({ 'blocker': '#Form' }); });

replace #Form with aspForm or whatever your form name is.


text:
Q: Data dots aren't showing up (Cartodb)
If I connect to my campus network, the map is not showing any data dots. And from the screenshot you can see the error messages.

If I use any other network, for example using my phone's hot spot via att lte, or comcast from my home, it is fine.
Any one knows what is happening?

A: iriberri is correct. I need to specify protocol in the options field, like this.
cartodb.createLayer(map, layerUrl, {'https':true})

Whiel the layerUrl is not necessarily https.


text:
Q: Wireless with 802.1x I have the following problem.
I'm trying to configure my router (Iskratel F50 or Mikrotik hAP lite) to control WiFi traffic with 802.1x and some kind of RADIUS server. But, when I configure everything on the router, and try to connect on that WiFi with my Android phone, it just refreshes the list of available wifi connections and shows the test connection as "saved". Nothing else happens.
If I'm right, the router should send UDP package, with access request data to RADIUS server or whatever it is on specified IP, right?
Can someone help me?
I need my device to get access request and then decide to allow or deny access to that client, depending on other details.
At the RADIUS IP is an Arduino device, that shows all data that came on RADIUS port to the LCD.
Thank you.

A: Generally, for a 802.1x-authentication over RADIUS, one would indeed expect to see several packets. The default ports for RADIUS are 1812/UDP (authentication) and 1813/UDP (accounting).
The first packet your router sends to the RADIUS IP should already have a User-Name-attribute. The connecting device should query the user for this. So, when you connected to that SSID, did your phone prompt you for a username (and password)?


text:
Q: How to put this JavaScript code into a loop? I have this piece of code who kinda follows a pattern but I don't know how to make it a loop to simplify.
setTimeout(() => {
    wrapper.classList.add("show-el-1");
    wrapper.classList.add("hide-el-0");
}, 600);

setTimeout(() => {
    wrapper.classList.add("show-el-2");
    wrapper.classList.add("hide-el-1");
}, 1800);

setTimeout(() => {
    wrapper.classList.add("show-el-3");
    wrapper.classList.add("hide-el-2");
}, 3000);

setTimeout(() => {
    wrapper.classList.add("show-el-4");
    wrapper.classList.add("hide-el-3");
}, 4200);

It adds 1200 in every setTimeout duration, and changes the show-el-x and hide-el-y numbers.

A: Something like this should get you going
for (let i = 0; i < 4; i++) {
  const delay = 600 + (i * 1200)
  setTimeout(() => {
    wrapper.classList.add("show-el-" + (i + 1));
    wrapper.classList.add("hide-el-" + i);
  }, delay);
}

A: You can use a for loop like so:
for(let i = 0; i < 4; i++){
    setTimeout(() => {
        wrapper.classList.add("show-el-" + (i + 1));
        wrapper.classList.add("hide-el-" + i);
    }, 600 + i * 1200);
}

A: If you just want to keep this running i.e. updating class after every timeout, then you could go for recursive approach as the snippet below, else for loop could be a more readable and easy to understand solution

let newTimeout = 600;
let firstClass= 1;
const func1 = () => {
    wrapper.classList.add(`show-el-${firstClass}`);
    wrapper.classList.add(`hide-el-${firstClass -1}`);
    newTimeout += 1200;
    firstClass += 1;
    setTimeout(func1, newTimeout);
};
setTimeout(func1, newTimeout);


text:
Q: how to mix views (html+css+js) between express.js (node.js) and backbone.js I am starting to learn Express.js (for Node.js) and Backbone.js. I have researched lots of documentation and tutorials, but there are some details i still haven't catched up, and there is no information related to it. I hope somebody could help here:
One of my biggest issues are the VIEWS. I understand how you can build up your MVRC in your backbone.js app.js, your MVC on your Express.js app, how to persist on the backend (express) via JSON, using Socket.io for real time, etc. But, how do you design VIEWS?
Both frameworks offer their own VIEWS, but is obvious that if you are using Backbone.js, is because you want to build up the VIEWs on the client side (HTML,CSS,jQuery and JS) with Backbone, and not with Express (Jade and templating). And if you use Express.js is because it offers more tools than Node.js, like authentication, session control, data base,etc.
How do you mix it up? i have seen some examples on internet like this book (O'Reilly Media):
http://addyosmani.github.com/backbone-fundamentals/
specifically, on their github source code related to "option7" for a TodoList app.
Here, they mix up both technologies (Backbone.js and Express.js with MongoDB). They do data persistant between client and server, connection to Redis, etc, but i still don't understand why they use Jade and /views for main HTML templating on Express.js, but CSS, jQuery and images inside /public on Backbone.js.
Shouldn't we build up the HTML5,CSS3 and JS entirely in Backbone.js? Whats the point of inyecting HTML templates from the backend through /ROUTES, if you want all your MVC on the front-end?
thank you very much and hope to get an answer :-)

A: One of my biggest issues are the VIEWS. I understand how you can build up your MVRC in your backbone.js app.js, your MVC on your Express.js app, how to persist on the backend (express) via JSON, using Socket.io for real time, etc. But, how do you design VIEWS?
The views in Express.js are templates which can be rendered  and returned to the client/browser through HTTP.
How do you mix it up?
You have a client-side and a server-side not sure what you mean with mix it up. If your browser needs data you can get it with a request to the server.
Shouldn't we build up the HTML5,CSS3 and JS entirely in Backbone.js?
Most of the time you would.
Whats the point of inyecting HTML templates from the backend through /ROUTES, if you want all your MVC on the front-end?
This is mostly to speed up web pages so you don't have to re-render the entire page but only a part.


text:
Q: Proof for a Legendre polynomial identity on a 2-sphere that appears in cosmology How can I prove the following identity?
\begin{equation}
\int d\Omega_{\hat k} P_l(\hat n \cdot \hat k) P_{l'}(\hat n'\cdot \hat k)=\frac{4\pi}{2l+1} P_l(\hat n\cdot \hat n')\delta_{ll'}\label{PP}
\end{equation}
Both hand-waving one and rigorous one are welcome


text:
Q: if every finitely generated $R$-module has Finite Free Resolution, then every finitely generated $R[x]$-module also has it I am reading the Rotman's book "An Introduction to Homological Algebra" and I do not understand the part of the proof of theorem 8.47 in page 481.
Theorem 8.47 Let R be a commutative noetherian ring. If every finitely generated R-module has Finite Free Resolution (FFR), then every finitely generated R[x]-module has Finite Free Resolution (FFR).
One step of the proof is based on proving the following:
if $M$ is a finitely generated $R[x]$-module such that $ann(M) \cap R  \neq \{0\}$, then $M$ has FFR.
Here is the proof in Rotman's book:
Let $m\in M$ be nonzero and let $I= ann(m) \cap R\neq 0$ be the R-ideal. We have that $R/I\simeq \langle m \rangle_R$ the R-submodule of $M$ generated by $m$.
Because R[x] is a flat R-module, we have the following exact sequence:
$$0 \to R[x] \otimes_R I \to R[x] \to R[x] \otimes_R \langle m\rangle_R \to 0 $$
Rotman concludes that the R[x]-module $R[x] \otimes_R \langle m\rangle_R \simeq R[x]/(R[x]\otimes_R I) \simeq R[x]/(R[x]I)$ is a cyclic submodule of $M$.
It is clear that it is cyclic, but why is it a submodule of $M$?
If we define a $R[x]$-homomorphism
$\phi:R[x] \otimes_R \langle m\rangle_R \to M$ by $\phi(p(x)\otimes_R m) = p(x)m$, I think that this may not be injective since $ann(m)\neq 0$
It is immediate that $R[x] \otimes_R \langle m\rangle_R$ has FFR, but would not it conclude the same if $I=0$. I do not see in which part of the proof the condition $I\neq 0$ is used.


text:
Q: Difference in spectrum between the damped harmonic oscillator and a HO in thermal equilibrium with a bath? I'm considering a damped, NOT driven harmonic oscillator, more specific an exponentially decaying oscillation. I would like to know the power spectral density of the signal.
What I did so far was taking the signal x(t)= $\exp(-\Gamma^{-1}|t|)\cos \omega t$ and taking the fourier transform of this signal.
This gives me the following spectrum (i.e. the signal x(t) displayed in frequency space):
two lorentzian peaks of width $\Gamma$, one centered at $\omega$ and one at $-\omega$.
Two problems with this:

*

*Maybe it is helpful to know what spectrum I expected to get: a lorentzian ONLY around $-\omega$.

*If I would do this thought experiment the other way, i.e. see a spectrum conisting of two lorentzian peaks of width $\Gamma$, one centered at $\omega$ and one at $-\omega$, I would interpretate this as a harmonic oscillator that is in thermal equilibrium and is certainly NOT damped (i.e. having an amplitude decaying to zero on a timescale relating to $\Gamma^{-1}$).
I would interprete the lorentzian around $-\omega$ as dissipation of energy, BUT I would interpret the lorentzian around $\omega$ as the reverse process, namely (re)absorption of energy: since the spectrum is symmetric for $\omega \to - \omega $, I would say indeed there are fluctuations, i.e. heat or energy is exchanged between the oscillator and the bath BUT in a noisy way: the signal decays a bit (dissipates energy to the bath), then regains amplitude/energy (absorbs energy from the bath) and this goes on in a fluctuating way.

*The signal x(t)= $\exp(-\Gamma^{-1}|t|)\cos \omega t$ is as you may have noticed not the exact description of an exponentially decaying oscillation. They only correspond for times t>0. I used this description because I do not know how to take the fourier transform of $x(t)= \exp(-\Gamma^{-1}t)\cos \omega t$. Not sure if this is relevant or not.
P.S.: I stumbled upon this problem while reading into quantum optics (or rather cavity optomechanics), where these spectra are ubiquitous but never really justified, and -as it seems to me- they appear in contradictory contexts.
I have in mind specifically the review paper 'Cavity Optomechanics' by Aspelmeyer (2014).


text:
Q: Selenium WebDriver Java - POM - console results point to an element not used in the test case Ran into an issue when the test cases fail and the console output says an element cannot be located, however, this element was not even used in the test case.
I am utilizing page object model pattern.
Does it have something to do with the order of execution of the elements of the class?
The test case:
public class FilterResultTestCaseActiveStudentsOnly {
public static void main(String[] args) throws InterruptedException {

    System.out.println(" enter username ");
    Login.userName.sendKeys(Account.loginElenaB);
    Thread.sleep(3000);

    System.out.println(" enter password ");
    Login.password.sendKeys(Account.pswdElenaB);
    Thread.sleep(3000);

    System.out.println(" click login btn ");
    Login.loginButton.click();
    Thread.sleep(3000);

    System.out.println("click on Students page ");
    NavBar.studentsPage.click();
    Thread.sleep(6000);

    System.out.println("click on Filter Results Dropdown ");
    FiltersResultDropdown.clickOnFilterResultsDropdown.click();
    Thread.sleep(3000);

    System.out.println("select Active Students only radiobutton ");
    FiltersResultDropdown.activeStudentsOnlyFilterResultsDropdown.click();
    Thread.sleep(3000);

    System.out.println("click on Apply Filters Results Dropdown ");
    FiltersResultDropdown.applyFilterButtonFilterResultsDropdown.click();
    Thread.sleep(3000);

     StudentsPage.studentLinkClickStudentsPage.click();
    Thread.sleep(3000);

     String activeStudentsOnlyText = GetTextForAsserts.getStatusActiveText.getText();

    try{
        Assert.assertEquals("STATUS: Active", activeStudentsOnlyText);
        System.out.println("The student is active");
    } catch(AssertionError e){  //What if there are not students filtered?  ToDo!
        System.out.println("The student not found");
        ;
        throw e;
    }

For asserts, I've created a class where I located necessary elements:
The class:
public class GetTextForAsserts {

    WebDriverSettings driver;

   public static WebElement getLetterOneText = WebDriverSettings.driver.findElement(By.xpath("//*[@id=\"studentLetters\"]/tr[5]/td[4]"));

    public static WebElement getChronicLetterText = WebDriverSettings.driver.findElement(By.xpath("//*[@id=\"studentLetters\"]/tr[4]/td[4]"));

    public static WebElement getStatusActiveText = WebDriverSettings.driver.findElement(By.xpath("//*[@id=\"studentOverview\"]/div[1]/div/div[4]/div[1]")); etc.

}

So, what it does - the test case fails, and the console says getLetterOneText cannot be located (or some another element), but it was not even used in the test case.
The Xpaths for all the elements are correct (even for the 'unlocated' ones), double checked multiple times.
To not fail the test case, I have to comment out the 'unlocated' element it points to, but it is not the solution.

A: Your GetTextForAsserts class scrapes the page for all three elements, including getLetterOneText. So when you instantiate that class, it scrapes the page whether it's used or not.
A better practice is to have your variables store the locators, By class, instead of storing the elements. That way you can call a method that uses the locator to scrape the page when needed.
You should spend some time looking at page object model tutorials and references to learn more standard ways of doing things like this. Also you should spend some time learning how to debug your own programs. If you stepped through your code, you would have seen those lines execute and known what the issue was.


text:
Q: Increment output for this Bash script Can I change this script so that I get an increment output file?
Here's the script:
#!/usr/bin/env bash

## Collect all files in the files array
files=( *jpg )
## How many should be done at once
batch=5
## Read the array in batches of $batch
for (( i=0; $i<${#files[@]}; i+=$batch ))
do
## Convert this batch
convert -delay 10 -morph 10 "${files[@]:$i:$batch}" $i.jpg
done

For now the output is like this:
0-0.jpg
1-3.jpg
1-30.jpg
12-3.jpg

and unsortable.

A: The following code should rename your files in order of creation.
#!/bin/bash

# modify the ls statement to include files you need
files=(`ls --sort=time -r *.jpg`)

for (( i=0; $i<${#files[@]}; i+=1 ))
do
 numStr=`printf "%05d\n" $i`
 # debug output
 echo "${files[i]} --> $numStr"
 mv "${files[i]}" "${numStr}.jpg"
done


text:
Q: C# Math.Pow(n,1/3) выдает 1, при любом n, как получить кубический корень? public static void Main (string[] args)
{
    int n = Convert.ToInt32 (Console.ReadLine());
    double d = Math.Pow (n, 1/3);
    Console.WriteLine (d);
    Console.ReadKey ();
}

Если написать "Math.Pow (n, 1.0/3.0)" выводит число, близкое к правильному, если "Math.Pow (n, 0.3)" , то еще ближе.
Например, при вводе 3, в первом случае ~1.44, а во втором ~1,39.
Почему это происходит?

A: Проблема в том, что выражение 1/3 выполняет целочисленное деление. В C# деление целых чисел даёт целое число (тяжёлое наследие C++). Так что 1/3 == 0, и вы возводите по сути в нулевую степень.
Чтобы получить кубический корень, возводите-таки в степень 1.0/3.0. Полученный результат 1.4422495703074083 правильный. В доказательство перемножим его само на себя трижды:
var cuberoot3 = Math.Pow(3.0, 1.0/3.0);
Console.WriteLine(cuberoot3);
Console.WriteLine(cuberoot3 * cuberoot3 * cuberoot3);

Выводит:

1.44224957030741
  3

http://ideone.com/dYGkCo


text:
Q: Designing a BJT transistor amplifier with a current gain greater than 1000? What would be an effective BJT transistor configuration for implementing an amplifier with a current gain of greater than 1000? This can be a multistage configuration, but it may only use BJT transistors. I was thinking of using a common-collector configuration for such a purpose. What would be appropriate biases for the resistors in the amplifiers (along with capacitor values if there any worth noting)?

A: As mentioned in the comments to your question, there are two simple beta-boosting configurations: Darlington and Sziklai.
For both configurations the effective beta (current gain) is a multiplication of the betas of the two transistors. Below are the schematics for these two configurations.
pay attention that the resistor in both cases is not necessary but it helps to improve the slow response time of these configurations and prevents leakage current through Q1 from biasing Q2 into conduction. Also make sure to choose its value so as not to steal substantial base current from Q2.

simulate this circuit – Schematic created using CircuitLab


text:
Q: How to handle fields' values constraints on Google Cloud Endpoints and Java? I come from Spring boot (with Jersey) to make APIs REST where I could easily handle if I wanted some value from a field have any constraint, like having some maximum value or not being null with the library javax.validation.
import javax.validation.Valid;
import javax.validation.constraints.NotNull;

...

@PUT
@Produces(MediaType.APPLICATION_JSON)
public Response gestionarVenta(@Valid @NotNull(message = CONSTRAINT_BODY_NOT_NULL) final ProductoCompradoDTO productoCompradoDTO) {
   ...
}

However, I'm checking out Google Cloud Endpoints now and I tried to use this same library but it just ignores it and goes on into the method.
import javax.validation.Valid;
import javax.validation.constraints.NotNull;

@Api(name = "echo", version = "v1", namespace = @ApiNamespace(ownerDomain = "echo.example.com", ownerName = "echo.example.com", packagePath = "")
// ...
)
public class MyApi {
    @ApiMethod(name = "echo")
    public Message echo(@Valid @NotNull(message = "cant be null") Message message, @Named("n") @Nullable Integer n) {
        ...
    }
}

I'm sending an empty body.
Why is it ignoring it? Is there some way or library to put constraints to fields' values on Google Cloud Endpoints?
Thanks!

A: Performing checks expressed by javax.validation annotations on REST API calls is a feature implemented in Spring Boot framework.
As of October 2019, Cloud Endpoints Frameworks for Java doesn't implement javax.validation checks. Also, it doesn't support equivalent features. You can file a feature request on https://github.com/cloudendpoints/endpoints-java/issues


text:
Q: Dockerfile, how should modify file into a pip package inside Docker In my Dockerfile, I pip install a few python packages (using requirements). One of them needs a credentials.json file filled with login and password credentials to work(The json file is empty after pip installing it).
So in the Dockerfile, I am trying to paste credentials into the config.json file. I have tried multiple path to find it but I always have "Directory nonexistent" error message.
Is it possible to access package directories in the docker image ? If yes, what is the "good" path to access it ?
Dockerfile
FROM python:3.7-slim

WORKDIR /app

## Install Pip
RUN apt-get update && \
   apt-get install -y python3 python3-dev curl && \
   curl https://bootstrap.pypa.io/pip/3.5/get-pip.py | python3

# pip install requirements
COPY requirements.txt requirements.txt
RUN pip install -r requirements.txt

# load env variables (including MY_LOGIN and MY_PASSWORD)
COPY .env ./.env
RUN . ./.env

# add credentials json into the python package
RUN echo "{'login': '$MY_LOGIN', 'password': '$MY_PASSWORD', 'url': 'https://url_test.com/vtest', 'login_url': 'https://auth.test.com/vtest/login'}" > ./package_name/folder/connector/credentials.json

COPY . .

CMD ["python3", "other_package/main.py"]

PS: This is my first Dockerfile so if you have any other comment to improve it you are more than welcome :)


text:
Q: Tagged unions (aka variant) in C++ with the same type multiple times I need to create an union, but 2 members of the union would have the same type, thus I need a way to identify them. For example in OCaml :
type A =
  | B of int
  | C of float
  | D of float

Boost.Variant doesn't seem to support this case, is there a known library which supports that ?

A: If you want to do this, I think your best option is to wrap the same-but-different-types into a struct which then lets the boost variant visit the proper one:
struct Speed
{
    float val_;
};

struct Darkness
{
    float val_;
};

You might be able to use BOOST_STRONG_TYPEDEF to do this automatically but I'm not sure it's guaranteed to generate types legal for use in a union (although it would probably be fine in a variant).

A: You cannot at the moment but C++17's implementation of std::variant fortunately allows it:

A variant is permitted to hold the same type more than once, and to hold differently cv-qualified versions of the same type.

Unlike with the boost version, you can get values by index, something like this (not tested):
// Construct a variant with the second value set.
variant<string, string, string> s(std::in_place_index<1>, "Hello");
// Get the second value.
string first = std::get<1>(s);

Michael Park has written a C++14 implementation of C++17's std::variant.

A: The c++ code here:
http://svn.boost.org/svn/boost/sandbox/variadic_templates/boost/composite_storage/pack/container_one_of_maybe.hpp
is truly a tagged union in that it can contain duplicate types.  One nice feature
is the tags can be enumerations; hence, the tags can have meaningful names.
Unfortunately, the compile time cost is pretty bad, I guess, because the implementation
uses recursive inheritance.  OTOH, maybe compilers will eventually figure out a way
to lessen the compile time cost.
OTOH, if you want to stick with boost::variant, you could wrap the types,
as Mark B suggested.  However, instead of Mark B's descriptive class names,
which require some thought, you could use fusion::pair<mpl::int_<tag>,T_tag>
where T_tag is the tag-th element in the source fusion::vector.  IOW:
variant
< fusion::pair<mpl::int_<1>,T1>
, fusion::pair<mpl::int_<2>,T2>
...
, fusion::pair<mpl::int_<n>,Tn>
>

As the fusion docs:
http://www.boost.org/doc/libs/1_55_0/libs/fusion/doc/html/fusion/support/pair.html
say, fusion::pair only allocates space for the 2nd template argument; hence,
this should not take any more room than boost::variant<T1,T2,...,Tn>.
HTH.
-regards,
Larry


text:
Q: Absolute Block Behaviour I have the following HTML snippet:
Block 1:

Block 2:

Block 1 is an ordinary absolute positioned DIV, while in block 2, the same DIV is enclosed within a relative positioned DIV.
My problem is, on Block 2, the absolute DIV inherits the width property from its parent, thus rendering the child DIVs on top of each other. Compare that to Block 1 where the child DIVs are floated side by side properly (because maximum allowable width is assigned).
Is there any fix for this situation? The height and width given are arbitrary and can change at any time. The child DIVs shouldn't set any width because the content keeps changing (I put some here for illustration purposes). I can set a certain width, but people with different browsers and DPI settings keep getting different result, so it's best to keep the child DIVs' width unset.
Update for bounty:
The intended usage of the above HTML is similar to the following:
Block 2:

    Main Text

                Item 1: Left Column, Line 1

                Item 2: Left Column, Line 2

                Item 3: Left Column, Line 3

                Item 4: Right Column, Line 1

                Item 5: Right Column, Line 2

Notes:

*

*leftcolumn and #rightcolumn width is not static, so there's no specific width that can be set. The width should follow the longest text (each item in a single line).

*I can set #columncontainer width to a specific width (which I am doing right now), but if the text is too long, then the left-right column is messed up (#rightcolumn below #leftcolumn, which is correct because of not enough space).

*main width is set to a specific width, which in all possible case will be much less than #columncontainer width.

*I'm open for JS solution, as that may seem to be the only consistent solution I can think of.

A: In Block 2, the absolutely positioned div doesn't strictly inherit its width from its parent. If that were the case, setting its width to auto would do the trick. Instead, its relatively positioned parent has become its "containing block", establishing a context inside which the absolute div lives, so to speak.
The only way to "break out" of that containing block is to set a width on it so it overflows, as you were doing. If you set that width to a value that will usually be good enough, you could further control how the floats inside it behave by setting (percentage) min-width and max-width values on them.
But do you really need the #columncontainer div to be inside #main, other than to position it relative to #main's coordinates?
What you could do instead is make them siblings in a common parent div (the rest of the CSS remains the same):

...

...

A: The width of the two inner divs 50 and 100 is wider than the enclosing 60px div. Is it necessary to set the enclosing div to 60px? If you remove the width and height restriction then the inner divs will occur next to each other as desired. Otherwise set the width of the div to a number higher than 60, lets say 110px so that the inner divs have room to be side by side.

A: I think the best way to do it is instead of defining width in pixels, do it in percentages. What will happen is that if you set each to 50% (or 49%), they will both be next to each other. Given that the largest the content can get is 100%, giving each box 50% should work out nicely, unless one side should sometimes be larger than the other.
Edit: Just saw the fact that each needs to be on a single line, which means that one side might be bigger than the other, so my solution might not work.


text:
Q: How does std::flush work? Can someone please explain (preferably using plain english) how std::flush works?

*

*What is it?

*When would you flush a stream?

*Why is it important?

Thank you.

A: A stream is connected to something. In the case of standard output, it could be the console/screen or it could be redirected to a pipe or a file. There is a lot of code between your program and, for example, the hard disk where the file is stored. For example, the operating system is doing stuff with any file or the disk drive itself might be buffering data to be able to write it in fixed size blocks or just to be more efficient.
When you flush the stream, it tells the language libraries, the os and the hardware that you want to any characters that you have output so far to be forced all the way to storage. Theoretically, after a 'flush', you could kick the cord out of the wall and those characters would still be safely stored.
I should mention that the people writing the os drivers or the people designing the disk drive might are free to use 'flush' as a suggestion and they might not really write the characters out. Even when the output is closed, they might wait a while to save them. (Remember that the os does all sorts of things at once and it might be more efficient to wait a second or two to handle your bytes.)
So a flush is a sort of checkpoint.
One more example: If the output is going to the console display, a flush will make sure the characters actually get all the way out to where the user can see them. This is an important thing to do when you are expecting keyboard input. If you think you have written a question to the console and its still stuck in some internal buffer somewhere, the user doesn't know what to type in answer. So, this is a case where the flush is important.

A: By default, std::cout is buffered, and the actual output is only printed once the buffer is full or some other flushing situation occurs (e.g. a newline in the stream). Sometimes you want to make sure that the printing happens immediately, and you need to flush manually.
For example, suppose you want to report a progress report by printing a single dot:
for (;;)
{
    perform_expensive_operation();
    std::cout << '.';
    std::flush(std::cout);
}

Without the flushing, you wouldn't see the output for a very long time.
Note that std::endl inserts a newline into a stream as well as causing it to flush. Since flushing is mildly expensive, std::endl shouldn't be used excessively if the flushing isn't expressly desired.

A: Here's a short program that you can write to observe what flush is doing
#include <iostream>
#include <unistd.h>

using namespace std;

int main() {

    cout << "Line 1..." << flush;

    usleep(500000);

    cout << "\nLine 2" << endl;

    cout << "Line 3" << endl ;

    return 0;
}

Run this program:  you'll notice that it prints line 1, pauses, then prints line 2 and 3.  Now remove the flush call and run the program again- you'll notice that the program pauses and then prints all 3 lines at the same time.  The first line is buffered before the program pauses, but because the buffer is never flushed, line 1 is not outputted until the endl call from line 2.

A: Since it wasn't answered what std::flush happens to be, here is some detail on what it actually is. std::flush is a manipulator, i.e., a function with a specific signature. To start off simple, you can think of std::flush of having the signature
std::ostream& std::flush(std::ostream&);

The reality is a bit more complex, though (if you are interested, it is explained below as well).
The stream class overload output operators taking operators of this form, i.e., there is a member function taking a manipulator as argument. The output operator calls the manipulator with the object itself:
std::ostream& std::ostream::operator<< (std::ostream& (*manip)(std::ostream&)) {
    (*manip)(*this);
    return *this;
}

That is, when you "output" std::flush with to an std::ostream, it just calls the corresponding function, i.e., the following two statements are equivalent:
std::cout << std::flush;
std::flush(std::cout);

Now, std::flush() itself is fairly simple: All it does is to call std::ostream::flush(), i.e., you can envision its implementation to look something like this:
std::ostream& std::flush(std::ostream& out) {
    out.flush();
    return out;
}

The std::ostream::flush() function technically calls std::streambuf::pubsync() on the stream buffer (if any) which is associated with the stream: The stream buffer is responsible for buffering characters and sending characters to the external destination when the used buffer would overflow or when the internal representation should be synced with the external destination, i.e., when the data is to be flushed. On a sequential stream syncing with the external destination just means that any buffered characters are immediately sent. That is, using std::flush causes the stream buffer to flush its output buffer. For example, when data is written to a console flushing causes the characters to appear at this point on the console.
This may raise the question: Why aren't characters immediately written? The simple answer is that writing characters is generally fairly slow. However, the amount of time it takes to write a reasonable amount of characters is essentially identical to writing just one where. The amount of characters depends on many characteristics of the operating system, file systems, etc. but often up to something like 4k characters are written in about the same time as just one character. Thus, buffering characters up before sending them using a buffer depending on the details of the external destination can be a huge performance improvement.
The above should answer two of your three questions. The remaining question is: When would you flush a stream? The answer is: When the characters should be written to the external destination! This may be at the end of writing a file (closing a file implicitly flushes the buffer, though) or immediately before asking for user input (note that std::cout is automatically flushed when reading from std::cin as std::cout is std::istream::tie()'d to std::cin). Although there may be a few occasions where you explicitly want to flush a stream, I find them to be fairly rare.
Finally, I promised to give a full picture of what std::flush actually is: The streams are class templates capable of dealing with different character types (in practice they work with char and wchar_t; making them work with another characters is quite involved although doable if you are really determined). To be able to use std::flush with all instantiations of streams, it happens to be a function template with a signature like this:
template <typename cT, typename Traits>
std::basic_ostream<cT, Traits>& std::flush(std::basic_ostream<cT, Traits>&);

When using std::flush immediately with an instantiation of std::basic_ostream it doesn't really matter: The compiler deduces the template arguments automatically. However, in cases where this function isn't mentioned together with something facilitating the template argument deduction, the compiler will fail to deduce the template arguments.


text:
Q: Insert values to a table from another table based on condition So I have a SQL table in which I am entering values by joining other columns and entering the column values from that table.
CREATE TABLE #temp_t (id INT, cname NVARCHAR(100), val INT, aid INT)
INSERT INTO #temp_t
SELECT DISTINCT
ISNULL(IDXC.id, 0) id, sg.name + '-webApp' cName, 0 val, ag.ID aid
FROM spgroup sg
JOIN APPA APP ON sg.id > 1 AND sg.val & 4 = 0 AND APP.dagi = sg.id
JOIN AIDBI XDI ON APP.bs = XDI.bsid
LEFT JOIN #IDXC ON IDXC.agpv = sg.id
WHERE IDXC.id IS NULL

Now while inserting values to the table I need to check if sg.name exists in sysName table if yes then -webApp needs to be replaced by -andApp otherwise it remains -webApp
How can I do the same?

A: You can use EXISTS in a CASE expression:
SELECT DISTINCT COALESCE(i.id, 0) as id,
       (sg.name +
        (CASE WHEN EXISTS (SELECT 1 FROM sysname sn WHERE sn.name = sg.name)
              THEN '-andApp' ELSE '-webApp'
         END)
       )  as cName,
       0 as val, ag.ID as aid
FROM spgroup sg JOIN
      APPA APP
      ON sg.id > 1 AND (sg.val & 4) = 0 AND APP.dagi = sg.id  JOIN
      AIDBI XDI
      ON APP.bs = XDI.bsid LEFT JOIN
      #IDXC i
      ON i.IDXCsgpv = sg.id
WHERE i.id IS NULL


text:
Q: How to take space separated input in dictionary with every new input stored against a new key value? How to create a dictionary from a string composed by space separated words with i for i in range(0, n) as key in the dictionary ?
Tried this:
i = 0
map(dic[i+=1],input().split())

It didn't work.
It should output this:
dic={0:'apple',1:'grapes',2:'orange',3:'banana'}

A: input_str = "Hello world"
result = {key: value for key, value in enumerate(input_str.split())}
print(result)

Output:

{0: 'Hello', 1: 'world'}

But you can use a list since this data structure is made for iterating over their contents and keeps order. If you want an int as key, just use enumerate(your_list).
In Python, when to use a Dictionary, List or Set?

A: You could use enumerate:
d = {}
for i, v in enumerate(input().split()):
    d[i] = v

Or simply:
d = dict(enumerate(input().split()))

But why do that? use a list...
Since your keys are simply (ordered!) integers, using a dict seems an overkill as to access integer-indexed values from a list is also O(1). For example, let's look at a small comparison with the 2 versions:
l = input().split()
d = dict(enumerate(l))

We have:
>>> print(l)
['apple', 'orange', 'banana']
>>> print(d)
{0: 'apple', 1: 'orange', 2: 'banana'}

Now let's see how we will grab values:
>>> l[0]
'apple'
>>> d[0]
'apple'
>>> l[2]
'banana'
>>> d[2]
'banana'

Dictionaries have a small memory overhead and so for this case using a dictionary doesn't give any advantage.

A: input_ = input("enter your fruits:").split(' ')

print (dict(zip([*range(len(input_))], input_)))
# print (dict(enumerate(input_)))

output:
enter your fruits:banana kiwi orange apple
{0: 'banana', 1: 'kiwi', 2: 'orange', 3: 'apple'}


text:
Q: WEB based application with desktop integration - technologies? This is a general question concerning technology decisions for a product development.
My aim is to develop a web based remote support (desktop sharing application) with audio and video communication.
My ideal solution would be to develop it as web product meaning that the client side always run in the browser. Client technology would be JavaScript (using Google GWT) and for desktop capturing, desktop presenting, audio and video I want to use Java applets.
The server side runs using Java Servlet technology with a database back-end (Hibernate and a SQL based data source). For data streaming my plan is to use RTP/RTSP transport over UDP (for desktop data the internal protocol will be VNC (RFB) but the transport will be RTP itself). For audio and video RTP is used for the transfer.
My basic version (prototype) will work using a relay server meaning that the clients always connects to the server (logon, authentication, session control) and the server always relays the data between peers.
My question is - is my technology decision correct? I mean, I decided to go pure Java because of multi-platform support. Nowadays we have Silverlight which have more advanced desktop support, but it is limited to only one platform (Windows).
I also fear of Java support for audio/video technologies. I have seen JMF (Java Media Foundation) which seems to have support for RTP/RTSP, audio and video capture/display but this package look very outdated. What do you think about it?
For actual screen capture I'd start with AWT Robot class. I know that for high performance desktop capture more low level techniques are necessary like API hooking or mirror driver, but my prototype aims to provide 1 FPS for screen capture so I believe Java Robot will make it.

A: Java applets can do it, but they're a bit legacy nowadays. In Java terms, you nowadays also have the choice of Java Web Start (the better Google keyword is JNLP) and JavaFX. If you don't shy away from learning a new language and wanted to have a real RIA, then go for JavaFX. Otherwise, Java Web Start A.K.A. JNLP is a fine choice. With Java you can just do everything as if it is a client application, as long as it's all within the borders of the security restrictions.
Here are some tutorials of use: JavaFX tutorial and Web Start tutorial.

A: You might want to check Glue42 (desktop integration platform) and Glue42 Core (open source web app integration platform). Github project is available here. The two products work together to integrate desktop and web applications using the FDC3 standard.


text:
Q: SCP on Ubuntu OpenSSH Server for Cisco backups I am having a bit of an issue and I believe I need some help. We have an On-prem SFTP server which will be deprecated soon, so in the mean time I need to set up another SFTP option in AWS running on EC2. I have looked at AWS Transfer Family, but the older cipers and Keys are not accepted on AWS Transfer Family.
Anyways I have the need for two users to use this SFTP server for automated backups. One is an accesscontrol system and the other one is Cisco Switches which use the SCP command from the Cisco CLI to backup.
I have a group on Ubuntu 20.04 called 'sftp' which has both users and from WinSCP it appears to work without issue. It will log the user into their '/home/%u' directory which they are able to write to.
Match Group sftp
ChrootDirectory /home
X11Forwarding no
AllowTcpForwarding no
ForceCommand internal-sftp -d /%u

Now when I attempt to run the SCP command from cisco I get the following error:
%his service allows sftp connections only.
%Error writing scp://*****@10.2.100.34//backups/b1sw007.cfg.test.20230228 (Permission denied)

I have done some reading into this and I think the ForceCommand is setting it to 'internal-sftp' which is causing this issue. The question is how do I remove that ForceCommand without breaking it for the other user. I 'think' if I remove the ForceCommand it will allow Cisco to use SCP?
Please let me know if you have any questions.
Thanks


text:
Q: The strangest docker fault I've ever seen I am using Docker with docker-mailserver on one of my servers. Very strange trouble appeared after migrating some services from legacy Debian Jessie server to Ubuntu 16.04 LTS server. Parameters of servers:
Legacy:
someuser@legacyserver:~$ uname -r
3.16.0-4-amd64
someuser@legacyserver:~$ dpkg -l | grep systemd
...215-17+deb8u7...
someuser@legacyserver:~$ cat /proc/cmdline
root=ZFS=rpool/ROOT/debian-1 ro boot=zfs quiet

New server:
someuser@newserver:~$ uname -r
4.4.0-21-generic
someuser@newserver:~$ dpkg -l | grep systemd
...229-4ubuntu4...
someuser@newserver:~$ cat /proc/cmdline
root=ZFS=rpool/ROOT/debian-1 apparmor=0 ro

I am running docker-mailserver on docker in systemd-nspawn Debian Jessie container. The first problem that I've encouraged was read-only cgroups at new systemd, this fixed that problem:
mount | grep cgroup | tail -n +2 | while read line
do
    umount -l $(echo $line | cut -f3 -d" ")
    mount -t $(echo $line | cut -f5 -d" ") -o $(echo $line | cut -f6 -    d" " | rev | cut -c2- | rev | cut -c2- | sed -e 's/ro,/rw,/g') $(echo     $line | cut -f1 -d" ") $(echo $line | cut -f3 -d" ")
done

It just remounts all cgroups read-write (cannot use -o remount).
But, then first I am rsh'ing to the systemd-nspawn container, and then from it to the docker container. When I am for example reloading Postfix (or doing anything else)... BOTH CONTAINERS (nested docker and systemd-nspawn) exits as quiet as a mouse... Like this:
someuser@newserver:~# rsh somesystemdcontainer
Last login: Sun Jun 25 15:27:24 CEST 2017 from host0 on pts/0
Linux somesystemdcontainer 4.4.0-21-generic #37-Ubuntu SMP Mon Apr 18 18:33:37 UTC     2016 x86_64

The programs included with the Debian GNU/Linux system are free software;
the exact distribution terms for each program are described in the
individual files in /usr/share/doc/*/copyright.

Debian GNU/Linux comes with ABSOLUTELY NO WARRANTY, to the extent
permitted by applicable law.
root@somesystemdcontainer:~# rsh mail #this is the docker container
Last login: Sun Jun 25 13:28:18 UTC 2017 from 172.18.0.1 on pts/0
Welcome to Ubuntu 14.04.5 LTS (GNU/Linux 4.4.0-21-generic x86_64)

 * Documentation:  https://help.ubuntu.com/
root@mail:~# service postfix reload
 * Reloading Postfix configuration...
   ...done.
root@mail:~# rlogin: connection closed.
root@newserver:~#

NOTHING IN DMESG, NOTHING IN KERNEL LOG, NOTHING ANYWHERE. As you've seen in cmdline, disabling apparmor both on kernel and userspace side doesn't help... After tring to stop the systemd-nspawn container:
jun 25 15:32:26 newserver kernel: INFO: task sh:10962 blocked for more than 120 seconds.
jun 25 15:32:26 newserver kernel:       Tainted: P           O    4.4.0-21-generic #37-Ubuntu
jun 25 15:32:26 newserver kernel: "echo 0 > /proc/sys/kernel/hung_task_timeout_secs" disables this message.
jun 25 15:32:26 newserver kernel: sh              D ffff88009ebb3c88     0 10962   9487 0x00000102
jun 25 15:32:26 newserver kernel:  ffff88009ebb3c88 0000000000000000 ffff88040dab3700 ffff8800c9450dc0
jun 25 15:32:26 newserver kernel:  ffff88009ebb4000 ffff8800c08008b0 0000000000000001 ffff8800c9450dc0
jun 25 15:32:26 newserver kernel:  ffff8800c2fe87e8 ffff88009ebb3ca0 ffffffff818203f5 ffff8800c9450dc0
jun 25 15:32:26 newserver kernel: Call Trace:
jun 25 15:32:26 newserver kernel:  [<ffffffff818203f5>] schedule+0x35/0x80
jun 25 15:32:26 newserver kernel:  [<ffffffff8111fd4f>] zap_pid_ns_processes+0x13f/0x1a0
jun 25 15:32:26 newserver kernel:  [<ffffffff8108432b>] do_exit+0xa6b/0xae0
jun 25 15:32:26 newserver kernel:  [<ffffffff8122383f>] ? dput+0x2f/0x220
jun 25 15:32:26 newserver kernel:  [<ffffffff81084423>] do_group_exit+0x43/0xb0
jun 25 15:32:26 newserver kernel:  [<ffffffff810904d2>] get_signal+0x292/0x600
jun 25 15:32:26 newserver kernel:  [<ffffffff8102e517>] do_signal+0x37/0x6f0
jun 25 15:32:26 newserver kernel:  [<ffffffff8181fd36>] ? __schedule+0x386/0xa10
jun 25 15:32:26 newserver kernel:  [<ffffffff81083526>] ? do_wait+0x116/0x240
jun 25 15:32:26 newserver kernel:  [<ffffffff8100320c>] exit_to_usermode_loop+0x8c/0xd0
jun 25 15:32:26 newserver kernel:  [<ffffffff81003c5e>] syscall_return_slowpath+0x4e/0x60
jun 25 15:32:26 newserver kernel:  [<ffffffff81824650>] int_ret_from_sys_call+0x25/0x8f
jun 25 15:32:53 newserver systemd[1]: systemd-nspawn-macvlan@somesystemdcontainer.service: State 'stop-sigterm' timed out. Killing.
jun 25 15:32:53 newserver systemd-nspawn[9483]: somesystemdcontainer login:
jun 25 15:32:53 newserver systemd[1]: systemd-nspawn-macvlan@somesystemdcontainer.service: Main process exited, code=killed, status=9/KILL
jun 25 15:32:53 newserver systemd[1]: Stopped Container somesystemdcontainer.
jun 25 15:32:53 newserver systemd[1]: systemd-nspawn-macvlan@somesystemdcontainer.service: Unit entered failed state.
jun 25 15:32:53 newserver systemd[1]: systemd-nspawn-macvlan@somesystemdcontainer.service: Failed with result 'signal'.
jun 25 15:32:53 newserver systemd[1]: Stopped Container somesystemdcontainer.
jun 25 15:32:53 newserver systemd-machined[2890]: Machine somesystemdcontainer terminated.

The 10962 is... bash inside DOCKER container, which "jumps out of namespace" on pstree...
What should I do now?


text:
Q: Kubernetes Manifest file won't convert from YML to JSON I've created a Kubernetes manifest file to create service account and roles. This is how it looks:
apiVersion: v1
kind: ServiceAccount
metadata:
  name: test-service-account
  namespace: test
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
  name: read-only-api
rules:
  - apiGroups:
      - ""
    resources: ["*"]
    verbs:
      - get
      - list
      - watch
---
kind: ClusterRoleBinding
apiVersion: rbac.authorization.k8s.io/v1beta1
metadata:
  name: read-only-api
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: ClusterRole
  name: read-only-api
subjects:
  - kind: ServiceAccount
  name: test-service-account
  namespace: test

However, when I try to execute and apply the manifest, I get this error. I'm not sure if I'm having issues with indention or something else.
error parsing service-account.yml: error converting YAML to JSON: yaml: line 10: did not find expected '-' indicator
All help is greatly appreciated. I've tried indenting it back and forth, adding the '-' indicator to that specific line it's complaining about - but then I receive a new error message:
error validating "service-account.yml": error validating data: ValidationError(ClusterRole.metadata): invalid type for io.k8s.apimachinery.pkg.apis.meta.v1.ObjectMeta: got "array", expected "map"; if you choose to ignore these errors, turn validation off with --validate=false
Thank you!

A: service account yaml is fine
correct clusterrole and clusterrolebinding yaml as below
apiVersion: v1
kind: ServiceAccount
metadata:
  name: test-service-account
  namespace: test
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
  name: read-only-api
rules:
- apiGroups:
  - ""
  resources:
  - "*"
  verbs:
  - get
  - list
  - watch
---
kind: ClusterRoleBinding
apiVersion: rbac.authorization.k8s.io/v1beta1
metadata:
  name: read-only-api
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: ClusterRole
  name: read-only-api
subjects:
- kind: ServiceAccount
  name: test-service-account
  namespace: test

master $ kubectl create ns test
namespace/test created

serviceaccount/test-service-account created
clusterrole.rbac.authorization.k8s.io/read-only-api created
clusterrolebinding.rbac.authorization.k8s.io/read-only-api created