text:
Q: BigQueryIO - Write to two tables for each item I'm trying to use Apache Beam to write a job in Dataflow.
This job needs gets an input and transforms it into my custom object.
This object represents a memory test, which contains fixed properties like timestamp, name ... and a list of the partitions with their properties too
public class TestResult {

    String testName;
    String testId;
    String testStatus;
    String testResult;
    List<Partition> testPartitions;
}
public class Partition {
    String testId;
    String filesystem;
    String mountedOn;
    String usePercentage;
    String available;
    String size;
    String used;
}

My last transform, takes this TestResult Object and transforms it into Table rows.
static class TestResultToRowConverter extends DoFn<TestResult, TableRow> {
    /**
     * In this example, put the whole string into single BigQuery field.
     */
    @ProcessElement
    public void processElement(ProcessContext c) {
      System.out.println("setting TestResult-> TestResult:" + c.element());
      c.output(new TableRow().set("testName", c.element().testName).set("testId", c.element().testId).set("testStatus", c.element().testStatus).set("testResult", c.element().testResult).set("memoryTestData", "example data test"));
      for (Partition pt :  c.element().testPartitions)
      {
        c.output(partitionsTag, new TableRow().set("testId", pt.testId).set("filesystem", pt.filesystem).set("mountedOn", pt.mountedOn).set("usePercentage", pt.usePercentage).set("available", pt.available).set("size", pt.size).set("used", pt.used));
      }
    }

And now I want to write them to BigQuery, but the table row of the test result goes to one table with an specific schema and the partitions go to another table with another schema. Also mention that there is an Id that links both and I need to autogenerate when the testResult is added and reused when the partition rows are inserted.
How can I accomplish this?
I was using this for writing to 1 table, but I'm lost if I want to write to two tables.
    .apply("MemoryTest_WriteToBigQuery", BigQueryIO.writeTableRows().to(TestResultToRowConverter.getTableSpec1())
        .withSchema(TestResultToRowConverter.getMemoryTestSchema())
        .withWriteDisposition(WriteDisposition.WRITE_APPEND))

EDIT:
Here is my pipeline:
pipeline.apply("ReadFromPubSubToBigQuery_MemoryTest", PubsubIO.readMessagesWithAttributes().fromTopic(options.getPubsubTopic()))
    .apply("MemoryTest_ProcessObject", ParDo.of(new ProcessTestResult()))
    .apply("MemoryTest_IdentifyMemoryTest",ParDo.of(new DetectTestType()))
    .apply("MemoryTest_TransformIntoTableRow", ParDo.of(new TestResultToRowConverter()).withOutputTags(partitionsTag))
    .apply("MemoryTest_WriteToBigQuery", BigQueryIO.writeTableRows().to(TestResultToRowConverter.getTableSpec1())
        .withSchema(TestResultToRowConverter.getMemoryTestSchema())
        .withWriteDisposition(WriteDisposition.WRITE_APPEND))

A: Beam pipelines are not limited to being a single straight line of transforms applied one after another - that would be very restrictive.
You can apply as many transforms as you want to any PCollection.
PCollection<TableRow> rows = ...;
rows.apply(BigQueryIO.writeTableRows().to(first table));
rows.apply(BigQueryIO.writeTableRows().to(second table));
rows.apply(some more processing)
    .apply(BigQueryIO.writeTableRows().to(third table));


text:
Q: Bind Param with array of parameters I have a function that does this:
function registerUser($firstName, $lastName, $address, $postcode, $email, $password)
{
    $params = array($firstName, $lastName, $address, $postcode, $email, $password);
    $result = $this->db->bind("INSERT INTO Users VALUES (?, ?, ?, ?, ?, ?)", 'ssssss', $params);
}

Which sends off to my database class, which does this:
public function bind($query, $type, $params)
{
    $this->query = $query;
    $stmt = $this->mysqli->prepare($this->query);
    $stmt->bind_param($type, $param);
    $stmt->execute;
}

The problem is this doesn't work.
What I was hoping to do, was to take the $params list and have it list them after the $type, so that the query would resemble:
$stmt->bind_param('ssssss', $firstName, $lastName, $address, $postcode, $email, $password);

But obviously I'm going about it the wrong way.
is there a way to make the array...transform as it were, into a list to be printed out at the bind_param query stage?

A: call_user_func_array
"Call a callback with an array of parameters"
call_user_func_array(array($stmt, "bind_param"), array_merge(array($type), $params));

should do the job
UPDATE: you have also to change your params array:
$params = array(&$firstName, &$lastName, &$address, &$postcode, &$email, &$password);

as mysqli_stmt::bind_param expects the second and the following parameters by reference.

EDIT: Your query seems to be wrong. Maybe you have less fields than you have variables there. Do:
"INSERT INTO Users (field1, field2, field3, field4, field5, field6) VALUES (?, ?, ?, ?, ?, ?)"

where you replace the name of the fields by the correct names

A: The easiest way would be apparently switching from mysqli to PDO
It will let you to do it the way you want, and even without any additional functions:
function registerUser($firstName, $lastName, $address, $postcode, $email, $password)
{
    $sql  = "INSERT INTO Users VALUES (NULL, ?, ?, ?, ?, ?, ?)";
    $stmt = $this->db->prepare($sql);
    $stmt->execute(func_get_args());
}

A: You get your error "Call to a member function bind_param() on a non-object" most likely, because your $this->mysqli->prepare encounters some kind of error.
(see http://php.net/manual/de/mysqli.prepare.php - it returns FALSE on error, which seems to be the case here)
After you have resolved that problem, try this instead of your call of $stmt->bind_param:
call_user_func_array(array($stmt, 'bind_param'), array_merge($type, $params));

A: As of PHP 5.6 you can utilize argument unpacking as an alternative to call_user_func_array, and is often 3 to 4 times faster.
<?php
function foo ($a, $b) {
     return $a + $b;
}

$func = 'foo';
$values = array(1, 2);
call_user_func_array($func, $values);
//returns 3

$func(...$values);
//returns 3
?>

Taken from here.
So your code should look something like this:
public function bind($query, $type, $params)
        {

            $this->query = $query;
            $stmt = $this->mysqli->prepare($this->query);
            $stmt->bind_param($type, ...$params);
            $stmt->execute;
        }

A: It is important to note that mysqli_stmt_bind_param() requires parameters to be passed by reference, so the parameters for call_user_func_array() must be a reference. An example taken from class context:
function execute( string $query, string $type, array $params )
{
    if ( !$stmt = $this->mysqli->prepare( $query ) )
        throw new \Exception( 'Prepare failed: ' . $query . PHP_EOL . $this->mysqli->error );

    // call stmt->bind_param() with variables to bind passed as a reference
    call_user_func_array(
        array( $stmt, 'bind_param' ),
        array_merge(
            array( $type ),
            array_map( function( &$item ) { return $item; }, $params )
        )
    );

    if ( !$stmt->execute() )
        throw new \Exception( 'Execute failed: ' . PHP_EOL . $stmt->error );

}

}

A: Today, I did some research myself in order to create a shorter method of using the prepare statement. The answer @bwoebi is very helpful but not working for an unknown amount of parameters so this is an addition to his answer.
For instance:
public function bind($query, $type, &...$params)
    {

        $this->query = $query;
        $stmt = $this->mysqli->prepare($this->query);
        call_user_func_array(array($stmt, "bind_param"), array_merge([$type], $params));
        $stmt->execute();
    }

using this thread:
PHP: variable-length argument list by reference?
I managed to accomplish to pass on an unknown amount of parameters to the bind function inside the class.
i then call upon the bind param function using call_user_func_array(...) with an array merge of the $type variable... (must be placed inside array for the merge)
Now i can call upon this function with $email and $password now being references:
$myClass->bind($query, "ss", $email, $password);

A: Not beautiful, but thats what I use.
function _BindParam(&$stmt, &$values){
    $types="";
    foreach($values as $val){
      if(is_string($val)){$types.="s";continue;}
      if(is_int($val)){$types.="i";continue;}
      if(is_float($val) || is_double($val)){$types.="d";continue;}
      throw new Exception('Invalid value type');
    }
   $stmt->bind_param($types,...$values);
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Performance of string buffer as function of number of appends I recently heard that there is an optimal point, where using a string buffer no longer offers better performance than simple concatenation. Apparently this was measured in the number of elements being appended (somewhere around 6).
Is this true?


text:
Q: Creating WCS using LAS Dataset I am looking for a way to serve up an LAS Dataset in order for others to consume it and to analyze it. So far what I've read says that it must be a map, raster/mosiac Dataset, or GDB. Is there a way to serve up an LAS Dataset specifically? It would need to be through proprietary services (i.e. ESRI).
https://enterprise.arcgis.com/en/server/10.6/publish-services/linux/wcs-services.htm


text:
Q: img loses center position after hiding and unhiding div element I have a function that hides and unhides a div element on button click and it works fine. The issue is once the div is hidden then unhidden the IMG loses its center position. I don't know what is causing this. Any help is appreciated. Thanks in advance.

function hide_unhide() {
  var x = document.getElementById("cont1");
  if (x.style.display === "none") {
    x.style.display = "block";
  } else {
    x.style.display = "none";
  }
}
#cont1 {
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: black;
}

<button onclick="hide_unhide()">toggle</button>

A: This is a simple mistake. You need to change it to flex, not block.
function hide_unhide() {
  var x = document.getElementById("cont1");
  if (x.style.display === "none") {
    x.style.display = "flex";
  } else {
    x.style.display = "none";
  }
}


text:
Q: shifting bits of input in verilog I have a 4-bit input A that I want to shift left and right. I was wondering if it's possible to shift just the input instead of assigning the shifted value to an output. For example I can do B = A<<1 but I don't want to make a new variable.
can the input itself be shifted so I can display it once I simulate it?

A: You won't be able to change the input value from inside the module, but you can shift it when you connect to the port at the level above:
module foo (A);

  input [3:0] A;

endmodule

module tb;

  wire [3:0] signal = 4'b0101;
  foo u_foo (.A(signal << 1));

endmodule


text:
Q: use a db2 trigger to identify the user initiating When creating a DB2 trigger (db2 version 10.1 LUW), I am looking to capture the userid that initiating the trigger.
For example, if a user inserts data, the after insert trigger should write to a log on who inserted the data.  This not meant for production purposes - just is to identify who is updating / inserting test data.

A: You can obtain the value of the SESSION_USER special registry variable. As an alternative look at the SYSTEM_USER registry. There are differences if you use features like SET SESSION AUTHORIZATION or use TRUSTED CONTEXTS.
Try this as a quick test:
select session_user from sysibm.sysdummy1;
select system_user from sysibm.sysdummy1;


text:
Q: $H^n_c(X)\cong H^n(X^+,\infty)$ where $X^+$ is the one-point compactification The following exercise is taken from section 3.3 of Hatcher.

21. For a space $X$, let $X^+$ be the one-point compactification. If the added point, denoted $\infty$, has a neighborhood in $X^+$ that is a cone with $\infty$ the cone point, show that the evident map $H^n_c(X;G)\to H^n(X^+,\infty; G)$ is an isomorphism for all $n$.

This is how far I have gotten:
By definition, $$H^n_c(X)=\operatorname{colim}_KH^n(X,X-K)$$
ranging over $K\subset X$ compact.
So let $U\subset X^+$ be the neighborhood which is a cone with cone point $\infty$. In particular $U^c\subset X$ is compact, and since $X-U^c=U-\{\infty\}$, we have a map $\phi:H^n(X,U-\{\infty\})\to H^n_c(X)$. By a Mayer-Vietoris argument, $$H^n(X,U-\{\infty\})\cong H^n(X^+,U)$$
and using the long exact sequence and the Five-Lemma, $$H^n(X^+,U)\cong H^n(X^+,\infty).$$
Therefore it would be enough to show that $\phi$ is an isomorphism. How can we see that? Is this the right approach?

A: Hatcher observes that singular homology has compact carriers which is made precise in Proposition 3.33. This is an immediate consequence of the definition of singular homology.
In contrast, singular cohomology does not have compact carriers. This motivates the construction of a variant of singular cohomology denoted by singular cohomology with compact support (or carriers) by considering only cocycles with compact support. This yields a cochain complex $C_c^\ast(X;G)$ whose cohomology groups $H^n(X;G) = H^n(C_c^\ast(X;G))$ are what we desire.
An alternative description can be given via the direct limit. Let $\mathfrak{K}(X)$ resp. $\mathfrak{K}'(X)$ denote the direct system of all compact subsets $K \subset X$ resp. all subsets $K' \subset X$ having compact closure, both partially ordered by inclusion. Note that $\mathfrak{K}(X)$ is a cofinal subsystem of $\mathfrak{K}'(X)$. Then
$$H^n_c(X;G) = colim_{K \in \mathfrak{K}(X)} H^n(X,X-K;G) = colim_{K' \in \mathfrak{K}'(X)} H^n(X,X-K';G) .$$
Let $X$ be locally compact. If $\infty$ has arbitrarily small contractible neighborhoods in $X^+$ (which means that each neigborhood $U$ of $\infty$ contains a contractible neigborhood $V$ of $\infty$), we say that $X$ satisfies the ASCN-condition. Note that we do not require neigborhoods to be open. If we want open neighborhoods $U$, we get the open ASCN-condition.
We can generalize Hatcher's Exercise 21 as the follows:
If $X$ is locally compact and satisfies the ASCN-condition, then the evident map $\phi : H^n_c(X;G) \to H^n(X^+,\{\infty \};G)$ is an isomorphism.
As in Yilong Zhang's comment we see that for a contractible neighborhood $U$ the map $\phi_U : H^n(X,U - \{ \infty \};G) \to H^n(X^+,\{\infty \};G)$ is an isomorphism. But now $K'_U  = X^+ - U \in \mathfrak{K}'(X)$, and by the ASCN-condition these $K'_U$ form a cofinal subsystem of $\mathfrak{K}'(X)$, which proves the above claim.
The existence of a "cone neighborhood" of $\infty$ is nothing else than a convenient criterion assuring that the ASCN-condition holds. Note that Hatcher is not really  precise when he requires that "$\infty$ has a neighborhood in $X^+$ that is a cone with $\infty$ the cone point". A cone has the form $CZ$ with some space $Z$, and obviously Hatchers requirement means that there exists a neigborhood $V$ of $\infty$ such that $(V,\infty) \approx (CZ,\ast)$ as pointed spaces. To conclude that the ASCN-condition holds we need the requirement that $Z$ is compact, i.e. that $V$ is a compact neighborhood.


text:
Q: Missing properties when using Web Reference feature in Visual Studio I am using a .NET Web Reference for consuming a web service that is using basic authentication. In the past I could set the credentials by accessing the same-named property. For example:
MyWebReference.Service1 client = new MyWebReference.Service1();
client.Credentials = new System.Net.NetworkCredential("username", "password");
client.MyOperation();

This worked fine in an older project. Now I am trying to set the Credentials block in a new VS project and I can't find the property anymore. I checked my old project and there were several properties like AllowAutoRedirect, ClientCertificates, ConnectionGroupName, Container, CookieContainer, ...
In my new VS project I just got Url and UseDefaultCredentials. I also included the web service from the older (working) VS project into my new project, but there are no properties either. So it must be something strange with the VS project or there are references missing.
I checked references, recreated the web reference several times but didn't get things working.
I am using Visual Studio 2010 Professional.
Any idea?
Thanks for your help

A: Make sure your Service class inherits from: System.Net.HttpWebRequest
This has properties that you are looking for.
using System;
using System.Net;
using System.Security.Cryptography.X509Certificates;
using System.Web.Services;
using System.Web.UI;

namespace WebApplication4
{
    public partial class WebForm1 : Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            MyService math = new MyService()
            {
                Credentials = new NetworkCredential("Joe", "mydomain", "password"),
                AllowAutoRedirect = false,
                ClientCertificates = new X509CertificateCollection(),
                ConnectionGroupName = ""
            };
        }
    }

    [WebService(Namespace = "http://tempuri.org/")]
    public class MyService : HttpWebRequest
    {
        [WebMethod]
        public int SumOfNums(int First, int Second)
        {
            return First + Second;
        }
    }
}

Reference: MSDN

A: I resolved the problem by myself. Unfortunately I had added a WCF Service named System.svc to the project map which resulted in a conflict between the System namespace and the class named System
I renamed the System.svc class and the Credentials-property became accessible.


text:
Q: python generating netaddr.core.NotRegisteredError invalid syntax exception I am trying to get a piece of software called Probemon
working and have come up with an error when I try to run it.
root@root:~/probemon/src$ python3 ./probemon.py -h
  File "./probemon.py", line 69
    except netaddr.core.NotRegisteredError, e:
                                          ^
SyntaxError: invalid syntax

I am not sure what it is trying to indicate here...
Prior to this I have run these commands:
git clone https://github.com/drkjam/netaddr
cd netaddr
sudo python setup.py install
cd
git clone https://github.com/secdev/scapy.git
cd scapy
sudo python setup.py install

to ensure netaddr and scapy dependencies are installed.
I have python 2 and python3 installed as this was default on the raspberrypi distro and I note from the probemon webpage, you

This is still using python2   . This is easily converted to
python3 script with 2to3 though

but I'm not sure where this needs to change.  I have found the first line of probemon.py as
#!/usr/bin/python2

and changed it to
#!/usr/bin/python3

although I am not sure whether this is what this means.
Does anyone know what is going on here?
Thanks

Edit to show response to running with python2:
root@root:~/probemon/src$ python2 ./probemon.py -h
Traceback (most recent call last):
  File "./probemon.py", line 11, in <module>
    import netaddr
  File "/usr/local/lib/python2.7/dist-packages/netaddr-0.8.0-py2.7.egg/netaddr/__init__.py", line 18, in <module>
    from netaddr.core import (AddrConversionError, AddrFormatError,
  File "/usr/local/lib/python2.7/dist-packages/netaddr-0.8.0-py2.7.egg/netaddr/core.py", line 11, in <module>
    from netaddr.compat import _callable, _iter_dict_keys
  File "/usr/local/lib/python2.7/dist-packages/netaddr-0.8.0-py2.7.egg/netaddr/compat.py", line 93, in <module>
    import importlib_resources as _importlib_resources
  File "/usr/local/lib/python2.7/dist-packages/importlib_resources-3.0.0-py2.7.egg/importlib_resources/__init__.py", line 5, in <module>
    from ._common import (
  File "/usr/local/lib/python2.7/dist-packages/importlib_resources-3.0.0-py2.7.egg/importlib_resources/_common.py", line 9, in <module>
    from ._compat import (
  File "/usr/local/lib/python2.7/dist-packages/importlib_resources-3.0.0-py2.7.egg/importlib_resources/_compat.py", line 42, in <module>
    from zipp import Path as ZipPath  # type: ignore
  File "/usr/local/lib/python2.7/dist-packages/zipp-3.1.0-py2.7.egg/zipp.py", line 217
    def open(self, mode='r', *args, pwd=None, **kwargs):
                                      ^
SyntaxError: invalid syntax

A: The script you have is compatible only with python2.
You can choose one of the following solutions:

*

*run it using  python2 ./probemon.py instead (if python2 is installed on your machine)

*convert it to python3 using an automatic tool like 2to3


text:
Q: How to Get Blazor Component HTML Source Code Is it possible to get the HTML source code of a server-side Blazor component/page? For example, to generate a PDF for any given Blazor page, I would need it's entire HTML source code rendered. Since it's SPA, each individual page does not really have any visible HTML source code ... Thanks!

A: It is not necessary to get all the html source code. Syncfusion Essential PDF is a .NET Core PDF library can help you create, read, and edit PDF documents in Blazor.

*

*Install the NuGet package: Syncfusion.PDF.Net.Core

*Create a new cs file named ExportService under Data folder and include the following namespaces in the file.
using Syncfusion.Pdf;
using Syncfusion.Pdf.Graphics;
using Syncfusion.Pdf.Grid;
using Syncfusion.Drawing;

*Add the following method in the ExportService class.
//Export weather data to PDF document.
public MemoryStream CreatePdf(WeatherForecast[] forecasts)
{
  if (forecasts == null)
  {
    throw new ArgumentNullException("Forecast cannot be null");
 }
//Create a new PDF document
using (PdfDocument pdfDocument = new PdfDocument())
{

 int paragraphAfterSpacing = 8;
 int cellMargin = 8;

 //Add page to the PDF document
 PdfPage page = pdfDocument.Pages.Add();

 //Create a new font
 PdfStandardFont font = new PdfStandardFont(PdfFontFamily.TimesRoman, 16);

 //Create a text element to draw a text in PDF page
 PdfTextElement title = new PdfTextElement("Weather Forecast", font, PdfBrushes.Black);
 PdfLayoutResult result = title.Draw(page, new PointF(0, 0));

 PdfStandardFont contentFont = new PdfStandardFont(PdfFontFamily.TimesRoman, 12);
 PdfTextElement content = new PdfTextElement("component generate the pdf", contentFont, PdfBrushes.Black);
 PdfLayoutFormat format = new PdfLayoutFormat();
 format.Layout = PdfLayoutType.Paginate;

 //Draw a text to the PDF document
 result = content.Draw(page, new RectangleF(0, result.Bounds.Bottom + paragraphAfterSpacing, page.GetClientSize().Width, page.GetClientSize().Height), format);

 //Create a PdfGrid
 PdfGrid pdfGrid = new PdfGrid();
 pdfGrid.Style.CellPadding.Left = cellMargin;
 pdfGrid.Style.CellPadding.Right = cellMargin;

 //Applying built-in style to the PDF grid
 pdfGrid.ApplyBuiltinStyle(PdfGridBuiltinStyle.GridTable4Accent1);

 //Assign data source
 pdfGrid.DataSource = forecasts;

 pdfGrid.Style.Font = contentFont;

 //Draw PDF grid into the PDF page
 pdfGrid.Draw(page, new Syncfusion.Drawing.PointF(0, result.Bounds.Bottom + paragraphAfterSpacing));

 using (MemoryStream stream = new MemoryStream())
 {
     //Saving the PDF document into the stream
     pdfDocument.Save(stream);
     //Closing the PDF document
     pdfDocument.Close(true);
     return stream;

  }
 }
}

*Register your service in the ConfigureServices.
public void ConfigureServices(IServiceCollection services)
{
    //...
    services.AddSingleton<ExportService>();
}

*Inject ExportService into FetchData.razor.
@inject ExportService exportService
@inject Microsoft.JSInterop.IJSRuntime JS
@using System.IO

*In this component, give one button.
<button class="btn btn-primary" @onclick="@ExportToPdf">Export to PDF</button>

*Add this method in FetchData.razor.
@functions
{

 protected async Task ExportToPdf()
 {
   using (MemoryStream excelStream = exportService.CreatePdf(forecasts))
   {
     await JS.SaveAs("Sample.pdf", excelStream.ToArray());
    }
  }
}

*Create the static class.
public static class FileUtil
{
   public static ValueTask<object> SaveAs(this IJSRuntime js, string filename, byte[] data)
=> js.InvokeAsync<object>(
    "saveAsFile",
    filename,
    Convert.ToBase64String(data));
 }

*Add the following JavaScript function in the _Host.cshtml.
 <script type="text/javascript">
   function saveAsFile(filename, bytesBase64) {
     if (navigator.msSaveBlob) {
         //Download document in Edge browser
         var data = window.atob(bytesBase64);
         var bytes = new Uint8Array(data.length);
         for (var i = 0; i < data.length; i++) {
             bytes[i] = data.charCodeAt(i);
         }
         var blob = new Blob([bytes.buffer], { type: "application/octet-stream" });
         navigator.msSaveBlob(blob, filename);
     }
     else {
         var link = document.createElement('a');
         link.download = filename;
         link.href = "data:application/octet-stream;base64," + bytesBase64;
         document.body.appendChild(link); // Needed for Firefox
         link.click();
         document.body.removeChild(link);
     }
    }
  </script>

Last, you can get the genereated pdf.


text: Q: What is the difference between these two Laurent series expansions I am working through problems in "Cracking the GRE Mathematics Subject Test" (4th edition) and one of the practice problems asks for the coefficient of $(z - 2)^{-1}$ in the Laurent series for $f(z) = \frac{1}{z-5}$ centered at $z = 2$. For my solution I did $$\frac{1}{z-5} = -\frac{1}{3 - (z - 2)} = -\frac{1}{3}\frac{1}{1 - \frac{z - 2}{3}} = \sum_{n = 0}^\infty{3^{-n - 1}(z - 2)^n}.$$ This expansion is valid on $|z - 2| < 3$. Hence, the coefficent is $0$. However, for the solution in the book they say $$\frac{1}{z-5} = \frac{\frac{1}{z - 2}}{1 - \frac{3}{z - 2}} = \frac{1}{z-2}\sum_{n = 0}^\infty{\left(\frac{3}{z-2}\right)^n} = \sum_{n = 0}^\infty{3^n(z-2)^{-n - 1}}.$$ This expansion is valid on $|z - 2| > 3$. Hence, the coefficent, using this expansion, is 1. Is there a reason that the second one is correct and the first one is not?


text:
Q: How do switches respond when more than 10 dial pulses are sent? Forgive me if this is off topic but this is actually about circuitry design:
My understanding is that electromechanical Strowger SxS switches have 10 "steps". What would happen if 11 pulses were dialed, either from a phone that happened to have 11 holes in the dial and could send 11 pulses or by tapping and depressing the switchhook/hookswitch rapidly 11 times in succession?
Similarly, what about 12, 13, etc. pulses in succession?
I'm not sure if 11 pulses would dial 10+1 or simply 10 and then stop listening.
I've tried and failed to test this out, even though I have 2 PBX systems at home. I can dial the lower five digits easily using the switchhook but I fail more than half the time simply dialing 0 using the switchhook. And because the PBXs are electronic, they may automatically recognize 11 as invalid and default to a reorder signal.
If there is a difference between how electromechanical switches and electronic switches would respond, please contrast them. (I don't know how many people just have a SxS switch at home to test with though...)

A: The extra pulses will simply be absorbed, except for the final digit which will be lost.
The 1st, 2nd etc. group selectors only accept a single digit, then hunt into the bank to find a free outlet to the next group. Once the carriage steps up to the top level it can't go any higher, so it just hammers into the backstop.
Final selectors step up for the penultimate digit, then step into the bank for the final digit. An extra pulse in the final digit will cause the carriage to step all the way around the bank and out the other side, where it will 'drop out' back to level 0 and start stepping up again.

Another selector type was the Discriminating Selector Repeater (DSR) which was designed to drop out when reaching certain levels, in order to absorb digits that weren't need in the local exchange. This monster had 29 relays, some with 2 or 3 independent coils. Here's a schematic - see if you can figure out how it works!

A: Old SXS switching centers were electro-mechanical and in addition to the step switches used several different types of relays.  The rotary dial was designed to pulse on the release of the dial, the number of pulses was determined by which hole you placed your finger in. Tapping out the digits is possible (I've done it) but tricky and doesn't work every time unless you have a very steady hand. If you had the proper pause between the 10th and 11th digit, the 11th digit would become a one for the next digit in sequence.  Each step switch in sequence has a different function as you progress throught the digits, 1st selector, second selector, line finder and so on. I'm trying to remember as much as possible as it's been since the early 1970's since I worked a SXS office.  A PBX will convert dial pulse to DTMF (not to be confused with MF). The PBX/keysystem will also store digits and send them all at one time.

A: If you did this to some SxS switches, the wiper would fall off the top or right side of the bank of contacts depending on if you do it for the final number or somewhere before.  The selector was then out of service until someone at the switching office put it back.
A friend of mine asked himself the same question many years ago as a child in a small town.  He pulsed the hook 11 times and heard nothing more until the phone engineer who lived nearby scolded him for doing it.  It was very clear to the engineer who did it because he frequently answered my friend's many questions on how the phone system worked.


text:
Q: AWS Lambda SDK - TooManyRequestsException I have around 50 AWS Lambda functions, I have a gulp tasks to deploy it, the script zip the functions and upload it to S3, then using Lambda JS SDK I call this task to create/update the functions:
gulp.task('upload', function (callback) {
  var AWS = require('aws-sdk');
  var lambda = Promise.promisifyAll(new AWS.Lambda(), {
    filter: function (name) {
      return name.indexOf('Async') === -1;
    }
  });
  var promises = require('./lambda-config.js').lambda.map(function (lambdaConfig) {
    return lambda.getFunctionConfigurationAsync({
      FunctionName: lambdaConfig.FunctionName
    }).then(function () {
      return lambda.updateFunctionCodeAsync({
        FunctionName: lambdaConfig.FunctionName,
        S3Bucket: lambdaConfig.Code.S3Bucket,
        S3Key: lambdaConfig.Code.S3Key
      });
    }).catch(function () {
      return lambda.createFunctionAsync(lambdaConfig);
    });
  });
  Promise.all(promises).then(() => callback()).catch(callback);
});

I am getting TooManyRequestsException error, the size of the zip is 13MB and unzipped version is 50MB. I don't think the size is the problem but the concurrent calls to the SDK.
Where can I find the information about how many concurrent calls I can perform for AWS SDK ? and how do you suggest I can solve the TooManyRequestsException error ? A code sample is appreciated.

A: Size of zip doesn't seem to be an issue (see http://docs.aws.amazon.com/lambda/latest/dg/limits.html).
I have received the TooManyRequestsException when exceeding the number of Lambda processes that AWS has authorized that account. Here are a few things to consider around that kind of limit:

*

*You start with a limit of about 100.See https://aws.amazon.com/lambda/faqs/ for details. As far as I understand, that means that best case, if nothing else is going on, you can only have at most 100 Lambda processes running at any given time.

*There is a lag between the time a Lambda process ends and the time that ended process is credited back to your limit. I'm not sure if there is clear guidance as to how long that time is; in my experience it ranges from a few seconds to maybe a minute or so. So if you have a process that uses 50 lamda's and each lambda takes 60 seconds to run, then best case, with a 100 limit, you can run that process twice per minute, but in reality it will probably be a little more constrained than that.

*Your limit can be increased if you send Amazon a service limit increase request (Support -> Create Case -> Service limit increase). You will have to provide info such as number of requests per second, duration of request, etc etc.

*VERY IMPORTANT: Lambda processes may automatically retry-- see https://aws.amazon.com/lambda/faqs/, esp "What happens if my account exceeds the default throttle limit on concurrent executions?" and "What happens if my Lambda function fails during processing an event?". This means that if you've exceeded your your limit, and you keep testing, you may have a backlog of processes that are still retrying (and using up your limit).
Based on this, you might want to do the following:

*

*Manage retries yourself, and don't use Amazon's built-in retry mechanism, especially for anything interactive and/or for testing purposes. e.g. in Node:
var lambda = new AWS.Lambda({
    region: REGION,
    maxRetries:0,
    ....
});

you can then manage using something like:
lambda.invoke(lambda_params, function(err, obj){
    if(err){
        if(err.toString().match(/TooManyRequestsException/)) ...

*If you want to be sure to stop any Lambdas that may still be running out of control (whether due to retries or because you may have had a bug in your code), delete your lambda function. e.g. from console:

aws lambda delete-function  --function-name my_outofcontrol_func

*Use the testing functionality a lot (AWS Dashboard -> Lambda -> choose your function -> Test) before you try to scale. The logs are also helpful-- so if you invoke 50 lambdas for a test, you can go to the log and see what happen to those 50 lambdas.

*When you need to scale, request it from Amazon ahead of time. It will take several days and for me, and others I have heard about, they always want to give you less than you ask for. It helps if you have a history of having already used the capacity you already have. Beware, once you get to around 1000 nodes, it doesn't take a lot of testing before you'll blow through the free tier and start having to pay for each use (more reason to do a lot of #3).

A: It looks like there is a problem with concurrency here. I had the same problem saving many promises and then executing them with Promise.all
This was solved by using the Bluebird Promise library that has a similar function, Promise.map, that also handles concurrency.
The code would be something in line with this:
const Promise = require('bluebird');

Promise.map(arrayWithLambdas, lambda => {

        //Deploy each lambda

    }, { concurrency: 5}) // Control concurrency
    .then(() => {

        // Handle successful deploy of lambdas
    })
    .catch(() => {

        // Handle unsuccessful deploy of lambdas
    })
};


text:
Q: Copiar de .txt para colar em software - Python Boa noite prezados, como vao?
Essa é a primeira pergunta que faço referente ao meu primeiro projeto em Python.
Estou desenvolvendo um projeto onde vou pegar algumas linhas de textos no .txt e enviar para um programa especifico que ira armazenar esse texto, consegui realizar essa automação assistindo a um video no YT, porem estou com um problema na parte de copiar e colar essas linhas. No video o Dev ensina o codigo utilizando o comando linha.split pois no txt dele cada linha tem 3 textos que ele vai inserir em capos diferentes: Campo 1, campo 2 e campo 3. Porem no meu caso eu tenho apenas um texto por linha.
Por conta disso eu nao consigo fazer com que a automacao pegue uma linha de cada vez e va iserindo no software. Do restante ja esta mapeado e funcionando mas o meu problema é encontrar o codigo que faça isso pra mim. Sou novato na area. Vou deixar meu codigo para entendimento.
from time import sleep

pyautogui.click(104, 30, duration=2)
pyautogui.click(96, 70, duration=1)

        # Copiar e colar - problema
with open('testes.txt', 'r') as arquivo:
    for linha in arquivo:
        chave = linha.split(',')[0]

pyautogui.click(874, 361, duration=2)
pyautogui.write(chave)
pyautogui.click(658, 400, duration=2)
pyautogui.click(679,444, duration=2)
sleep(1)```

Desde já, agradeço.

A: O codigo Final ficou assim:
    import pyautogui
    from time import sleep
    pyautogui.click(45, 34, duration=0.5)
    pyautogui.click(75, 69, duration=0.5)
    with open('testes.txt', 'r') as arquivo:
        for linha in arquivo:
            chave = linha.split(',')[0]
            pyautogui.click(479, 360, duration=1)
            pyautogui.write(chave)
            pyautogui.click(658, 400, duration=0.5)
            pyautogui.click(679, 444, duration=0.5)
            sleep(0.5)
            pyautogui.click(45, 34, duration=0.5)
            pyautogui.click(75, 69, duration=0.5)```

Ainda ficou faltando um condição para o loop parar sozinho, mas ja cumpriu o que eu queria.


text:
Q: An interesting Cubic equation $x^3-3x-1=0$ For the cubic equation $x^3-3x-1=0$, you can check it has three real roots by calculus knowledge. Let them be $x_1<x_2<x_3$. Now prove that
$$x_3^2-x_2^2=x_3-x_1.$$
It is not difficult to check that:
$$x_1=2\cos 140 ^{\circ},x_2=2\cos 100 ^{\circ},x_3=2\cos 20 ^{\circ}.$$
(Here use the formula: $\cos 3x=4\cos^3x-3\cos x.$ )
And then we can check:
$$x_3^2-x_2^2=x_3-x_1.$$
I just want to know how to get: $x_1=2\cos 140 ^{\circ},x_2=2\cos 100 ^{\circ},x_3=2\cos 20 ^{\circ}.$ Is there some trick. Any help and hint will welcome.

A: Using the formula $\cos(3\theta) = 4\cos^3(\theta) - 3\cos(\theta)$ is actually quite useful, but first we have to do $x=2y$, then we get
$$8y^3 - 6y - 1 = 0$$
Now we have the 4:-3 ratio and we can substitute $y=\cos(\theta)$ to get, from the above formula,
$$2\cos(3\theta) = 1$$
and from there we can get cosine form of the roots.

A: Since the roots are of the form $\cos(\theta)$, make the substitution $x=t+t^{-1}$ and expand to get
$$P(t+t^{-1})=\frac {t^6-t^3+1}{t^3}=\frac {t^9+1}{t^3(t^3+1)}$$
Set the above expression equal to zero and it's easy to see that$$t^9=-1$$Let $t=\cos\theta+i\sin\theta$ and expand to see that$$\theta=\frac {\pi(2k+1)}{9}$$where $k=0,2,3,\ldots$. Hence$$x=t+t^{-1}=2\cos\left(\frac {\pi(2k+1)}9\right)$$


text:
Q: python isabs does not recognize Windows UNC path as absolute path Running on Python 2.7.10 on windows.
> os.path.isabs(r"\\\unc_path\file")
False

> os.path.isabs(r"\\\unc_path\")
False

Is this by design?

A: You need to pay attention to string escaping, which is usually done with \.
For example \n is the newline symbol. \\ yields the single slash \.
Thus, the string "\\something" will print as \something.
If you wanted to have the contents \\something you need to type \\\\something, i.e. double any backslash. Alternatively you can use raw strings: r"\\something" will also work. You cannot enter a newline there anymore, but you don't have them in path names anyway.
So the path names you typed may not be what you think they are. \ is a special character, and unfortunately Microsoft back in the time of DOS thought it would be a good character to use as path separator. Unix operating systems (where most programming languages, and the convention of using the \ escape character originate) use the forward slash /, which is unproblematic.

A: os.path.isabs will only return True for a UNC path if there is some path information (even just a single slash) after the \\server\share part.
Python 2.7.12 (v2.7.12:d33e0cf91556, Jun 27 2016, 15:24:40) [MSC v.1500 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>> os.path.isabs('\\\\server\\share')
False
>>> os.path.isabs('\\\\server\\share\\')
True

To understand why, it is helpful to understand that isabs is just a tiny bit of code on top of splitdrive. In ntpath, the Windows implementation of os.path, it looks like this:
def isabs(s):
    """Test whether a path is absolute"""
    s = splitdrive(s)[1]
    return s != '' and s[:1] in '/\\'

The splitdrive implementation is intended to handle both paths with drive letters as well as UNC paths, and to have some consistency between them. Documentation for ntpath.splitdrive says:

If the path contained a drive letter, drive_or_unc will contain
  everything up to and including the colon. e.g. splitdrive("c:/dir")
  returns ("c:", "/dir")
If the path contained a UNC path, the drive_or_unc will contain the
  host name and share up to but not including the fourth directory
  separator character. e.g. splitdrive("//host/computer/dir") returns
  ("//host/computer", "/dir")

So...
>>> os.path.splitdrive('\\\\server\\share')
('\\\\server\\share', '')

You can see that isabs will return False.
That being said, this behavior changed between Python 2.7.7 and Python 2.7.8:
Python 2.7.7 (default, Oct 12 2015, 14:42:48) [MSC v.1500 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>> os.path.isabs('\\\\server\\share')
True
>>> os.path.isabs('\\\\server\\share\\')
True

The change was to fix a bug in os.path.join. I'm not totally sure if the Python developers realized it would be a breaking change for some os.path functions, but the behavior is consistent with Python 3.5:
Python 3.5.2 (v3.5.2:4def2a2901a5, Jun 25 2016, 22:18:55) [MSC v.1900 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>> os.path.isabs('\\\\server\\share')
False
>>> os.path.isabs('\\\\server\\share\\')
True


text:
Q: Modifying a column in a dataframe by condition can you please tell me about this question: I have a dataframe

I want to do the following with it: if the line in the proba column is nan, then change the value in the corresponding line in the flag column to 0. How can I do this?

A: Try with isna and loc:
df.loc[df['proba'].isna(), 'flag'] = 0

Or np.where:
df['flag'] = np.where(df['proba'].isna(), 0, df['flag'])


text:
Q: void*,pointers of strings and characters #include<stdio.h>
#include<conio.h>
void main()
{
   char cr[] = "Yash";
   clrscr();
   printf("%p\n",(void*)cr);
   printf("%p\n",cr);
   printf("%p\n",&cr);
   printf("%p\n",&cr[0]);
   printf("%p\n",cr[0]);
   printf("%p\n",(void*)cr[0]);

   printf("%c\n",&cr[0]);
   printf("%s\n",&cr);
   printf("%c\n",(void*)cr[0]);
   printf("%s\n",(void*)cr);
   getch();
}

Output:
FFEE
FFEE
FFEE
FFEE
0059
0059
ε
Yash
Y
Yash

Question:
I fail to understand exactly the output which I get in this code. Can somebody please explain each output why is it the way it is. Especially why does printf("%c",&cr[0]); give some sought of ε this weird or may be be null symbol?
 And why are outputs of (void*)cr[0] and cr[0] different from the other 3 in the half of %p? If they are just addresses then why different?(I am really really sorry for the last minute changes I made:/)

A:
explain each output

UB is undefined behavior: Anything may happen.
"%p" expects a void*.  pointers to characters and void* have same representation.
char cr[] = "Yash";
printf("%p\n",(void*)cr);     // OK:  address of CR[0]
printf("%p\n",cr);            // OK:  address of CR[0]
printf("%p\n",&cr);           // UB,  &cr is neither a void * or pointer to a character
printf("%p\n",&cr[0]);        // OK:  address of CR[0]
printf("%p\n",cr[0]);         // UB   cr[0] is neither a void * or pointer to a character
printf("%p\n",(void*)cr[0]);  // UB,  conversion to void* from arbitrary integer

"%s" expects a char* to a valid string
printf("%s\n",&cr);           // UB,  Not a `char *`
printf("%s\n",(void*)cr);     // OK

"%c" expects a int, converts that to a unsigned char and prints that character.
printf("%c\n",&cr[0]);        // UB, pointer passed as int
printf("%c\n",(void*)cr[0]);  // UB, pointer passed as int

why does printf("%s",&cr); give ....

printf("%s",&cr); --> printf expects &cr to be a valid pointer  to a string.  It is not.  Results: undefined behavior - anything may occur.

why are outputs of (void*)cr[0] and cr[0] different from the other 3 in the half of "%p

printf("%p\n",(void*)cr[0]); and printf("%p\n",cr[0]); are UB.

Explaining output when UB occurs is not productive until one clearly understands why explaining UB is not generally useful.


text:
Q: Laravel 5.3 resource: change action I'm new to laravel, now using v5.3.
Is it possible to change the called methods when using route::resource
Route::resource('user','UserController');

+--------+-----------+---------------------------------+--------------+-----------------------------------------------------------------+--------------+
| Domain | Method    | URI                             | Name         | Action                                                          | Middleware   |
+--------+-----------+---------------------------------+--------------+-----------------------------------------------------------------+--------------+
|        | GET|HEAD  | GameServiceAPI/user             | user.index   | App\Http\Controllers\Interfaces\UserController@index   | web          |
|        | POST      | GameServiceAPI/user             | user.store   | App\Http\Controllers\Interfaces\UserController@store   | web          |
|        | GET|HEAD  | GameServiceAPI/user/create      | user.test    | App\Http\Controllers\Interfaces\UserController@create  | web          |
|        | DELETE    | GameServiceAPI/user/{user}      | user.destroy | App\Http\Controllers\Interfaces\UserController@destroy | web          |
|        | PUT|PATCH | GameServiceAPI/user/{user}      | user.update  | App\Http\Controllers\Interfaces\UserController@update  | web          |
|        | GET|HEAD  | GameServiceAPI/user/{user}      | user.show    | App\Http\Controllers\Interfaces\UserController@show    | web          |
|        | GET|HEAD  | GameServiceAPI/user/{user}/edit | user.edit    | App\Http\Controllers\Interfaces\UserController@edit    | web          |
|        | GET|HEAD  | api/user                        |              | Closure                                                         | api,auth:api |
+--------+-----------+---------------------------------+--------------+-----------------------------------------------------------------+--------------+

I want to call my own methods without using the default (index,show,create,...)
Also what the 'Name' column refer to, I found that I can change it using some options that can be added to resource but I don't know its perpose.

A: The point of using Resource Controllers is that it provides the basic CRUD methods.
If you want to define your own routes, you need to use Route::get(), Route::post(), Route::any() and so on. It is not possible to change the linked methods of a resource controller.

A: You can't change these methods, but you could disable the ones you want to change and add your own instead:
Route::resource('user', 'UserController', ['except' => ['edit']]);

Route::get('user/{id}/customEdit', 'UserController@customEdit');

A: You can't change these methods, you should create your own get, post, put etc routes instead of using resource route.
The name column is a route name. You can set it for any route with as:
Route::get('some-path', ['as' => 'route-name', 'uses' => 'SomeController@comeAction'])

Or with ->name():
Route::get('some-path', `SomeController@comeAction`)->name('route-name');

A: You just create your own routes like below:

Available Router Methods

Route::get($uri, $callback);
Route::post($uri, $callback);
Route::put($uri, $callback);
Route::patch($uri, $callback);
Route::delete($uri, $callback);
Route::options($uri, $callback);

E.g:
Route::get('uri-path', [
    'as' => 'route-name',
    'uses' => 'YourController@index'
]);

Docs


text:
Q: How to round off decimals in values when ISNULL exists in SELECT clause? I have problem with rounding off decimals in this pivot table:
enter image description here
Here's the code:
SELECT P.LastName,  [Bike Racks]=ISNULL([Bike Racks],0), [Bottles and Cages]=ISNULL([Bottles and Cages],0), [Bottom Brackets]=ISNULL([Bottom Brackets],0), [Brakes]=ISNULL([Brakes],0)
FROM #TabPivot
PIVOT (
SUM(Total)
FOR Name IN ( [Bike Racks], [Bottles and Cages], [Bottom Brackets], [Brakes])) AS P
ORDER BY P.LastName;

I tried to use ROUND and CAST...AS NUMERIC functions but it didn't worked (maybe I did something wrong):
SELECT P.LastName,  ROUND([Bike Racks]=ISNULL([Bike Racks],0),2), ...

SELECT P.LastName,  ROUND(([Bike Racks]=ISNULL([Bike Racks],0)),2), ...

SELECT P.LastName,  ROUND(([Bike Racks]=ISNULL([Bike Racks],0), [Bottles and Cages]=ISNULL([Bottles and Cages],0), [Bottom Brackets]=ISNULL([Bottom Brackets],0), [Brakes]=ISNULL([Brakes],0)),2)

SELECT P.LastName,  CAST([Bike Racks]=ISNULL([Bike Racks],0) AS Numeric(15,2))

SELECT P.LastName,  CAST([Bike Racks]=ISNULL([Bike Racks],0)) AS Numeric(15,2)

Could you help me?

A: column name cannot be inside the function, but outside, try this:
SELECT [Bike Racks] = cast(isnull(0.66666, 0)  as decimal(18,2))

as an alternative, maybe it's more clear when you use the AS syntax for specifying column name:
SELECT cast(isnull(0.66666, 0)  as decimal(18,2)) AS [Bike Racks]

A: You simply need to cast your data to a decimal data type specifying the correct scale and precision.
For example
declare @v float=14
select @v/3.066, Cast(@v/3.066 as decimal (5,2))

Returns
4.5662100456621 4.57

A: Try this one :
Select Convert(Decimal (17,0),[Bike Racks]) AS [Bike Racks with convert]
      ,Floor(ISNULL([Bike Racks], 0)) AS [Bike Racks round down number]
      ,Ceiling(ISNULL([Bike Racks], 0)) AS [Bike Racks round to up number]

you can find other model of round and usable in below example :
DECLARE @value decimal(10,2)
SET @value = 11.05

SELECT ROUND(@value, 1)  -- 11.10
SELECT ROUND(@value, -1) -- 10.00

SELECT ROUND(@value, 2)  -- 11.05
SELECT ROUND(@value, -2) -- 0.00

SELECT ROUND(@value, 3)  -- 11.05
SELECT ROUND(@value, -3) -- 0.00

SELECT CEILING(@value)   -- 12
SELECT FLOOR(@value)     -- 11

Reference


text:
Q: How to replace NULL with value in MySQL? I have a table with soccer scores. Whenever I add a score to one player it automatically adds NULL in the same row for the other players:
Like this:
player1 1-0, NULL, 4-1
player2 5-2, 4-1, NULL
player3 2-1, NULL, NULL

What I want is when I add a new score to a player, the Null should be replaced with that value (for example for player one it should be 1-0, 4-1 and not 1-0, NULL, 4-1)
How can I do that?

A: Even if its easy to find on the manual, something like this should work...
UPDATE yourTable p
SET p.SomeField = p.NewValue
WHERE p.SomeField is NULL;

A: In your question you seem to have three columns next to each player. Why is that? What are those columns representing?
I propose that the cells in your examples are games, and that's really what you're modelling. You should create a game table with columns such as player1, player2, score1, score2. That would model who played against whom, and what the respective scores were.
You could add further information to each game, for example, when the game was played.


text:
Q: viewpager get stuck while swiping
Hi everyone,
viewpager sometimes get stuck while swiping through articles
Here is the code:
@Override

protected void onCreate(Bundle savedInstanceState) {

    Preferences.applyTheme(this);

    super.onCreate(savedInstanceState);

    setContentView(R.layout.detail);

    feed = (RSSFeed) getIntent().getExtras().get("feed");

    pos = getIntent().getExtras().getInt("pos");

    adapter = new DescAdapter(getSupportFragmentManager());

    pager = (ViewPager) findViewById(R.id.pager);

    pager.setAdapter(adapter);

    pager.setCurrentItem(pos);

}

public class DescAdapter extends FragmentStatePagerAdapter {

    public DescAdapter(FragmentManager fm) {

        super(fm);

    }

    @Override

    public int getCount() {

        return feed.getItemCount();

    }

    @Override

    public Fragment getItem(int position) {

        ArticleFragment frag = new ArticleFragment();

        Bundle bundle = new Bundle();

        bundle.putSerializable("feed", feed);

        bundle.putInt("pos", position);

        frag.setArguments(bundle);

        return frag;

    }

}

The source code is here if You need more code details
https://github.com/enricocid/lffl-feed-reader
Thanks for any reply

A: Try adapter = new DescAdapter(getChildFragmentManager());


text:
Q: Renaming files gives weird result in tcsh #!/usr/bin/tcsh
setenv LC_ALL de_DE
rm /home/users0/me/master/me/LookupScripts/Sampa/*
foreach f ( /home/users0/me/master/me/LookupScripts/Tokenized/*.txt )
set g = "`basename $f .txt`"
set h = "`echo $g | tr "tokenized" "sampa"`"
cat $f | ./a4.lookup > Sampa/$h.txt
end

In /home/users0/me/master/me/LookupScripts/Tokenized/ I have some .txt files which are named randomnumber_tokenized.txt. I want to run a script on them and I want to put the output of the script to the folder Sampa/ and I want to keep randombumber_ in the file names but I want to rename the tokenized part to sampa, so that the new files look like randomnumber_sampa.txt.
Strangely though in the end the files are not called randomnumber_sampa.txt but randomnumber_samaaaaaa.txt
I suspect that it is either an issue with tcsh or it is because of the setenv command.
What am I doing wrong?

A: Your immediate problem is that tr doesn't do what you think it does. tr performs character replacement, not string replacement. The command tr "tokenized" "sampa" replaces t by s, o by a, k by m, (e by p is overridden by a subsequent occurrence of e), and n, i, z, e and d by a.
To perform a string replacement, you can use sed. But that's somewhat inconvenient, and hard to get right. For simple string manipulation, use the shell's string manipulation constructs instead of external tools.
Tcsh lacks string manipulation constructs. But (t)csh has not been a tier-1 command line shell for the past 20 years or so, and has never been good for scripting. Just don't write csh scripts.
Also:

*

*Never set LC_ALL to anything other than C (or its synonym POSIX). LC_ALL overrides all categories and this can cause problems. To set a default for all categories, use LANG. But in scripts, C is usually what you need except for LC_CTYPE (character set) and LC_MESSAGES (messages for the user).

*String manipulation in sh is done via parameter expansion.

*Plain sh has no string replacement construct, but bash does.

*Always use double quotes around variable substitutions
#!/bin/bash
export LC_ALL=C
for f in /home/users0/me/master/me/LookupScripts/Tokenized/*.txt; do
  g="${f##*/}"
  h="${g//tokenized/sampa}"
  ./a4.lookup <"$f" >"Sampa/$h.txt"
end


text:
Q: Conflict between libtwolame0 and libtwolame0:i386 I am trying to install Skype on Debian Stretch (testing) amd64 (skype-debian_4.3.0.37-1_i386.deb), which depends on libasound2-plugins:i386 which itself transitively depends on libtwolame0:i386. Multiarch is already set and working on my machine.
But apparently, there is a conflict between libtwolame0 (amd64 version) and libtwolame0:i386:
$ sudo apt-get install libtwolame0 libtwolame0:i386
[...]
libtwolame0 is already the newest version.
Some packages could not be installed. This may mean that you have
requested an impossible situation or if you are using the unstable
distribution that some required packages have not yet been created
or been moved out of Incoming.
The following information may help to resolve the situation:

The following packages have unmet dependencies:
libtwolame0 : Conflicts: libtwolame0:i386 but 0.3.13-1.1 is to be installed
libtwolame0:i386 : Conflicts: libtwolame0 but 0.3.13-1.1 is to be installed
E: Unable to correct problems, you have held broken packages.

$ sudo apt-cache showpkg libtwolame0
Package: libtwolame0
Versions:
0.3.13-1.1 (/var/lib/apt/lists/ftp.fr.debian.org_debian_dists_stretch_ma [...]
[...]

Reverse Depends:
libtwolame0:i386,libtwolame0
vlc-nox,libtwolame0
twolame,libtwolame0
libtwolame-dev,libtwolame0 0.3.13-1.1
libsox-fmt-mp3,libtwolame0
gstreamer1.0-plugins-ugly,libtwolame0
gstreamer0.10-plugins-ugly,libtwolame0
libavcodec-ffmpeg56,libtwolame0
darkice,libtwolame0
audacity,libtwolame0
Dependencies:
0.3.13-1.1 - libc6 (2 2.3.4) libtwolame0:i386 (0 (null)) # Why libtwolame0:i386 ?

How can I know if it is a general Debian issue or an issue with my installation? If it is an issue with my installation, how can I fix it?

A: It's a bug in the twolame packages, tracked as #777223. There's a pending upload which should go into unstable on Sunday; you'll be able to fix your system then (or five days later in stretch).
In the meantime, you can revert to the previous version of libasound2-plugins (amd64 and i386), then hold them until libtwolame0 is available; that should fix your system right now.


text:
Q: Error: Counter too large! with \alph{cntr} and cntr>26 I would like to have \alph{counter} for values larger than 26. The following MnWE gives me the error ! LaTeX Error: Counter too large.
\documentclass{article}
\begin{document}

\begin{enumerate}
\def\theenumi{\alph{enumi}}
\setcounter{enumi}{24}
\item twenty-five
\item twenty-six
\item twenty-seven
\end{enumerate}

\end{document}

I would like it to behave like one of these:
..., x, y, z, aa, bb, cc, ..., xx, yy, zz, aaa, bbb, ccc, ... (preferred)
..., x, y, z, aa, ab, ac, ..., ax, ay, az, ba,  bb,  bc,  ... (can be if nothing else works)

A solution without LaTeX3 extensions would be awesome as I cannot run LaTeX3 extensions.

A: Should you happen to use biblatex for your bibliography, you may use its \mknumalph macro for counter values up to 702 ("zz").
\documentclass{article}

\usepackage{biblatex}

% Everything from here to \begin{document} only serves to avoid biber errors
\usepackage{filecontents}

\begin{filecontents}{\jobname.bib}
@misc{A01,
  author = {Author, A.},
  year = {2001},
  title = {Alpha},
}
\end{filecontents}

\addbibresource{\jobname.bib}

\nocite{*}

\begin{document}

\begin{enumerate}
\def\theenumi{\mknumalph{\value{enumi}}}
\setcounter{enumi}{24}
\item twenty-five
\item twenty-six
\item twenty-seven
\end{enumerate}

\end{document}

A: The alphalph package by H. Oberdiek provides the second numbering system out of the box. As usual with Heiko's packages, a counter representation such as
\renewcommand{\thesection}{\alphalph{\value{section}}}

is completely expandable.
And, as you remark in comments, with
\makeatletter
\newalphalph{\alphmult}[mult]{\@alph}{26}
\makeatother
\renewcommand{\thesection}{\alphmult{\value{section}}}

you get your preferred way. Of course, replace section with the counter you need.


text:
Q: Use injected dll code as delphi *.dll plugin which contains TForm maybe this is a lame question, but nevertheless...
I asked some questions about the plugins in delphi. What is the better way dll, bpl, OCX, scripting engine...
I dont feel like to distribute all *.bpls, and all its dependencies...
All I need is a *.dll which contains a TForm. And that Form should be placed into the host application.
There is no direct support for this in delphi (very sad situation). Some workarounds exists, but there are problems with tab key etc... So non workaround is perfect.
But maybe there is an another possibility. Inject dll code directly into the host *.exe.
So the *.exe will think that injected code his its own... And lot of problems (e.g. with tab key in form) should be gone.
Is it possible? isn't it a dirty hack, e.g. is that technique "programatically" legal?
(I have no experience with code injecting, and maybe it doesn't make sence what I'm saying here ;)
best regards
Peter
[edited]
To clarify some things... When we put a TForm in dll and than we try this form embed to the host *.exe application, a lot of problems arise. First is an error "cannot assign TFont to a TFont", but there is a some workaround for this.
Second is that host application take whole embeded form as one component, so you cannot use a tab key. (After pressing tab, focus will completly jump out of embeded form). Also we have some workaround for this, but it is far away from perfect...
So I had an idea, if we inject some code to the host, maybe host will be think that emebeded form his is own code, so tab key will be working.
But as I said before, I dont know anything about injecting, just a (maybe) crazy idea ;)

A: This is perfectly possible without recourse to any of the hacks you describe. For example:
library FormDLL;

uses
  Windows,
  Forms,
  uMyForm in 'uMyForm.pas' {MyForm};

procedure ShowForm(MainFormHandle: HWND); stdcall;
begin
  Application.Handle := MainFormHandle;
  with TMyForm.Create(nil) do begin
    ShowModal;
    Free;
  end;
end;

exports
  ShowForm;

begin
end.

You can put pretty much anything you like in TMyForm. On the other side create a Delphi app and add the following code to call the DLL:
procedure ShowForm(MainFormHandle: HWND); stdcall; external 'FormDLL.dll';

procedure TMainForm.Button1Click(Sender: TObject);
begin
  ShowForm(Handle);
end;

This behaves just perfectly.
So, I'm afraid it's not obvious what your problem is. If you can supply more details, then please do so.


text:
Q: Jasmine how to spy function inside object [Angular]? I have a written method down below in the service CapacitorManager
backButtonHandler() {
        return () => {
            const activeModalInstance = this.dataService.getItem(Constants.activeModalInstanceKey);
            const doesActiveModalExist = activeModalInstance !== -1;
            if (doesActiveModalExist) {
                activeModalInstance.close();
            }
            else {
                this.location.back();
            }
        }
    }

this method should call method close inside the object activeModalInstance(activeModalInstance is an instance of NgbModal) in case there is activeModalInstance inside the instance where dataService.getItem() refers to.Method getItem already mocked to be returned as object including close method.
fdescribe('CapacitorManager', () => {
    let service: CapacitorManager;
    let dataService: DataService;
    let location: Location;
    let dataServiceStub: Partial<DataService>;
    beforeEach(async(() => {
        dataServiceStub = {
            getItem: () => {
                return {
                    close: () => {

                    }
                }
            }
        }
        TestBed.configureTestingModule({
            providers: [
                { provide: Location, useClass: SpyLocation },
                { provide: DataService, useValue: dataServiceStub },
                CapacitorManager
            ],
            imports: [
                RouterTestingModule
            ]
        }).compileComponents().then(() => {
            service = TestBed.inject(CapacitorManager);
            dataService = TestBed.inject(DataService);
            location = TestBed.inject(Location);
        });
    }));

    afterEach(() => {
        service = null;
    });

    it('should create the component', () => {
        expect(service).toBeTruthy();
    });

    it('should backButtonHandler call activeModal in case activeModalInstance exists', () => {
        const activeModalInstance = dataService.getItem("activeModal");
        spyOn(activeModalInstance, "close");
        service.backButtonHandler();
        expect(activeModalInstance.close).toHaveBeenCalled();
        expect(location.back).not.toHaveBeenCalled();
    });

});

Last test case where I'm testing Expected a spy, but got Function. . How can I succed this test case?

A: So this threw me for a bit. I think the code below will work for you.
I have added comments to indicate what I changed to make it pass for me.
Last thoughts, check the line number to make sure that expect(location.back).not.toHaveBeenCalled(); isn't what it is breaking on.
fit('should backButtonHandler call activeModal in case activeModalInstance exists', () => {
  const modal = {
    close: () => {

    }
  };
  // so it looks like because you return a new item EVERY TIME above, you spy on a different item than you think
  // here we set a specific object to return
  dataService.getItem = () => modal;
  const activeModalInstance = dataService.getItem("activeModal");
  spyOn(activeModalInstance, "close");
  const func = service.backButtonHandler();
  // Your capacitor manager, as written, is a function that returns a function.
  // to get it to run you have to call the function that gets returned
  func();
  expect(activeModalInstance.close).toHaveBeenCalled();
  expect(location.back).not.toHaveBeenCalled();
});

Also marked an if statement here that typescript wasn't a fan of, as you have an object that you're comparing to -1
backButtonHandler() {
  return () => {
    const activeModalInstance =
    this.dataService.getItem(Constants.activeModalInstanceKey);
    // not sure what this is checking (as written, maybe you translated)
    const doesActiveModalExist = activeModalInstance !== -1;
    if (doesActiveModalExist) {
      activeModalInstance.close();
    }
    else {
      this.location.back();
    }
  }
}


text:
Q: How to switch git accounts in Android Studio I have multiple git accounts such as my personal GitHub account, bitbucket account , official github account and so on. Currently my official GitHub account is set as my global git username. I'm doing some personal projects as well in my system, where I don't want the commits to be under my official GitHub username and email Id. Currently, since my official GitHub account is synced with Android studio, the commits are showing the office email id and the email id even for the projects I kept in BitBucket. Is there any way in Android Studio to set individual git accounts for each project? Or do I need to change the git config user.email and git config user.name each time when I switch projects? Can anyone suggest a better solution? Thanks in advance!!

A: You can use git config with/without --global option to set your email and username.
If you want to use one single username and email for all your projects then use :
git config --global user.name <Your username>
git config --global user.email <Your email>

Remember the --global option will set this information globally to all your projects.
You can also change this information for each individual project. Just exclude the --global option.
git config user.name <Your username>
git config user.email <Your email>

This will set username and email for that particular project.
Remember that Git will first try to make use of local configuration, i.e. the one you set without the --global option. If that is empty, then the one set with --global option is used. So basically, your local configuration will override any global configuration.
You can check which value is set just by running the above command with empty value.
Eg. to see your global username:
git config --global user.name

Or to see our local email
git config user.email

Hope this helps.


text:
Q: My vs code is not showing drop down option to select terminal from a list of terminal. How to change it to normal? Instead, it is showing side pane with list of open terminals. enter image description here

A: *

*Click on the down arrow besides the + icon in the terminal

*Select terminal settings. it would open the settings.

*Search for Terminal → Integrated → Tabs: Enabled

*De-select the option . it would display the open terminals in a drop down menu.

See image for the setting:


text:
Q: How to format "datetime -local" value in php fetched from mysql? I have an input field in html where I want to echo the value of datetime stored in mysql.
<input type="datetime -local" name="schedule" value="<?php echo $result['schedule']; ?>

But despite the value being there in mysql db as YY/mm/dd h:m:s the value is not showing up. What could be the possible issue? When I try to echo outside the input value it displays the result. My thoughts are that the datetime needs formatting according to the html datetime -local input field.
Please suggest me any way if possible.

A: T is a format character(Timezone abbreviation e.g: EST, MDT…) so you can't use it directly. Escape it (\T) to get a literal T character:
datetime.format.php

You can prevent a recognized character in the format string from being expanded by escaping it with a preceding backslash.

<?php
    $date = date("Y-m-d\TH:i:s", strtotime($result['schedule']));
?>

<input type="datetime-local" name="schedule" value="<?php echo $date; ?>"/>

use <?=$date?> instead of <?php echo $date; ?>

A: You are filling it the wrong way. Read the documentation about the input-type datetime-local The correct format is YYYY-MM-DDTHH:MM - note the T as divider between date and time.
Also:

*

*you wrote the type wrong. Correct is datetime-local

*you are missing the closing quote at the value attribute.

A: This is how to fix it
<input type="datetime-local" name="schedule" value="<?php echo $date = date("Y-m-d\TH:i:s", strtotime($result['schedule']));?>">


text:
Q: install sonarqube with docker compose i want to install sonarqube with docker compose. I use the command sudo docker-compose up -d, installation is begin but after 5 minutes i show this error
Error response from daemon: driver failed programming external connectivity on endpoint sonarqube (fb1dcfd9efc1877f73cdcd256e3666e0f3268d3cb861c97347bc5028e126e9c9): Error starting userland proxy: listen tcp4 0.0.0.0:9000: bind: address already in use


text:
Q: Java: Memory usage of the final keyword? When you declare a final variable (constant) in a class, for example:
private static final int MyVar = 255;
How much memory will this require if I have 100,000 instances of the class which declared this?
Will it link the variable to the class and thus have 1*MyVar memory usage (disregarding internal pointers), or will it link to the instance of this variable and create 100,000*MyVar copies of this variable?
Unbelievably fast response! The consensus seems to be that if a variable is both static and final then it will require 1*MyVar. Thanks all!

A: The static declaration means it will only have one instance for that class and it's subclasses (unless they override MyVar).
An int is a 32-bit signed 2's complement integer primitive, so it takes 4 bytes to hold it, if your example wasn't using static you'd just multiply that by the number of instances you have (for your example of 100,000 instances that's 0.38 of a megabyte - for the field alone, extra overhead for actual classes).
The final modifier on a field means it cannot be repointed to another value (whereas final on a class of method means it cannot be overridden).

A: It's static and thus class scope -> 1.
Edit: actually, it depends on the class loaders. In the general case you have one copy of the class but if you have multiple class loaders/class repositories (might be the case in application servers etc.) you could end up with more.

A: The final keyword is irrelevant to the amount of memory used, since it only means that you can't change the value of the variable.
However, since the variable is declared static, there will be only one such variable that belongs to the class and not to a specific instance.
Taken from here:

If a field is declared static, there exists exactly one incarnation of the field, no matter how many instances (possibly zero) of the class may eventually be created. A static field, sometimes called a class variable, is incarnated when the class is initialized . A field that is not declared static (sometimes called a non-static field) is called an instance variable. Whenever a new instance of a class is created, a new variable associated with that instance is created for every instance variable declared in that class or any of its superclasses.

A: In addition to the fact that static fields belong to their classes, and thus there is only one instance of static varaible per class (and per classloader), it's important to understand that static final variables initialized by compile-time constant expressions are inlined into classes that use them.
JLS §13.1 The Form of a Binary:

References to fields that are constant variables (§4.12.4) are resolved at compile time to the constant value that is denoted. No reference to such a constant field should be present in the code in a binary file (except in the class or interface containing the constant field, which will have code to initialize it), and such constant fields must always appear to have been initialized; the default initial value for the type of such a field must never be observed.

So, in practice, the instance of static final variable that belong to its class is not the only instance of value of that variable - there are other instances of that value inlined into constant pools (or code) of classes that use the variable in question.
class Foo {
    public static final String S = "Hello, world!";
}

class Bar {
    public static void main(String[] args) {
        // No real access to class Foo here
        // String "Hello, world!" is inlined into the constant pool of class Bar
        String s = Foo.S;

        System.out.println(s);
    }
}

In practice it means that if you change the value of Foo.S in class Foo, but don't recompile class Bar, class Bar will print the old value of Foo.S.

A: There will be only 1*MyVar memory usage because it is declared as static.

A: static means you will have only one instatnce
final just means, that you can't reassign that value.

A: The crucial part here is that you declared the variable as static because static variables are shared among all instances of the class, thus requiring only as much space as one instance of the variable. Declaring a variable final makes it immutable outside its declaration or constructor.

A: final makes is 1*instances memory usage.
However, static makes it simply 1.

A: The keyword "final" helps you to declare a constant with a specific amount of memory, where as the keyword "static" as its prefix will gives a single instance of this constant, what ever be the amount of memory consumed...!!!

A: Static means, one instance per class, static variable created once and can be shared between different object.
Final variable, once value is initialized it can't be changed. Final static variable use to create constant (Immutable) and refer directly without using the object.

A: It's static, so there will be only one instance created, so however many bytes are required to hold one int primitive will be allocated

A: You will have one instance per class. If you have the class loaded more than once (in different class loaders) it will be loaded once per class loader which loads it.
BTW: Memory is surprising cheap these days. Even if there was a copy per instance, the time it takes you to ask the question is worth more than the memory you save.  You should make it static final for clarity rather than performance. Clearer code is easier to maintain and is often more efficient as well.


text:
Q: 500 Internal Server Error by PHP Script for permutation Hi to generate a list of combinations of an array I use this script. My Problem is that I get after some minutes an 500 Internal Server error and I don't know why. The php and mysql timeouts are set to 64000. Perhaps there is an other good solution to generate all combinations. I know that there are lots of combinations. But our Serverhardware is very good, so I think it can't be the problem.
    ini_set("default_socket_timeout", 64000);
    ini_set('mysql.connect_timeout', 64000);

    error_reporting(E_ALL);
    ini_set("display_errors", 1);

    set_time_limit(0);
    define("SYS_PATH", "");

function buildCombos($chars, $n)
{
      if ($n <= 0) return array('');

      $built = array();
      foreach ($chars as $char)
            foreach (buildCombos($chars, $n - 1) as $b)
                  $built[] = $b . $char;
      return $built;
}
$chars = array('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', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '-');
$combo = buildCombos($chars, 4);

foreach ($combo as $key => $inhalt) {
    set_time_limit(0);
    $domain = $inhalt.'.de';

    $dbusername = "xxx";
    $dbdatabase = "xxx";
    $dbhost = "localhost";
    $dbpassword = "xxxx";

    $link = mysql_connect($dbhost,$dbusername,$dbpassword);
    mysql_select_db($dbdatabase);

    mysql_query("SET NAMES 'utf8'");
    mysql_query("SET CHARACTER SET 'utf8'");

    mysql_query("INSERT IGNORE INTO de_list SET val = '$domain', val1 = 4, val2 = 0");
    //
    mysql_close($link);
}

echo 'Ready';


text:
Q: wpf textblock focus on mouse right click hello I am pretty new to wpf c#, I have a treeview which is populated at run time and  here is my xaml code
<StackPanel Orientation="Horizontal">
    <Image Source="Properties\accessories-text-editor-6.ico" Margin="0,0,5,0" />
    <TextBlock Text="{Binding Name}" Foreground="Green" MouseLeftButtonDown="TextBlock_MouseLeftButtonDown" MouseRightButtonDown="TextBlock_MouseRightButtonDown" >
        <TextBlock.ContextMenu>
            <ContextMenu>
                <MenuItem Header="HeadLine" ></MenuItem>
                <MenuItem Header="Textblock" ></MenuItem>
                <MenuItem Header="Author" ></MenuItem>
                <MenuItem Header="PageNumber" ></MenuItem>
                <MenuItem Header="RunningTitle" ></MenuItem>
                <MenuItem Header="Illustration" ></MenuItem>
            </ContextMenu>
        </TextBlock.ContextMenu>
    </TextBlock>
</StackPanel>

what I want is when I right click the textblock that is inside the treeview. the textblock need to be focus. As of now what it does is show the context menu item.
so how do I get the index of the Right clicked textblock? so I can focus to that item.
Thank you

A: A TextBlock cannot be focused...but you can get a reference to it in the MouseRightButtonDown event handler by casting the sender argument:
private void TextBlock_MouseRightButtonDown(object sender, MouseButtonEventArgs e)
{
    TextBlock txt = sender as TextBlock;
    //do whatever you want with the TextBlock...
}

If you are in the context of a TreeView you may want to select the parent TreeViewItem:
private void TextBlock_MouseRightButtonDown(object sender, MouseButtonEventArgs e)
{
    TextBlock txt = sender as TextBlock;
    TreeViewItem tvi = FindParent<TreeViewItem>(txt);
    if (tvi != null)
        tvi.IsSelected = true;
}

private static T FindParent<T>(DependencyObject dependencyObject) where T : DependencyObject
{
    var parent = VisualTreeHelper.GetParent(dependencyObject);

    if (parent == null) return null;

    var parentT = parent as T;
    return parentT ?? FindParent<T>(parent);
}


text:
Q: Groovy: writing dynamically compiled class to disc In my app I need to compile classes / scripts in runtime.
as a Class:
Class<? extends LoginAdapter> clazz = groovyClassLoader.loadClass name
LoginAdapter la = clazz.newInstance id, logo

or as a Closure:
Closure action = groovyShell.evaluate( script, name ) as Closure

Both ways work like charm.
Now I need to be able to write the compiled classes/scripts to some persistant storage (disc) and later restore them back without compiling from scratch.
How can this be done?

A: For those who might be interested, this is my programming kata:
class Base {
  String answer() { null }
  String question() { 'WHAT IS.... ?' }
}

class ClazzSpec extends Specification {

  def "test compile"() {
    given:
    String packageName = 'some.pckg'
    String body = """
package $packageName

class SomeClass extends Base {
  Closure cl = { a -> println a }
  @Override String answer(){ '42' }
  String json( m ){ JsonOutput.toJson( m ) }
  String longOne( int times ){
    times.times{ sleep 100 }
    'done'
  }
}
"""

    CompilerConfiguration cc = new CompilerConfiguration( targetDirectory:new File( './out' ) )
    ImportCustomizer imp = new ImportCustomizer()
    imp.addStarImports 'groovy.json', Base.package.name
    cc.addCompilationCustomizers imp, new ASTTransformationCustomizer( value:1, TimedInterrupt )

    new Compiler( cc ).compile packageName + '.SomeClass', body

    File base = new File( './out' )

    GroovyClassLoader gcl = new GroovyClassLoader()
    gcl.addClasspath './out'
    Class clazz = gcl.loadClass 'some.pckg.SomeClass'

    when:
    def inst = clazz.newInstance()

    then:
    inst.question() == 'WHAT IS.... ?'
    inst.answer() == '42'
    inst.json( [ q:42 ] ) == '{"q":42}'
    inst.longOne( 2 ) == 'done'

    when:
    inst.longOne 11

    then:
    thrown TimeoutException
  }

}


text:
Q: Sphinx doc: Process image directive to create HTML with base64 image data URI When Sphinx compiles an RST file with image directive, it results in a HTML that has  tag where the "src" attribute points to the image file.
Sample RST file
..image:: path/image.jpg

Resulting HTML

This means that the image is not contained within the HTML. The image file is a separate document from the HTML.
How can image directive be processed such that the resulting HTML has the  tag with 'src' attribute containing base64 encoded image data as shown below

In the above example, the image data is embedded into the HTML. How can this be achieved?


text:
Q: About graph of a Lebesgue measurable function I have been dealing with the following question, but could not find the answer. How can I solve ?
Question: Let $f\colon\mathbb{R} \to \mathbb{R}$ be a Lebesgue measurable function and $E:=\{(x,f(x)) \in \mathbb{R}^2 \mid x \in \mathbb{R} \} \subset \mathbb{R}^2$ be graph of the function. If $\operatorname{esssup}\{|f(x)| : x \in [-n,n] \} < \infty$ for all $n \in \mathbb{N}$, then for each $\epsilon > 0$
there exists a Lebesgue measurable set $K \subset \mathbb{R}^2$ such that $E \subset K$ and $\operatorname{Area}(K) < \epsilon$.
EDIT: My idea is that
Let $\{(a_i,b_i)\}$ be a sequence covering $\mathbb{R}$ with $b_i−a_i=1, \forall i \in \mathbb{N}$.
Define $$K_i:=\{(x,f(x)−\frac{\epsilon}{2^{i+2}})\times(x,f(x)+\frac{\epsilon}{2^{i+2}}) \mid x \in (a_i,b_i)\}$$
Then $K = \bigcup_i K_i$ covers $E$ and
$$\lambda(K) \leq \sum_i(b_i−a_i)\frac{2\epsilon}{2^{i+2}}= \frac{\epsilon}{2} < \epsilon.$$
If it is true, can you tell me in which step I used essentially boundedness of $f$ ?
Since $f(x)$ is essentially bounded, $\lambda((f(x)+\epsilon) - (f(x)-\epsilon))=2\epsilon$ ?


text:
Q: ArrayIndexOutOfBoundsException: 2 >= 1 on for each I'm new to Java and I'm coding a program that uses some JTables.
I have a button to remove the selected rows, which executes this :
public static void removerows() {
    int[] row_indexes = TableCA.table.getSelectedRows();
    for(int i=0;i<row_indexes.length;i++) {
        TableCA.model.removeRow(row_indexes[i]);
    }
}

but when it executes, I get this error :
Exception in thread "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException: 2 >= 1
    at java.util.Vector.removeElementAt(Vector.java:554)
    at javax.swing.table.DefaultTableModel.removeRow(DefaultTableModel.java:463)
    at fr.diagamma.project.PanelCaisse.removerows(PanelCaisse.java:78)

I searched a lot, and I didn't found anything for this case of OutOfBounds.
Thanks for help !

A: My suggestion is that you reverse the order of the loop:
public static void removerows() {
    int[] row_indexes = TableCA.table.getSelectedRows();
    for(int i=row_indexes.length - 1; i >= 0; i--) {
        TableCA.model.removeRow(row_indexes[i]);
    }
}

This starts with the last element and removes until it reaches the first.
Because, unless your row_indexes has only 1 element, otherwise it is wrong in 2 ways:

*

*The indexes in row_indexes is no longer updated after the removeRow().

*If the row_indexes is in increasing order, it is easily raise OutOfBoundException.


text:
Q: cypress: css selector to select an anchor by text I'm starting to play with cypress and I need to select a link like this:

           Alta

           Baja

Following this page I already tried with these:
cy.contains('a[href~=Agregar]')
cy.contains('a[href*="Agregar"]')
cy.contains('a:contains("^Agregar$") ')
cy.contains('a:contains("^Alta$") ')

But none of them seems to work. Any idea?

A: cy.contains() can also take two arguments:
cy.contains('a', 'Alta')

This gets the first a element containing the text Alta

A: There is this popular library > cypress-testing-library
This makes it really easy to get selectors by text, title, value, alt text etc.
For your issue you can simply use getByText method from this library:
cy.getByText('Agregar').click()

A: This seems to work, had to use cy.get instead of contains
cy.get('a[href*="Agregar"]')
  .click()

A: Another way is, you could probably drill down till  tag via parent() and find() method in cypress;
cy.get('a:contains("Agregar")').parents('.ToolBarBkg').find('tbody').find('tr').find('td').find('a').contains("Agregar").click();


text:
Q: Swift must use lazy for stored property when use self in closure? I create subclass for UITableViewCell, and want to add UILabel for subview. I use the stored property for get UILabel, like this
class ZXArtistListCell: UITableViewCell {
  lazy var label: UILabel = {
    let view = UILabel()
    self.contentView.addSubview(view)
    return view
  }()
}

but ,when I delete lazy or replace lazy var with let, it's give me error,

Value of type'(NSObject) -> ZXArtistCell' has no member 'contentView'

So, What's that meaning?

A: When you are declaring label with lazy initial value is not calculated until the first time it is used.
so the probably the Instantiates views was completed.
But the concept of using let in Swift, variables which are let have to be initialized before you can use self.
Using lazy var means that the compiler can verify that the value assigned to label won't be accessed before self is a valid object, because it won't be possible to call label until all other members of the class have been initialized.

A:
You must always declare a lazy property as a variable (with the var
  keyword), because its initial value might not be retrieved until after
  instance initialization completes. Constant properties must always
  have a value before initialization completes, and therefore cannot be
  declared as lazy.

Apple Document


text:
Q: Safari issues, variable undefined (XML/Javascript) I have this piece of code, it works in all browsers, except for Safari:
        // Create a connection to the file.
        var Connect = new XMLHttpRequest();

        // Define which file to open and
        // send the request.
        Connect.open("GET", "<?php echo $fileName;?>", false);
        Connect.setRequestHeader("Content-Type", "text/xml");
        Connect.setRequestHeader("Cache-Control", "no-cache");
        Connect.send();

        // Place the response in an XML document.
        var TheDocument = Connect.responseXML;

        // Place the root node in an element.
        var questions = TheDocument.childNodes[0];

        // Retrieve each customer in turn.
        for (var i = 0; i < 1; i++) {
            console.log(i);
            console.log("fake var");
            var question = questions.children[0];
            console.log(question);
        }

Variable $filename is the php link to the XML file i'm reading.
I have the following issue, the code runs into the For loop, i can log var "i", and "fake var". But once i define var question as questions.children[0], the code stops. I cant log the question var in safari.
Any ideas? ( Feedback also welcome, still learning javascript/xml )
Example of my XML:
<?xml version='1.0' encoding="UTF-8" ?>
<Beantwoordt_kritiek id="1" admin="Jan Hut" categorie="Omgaan met elkaar" winswf="images/Kado (1).jpg">
  <gebruikers_vraag1>
    <vraag><![CDATA[Sleep de puzzelstukken naar het juiste vakje.]]></vraag>
    <s_vraag><![CDATA[sounds/puzzel.mp3]]></s_vraag>
    <thumb1><![CDATA[images/527puzzel1_1.jpg]]></thumb1>
    <thumb2><![CDATA[images/527puzzel1_2.jpg]]></thumb2>
    <thumb3><![CDATA[images/527puzzel1_3.jpg]]></thumb3>
    <thumb4><![CDATA[images/527puzzel1_4.jpg]]></thumb4>
    <vraagFoto><![CDATA[images/527puzzel1.jpg]]></vraagFoto>
  </gebruikers_vraag1>
</Beantwoordt_kritiek>

A: You could use this script, so safari give back the same result.
<script>
function getChildren(element) {
  if (element.children == undefined) {
    var childNodes = element.childNodes
    var children = []
    for(var i = 1; i < childNodes.length; i += 2) {  // take every second element
      children.push(childNodes[i]);
    }
    return children;
  } else {
    return element.children
  }
}
</script>

and then call this in your script
var question = getChildren(questions)[0];


text:
Q: Java how can remove everything between two substring in a string I want to remove any substring(s) in a string that begins with 'galery' and ends with 'jssdk));'
For instance, consider the following string:
Galery something something.... jssdk));
I need an algorithm that removes 'something something....' and returns 'Galery jssdk));'
This is what I've done, but it does not work.
newsValues[1].replaceAll("Galery.*?jssdK));", "");

A: Could probably be improved, I've done it fast:
  public static String replaceMatching(String input, String lowerBound, String upperBound{
    Pattern p = Pattern.compile(".*?"+lowerBound+"(.*?)"+upperBound+".*?");
    Matcher m = p.matcher(input);
    String textToRemove = "";

    while(m.find()){
        textToRemove = m.group(1);
    }
    return input.replace(textToRemove, "");
}

UPDATE Thx for accepting the answer, but here is a smaller reviewed version:
 public static String replaceMatching2(String input, String lowerBound, String upperBound){
      String result = input.replaceAll("(.*?"+lowerBound + ")" + "(.*?)" + "(" + upperBound + ".*)", "$1$3");
      return result;
 }

The idea is pretty simple actually, split the String into 3 groups, and replace those 3 groups with the first and third, droping the second one.

A: You are almost there, but that will remove the entire string. If you want to remove anything between Galery and jssdK));, you will have to do something like so:
String newStr = newsValues[1].replaceAll("(Galery)(.*?)(jssdK\\)\\);)","$1$3");
This will put the strings into groups and will then use these groups to replace the entire string. Note that in regex syntax, the ) is a special character so it needs to be escaped.
String str = "GaleryABCDEFGjssdK));";
String newStr = str.replaceAll("(Galery)(.*?)(jssdK\\)\\);)","$1$3");
System.out.println(newStr);

This yields: GaleryjssdK));
I know that the solution presented by @amit is simpler, however, I thought it would be a good idea to show you a useful way in which you can use the replaceAll method.

A: Simplest solution will be to replace the string with just the "edges", effectively "removing" 1 everything between them.
newsValues[1].replaceAll("Galery.*?jssdK));", "GaleryjssdK));");

1: I used "" here because it is not exactly replacing - remember strings are immutable, so it is creating a new object, without the "removed" part.

A: newsValues[1] = newsValues[1].substring(0,6)+newsValues.substring(newsValues[1].length()-5,newsValues[1].length())

This basically concatenates the "Galery" and the "jssdk" leaving or ignoring everything else. More importantantly, you can simply assign newValues[1] = "Galeryjssdk"


text:
Q: Shadow or Border around a scrollview iphone i would like to draw a border / shadow around a uiscrollview, i know that i could get there with an additional view or scrollview but dont like the handling an drawbacks but i heard that there should be a possibility to dirctly draw a border to a scrollview and that is what i would prefer.
I am quiet new to iphone developement,any answer would helpful.

A: Dont forget to:
#import <QuartzCore/QuartzCore.h>

If you want to use
myView.layer.borderWidth = 2;
myView.layer.borderColor = [UIColor blackColor].CGColor;

A: To get the CGColorRef from an UIColor you can also use this example:
myView.layer.borderWidth = 2;
myView.layer.borderColor = [UIColor blackColor].CGColor;

A: If you use the layer property of your scroll view (or any UIView) you can easily get a solid border...
#import <QuartzCore/QuartzCore.h>
...
myView.layer.borderWidth = 2;
myView.layer.borderColor = [UIColor blackColor].CGColor;

You can also use the layer to apply real-time shadows by setting the layer.shadow* properties, but performance can be slow with this technique, so I generally prefer to use the following more complex, but more performant technique. You can create a PNG image with transparency in the middle and shadows around the edge - it needs to have 9 distinct areas: 4 for each corner, 4 for each edge, and a completely transparent 1x1 pixel area in the middle. For example if your shadow extends 6 pixels into your image, your image would be 13x13 with the 6 pixel wide/high borders and the 1x1 area in the middle. Then you set it as a scalable image using:
newImage = [image stretchableImageWithLeftCapWidth:6 topCapHeight:6];

UPDATE: Since iOS 5.0 stretchableImageWithLeftCapWidth:topCapHeight: is deprecated so only use this if you still want to support iOS 4.x devices. If you want to support only iOS 5.0+ devices use this instead:
newImage = [image resizableImageWithCapInsets:UIEdgeInsetsMake(6, 6, 6, 6)];

Then you put the image on the parent view so it takes up the entire area of the scroll view.  If you want the shadows to go OVER your scrollable elements, (so your scroll view looks inset/behind the rest of the page) then place a transparent UIView over the top with the shadow image on it so that it shows through to your scroll view behind it.

A: myView.layout.borderColor generates an incompatible pointer warning when using UIColor, and did not change the border for me.
Using CGColorRef worked for me instead:
CGFloat lComponents[4] = {0,0,0,1};
CGColorSpaceRef lColorSpace = CGColorSpaceCreateDeviceRGB();
myView.layer.borderColor = CGColorCreate(lColorSpace, lComponents);
CGColorSpaceRelease(lColorSpace);


text:
Q: Deprecated vs. Denigrated in JavaDoc? In the JavaDoc for X509Certificate getSubjectDN() it states:

Denigrated, replaced by getSubjectX500Principal().

I am used to seeing Deprecated in the for methods that should not be used any longer, but not Denigrated. I found a bug report about this particular case where it was closed with comment:

This isn't a bug. "Deprecated" is meant to be used only in serious
  cases.

When we are using a method that is Deprecated, the general suggested action is to stop using the method.
So what is the suggested action when a method is marked as Denigrated?

A: Merriam-Webster definition of denigrate suggests:

1: to attack the reputation of : defame <denigrate one's opponents>
  2: to deny the importance or validity of: belittle <denigrate their achievements>

Based on what is written in another related bug, defame / belittle appears to match the intent of wording used in javadocs - Bug ID: 4959744 Denigrate X509Certificate.getSubjectDN() & co:

The methods getSubjectDN() and getIssuerDN() in X509Certificate and getIssuerDN() in X509CRL are problematic. They return an unspecified class implementing the java.security.Principal interface, which has a very loose specification.
Because no additional specification is present in the getSubjectDN() and getIssuerDN() methods, it is permissible for implementations to return an arbitrary, implementation specific class. Real world experience has shown that this is the case resulting in non-portability or unreliability of the code. For compatibility reasons, the specifications for those methods cannot be changed and they must be considered unsalvageable.
Replacement methods getSubjectX500Principal() & co that return an instance of the well-defined X500Principal class were added in JDK 1.4. The implementations of those methods have been designed to avoid all problems of this sort. However, the new methods suffer from underexposure and programmers continue to use the familiar and more intuitively named getSubjectDN() & co methods.
To change this, the old getSubjectDN() and getIssuerDN() methods should be deprecated. That will ensure that developers who use this methods receive a compile time warning....
EVALUATION
...Deprecation was considered inappropriate in this case. Instead, cautionary comments were added to the JavaDoc.

The fact that reading Bug ID 5008142 has left you confused about this "denigrated" stuff looks more like a fault of developer who dealt with it.
They should have found bug 4959744 and refer it in their evaluation, instead of vague statement "meant to be used only in serious cases". They could probably even close as duplicate, with justification like "Deprecation has been considered, evaluated and rejected in favor of denigration per Bug ID 4959744".
At the very very least they could refer Bug ID 4959744 (maybe along with 4638294) in the Related Reports field (called See Also in old bugs.sun.com iirc) of their bug tracker. That this has not been done makes one suspect that they did not search for related issues at all.

A: After some more digging I was able to find a blog post called Deprecation in the JDK. It basically states that things marked Deprecated are considered harmful to be used, and that there are some things that are simply discouraged.

The general policy for several feature releases is that core JDK
  components are only marked as deprecated if they are actively harmful.
  If using a class or method is just ill-advised, that is usually not
  sufficient to earn the deprecated mark.

He mentioned that there currently a way to mark an item as being discouraged to use, but that they might eventually add a way to do this.

At some point, this kind of advice might be formalized with a
  less-harmful-than-deprecated "denigration" facility based a
  combination of javadoc tags and annotations to allow programmatic
  checks be made for usage of these less harmful API elements to.

While I can not find anything else specifically about a decision to use the term Denigrated this seems pretty close. And based on this it seems the action a developer should take is the same as Deprecated, do not use the method.


text:
Q: django dynamic translate on AppEngine I need dynamic translation in django on AppEngine.
I found nice django modul for dynamic translations: django-rosetta, but it open files (django.po...) and it is not allowed on AppEngine.
Exist some other translate modul where is compatibile (or with small fix) with AppEngine?
Thanks. Martin

A: There is a rosettaappengine Github project that should help you to get django-rosetta to work in GAE. The process seems a bit complicated though.