text:
Q: How to grep with a regex to eliminate this stacktrace? I would like to eliminate a stacktrace from my log file, such that only the SQL text is displayed. This works as I would like on RegExr.com:
'java.lang((.|\n)*)java:745'
But it does not work with grep -v
grep -v 'java.lang((.|\n)*)java:745'
Any suggestions how I can use grep -v to only display the query text?
CONFIG: 204658E4 SQL: select  *
        from    table
        where   column =  :1
java.lang.Throwable: No Error
    at oracle.jdbc.driver.OracleStatement.doExecuteWithTimeout(OracleStatement.java:1624)
    at oracle.jdbc.driver.OraclePreparedStatement.executeInternal(OraclePreparedStatement.java:4347)
    at oracle.jdbc.driver.OraclePreparedStatement.executeQuery(OraclePreparedStatement.java:4426)
    at oracle.jdbc.driver.OraclePreparedStatementWrapper.executeQuery(OraclePreparedStatementWrapper.java:4733)
    at sun.reflect.GeneratedMethodAccessor47.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at oracle.ucp.jdbc.proxy.PreparedStatementProxyFactory.invoke(PreparedStatementProxyFactory.java:125)
    at com.sun.proxy.$Proxy60.executeQuery(Unknown Source)
    at sqlj.runtime.ExecutionContext$OracleContext.oracleExecuteQuery(ExecutionContext.java:71)
    at me.loadQuery(DataBean.java:364)
    at me.loadQuery(DataBean.java:411)
    at org.apache.jsp.jsp.secure.navigate_jsp.displayMenu(navigate_jsp.java:43)
    at org.apache.jsp.jsp.secure.navigate_jsp._jspService(navigate_jsp.java:472)
    at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
    at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:438)
    at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:396)
    at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:340)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:292)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:240)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:212)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:94)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:504)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:141)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
    at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:620)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:502)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1132)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:684)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1539)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1495)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:745)

A: From your given output, you can see that the the Java exception follows a very specific pattern:

*

*the line with the error message, starting with java.lang.Throwable

*the stacktrace lines, all starting with 0 or more spaces, followed by at
Using grep to filter the lines, we can see from the man page, that you only need to specify a part of the line to dismiss it (when using the -v flag to ignore lines matching the pattern).
So based on that, we can build the regular expression and the command:
grep -v '^java.lang.Throwable\| *at' your_log_file.log

*

*^<expression> The expression must match a the beginning of the line

*<expr1>\|<expr2> The expression matches if expr1 OR expr2 matches.

*java.lang.Throwable matches this exact string

**at can be decomposed in 2:

*

** (a space followed by a *) matches any number of spaces (0 or more)

*at matches this exact string

So to sum it up, it will ignore all the lines that starts by either java.lang.Throwable or any number of spaces followed by at.


text:
Q: Replacing £ sign with £ when page gets loaded through JQuery I have a problem with the £ sign. When the page is loaded it adds an additional character and appears like this: £, I want to write Jquery from which I can replace this character with £ for the entire page.
I am using the utf-8 charset, so that's not where the problem is.

A: To me, looks like a UTF-8 character being shown in an ISO-8859-1 charset.
I wouldn't recommend you to do text replacements on your page, since all the text nodes have to be traversed and inspected.
I recommend you to re check your encoding, and maybe you could use '£' rather than '£'.

A: My suggestion is that you should double check the encoding.
Using UTF-8 as a character encoding does not ensure by itself things are right.
For example, sending UTF-8 which is then decoded as if it were ISO-8859-15 would explain such a problem.
Verify all the data sources, you might have one in an unexpected encoding. I agree with cms, do not use text replace to delete this, fix the problem at its source.
You can play with iconv to see how your data looks when converted from and to different encodings.
UPDATE: I see your page perfectly, so maybe it's your browser decoding the characters wrongly, check the character encoding settings on your browser

A: I have resolved this issue with web.config
I have add below entry in my web.config
<globalization requestEncoding="utf-8" responseEncoding="utf-8" fileEncoding="utf-8" culture="en-GB"  uiCulture ="en-GB" />

Cheers!
Thanks for your support

redpajama_set_name: RedPajamaStackExchange


text:
Q: Mandar ID en la URL del Google Form y almacenarla He creado un formulario de Google y quiero que cuando se rellene la hoja de cálculo almacene el dato ID (identificador de la persona) es decir, quiero enviar ese ID en la URL.
Este ID es único y lo saco de una web en la que se tienen que loguearse los usuarios. ¿Cómo podría hacerlo?
He encontrado un ejemplo que está muy bien, pero no consigo sacar la FORMKEY en los nuevos formularios.
https://docs.google.com/spreadsheets/d/19mZRWDE76ijno7Y3oU7QkfxMqLmPYeHFw8f4-1vV3fE/edit?hl=en_US&hl=en_US#gid=0

A: Me parece que lo que quieres hacer es mas sencillo lograrlo usando el URL prellenado. En Enviar un formulario a los encuestados se indica como obtenerlo.
Por otro lado, también me parece que la fuente a la que has recurrido corresponde a una versión muy vieja ya que ahora el FORMKEY es llamado simplemente id. Si mal no recuerdo hace tiempo el id era el mismo para el formulario en modo de edición que en modo publicado, pero ahora no. Abajo pongo un ejemplos de estos URLs, pongo en formato normal los id's.
Edición

*

*https://docs.google.com/forms/d/1t-J3rvQDnsV6avLe-mn6Zf3QALmVp8iHnKz-UYH3Fow/edit
Publicado

*

*https://docs.google.com/forms/d/e/1FAIpQLScwZm_emVRyey8N9gzD_fj-OEs5hhOrRnVM7it1KUowWPk_4A/viewform
Si continuas con la intención de usar el id, te podría resultar conveniente obtenerlo mediante Google Apps Script con el método getId.


text:
Q: How does the operating system read the page size from hardware? Books on operating systems usually mentions that the page size is decided by the processor architecture, for example Intel x86 supports 4KB page size. I have a perception that when we were installing an operating system on our hardware, the OS had read the page size of 4KB from hardware and logically divided the virtual address space into 4KB size pages and memory into frames respectively.
If my perception is true, from where or from which location in hardware does the operating system read this value of 4KB from the processor? What mechanism does the OS use to determine the page size provided by hardware? Can anybody enlighten me on this? How (On What Basis) Intel decides to keep 4KB page size.

A: Operating systems hard code the page size depending on the architecture (and in some cases, build-time kernel configuration). For example, on x86 the basic page size is always 4KiB — this is a property of the CPU architecture; on Linux you'll see this defined in include/asm/page_types. On 64-bit ARM, the page size can be configured at build-time as 4KiB, 16KiB or 64KiB. Some architectures multiple page sizes at runtime (e.g. huge pages on x86), but all the sizes are known ahead of time and the base size is fixed.
On Linux, the canonical definition of the page size is PAGE_SIZE, and you get it by including asm/page.h, which is architecture-specific (which might pull in other headers, as happens on x86). Elixir provides a handy list of all the PAGE_SIZE definitions.
Most architectures supported by the Linux kernel support 4KiB pages; the exceptions are Alpha, ARC, some Motorola 68k systems, OpenRISC and 64-bit SPARC, which all use 8KiB pages. Many architectures can be configured to use other pages sizes.


text:
Q: How to detect whether physical device is online or offline in Windows using pInvoke I wrote code that can write and read data from physical disk.
I open the physical disk using pInvoke CreateFile and use FileStream to perform read and write data.
When physical disk is online, every thing works great.
In case the physical disk is offline and I try to write to disk, I get an error
System.IO.IOException: 'The media is write protected.'
How can I detect if disk is offline without trying to write to disk.
Here is the code that create the FileStream and perform writes to disk
    private const uint GENERIC_READ = 0x80000000;
    private const uint GENERIC_WRITE = 0x40000000;
    private const uint OPEN_EXISTING = 3;
    private const uint FILE_FLAG_NO_BUFFERING = 0x20000000;
    private const uint FILE_FLAG_WRITE_THROUGH = 0x80000000;

    [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
    private static extern SafeFileHandle CreateFile(string lpFileName, uint dwDesiredAccess,
                                        uint dwShareMode, IntPtr lpSecurityAttributes, uint dwCreationDisposition,
                                        uint dwFlagsAndAttributes, IntPtr hTemplateFile);

    public void OpenFile()
    {
        m_handleValue = CreateFile(DevicePath, GENERIC_WRITE | GENERIC_READ,
                            0x3, IntPtr.Zero, OPEN_EXISTING,
                            FILE_FLAG_NO_BUFFERING | FILE_FLAG_WRITE_THROUGH
                            , IntPtr.Zero);

        m_fileStream = new FileStream(m_handleValue, FileAccess.ReadWrite, 512);
    }

    public void WriteData(int offset, byte[] data)
    {
        m_fileStream.Seek(offset, SeekOrigin.Begin);
        m_fileStream.Write(data, 0, data.Length);
    }

A: Using DeviceIoControl pInvoke we can review attribute DISK_ATTRIBUTE_OFFLINE
public static class RawDeviceInfoProvider
    {
        private const int IOCTL_DISK_GET_DISK_ATTRIBUTES = 0x000700F0;
        private const uint DISK_ATTRIBUTE_OFFLINE = 0x1;

        [StructLayout(LayoutKind.Sequential)]
        public struct GetDiskAttributes
        {
            public uint Version;
            public uint Reserved;
            public ulong Attributes;
        }

        [DllImport("kernel32.dll", ExactSpelling = true, SetLastError = true, CharSet = CharSet.Auto)]
        public static extern bool DeviceIoControl(SafeHandle hDevice, uint dwIoControlCode, IntPtr lpInBuffer,
            uint nInBufferSize, IntPtr lpOutBuffer, uint nOutBufferSize, out uint lpBytesReturned, IntPtr lpOverlapped);

        public static bool GetOnlineStatus(SafeFileHandle hDevice)
        {
            uint dummy;
            GetDiskAttributes attributes = new GetDiskAttributes();
            IntPtr lpOutBuffer = Marshal.AllocHGlobal(Marshal.SizeOf(attributes));
            bool success = DeviceIoControl(hDevice, IOCTL_DISK_GET_DISK_ATTRIBUTES, IntPtr.Zero, 0,
                lpOutBuffer, (uint)Marshal.SizeOf(typeof(GetDiskAttributes)), out dummy, IntPtr.Zero);
            attributes = (GetDiskAttributes)Marshal.PtrToStructure(lpOutBuffer, typeof(GetDiskAttributes));
            Marshal.FreeHGlobal(lpOutBuffer);
            if (!success)
            {
                int errorCode = Marshal.GetLastWin32Error();
                throw new IOException("Unable to retrieve disk attributes, Error: " + errorCode);
            }
            bool isOffline = (attributes.Attributes & DISK_ATTRIBUTE_OFFLINE) > 0;
            return !isOffline;
        }
    }


text:
Q: Determine order of pole under condition: $ N|z-a|^{-\frac{5}{2}}| \leq |f(z)| \leq M|z-a|^{-\frac{7}{2}}. $ Let $f: D \Rightarrow \mathbb{C}$ be analytic, where $D$ is some domain. Let $a$ be a singularity of $f$.
Assume that there are an $r > 0$ and positive numbers $M$ and $N$ such that
$$
N|z-a|^{-\frac{5}{2}}| \leq |f(z)| \leq M|z-a|^{-\frac{7}{2}},
$$
when $0 <|z-a|< r$.
Now $a$ is a pole of $f$ since $\lim_{z\to a} f(z) = \infty$.
The order of the pole is higher than 2, since $\lim_{z\to a} (z-a)^2f(z) = \infty$. It is smaller than or equal to 4, since $\lim_{z\to a} (z-a)^4f(z) = 0$.
But my question is how would I determine whether the order of the pole is really 4, or in fact 3?
Thanks in advance!

A: If $f$ has a pole of order $d$ at $z=a$ then $
 \lim_{z \to a} (z-a)^d f(z)$ exists and is $ \ne 0, \infty $.
It follows from your estimates that $\frac 52 \le d \le \frac 72$, and that leaves only one possible choice for the integer $d$.


text:
Q: php will date function with week ever return 0? I came across this conditional in a function I'm working with:
<?php
$thisweek = date('W');
if ($thisweek == 0) {
  // ...
}

I didn't write this conditional and when I went to look up the range of the date('W') http://us3.php.net/manual/en/function.date.php it gives an example but no range like 00-52 or 01-52.
My question is will date('W') ever return zero meeting this conditional?

A: No. It starts at 01 and ends at 52. See my test.:
echo date('W', strtotime('2013-01-01')) . PHP_EOL;
echo date('W', strtotime('2012-12-30')) . PHP_EOL;

Output
 01
 52

Just don't assume that Jan 1st will be week 01 or Dec 31st will be week 52:
echo date('W', strtotime('2012-12-31')) . PHP_EOL;

Output
 01

A: The PHP date('W') function will never1 return 0.
Look it up in the source code of PHP, ext/date/php_date.c.
Slightly formatted around line 950-1000:
timelib_sll isoweek, isoyear;
int weekYearSet = 0;
...
/* week */
case 'W':
    if(!weekYearSet) {
        timelib_isoweek_from_date(t->y, t->m, t->d, &isoweek, &isoyear);
        weekYearSet = 1;
    }
    length = slprintf(buffer, 32, "%02d", (int) isoweek); break; /* iso weeknr */

What is timelib_isoweek_from_date? Well... looking at the logic in ext/date/lib/dow.c, from line 82 it can be concluded that the week number varies from 1 to 53:
/* Find if Y M D falls in YearNumber Y-1, WeekNumber 52 or 53 */
...
/* 8. Find if Y M D falls in YearNumber Y+1, WeekNumber 1 */
...
/* 9. Find if Y M D falls in YearNumber Y, WeekNumber 1 through 53 */

If you do not believe me, look in the code yourself:

*

*http://git.php.net/?p=php-src.git;a=blob;f=ext/date/php_date.c

*http://git.php.net/?p=php-src.git;a=blob;f=ext/date/lib/dow.c

1) "Never" means "as long as there is no bug in PHP".


text:
Q: Getting silent notification values when app starts I am trying to implement cache meachanism for FCM on IOS. I am using Xamarin Forms with  CrossGeeks FirebasePushNotificationPlugin
Push notification service works fine. I am using payload pattern as below
{
    "data": {
        "message" : "my_custom_value",
        "other_key" : true,
        "body":"test"
     },
     "notification": {
       "body" : "hello",
       "title": "firebase",
       "sound": "default",
        "content_available" : true
     },
     "priority": "high",
     "condition": "'general' in topics"
}

Above pattern appears delivered notification as alert on IOS main screen.
I have written a Dependency Service for getting undeleted or unopened accumulated notifications when app starts. Dependency Service include below codes
await UNUserNotificationCenter.Current.GetDeliveredNotificationsAsync();

When I use above payload, I can get accumulated notifications. But when I use payload pattern as below, I can not.
{
    "data": {
        "message" : "my_custom_value",
        "other_key" : true,
        "body":"test"
     },
     "notification": {
        "content_available" : true
     },
     "priority": "high",
     "condition": "'general' in topics"
}

Actually I would like to send 2 payload types for every notification for my cache mechanism because of prevent the user's delete action. After that, I would like to show cached notifications without any lost in my app's notification page.
Shortly my question about "I am not getting silent payload values from UNUserNotificationCenter this approach is possible or not?"
Or can I prevent the user's notification delete action from IOS main screen when my app is terminated.
Note: My minimum OS version is 10.0 in info.plist
Thank you in advance.


text:
Q: HtmlHelper in ASP.NET MVC3 that uses Action as template: Razor syntax? Let me preface this by saying that perhaps there's a better way to do this, and Razor is lighting the way. In any case, I have an HTML helper that acts as a repeater of sorts, but after an arbitrary number of repeats, it inserts an alternate template. Most obvious use? Tables that start a new row after x cells. The helper looks like this:
public static void SeriesSplitter<T>(this System.Web.Mvc.HtmlHelper htmlHelper, IEnumerable<T> items, int itemsBeforeSplit, Action<T> template, Action seriesSplitter)
{
    if (items == null)
        return;
    var i = 0;
    foreach (var item in items)
    {
        if (i != 0 && i % itemsBeforeSplit == 0)
            seriesSplitter();
        template(item);
        i++;
    }
}

And in a Webforms view, the usage looks like this:

    <% Html.SeriesSplitter(Model.Photos, 4, photo => { %>
            <img src="<%=ResolveUrl("~/Thumbnail.ashx?id=" + photo.ID)%>" alt="<%=Html.Encode(photo.Title)%>" />
    <% }, () => { %>

<% }); %>

In this case, you'd have a table that renders four cells, then starts a new row by using the alternate template (the row start and end tags). The problem is that I can't find a way to make this work in Razor. Using a lambda inside of a Razor view seems like a pretty weird construct.
What would you do?

A: Phil actually had a good post that solves the problem here:
http://haacked.com/archive/2011/02/27/templated-razor-delegates.aspx

A: This is a job for Func<object, HelperResult> (though I'm doing this from memory so it might need tweaking):
public static void SeriesSplitter<T>(this System.Web.Mvc.HtmlHelper htmlHelper,
                                     IEnumerable<T> items,
                                     int itemsBeforeSplit,
                                     Func<object, HelperResult> template,
                                     Func<object, HelperResult> seriesSplitter) {
    //pretty  much same code here as before
}

Then you would call it like so
@Html.SeriesSplitter(Model.Items, 3, @item.Id	, @:
)

Just note that because of how Razor does tag balancing during parsing you need the new line after @:


text:
Q: How to change backgroundColor for Touchable Opacity using .map() in function? So i am making a quiz app and the problem is i need to highlight checked answer button. I figured out how to do it with Refs, but it works for only three questions. How do i change it to work for the whole test.
mapping through question answers
                <TouchableOpacity
                  key={answers.buttonId}
                  onPress={() => {
                    checkIfCorrect(answers.isCorrect);

                    resetColors(answers.buttonId);
                    highlightBlack(answers.buttonId);
                  }}
                  style={{
                    borderWidth: 1,
                    width: "80%",
                    margin: "5%",
                  }}
                >
                  <View ref={(el) => (myRefs.current[answers.buttonId] = el)}>
                    <Text
                      style={{
                        color: "grey",
                        fontSize: 32,
                        textAlign: "center",
                      }}
                    >
                      {answers.answerText}
                    </Text>
                  </View>
                </TouchableOpacity>
              ))}```
Array element with question
```{
      questionNumber: 3,
      questionText: "Solve 1 - 5x = 0.",
      questionImage: "",
      answers: [
        { answerText: "5", isCorrect: true },
        { answerText: "-1/5", isCorrect: false },
        { answerText: "1/5", isCorrect: true },
        { answerText: "4", isCorrect: false },
      ],
    },```

This how i use refs
```  const highlightBlack = (itemId) => {
    myRefs.current[itemId].setNativeProps({
      style: { backgroundColor: "black" },
    });
  };

  const resetColors = (itemId) => {
    myRefs.current.forEach((ref) => {
      if (ref !== itemId) {
        ref.setNativeProps({ style: { backgroundColor: "white" } });
      }
    });
  };```

It crashes after the 3rd question


text:
Q: Weird behavior trying to convert case classes to heterogeneous lists recursively with Shapeless I stayed up way too late last night trying to figure out this Shapeless issue and I'm afraid it's going to eat my evening if I don't get it off my chest, so here goes.
In this minimized version I'm just defining a type class that will recursively convert case classes into heterogeneous lists:
import shapeless._

trait DeepHLister[R <: HList] extends DepFn1[R] { type Out <: HList }

trait LowPriorityDeepHLister {
  type Aux[R <: HList, Out0 <: HList] = DeepHLister[R] { type Out = Out0 }

  implicit def headNotCaseClassDeepHLister[H, T <: HList](implicit
    dht: DeepHLister[T]
  ): Aux[H :: T, H :: dht.Out] = new DeepHLister[H :: T] {
    type Out = H :: dht.Out
    def apply(r: H :: T) = r.head :: dht(r.tail)
  }
}

object DeepHLister extends LowPriorityDeepHLister {
  implicit object hnilDeepHLister extends DeepHLister[HNil] {
    type Out = HNil
    def apply(r: HNil) = HNil
  }

  implicit def headCaseClassDeepHLister[H, R <: HList, T <: HList](implicit
    gen: Generic.Aux[H, R],
    dhh: DeepHLister[R],
    dht: DeepHLister[T]
  ): Aux[H :: T, dhh.Out :: dht.Out] = new DeepHLister[H :: T] {
    type Out = dhh.Out :: dht.Out
    def apply(r: H :: T) = dhh(gen.to(r.head)) :: dht(r.tail)
  }

  def apply[R <: HList](implicit dh: DeepHLister[R]): Aux[R, dh.Out] = dh
}

Let's try it out! First we need some case classes:
case class A(x: Int, y: String)
case class B(x: A, y: A)
case class C(b: B, a: A)
case class D(a: A, b: B)

And then (note that I've cleaned up the type syntax for the sake of this not being a totally unreadable mess):
scala> DeepHLister[A :: HNil]
res0: DeepHLister[A :: HNil]{
  type Out = (Int :: String :: HNil) :: HNil
} = DeepHLister$$anon$2@634bf0bf

scala> DeepHLister[B :: HNil]
res1: DeepHLister[B :: HNil] {
  type Out = (
    (Int :: String :: HNil) :: (Int :: String :: HNil) :: HNil
  ) :: HNil
} = DeepHLister$$anon$2@69d6b3e1

scala> DeepHLister[C :: HNil]
res2: DeepHLister[C :: HNil] {
  type Out = (
    ((Int :: String :: HNil) :: (Int :: String :: HNil) :: HNil) ::
    (Int :: String :: HNil) ::
    HNil
  ) :: HNil
} = DeepHLister$$anon$2@4d062faa

So far so good. But then:
scala> DeepHLister[D :: HNil]
res3: DeepHLister[D :: HNil] {
  type Out = ((Int :: String :: HNil) :: B :: HNil) :: HNil
} = DeepHLister$$anon$2@5b2ab49a

The B didn't get converted. If we turn on -Xlog-implicits this is the last message:
<console>:25: this.DeepHLister.headCaseClassDeepHLister is not a valid implicit value for DeepHLister[shapeless.::[B,shapeless.HNil]] because:
hasMatchingSymbol reported error: diverging implicit expansion for type DeepHLister[this.Repr]
starting with method headNotCaseClassDeepHLister in trait LowPriorityDeepHLister
              DeepHLister[D :: HNil]
                         ^

Which doesn't make sense to me—headCaseClassDeepHLister should be able to generate DeepHLister[B :: HNil] just fine, and it does if you ask it directly.
This happens on both 2.10.4 and 2.11.2, and with both the 2.0.0 release and master. I'm pretty sure this has to be a bug, but I'm not ruling out the possibility that I'm doing something wrong. Has anyone seen anything like this before? Is there something wrong with my logic or some restriction on Generic I'm missing?
Okay, thanks for listening—maybe now I can go read a book or something.

A: This now works more or less as written using recent shapeless-2.1.0-SNAPSHOT builds, and a close relative of the sample in this question has been added there as an example.
The problem with the original is that each expansion of a Generic introduces a new HList type into the implicit resolution of the DeepHLister type class instances and, in principle, could produce an HList type that is related to but more complex than some type seen previously during the same resolution. This condition trips the divergence checker and aborts the resolution process.
The exact details of why this happens for D but not for C is lurking in the details of the implementation of Scala's typechecker but, to a rough approximation, the differentiator is that during the resolution for C we see the B (larger) before the A (smaller) so the divergence checker is happy that our types are converging; conversely during the resolution for D we see the A (smaller) before the B (larger) so the divergence checker (conservatively) bails.
The fix for this in shapeless 2.1.0 is the recently enhanced Lazy type constructor and associated implicit macro infrastructure. This allows much more user control over divergence and supports the use of implicit resolution to construct the recursive implicit values which are crucial to the ability to automatically derive type class instances for recursive types. Many examples of this can be found in the shapeless code base, in particular the reworked type class derivation infrastructure and Scrap Your Boilerplate implementation, which no longer require dedicated macro support, but are implemented entirely in terms of the Generic and Lazy primitives. Various applications of these mechanisms can be found in the shapeless examples sub-project.

A: I took a slightly different approach.
trait CaseClassToHList[X] {
  type Out <: HList
}

trait LowerPriorityCaseClassToHList {
  implicit def caseClass[X](implicit gen: Generic[X]): CaseClassToHList[X] {
    type Out = generic.Repr
  } = null
}

object CaseClassToHList extends LowerPriorityCaseClassToHList {
  type Aux[X, R <: HList] = CaseClassToHList[X] { type Out = R }

  implicit def caseClassWithCaseClasses[X, R <: HList](
    implicit toHList: CaseClassToHList.Aux[X, R],
    nested: DeepHLister[R]): CaseClassToHList[X] {
    type Out = nested.Out
  } = null
}

trait DeepHLister[R <: HList] {
  type Out <: HList
}

object DeepHLister {

  implicit def hnil: DeepHLister[HNil] { type Out = HNil } = null

  implicit def caseClassAtHead[H, T <: HList](
    implicit head: CaseClassToHList[H],
    tail: DeepHLister[T]): DeepHLister[H :: T] {
    type Out = head.Out :: tail.Out
  } = null

  def apply[X <: HList](implicit d: DeepHLister[X]): d.type = null
}

Tested with the following code:
case class A(x: Int, y: String)
case class B(x: A, y: A)
case class C(b: B, a: A)
case class D(a: A, b: B)

object Test {

  val z = DeepHLister[HNil]
  val typedZ: DeepHLister[HNil] {
    type Out = HNil
  } = z

  val a = DeepHLister[A :: HNil]
  val typedA: DeepHLister[A :: HNil] {
    type Out = (Int :: String :: HNil) :: HNil
  } = a

  val b = DeepHLister[B :: HNil]
  val typedB: DeepHLister[B :: HNil] {
    type Out = ((Int :: String :: HNil) :: (Int :: String :: HNil) :: HNil) :: HNil
  } = b

  val c = DeepHLister[C :: HNil]
  val typedC: DeepHLister[C :: HNil] {
    type Out = (((Int :: String :: HNil) :: (Int :: String :: HNil) :: HNil) :: (Int :: String :: HNil) :: HNil) :: HNil
  } = c

  val d = DeepHLister[D :: HNil]
  val typedD: DeepHLister[D :: HNil] {
    type Out = ((Int :: String :: HNil) :: ((Int :: String :: HNil) :: (Int :: String :: HNil) :: HNil) :: HNil) :: HNil
  } = d
}


text:
Q: How to add to an NSSet using Core Data in Swift 5 So I'm practicing a little more with core data after finishing a course. So I am still a little new to it. So I Have 3 entities named Pokemon, Type & Ability. So a Pokemon can have many types like Fire,Water,Flying and so on. Type can also have multiple Pokemon that are Fire,Water,Flying and so on. Same goes for the Ability, so I made a many-to-many relationship. Here is how it looks like.

I am parsing some JSON form an api and trying to save it into core data. Now here is where I am having a bit of trouble. This is how my code looks and it just basically parse the JSON.
struct Service {
static let shared = Service()

func downloadPokemonsFromServer(completion: @escaping ()->()) {
    let urlString = "https://pokeapi.co/api/v2/pokemon?limit=9"
    guard let url = URL(string: urlString) else { return }

    URLSession.shared.dataTask(with: url) { (data, response, error) in
        if let err = error {
            print("Unable to fetch pokemon", err)
        }

        guard let data = data else { return }
        let privateContext = NSManagedObjectContext(concurrencyType: .privateQueueConcurrencyType)
        privateContext.parent = CoreDataManager.shared.persistentContainer.viewContext

        let decoder = JSONDecoder()
        decoder.keyDecodingStrategy = .convertFromSnakeCase

        do {
            let pokemonJSON = try decoder.decode(PokemonsJSON.self, from: data)
            pokemonJSON.pokemons.forEach { (JSONPokemon) in
               let pokemon = Pokemon(context: privateContext)
                pokemon.name = JSONPokemon.name
                pokemon.url = JSONPokemon.detailUrl

                //Would want to set pokemon types here but
                //When i call fetchMoreDetails(pokemon:,urlString:,completion:)
                //The pokemon is always nil inside fetchMoreDetails
            }

            try privateContext.save()
            try privateContext.parent?.save()
            completion()
        } catch let err {
            print("Unable to decode PokemonJSON. Error: ",err)
            completion()
        }

    }.resume()
}

func fetchMoreDetails(pokemon: Pokemon, urlString: String, completion: @escaping ()->()) {
    guard let url = URL(string: urlString) else { return }

    let privateContext = NSManagedObjectContext(concurrencyType: .privateQueueConcurrencyType)
    privateContext.parent = CoreDataManager.shared.persistentContainer.viewContext

    URLSession.shared.dataTask(with: url) { (data, response, error) in
        if let err = error {
            print("Unable to get more details for pokemon", err)
        }

        guard let data = data else { return }

        let decoder = JSONDecoder()
        decoder.keyDecodingStrategy = .convertFromSnakeCase

        do {
            let pokemonDetailJSON = try decoder.decode(PokemonDetailJSON.self, from: data)
            pokemonDetailJSON.types.forEach { (nestedType) in
                let type = Type(context: privateContext)
                type.name = nestedType.type.name

                //How do I add type to pokemon.types this does work
                //pokemon.types?.adding(type)

            }

            try privateContext.save()
            try privateContext.parent?.save()

            completion()

        } catch let err {
            print("Unable to decode pokemon more details", err)
            completion()
        }

    }.resume()
}
}

I am able to parse everything fine and all but I just can't seem to add a new type to pokemons.types. I have look on stack overflow but most of the solutions seem to be in Objective C.
This is how my ViewController looks like and I am also using a NSFetchResultController.
class PokemonTableVC: UITableViewController {

lazy var pokemonController: NSFetchedResultsController<Pokemon> = {
    let context = CoreDataManager.shared.persistentContainer.viewContext
    let request: NSFetchRequest<Pokemon> = Pokemon.fetchRequest()
    let nameSort = NSSortDescriptor(key: "name", ascending: true)
    request.sortDescriptors = [nameSort]

    let controller = NSFetchedResultsController(fetchRequest: request, managedObjectContext: context, sectionNameKeyPath: nil, cacheName: nil)
    controller.delegate = self
    return controller
}()

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view.

    let refreshControl = UIRefreshControl()
    refreshControl.addTarget(self, action: #selector(handleRefresh), for: .valueChanged)
    tableView.refreshControl = refreshControl

    navigationItem.leftBarButtonItem = UIBarButtonItem(title: "Delete", style: .done, target: self, action: #selector(handleDelete))

    try? pokemonController.performFetch()
}

@objc func handleDelete() {
    print("Deleting")
    let context = CoreDataManager.shared.persistentContainer.viewContext

    guard let pokemons = pokemonController.fetchedObjects else { return }
    pokemons.forEach { (pokemon) in
        context.delete(pokemon)
    }

    do {
        try context.save()
    } catch let err {
        print("Unable to save data", err)
    }
}

@objc func handleRefresh() {
    print("DDDDD")
    Service.shared.downloadPokemonsFromServer {
        self.pokemonController.fetchedObjects?.forEach({ (pokemon) in
            print(pokemon.name)
           Service.shared.fetchMoreDetails(pokemon: pokemon, urlString: pokemon.url ?? "") {
                print(pokemon.abilities?.count)

            }
        })
    }
    tableView.refreshControl?.endRefreshing()
}

}

I can provide my other structs if needed. But basically I am trying to add a type to pokemon.types would also like to add fetchMoreDetails when I fetch pokemons where I put the comment at. Would
really appreciate any feedback.

A: When you add a relationship to an entity Xcode creates methods for getting and setting values for that relationship using a pre-defined naming standard. So you should have some methods in your Pokemon class for setting Type instances (and code completion should be able to help here):
addToTypes(value:) // single object
addToTypes(values:) //set of objects

So in your code it should be
pokemon.addToTypes(value: type)

You also have the same methods on Type for the opposite direction


text:
Q: Ubuntu 12.04 does not recognize Kingston DT108 16GB USB drive I bought a Kingston DT108 16GB USB pen drive and Ubuntu did not recognize it. What should i do?
Output of dmesg | tail after connecting pen drive:
[ 1455.253010] CPU5: Package power limit notification (total events = 488)
[ 1455.253013] CPU1: Package power limit notification (total events = 489)
[ 1455.263966] CPU4: Package power limit normal
[ 1455.263969] CPU2: Package power limit normal
[ 1455.263972] CPU0: Package power limit normal
[ 1455.263975] CPU6: Package power limit normal
[ 1455.263998] CPU1: Package power limit normal
[ 1455.264001] CPU5: Package power limit normal
[ 1455.264004] CPU7: Package power limit normal
[ 1455.264007] CPU3: Package power limit normal

A: first format the USB in NTFS. just use fidisk-l to check wether if it is showing in the device list WITH NTFS file system. Remember the device name and mount the device using command sudo mount /dev/sda2 /mnt  //assuming sda2 is NTFS formatted USB device.
edit: I recommend you to format the USB device as ntfs for it makes easy on a linux system to check the ntfs device and figure out what it is.

A: Does that particular USB port work when other devices are plugged in?  It is possible that that USB hub on your machine isn't working under Ubuntu.   It should always recognize that there is a device being plugged in -- do dmesg |grep /dev and see what the last device comes out to be.
As a test, plug a mouse into that USB port and see if it is working as expected (watch "dmesg | tail",  CTRL+C to break out)
Another possibility is that, the device requires more power than the port can provide, but whatever the case, try another USB port on your machine and see if the behavior continues.


text:
Q: Getting the CSS-transformed value of an input via JavaScript Consider the following scenario:
HTML

<input type="text" id="source" value="the quick brown fox">
<input type="text" id="target">

CSS

#source
{
  text-transform: capitalize;
}

JavaScript

function element(id) {
  return document.getElementById(id);
}

element('target').value = element('source').value;

After CSS styling, #source should display "The Quick Brown Fox".
The objective is to get the text-transform-ed value and dump it into #target. Is this possible to achieve?

A: No. You need to use JavaScript to transform it physically
Assuming you already know that source is text-transformed to capitalize, you can do
window.onload=function() {
  document.getElementById("source").onblur=function() {
    var tgt = document.getElementById("target");
    var capitalised = [];
    var parts = this.value.split(" ");
    for (var i=0;i<parts.length;i++) {
      capitalised.push(parts[i].substring(0,1).toUpperCase()+parts[i].substring(1));
    }
    tgt.value=capitalised.join(" ");
  }
}

A: mplungjan's answer is correct in that you can't use a JavaScript function to determine the transformed value. Ultimately, you'll need to do the transform in JavaScript.
However, you don't need to hard code in the capitalization transform as in mplungjan's answer. Perhaps some of your text is capitalized, while some other text is uppercase, and other text yet is normal. You can dynamically handle each of these cases, so long as you know all of the options.
What you would do is determine the style of the elements using JavaScript, then apply the appropriate transformation in your script and go from there. An excellent example of such a transformation is in mplungjan's answer.

A: No, text-transform is a display only transformation and doesn't actually modify the data inside the element.

A: Copying the CSS-transformed value from source to target won't work because the value hasn't actually changed, only the styling has. Other style attributes (like font-family, or color) would not transfer; text-transform will behave in the same limited way.
If you want to actually change the value of the string, which it sounds like you do, you will need to use JavaScript, possibly with RegExp.
Instead of this...
element('target').value = element('source').value;

...this short bit of code should do exactly what you need:
element('target').value = element('source').value.replace(/(\b\w)/g, function (m, p1) {
     return p1.toUpperCase();
});

JSFiddle demonstration here.
SHORT EXPLANATION: The \b at the beginning of the RegExp looks for the beginning of any word and the \w (because it's captured inside the parentheses) captures any single alphanumeric character in that position. This is then stored in the argument p1 for the function, which merely returns a capitalised version.


text:
Q: Is it safe to pass a struct with "ref this" to native code I am currently integrating the Steamworks SDK into my game and have a couple of methods which require to pass a struct as a pointer, for example:
// Public interface method declared by the library
S_API bool SteamAPI_SteamNetworkingIPAddr_IsLocalHost( SteamNetworkingIPAddr* self );

// C# implementation

[StructLayout(LayoutKind.Explicit, Size = 18, Pack = 1)]
public struct SteamNetworkingIPAddr {

    // My current usage of "ref this"
    public bool IsLocalhost => NativeMethods.SteamAPI_SteamNetworkingIPAddr_IsLocalHost(ref this);

    // How another library solves it
    public bool IsLocalhost {
        get {
            SteamNetworkingIPAddr copy = this;
            NativeMethods.SteamAPI_SteamNetworkingIPAddr_IsLocalHost(ref self);
        }
    }

    private static class NativeMethods {
        [DllImport(SteamAPI.LIBRARY_NAME, EntryPoint = "SteamAPI_SteamNetworkingIPAddr_IsLocalHost", CallingConvention = CallingConvention.Cdecl)]
        internal static extern bool SteamAPI_SteamNetworkingIPAddr_IsLocalHost(ref SteamNetworkingIPAddr self);
    }
}

I am a bit concerned about passing this with ref to the native method because I've seen other implementations which create a copy of the struct before passing it but I could not find something which officially says that it's either safe or unsafe to do so.
So, my question is - should I make a copy or keep my solution?

A: In a instance method or property of a struct, the implicit this parameter is a ref managed reference. So any changes to the struct do mutate (change) the struct passed in.
Therefore, when you call the native function, you are passing an actual reference to your own struct. So it is possible for your caller to see these changes, if they have passed in a reference to their own struct. But depending on how your caller makes this call, there may be a defensive copy anyway.
For example:
var isLocal = SomeClass.IPAddrProperty.IsLocalhost

this will create a copy of the struct, and any changes will disappear.
Whereas this:
var ipAddr = SomeClass.IPAddrProperty;
var isLocal = ipAddr.IsLocalhost;
SomeClass.IPAddrProperty = ipAddr;

means that the results are copied back.


text:
Q: Searching for Terms and Printing lines in a Text File The file name is searcher.scala and I want to be able to type:
scala searcher.scala "term I want to find" "file I want to search through" "new file with new lines"

I tried this code but keeps saying I have an empty iterator
import java.io.PrintWriter

val searchTerm = args(0)
val input = args(1)
val output = args(2)

val out = new PrintWriter(output);

val listLines = scala.io.Source.fromFile(input).getLines

for (line <- listLines)
{
    { out.println("Line: " + line) }

    def term (x: String): Boolean = {x == searchTerm}
    val newList = listLines.filter(term)
    println(listLines.filter(term))
}
out.close;

A: You have iterator listLines and you read it few times but iterator is one-time object:

*

*for (line <- listLines)

*val newList = listLines.filter(term)

*println(listLines.filter(term))
You need revise your code to avoid repeat using of iterator.


text:
Q: Doctrine 2 select entities with none or less than relations I'm trying to find all rows with none or less than 3 relations. What would be the best approach for that?
I tried the following code with several different selects, having, joins  but I can't figure out how to do it the right way:
    $db = $this->createQueryBuilder('u');
    $db->addSelect('COALESCE(COUNT(errors), 0) AS HIDDEN errorCount');
    $db->join('u.errors', 'errors');
    $db->where('u.field1 IS NULL AND u.field2 NOT LIKE \'\'');
    $db->having('errorCount < 3');

Thank you very much in advance.

A: The COUNT function is an aggregate function which will return a single result unless you instruct it to group by something.
$db = $this->createQueryBuilder('u');
$db->addSelect('COUNT(errors) AS HIDDEN errorCount');
$db->leftJoin('u.errors', 'errors');
$db->where('u.field1 IS NULL AND u.field2 NOT LIKE \'\'');
$db->having('errorCount < 3');
$db->groupBy('u');

Additionally, if you want to count the number of relations that may or may not exist use a LEFT JOIN. The count on these results will be 0 which is < 3.


text:
Q: Is there another way to click on a menu item with Capybara Friends try anyway but it is not being possible to click on the Gestão de Materiais Menu item. One situation I need is to scroll this menu to view and click on the item menu. But I'm not sure why he is clicking on the menu item below
I tried using SitePrism and pure capybara but it is not possible.
When it runs, it is clicking on Gestao de Empresas
capybara:
find(:xpath, "//div[contains(text(),'Gestão de Materiais')]" ).click
find(:xpath, '//*[@id="TBB_tbm2"]/div[3]/div[2]').click
site Prism:
element :item_mn_gestao_materiais, :xpath,  "//div[contains(text(),'Gestão de Materiais')]"
element :item_mn_gestao_materais,  :css,    '#TBB_tbm2 img[src*=articoli64]'
def cadastra_diametro_material_ativo
item_mn_gestao_materiais.click
end

Menu Principal

Modulo Básico

Gestão Instalações

Gestão de Materiais

<div

A: There is no point in trying Capybara and SitePrism, SitePrism uses capybara so if capybaras click doesn't work for you then SitePrism isn't going to either.
It's very hard to tell what is going on here because your screen shots have popups over the structure of the page, also screen shots make it much harder to answer since we can't copy paste from them (use screenshots for pictures of your page, not HTML. Add HTML as text in the question). You also aren't showing how you're detecting that it's clicking the wrong button. What exactly is failing? Please see https://stackoverflow.com/help/how-to-ask
Given the visible info, if I was writing this I'd write
find('#TBB_tbm2 > div', text: 'Gestão de Materiais').click

following the two rules

*

*Don't use XPath unless absolutely necessary

*Write the minimal selector necessary

beyond that it's impossible to go any further with the current information


text:
Q: How to create JS class and use of class object in Laravel 8? Controller load the view and load the jQuery.
index.blade.php

                            ID
                            Name
                            Country
                            Dept
                            Title
                            Username
                            Role
                            Status
                            Created at
                            Action

@php
    $pageJsScript = array(
        ''

    );

    $pageJsCalls  = array(
        'User_search.init();'
    );
@endphp

The above code is in between the
 tags
In my master page I call these functions:
<?php foreach ($pageJsScript as $jsScript)
{
    echo $jsScript.PHP_EOL;
}
?>

And the then I created a separated file kept in JS folder:
var User_search = function () {

    var DataGrid = $('#UserGrid');

    var loadGridUrl =  "{{url('/show_user_list')}}";

    var dataTable = null;
    var loadGrid = function () {
        alert('called');

        var url = loadGridUrl;

        dataTable = DataGrid.DataTable({
            dom: "Blfrtip",
            aaSorting: [], //disabled initial sorting
            ajax: url,
            paging: true,
            searching: true,
            info: true,

            processing: true,
            serverSide: false,
            lengthMenu: [[25, 50, 100, 200, 500], [25, 50, 100, 200, 500]],
            pageLength: 25,

            "columnDefs": [
                {"width": "13%", "targets": 4, "class":'word-wrap'},
            ],

            buttons: [
                {extend: "csv"}
            ],

            columns: [
                //Table Column Header Collection

                {data: "id"},
                {data: "name"},
                {data: "field_office"},

                {data: "department"},
                {data: "designation"},
                {data: "email"},
                {data: "role"},
                //{data: "is_locked"},
                {
                    data: null, render: function (data, type, row) {
                    if (data.is_locked == '1') {
                        return 'Pending';
                    }
                    else if (data.is_locked == '2') {
                        return 'Unlock';
                    }
                    else if (data.is_locked == '3') {
                        return 'Locked';
                    }
                }
                },
                {data: "created_at"},
                {
                    data: null, render: function (data, type, row) {
                    // Combine the first and last names into a single table field

                    if(user_id==1 || user_id==21) {

                        return ' Edit' +
                            '|  Delete';

                    }else {
                        return '';
                    }
                }
                },

            ],
        });

        $("#UserGrid_tools > li > a.tool-action").on("click", function () {
            var e = $(this).attr("data-action");
            dataTable.button(e).trigger();
        });

        $(".dt-buttons").hide();

        jQuery('#UserGrid_wrapper .dataTables_filter input').addClass("form-control input-small"); // modify table search input
        jQuery('#UserGrid_wrapper .dataTables_length select').addClass("form-control input-small"); // modify table per page dropdown
        jQuery('#UserGrid_wrapper .dataTables_length select').select2(); // initialize select2 dropdown
    }

    return {
        //main function to initiate the module,
        init: function () {

            //Grid loading
            if (!jQuery().dataTable) {
                return;
            }
            loadGrid();
        },
    };
}();

Kindly guide me in order to get run all things, infact alert is working by the function loadGrid() is not working.


text:
Q: Function module to delete an IDoc Is there any Function Module using which I can delete an IDoc generated in SAP system.
The FM should take IDoc number as input.

A: No there is no specific FM to delete an IDOC, but why do you want to delete IDOC's?
SAP uses IDOC status to control IDOC's . If you don't want IDOcs to be processed you may set a status to provide that.

A: RFC EDI_DOCUMENT_DELETE can be used to delete the IDoc number.


text:
Q: Normalize unicode character in sql query Unicode characters can be encoded in different ways, canonical equivalence and compatibility. We can normalize them to get the same character as it is important for exact string match. My sample code base
$search = Normalizer::normalize($request->get('search'), Normalizer::FORM_C);

I am normalizing the request search keyword in NFC (Canonical Decomposition followed by Canonical Composition). And then I used that normalized string to search in database.
$products = Product::where('title', "LIKE", "%" . $search . "%")->get();

this line generates a sql query
select * from `products` where `title` LIKE %রায়হান% and `products`.`deleted_at` is null

Here রায়হান is my search string. I get two different encoding for the character য়. One is for য় itself that is %E0%A7%9F and one is %E0%A6%AF%E0%A6%BC that is য + ়
My database values may have both the encoding as I didn't normalize them before saving. So when searching I get the values only those matches the normalized search key. Even if I don't normalize the search key, getting only matching encoded values.
Now I know I can normalize the string before saving and then search with the normalized string. But I already have some values that is not normalized. So is there any way to normalize the string when querying the database? Something like
select * from `products` where NormalizedNFC(`title`) LIKE %my_normalized_value_in_php% and `products`.`deleted_at` is null


text:
Q: Selecting all combinations and show which don't exist I have three tables: X, Y and XY. Each table has a field called [Identity] which is the primary key. (And an auto-increment field.) Table XY has two other fields, one to link to X and the other to link to Y. (Named [X_Identity] and [Y_Identity])The combination of these links is an unique key. Table X has 6 fields (X1 to X6) and table Y has 3 fields (Y1 to Y3). Table XY has 4 fields called X2, X4, X5 and Y2. These are similar in purpose as the fields in the X or Y tables with the same name. Table X will be about 200 records, Y about 10 records. Table XY has about 75 records, out of a possible 2000 records.
Now my problem:I need a view that generates all 2000 combinations of X and Y and it should return values from the XY record if a record for such a combination exists! If not, it should just combine the fields from X and Y. Thus this table has two possible record types:

*

*[X].[X1], [X].[X2], [X].[X3], [X].[X4], [X].[X5], [X].[X5], [Y].Y1], [Y].Y2], [Y].Y3] if no XY record is found.

*[X].[X1], [XY].[X2], [X].[X3], [XY].[X4], [XY].[X5], [X].[X5], [Y].Y1], [XY].Y2], [Y].Y3] if an existing XY record is found.

Seems to me I have to do a union between a selection of all XY records to generate one half of the result. (Easy!) And I need to somehow combine the X and Y table for which there's no XY record to generate the other half. And that last one is a bit complex... Suggestions?
Oh, and it's going to be a read-only view in my system! So it needs to be a single SQL statement!

A: I was thinking along the lines of creating a cross join of X and Y, and then replace in the result set the values that are available in XY:
SELECT [X].[X1] AS [X1]
       ,COALESCE([XY].[X2], [X].[X2]) AS [X2]
       ,[X].[X3] AS [X3]
       ,COALESCE([XY].[X4], [X].[X4]) AS [X4]
       ,COALESCE([XY].[X5], [X].[X5]) AS [X5]
       ,[X].[X6] AS [X6]
       ,[Y].[Y1] AS [Y1]
       ,COALESCE([XY].[Y2], [Y].[Y2]) AS [Y2]
       ,[Y].[Y3] AS [Y3]
FROM [X]
CROSS JOIN [Y]
LEFT OUTER JOIN [XY]
ON [XY].[X_Identity] = [X].[Identity]
AND [XY].[Y_Identity] = [Y].[Identity]

Have not tried this, so it might need some tweaking.

A: Here's my answer.
SELECT [X].[X1] AS [X1]
       ,CASE WHEN XY.X_Identity is not null then [XY].[X2] else [X].[X2] end [X2]
       ,[X].[X3] AS [X3]
       ,CASE WHEN XY.X_Identity is not null then [XY].[X4] else [X].[X4] end [X4]
       ,CASE WHEN XY.X_Identity is not null then [XY].[X5] else [X].[X5] end [X5]
       ,[X].[X6] AS [X6]
       ,[Y].[Y1] AS [Y1]
       ,CASE WHEN XY.X_Identity is not null then [XY].[Y2] else [Y].[Y2] end [Y2]
       ,[Y].[Y3] AS [Y3]
FROM (X
CROSS JOIN Y)
LEFT OUTER JOIN XY
ON [XY].[X_Identity] = [X].[Identity]
AND [XY].[Y_Identity] = [Y].[Identity]

This is based on the direct application of "CASE (pk) == does it exist" using one of the answers.  However, you might want to look at the other form of writing LEFT JOIN:
SELECT  [X].[X1]
       ,[XY].[X2]
       ,[X].[X3]
       ,[XY].[X4]
       ,[XY].[X5]
       ,[X].[X6]
       ,[Y].[Y1]
       ,[XY].[Y2]
       ,[Y].[Y3]
FROM (X
CROSS JOIN Y)
INNER JOIN XY ON [XY].[X_Identity] = [X].[Identity]
             AND [XY].[Y_Identity] = [Y].[Identity]

UNION ALL

SELECT  [X].[X1]
       ,[X].[X2]
       ,[X].[X3]
       ,[X].[X4]
       ,[X].[X5]
       ,[X].[X6]
       ,[Y].[Y1]
       ,[Y].[Y2]
       ,[Y].[Y3]
FROM (X
CROSS JOIN Y)
WHERE NOT EXISTS (
    SELECT * FROM XY
    WHERE [XY].[X_Identity] = [X].[Identity]
      AND [XY].[Y_Identity] = [Y].[Identity])

A: I managed to find a solution myself, although not too pretty:
SELECT
    [X].[X1] AS [X1],
    [XY].[X2] AS [X2],
    [X].[X3] AS [X3],
    [XY].[X4] AS [X4],
    [XY].[X5] AS [X5],
    [X].[X6] AS [X6],
    [Y].[Y1] AS [Y1],
    [XY].[Y2] AS [Y2],
    [Y].[Y3] AS [Y3]
FROM
    [X],
    [Y],
    [XY]
WHERE
    [XY].[X_Identity] = [X].[Identity]
AND
    [XY].[Y_Identity] = [Y].[Identity]

UNION

SELECT
    [X].[X1] AS [X1],
    [X].[X2] AS [X2],
    [X].[X3] AS [X3],
    [X].[X4] AS [X4],
    [X].[X5] AS [X5],
    [X].[X6] AS [X6],
    [Y].[Y1] AS [Y1],
    [Y].[Y2] AS [Y2],
    [Y].[Y3] AS [Y3]
FROM
    [X],
    [Y]
WHERE
    NOT (CAST([X].[Identity] AS nvarchar(12)) + '/' + CAST([Y].[Identity] AS nvarchar(12))) IN (
    SELECT
        CAST([XY].[X_Identity] AS nvarchar(12)) + '/' + CAST([XY].[Y_Identity] AS nvarchar(12))
    FROM
        [XY]
    ))

It's a union of two select statements (and even a third), where the first one selects all records from XY and adds the related data from the X and Y tables to it.
The second select is doing some additional calculation to combine the X and Y table into one field which I can look up in the XY table by doing the same calculation there.While it works, I just wonder if this can be done easier...

A: Josien came close and gave me an idea for a second solution to do this! It doesn't require me to do the calculations and thus it's slightly more reliable. But it's still not very pretty.
SELECT
    [COMBI].[X1] AS [X1],
    COALESCE([XY].[X2], [COMBI].[X2]) AS [X2],
    [COMBI].[X3] AS [X3],
    COALESCE([XY].[X4], [COMBI].[X4]) AS [X4],
    COALESCE([XY].[X5], [COMBI].[X5]) AS [X5],
    [COMBI].[X6] AS [X6],
    [COMBI].[Y1] AS [Y1],
    COALESCE([XY].[Y2], [COMBI].[Y2]) AS [Y2],
    [COMBI].[Y3] AS [Y3]
FROM (
    SELECT
        [X].[Identity] AS [X_Identity],
        [Y].[Identity] AS [Y_Identity],
        [X].[X1] AS [X1],
        [X].[X2] AS [X2],
        [X].[X3] AS [X3],
        [X].[X4] AS [X4],
        [X],[X5] AS [X5],
        [X].[X6] AS [X6],
        [Y].[Y1] AS [Y1],
        [Y].[Y2] AS [Y2],
        [Y].[Y3] AS [Y3]
    FROM
        [X]
    CROSS JOIN
        [Y]
} AS [COMBI]
LEFT OUTER JOIN
    [XY]
ON
    [XY].[X_Identity] = [COMBI].[X_Identity]
AND
    [XY].[Y_Identity] = [COMBI].[Y_Identity]

I actually forgot about COALESCE. :-)
Only thing is that it has a small problem! While XY can have a value, one of it's fields can still be NULL. If that's the case, it won't override the value from X or Y with the NULL value from XY but keep the old value.It's why it's a good solution, but I need to override values from X and Y with all values from XY, even if those are NULL.


text:
Q: Looking for a tool to generate bindingRedirect-s for .NET assemblies Say, my .NET project deployment directory looks like:
MyComponent.dll
MyComponent.dll.config
3rdPartyComponent.dll
3rdParty.dll.config
Newtonsoft.Json.dll (v7)
etc.

MyComponent.dll refers Newtonsoft.Json version 7 and 3rdPartyComponent.dll refers Newtonsoft.Json version 6. I'd like to catch this case and get a hint that bindingRedirect for Newtonsoft.Json assembly is needed in 3rdParty.dll.config.
Of course, tool should be clever enough to analyze existing bindingRedirect-s and find that correct redirect is already in config file.


text:
Q: Dynamically generate and populate Powerpoint from database values Here in a product manager capacity.
Our goal is to generate a powerpoint presentation that populates a pre-defined template using specific values in our database (Amazon RDS)
The values will be photos and text data.
Ideal flow would be:

End user generates some data/photo output from other flows in our web application. All data will be in our database.
The user clicks 'Generate Powerpoint'
The application dynamically generates and populates the Powerpoint template with these values.
The end user will be sales people, and with the greatest of respect, not super technical or willing to mess around with configuring.

We have been investigating some node.js solutions to generate PDF of the above, early prototypes are fine....but the beauty of PowerPoint is the sales people will then be able to make any minor edits one the document is generated.
What would be great to confirm with this community:
1) Is the above broadly possible?
2) Any existing components we could buy/license to speed up development?
3) Any technical/non-technical suggestions?
Thanks


text:
Q: "Error watching file for changes: EMFILE" when run the examples from facebook/react-native/Examples I want to run the Examples from facebook/react-native/Examples in OS X 10.12.
First I use npm install and then use npm start:
There is an error:
Error watching file for changes: EMFILE
{"code":"EMFILE","errno":"EMFILE","syscall":"Error watching file for changes:","filename":null}
Error: Error watching file for changes: EMFILE
    at exports._errnoException (util.js:1008:11)
    at FSEvent.FSWatcher._handle.onchange (fs.js:1406:11)

Then I use Xcode run the code but there is the same error.
I need help or advice. Thanks very much.

A: The react-native-cli depends on watchman, you can try to install watchman with brew install watchman,then have another try.

A: This solved the issue for me:
brew install watchman


text:
Q: First time creating an app for Android and IOS I'm trying to create an app for Andriod and IOS, but i have no clue how to do the front-end and have a hard time deciding to use HTML5, CSS & JS or Objective objective C/Java.
I'ts going to be use network options, checkout-features, joined checkout-features. Maps api, facebook api.
I've got expierence in HTML5, CSS3, SASS, PHP and JS.
I've tried looking online, but i've still got no clue how to do the front-end for app.

A: For android:
I would recommend using Android Studio.
It is a powerful tool for creating an android app - the front end can be implemented by dragging and dropping items or by using xml.
It is easy to use and there a lot of tutorials online.

A: To answer your question, you will use framework like phonegrap, Titanium Appcelarator and I guess you can use NativeScript,  Ionic, Framework7 as well. For Titanium, you have to use different environment for different app (OSX for iOS products and OsX, Windows or Linux distros to run android app) and have it's own syntax and everything. Language is one of Javascript versions (I am guessing, I have used it once 2 years ago). And Phonegap and other Frameworks use a varient of JS, so basically you will have to use HTML and CSS to work with UI. However, you will face some hardware constraint like unable to access hardware buttons (from my experience with one project some months ago) and memory management and other functionalities will mostly depend on your JS coding skill.
[My opinion] I believe, the best way to develop an app is to develop in its native language/framework. I believe it. Unless you're bound to use Html, JS to build app (you can!), don't use those. Java is there to help you with Android Development, since I am an developer, I can tell you that starting might seem a bit difficult than iOS development. But in the end, communities like stackOverFlow and thousands of thousands blogs will help you. Same case for iOS app development. You can find lots of different tutorials. New Bostons tutorial helped with android however, it's contents are bit old (android 2.3) and mostly everything has changed since. However, you can check his iOS app development with Swift. Learning a new language is mostly like learning how to ride bicycle. If you can know how to ride, keep learning the advance parts after basic mechanics, you can become a pro one day. However, for that you have to pass a whole cartoon of hurdles (unknown bugs, sleepless nights to name a few) like the falls you did when learning how to ride.
I would really suggest you to focus on building a real stack.
Happy coding!

A: I'm an iOS developer on the native side. If you want to do native development, I would recommend Stanford course CS193P by Paul Hegarty. You can find this course on iTunes U, Coursera and other MOOC platforms. For advanced features, follow a GitHub repo called "awesome-ios" where you'll learn some production level stuff for iOS apps. If you want to do hybrid apps, have a look at PhoneGap, Ionic, React.
In either case, you would be able to implement features you've described in your question.
Tools needed for Native Development: a machine which runs macOS and Xcode(free download from app store).

A: I started developing native apps years ago. The last 2 years I've been using only hybrid possibilities. Designing and developing an app in HTML / CSS / JS is much easier and more efficiently.
I recommend taking a look at Phonegap, Ionic, Framework7. These are open source and there are already some templates.


text:
Q: How do I create a dynamic table with rows and columns using the windows 7 platform I am making a app for roller derby that will get information such as bouts , team names and stats. The information is stored in the JSON format. When I eventually get and parse the data i want to arrange in in a format similar to this:   Team1 Team2  Venue Date Result. The amount of rows should be the length of each list of bouts. I am having trouble finding a way to do this in the C# code. Can anyone point me in the right direction.
Edit: I have tried implementing a list box and I am trying to follow the tutorial found here http://msdn.microsoft.com/en-us/library/cc265158%28v=vs.95%29.aspx
When I run the program I get this error message: Error  1   Event handler 'PhoneApplicationPage_Loaded' not found on class 'PhoneApp2.Page1'    c:\users\lewis\documents\visual studio 2010\Projects\PhoneApp2\PhoneApp2\Page1.xaml Roller Derby App
Here is my Xaml for page1
<!--LayoutRoot is the root grid where all page content is placed-->
<Grid x:Name="LayoutRoot" Background="Transparent">
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto"/>
        <RowDefinition Height="*"/>
    </Grid.RowDefinitions>

    <!--TitlePanel contains the name of the application and page title-->
    <StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="12,17,0,28">
        <TextBlock x:Name="ApplicationTitle" Text="MY APPLICATION" Style="{StaticResource PhoneTextNormalStyle}"/>
        <TextBlock x:Name="PageTitle" Text="Upcoming Bouts" Margin="9,-7,0,0" Style="{StaticResource PhoneTextTitle1Style}" Width="297" TextWrapping="NoWrap" FontSize="40" HorizontalAlignment="Left" />
        <Button Name="Home" Content="Home" Width="310" HorizontalContentAlignment="Center" HorizontalAlignment="Left" Click="Home_Click" />
    </StackPanel>

    <!--ContentPanel - place additional content here-->
    <Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
        <ListBox Height="100" HorizontalAlignment="Left" Margin="544,177,0,0" Name="ListofBouts" VerticalAlignment="Top" Width="460" Loaded="ListofBouts_Loaded">
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <StackPanel Orientation="Horizontal">
                        <TextBlock Padding="5,0,5,0"
                     Text="{Binding Venue}" />
                        <TextBlock Text="{Binding Team1}" />
                        <TextBlock Text="{Binding Team2}"/>
                        <TextBlock Text="{Binding Date}"/>
                    </StackPanel>
                </DataTemplate>
            </ListBox.ItemTemplate>

            </ListBox>

    </Grid>
</Grid>

<!--Sample code showing usage of ApplicationBar-->
<!--<phone:PhoneApplicationPage.ApplicationBar>
    <shell:ApplicationBar IsVisible="True" IsMenuEnabled="True">
        <shell:ApplicationBarIconButton IconUri="/Images/appbar_button1.png" Text="Button 1"/>
        <shell:ApplicationBarIconButton IconUri="/Images/appbar_button2.png" Text="Button 2"/>
        <shell:ApplicationBar.MenuItems>
            <shell:ApplicationBarMenuItem Text="MenuItem 1"/>
            <shell:ApplicationBarMenuItem Text="MenuItem 2"/>
        </shell:ApplicationBar.MenuItems>
    </shell:ApplicationBar>
</phone:PhoneApplicationPage.ApplicationBar>-->

Here is the C#
namespace PhoneApp2
{
  public partial class Page1 : PhoneApplicationPage
  {
    public Page1()
    {
        InitializeComponent();
    }

    private void Home_Click(object sender, RoutedEventArgs e)
    {
        NavigationService.Navigate(new Uri("/MainPage.xaml", UriKind.Relative));
    }

    private void ListofBouts_Loaded(object sender, RoutedEventArgs e)
    {
        InitializeComponent();
    }
    public class Bouts
    {
        public string Venue { get; set; }
        public string Team1 { get; set; }
        public string Team2 { get; set; }
        public string Date { get; set; }

        public Bouts(String venue, String team1, String team2, String date)
        {

            this.Venue = venue;
            this.Team1 = team1;
            this.Team2 = team2;
            this.Date = date;

        }
    }

    public class bouts : ObservableCollection<Bouts>
    {
        public bouts()
        {
            Add(new Bouts("Yankee Sadium", "Yankees", "Mets", "March 3"));
            Add(new Bouts("Yankee Sadium", "Yankees", "Mets", "March 3"));
            Add(new Bouts("Yankee Sadium", "Yankees", "Mets", "March 3"));
            Add(new Bouts("Yankee Sadium", "Yankees", "Mets", "March 3"));

        }
    }

  }
}

A: The error is saying that there is an event defined the Loaded event for Page1. Since the event is not defined in the code-behind, it must be declared in the XAML:
<phone:PhoneApplicationPage
  x:Class="PhoneApp2.Pag1"
  Loaded="PhoneApplicationPage_Loaded"
  OtherStuff...
  >
  <RestOfXaml>

Delete the Loaded="PhoneApplicationPage_Loaded" and the error should go away. Or define the event in the code behind. Either should work.


text: Q: How can I hook windows microphone settings to keep other applications from changing it The voice chat application is always automatically changing the microphone settings and cannot be stopped. So I just want to make something that can lock it. I only found the windows message hooking in Windows APIs but it is not likely to work on audio settings. Is there any way to hook any change on audio settings instead of briefly changing it?


text:
Q: Change default Xamarin Studio's web server Is it possible to change Xamarin Studio's web server from XPS to another like Nginx or Apache with mod_mono?
I did not find any option that looks like the one Visual Studio has where you have the ability to point to any kind of web server:

I'm on Mac OS X lion 10.7.3


text:
Q: Efficient way of communicating variables between a Dialog Fragment and an Activity? My main activity sets up and begins a dialog fragment for the user to interact with.  The dialog displays several radio buttons to choose and can cancel or accept the choice when done.  The main activity employs an interface to check the event once the dialog fragment has been dismissed and then changes a local variable according to the same variable that exists in the dialog fragment.  This seems really redundant to me so is there a better way to achieve this communication?  Take a look at the NOTI_TIMER in main activity.
Main activity:
    public void dialogSetup(){

    RadioButtonDialog dialog = new RadioButtonDialog();

    dialog.show(getFragmentManager(), "Radio Button Dialog");
}

@Override
public void onDialogPositiveClick(DialogFragment dialog) {

    NOTI_TIMER = RadioButtonDialog.getNOTI();
    startAlarm();
}

@Override
public void onDialogNegativeClick(DialogFragment dialog) {

    log("in onDialogNegativeClick");
}

Dialog Fragment:
public class RadioButtonDialog extends DialogFragment{

public String TAG = "RadioButtonDialog";
public static long NOTI_TIMER = 0;

RadioGroup mRadioGroup;
Button timerChoice;

/* The activity that creates an instance of this dialog fragment must
 * implement this interface in order to receive event callbacks.
 * Each method passes the DialogFragment in case the host needs to query it. */
public interface RadioButtonDialogListener {
    public void onDialogPositiveClick(DialogFragment dialog);
    public void onDialogNegativeClick(DialogFragment dialog);
}

// Use this instance of the interface to deliver action events
RadioButtonDialogListener mListener;

// Override the Fragment.onAttach() method to instantiate the NoticeDialogListener
@Override
public void onAttach(Activity activity) {
    super.onAttach(activity);
    // Verify that the host activity implements the callback interface
    try {
        // Instantiate the NoticeDialogListener so we can send events to the host
        mListener = (RadioButtonDialogListener) activity;
    } catch (ClassCastException e) {
        // The activity doesn't implement the interface, throw exception
        throw new ClassCastException(activity.toString()
                + " must implement NoticeDialogListener");
    }
}

@Override
public Dialog onCreateDialog(Bundle SavedInstanceState){

AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
LayoutInflater inflater = getActivity().getLayoutInflater();
View view = inflater.inflate(R.layout.timer_choice_layout, null);
mRadioGroup = (RadioGroup) view.findViewById(R.id.radioGroup1);
builder.setView(view);
builder.setTitle("Choose Selfie Timer Duration");
//timerChoice = (Button)view.findViewById(R.id.button1);

builder.setNegativeButton(R.string.delete_cancel, new DialogInterface.OnClickListener() {

    @Override
    public void onClick(DialogInterface dialog, int which) {

        Log.i(MainActivity.TAG, "User pressed 'Cancel'.");
        mListener.onDialogNegativeClick(RadioButtonDialog.this);

    }
});

builder.setPositiveButton(R.string.timer_btn_confirm, new DialogInterface.OnClickListener() {

    @Override
    public void onClick(DialogInterface dialog, int which) {

        switch (mRadioGroup.getCheckedRadioButtonId()){

        case R.id.radioButton1:
            NOTI_TIMER = 10800000;
            Toast.makeText(getActivity(), R.string.three_hours, Toast.LENGTH_LONG).show();
            break;

        case R.id.radioButton2:
            Toast.makeText(getActivity(), R.string.six_hours, Toast.LENGTH_LONG).show();
            NOTI_TIMER = 21600000;
            break;

        case R.id.radioButton3:
            Toast.makeText(getActivity(), R.string.nine_hours, Toast.LENGTH_LONG).show();
            NOTI_TIMER = 32400000;
            break;

        case R.id.radioButton4:
            Toast.makeText(getActivity(), R.string.twelve_hours, Toast.LENGTH_LONG).show();
            NOTI_TIMER = 43200000;
            break;

        case R.id.radioButton5:
            Toast.makeText(getActivity(), R.string.twentyfour_hours, Toast.LENGTH_LONG).show();
            NOTI_TIMER = 86400000;
            break;

        }
        mListener.onDialogPositiveClick(RadioButtonDialog.this);
    }
});

Dialog dialog = builder.create();
return(dialog);
}

public static long getNOTI() {

    return NOTI_TIMER;
}

}


text:
Q: Using get_file_contents to get info from a page? I have been searching all over the internet on how I could get the contents of a webpage and then use the information and add it to a database. I finally found get_file_contents. Except I need to be able to not only take the entire contents, I also need to be able to translate the information into variables to add to a database. It also has to support multiple people to be added to the database.
Can someone help me with this? http://www.pixelhoster.net/api/m-shopping-purchases/m/4087396 is the link of the API of the page.

A: Yes this is a very common question on SO.
But im feeling nice:
<?php
//Get the json string from the api
$data = file_get_contents('http://www.pixelhoster.net/api/m-shopping-purchases/m/4087396');

//Decode that string, true to decode into an array
$data = json_decode($data,true);

print_r($data);
/*Echos
Array
(
    [0] => Array
        (
            [user] => Array
                (
                    [user_id] => 917115
                    [username] => Fiskarbengtson
                )

            [item_name] => VIP
            [item_price] => 15.00
            [purchase_date] => 1330322376
            [currency] => USD
            [item_id] => 1639
            [custom_field] =>
        )

)

*/

//So to access the array
echo $data[0]['user']['username'];
echo $data[0]['item_name'];
?>

A: The "API" link you posted seems to return data in JSON format. So, you should consider using your file_get_contents trick with the json_deocde function.


text:
Q: When i select a radio button value i need to display and hide some of the controls... this is my code below and it is not working protected void RadioButtonList1_SelectedIndexChanged(object sender, System.EventArgs e)
{

    if (RadioButtonList1.SelectedValue == "yes")
    {
        TextBox1.Visible = true;
        FileUpload1.Visible = true;
        Image1.Visible = true;
    }
    else
    {
        TextBox1.Visible = true;
        FileUpload1.Visible = false;
        Image1.Visible = false;
    }
}

This is my c# code. i have added OnSelectedIndexChanged="RadioButtonList1_SelectedIndexChanged" this is my asp.net code...  please help me with error!
Here is the important part of my .aspx page:
<asp:RadioButtonList ID="RadioButtonList1"
      OnSelectedIndexChanged="RadioButtonList1_SelectedIndexChanged" runat="server">
      <asp:ListItem Selected="True">Yes</asp:ListItem>
      <asp:ListItem>No</asp:ListItem>
</asp:RadioButtonList>

A: make your RadioButtonList1's autopost back property true ! in .aspx page and check....

A: It seems like the autopostback of the RadioButtonList  is  not set .
The AutoPostBack property is used to set or return whether or not an automatic post back occurs when the user selects an item in a list control.
<asp:SomeListControl AutoPostBack="TRUE|FALSE" runat="server"/>

If this property is set to TRUE the automatic post back is enabled, otherwise FALSE. Default is FALSE.
For information :W3School


text:
Q: How to connect Calendar control with existing Membership system in ASP.NET? I have a built-in Membership system in ASP.NET and I handle member data with Profiles in web.config.
I would like to add an Event Calendar where a member could add notes to any day he wants but I don't know how to integrate the Calendar control with the existing Membership system.
I can't query a database because I don't handle member login credentials manually, Login control does that for me so I would have to connect the Calendar with the existing ASPNETDB.MDF Membership database but I'm clueless.

A: If you are using built-in sql membership provider then it is easier. You can get Logged-in user and access database using that.
object id= Membership.GetUser(Page.User.Identity.Name).ProviderUserKey;

Now yo can store calendar data in table and link user with his calendar with his id (which is GUID).
EDIT:- Here are some links for exploring membership further.

*

*Patterns and Practices group paper

*How to video on setting up membership

*In depth article at 4guysatrolla by Scott Mitchell


text:
Q: Why the `cooks.distance()` function doesn't detect an obvious outlier? I have the next plot:

I want to detect outliers to delete them. I apply next code to detect them and delete them:
model <- lm(VeDBA.X16 ~ VeDBA.V13AP, data = data)
cooksD <- cooks.distance(model)
n <- nrow(data)
influential_obs <- as.numeric(names(cooksD)[(cooksD >= (4/n))])
data_removed <- data[-influential_obs, ]

After that, I plot again the relationship between VeDBA.X16 ~ VeDBA.V13AP and find out this:

I don't understand why the point in the upper left corner is not detected as an influential observation.
Does anyone know why? Is there something wrong?
I add the dataframe just in case someone wants to play with it
data <- read.table(header=TRUE, text="
    VeDBA.V13AP   VeDBA.X16
1    1.05710000 0.010506809
2    0.05125333 0.007041587
3    0.04183176 0.004206603
4    1.13878500 0.027639652
5    2.64275000 0.013776637
6    0.06406667 0.004456838
7    0.34596000 0.016776946
8    0.26199895 0.008196768
9    0.13749692 0.004797024
10   0.16378783 0.007629357
11   0.15307357 0.007445059
12   0.41879368 0.012262484
13   0.09404071 0.005716708
14   0.61134385 0.016408606
15   0.75038083 0.025541278
16   0.11364870 0.006871933
17   0.14415000 0.005706591
18   0.19220000 0.007479061
19   0.48050000 0.016482735
20   1.55682000 0.047469326
21   1.07774370 0.046832280
22   0.92398370 0.037246095
23   0.81547714 0.035567557
24   0.98637040 0.037141908
25   0.78802000 0.035064956
26   0.88662696 0.036234356
27   0.45459478 0.023970053
28   0.62964720 0.023842654
29   1.44680207 0.037573007
30   0.97925900 0.027740006
31   0.55590154 0.020548773
32   0.54259538 0.021703898
33   0.54056250 0.022075685
34   0.81723440 0.029084513
35   0.86490000 0.031344493
36   0.77456600 0.026346886
37   0.58380750 0.022517729
38   0.15496125 0.009267116
39   0.56561714 0.022334537
40   0.25236696 0.008732695
41   0.62705250 0.022085656
42   0.68281579 0.021273556
43   0.84568000 0.027041421
44   1.52898414 0.035010257
45   1.86250952 0.035567753
46   1.33730737 0.035620930
47   1.01074588 0.043873363
48   0.46937263 0.021688041
49   0.73849154 0.026023571
50   0.51765867 0.018627751
51   0.95878231 0.031115668
52   1.46663385 0.034777541
53   1.54817100 0.039113216
54   0.92773462 0.023049018
55   1.52078250 0.044672864
56   0.76584308 0.022634866
57   1.54144400 0.025643141
58   1.80393429 0.052413459
59   2.24713833 0.069581385
60   2.48899000 0.066594268
61   2.01249417 0.056004661
62   2.50194261 0.062224496
63   1.66445200 0.040947821
64   0.93537333 0.024518350
65   1.40306000 0.037986642
66   0.88228952 0.028022503
67   0.88892500 0.029557877
68   1.15935040 0.030355095
69   0.87643200 0.027532811
70   1.80898640 0.048795144
71   1.52991200 0.047450421
72   1.52914320 0.045071540
73   1.15177630 0.039557676
74   0.89151231 0.028493862
75   0.99245091 0.032069627
76   0.91871600 0.030344117
77   1.08814769 0.030066112
78   1.45431333 0.039615550
79   1.25083760 0.042281118
80   1.03263818 0.028800153
81   1.54094261 0.048479181
82   0.61671130 0.022140652
83   0.78432385 0.023690456
84   1.88561929 0.040069812
85   1.14651478 0.038654436
86   1.09909926 0.032120256
87   1.52799000 0.045198773
88   1.26852000 0.051710038
89   0.04420600 0.004244429
90   0.78252857 0.010350877
91   2.40250000 0.007627478
92   0.81685000 0.025706513
93   1.58565000 0.022370744
94   1.00091846 0.035563172
95   1.08400800 0.028789636
96   0.14415000 0.009583793
97   0.28830000 0.008425635
98   0.30752000 0.006911184
99   1.56730364 0.042121191
100  1.59969538 0.046112747
101  0.88320476 0.027019363
102  1.36862417 0.038251774
103  1.34236526 0.041124148
104  1.02250400 0.020569667
105  0.80724000 0.034182504
106  1.34365273 0.049881018
107  1.60967500 0.049401549
108  1.25955067 0.033999752
109  1.45248286 0.036653933
110  1.64971667 0.046624228
111  1.64715400 0.039119497
112  0.65604267 0.023550171
113  0.69466571 0.025732193
114  1.02862593 0.029998028
115  1.05517800 0.027092325
116  1.56643000 0.047986329
117  2.04430909 0.042543590
118  2.25130267 0.057967486
119  2.16331778 0.056144585
120  1.73172200 0.034704222
121  1.17416727 0.033823668
123  1.23599385 0.019911027
124  1.26240455 0.024325601
125  1.43749583 0.031187043
126  0.81765083 0.017482967
127  1.26160080 0.038708743
128  1.45184923 0.028197584
129  1.62302222 0.038035325
130  1.63517846 0.036308297
131  1.25341857 0.026853402
132  1.21326250 0.024963006
133  1.37926381 0.027407291
134  1.08785200 0.025043999
135  1.85190353 0.049342683
136  1.57315700 0.037928747
137  1.38753615 0.035929334
138  1.37253412 0.070932068
139  1.93374556 0.079448030
140  1.36675556 0.043796092
141  1.83688286 0.046827803
142  2.30365429 0.060091698
143  0.90334000 0.013686740
144  1.40306000 0.062339730
145  0.10763200 0.007276758
146  0.26995364 0.011711775
147  0.51719273 0.041075330
148  0.38440000 0.047655380
150  0.27388500 0.009328511
152  2.24874000 0.026286529
153  0.13454000 0.008932444
154  0.32674000 0.008322436
155  0.17298000 0.012461044
156  1.41074800 0.017904123
157  0.67630375 0.028226427
158  0.93697500 0.032562799
159  1.16789765 0.040773114
160  0.95347913 0.027703995
161  0.77520667 0.018606375
162  0.44526333 0.013713823
163  0.64579200 0.025421117
164  1.14166800 0.015551190
165  0.82774133 0.020122139
166  0.59453867 0.016039311
167  0.93697500 0.023504283
168  1.19035867 0.030955743
169  1.29254500 0.028927788
170  1.12215231 0.026397060
171  0.86329833 0.026113615
172  0.91012353 0.022546978
173  0.81925250 0.023960353
174  0.91935667 0.021455930
175  1.33739167 0.033023607
177  1.50877000 0.020575355
178  0.69992833 0.015537802
179  1.03908125 0.022008474
180  0.50132167 0.013699175
181  1.06840588 0.037788411
182  0.57852200 0.016731543
183  1.28182615 0.037938165
184  1.05406526 0.022118990
185  0.52534667 0.014135345
186  0.77627444 0.020491684
187  0.87771333 0.029328708
188  0.85288750 0.026760620
189  0.27548667 0.015437148
190  0.90718400 0.017377823
191  0.63151429 0.018436981
192  0.95379250 0.016484012
193  1.34426941 0.039659989
194  0.89052667 0.021256031
195  0.57660000 0.013969105
196  0.37959500 0.013734296
197  0.12644737 0.006813713
198  0.38920500 0.014058205
199  1.14118750 0.031947582
200  0.76181091 0.023178526
201  0.36838333 0.013728367
202  0.79675636 0.017578227
203  0.95986941 0.022741177
204  1.10427636 0.029618188
205  1.10087889 0.028094766
206  1.32844118 0.038065181
207  0.75975529 0.026631957
208  1.31056375 0.039171698
209  1.05421700 0.033062699
210  1.11668200 0.035669894
211  1.00136200 0.021974308
212  1.39345000 0.031930357
213  1.24209250 0.033808273
214  1.27591231 0.032722364
215  0.76330857 0.029296236
216  0.99944000 0.025064766
217  1.18377727 0.037457588
218  1.34641158 0.042945194
219  0.88171750 0.027451418
220  0.87400421 0.025875555
221  0.88924533 0.028533462
222  0.92135875 0.031501937
223  1.33491636 0.026283906
224  1.25891000 0.032072474
225  0.87330875 0.030152562
226  0.05200706 0.011501541
227  0.04509308 0.003706931
228  0.05470308 0.003600341
229  0.04345391 0.003583414
230  0.37731895 0.018747462
231  2.23839077 0.077033317
232  1.93968240 0.060249362
233  1.04668917 0.036998997
234  1.95607182 0.064847042
235  1.26935565 0.040054101
236  2.15264000 0.068858710
237  2.16819905 0.073791011
238  2.29563680 0.066262406
239  2.54456087 0.061088788
240  2.21314741 0.050528380
241  2.16402963 0.049389097
242  2.10870857 0.048441677
243  2.07652880 0.047867801
244  1.76824000 0.040602190
245  1.41766720 0.028873391
246  1.33787913 0.028314367
247  1.26691833 0.026998519
248  1.70009636 0.061441406
249  1.59372240 0.035966262
250  0.51355840 0.012283114
251  1.57254545 0.035230538
252  1.14221714 0.030293795
253  0.80163417 0.020106771
254  0.98196727 0.029185467
255  1.06094400 0.025831982
256  1.85566000 0.051023837
257  1.07204889 0.037846351
258  0.82820727 0.027304010
259  0.62290273 0.020949164
260  1.57254545 0.048940718
261  1.72908815 0.051882741
262  0.08008333 0.078916880
263  0.33085857 0.015886360
264  0.92015750 0.015088982
265  0.48656947 0.010595939
266  0.52662800 0.013675643
267  0.18739500 0.008559706
268  0.04522353 0.004203519
269  0.05018556 0.003620940
270  0.31101455 0.004023402
271  0.05087647 0.003122690
272  0.04349789 0.003071765
273  0.09085818 0.005381695
274  0.17734818 0.005037032
275  0.46021222 0.013599517
276  0.11228526 0.012151023
277  0.10318105 0.011409172
278  0.20463647 0.013198637
279  0.19898353 0.018187459
280  0.05539882 0.005360736
281  0.36325800 0.010929157
282  0.04036200 0.006140402
283  0.31713000 0.009615104
284  0.04805000 0.003554966
285  0.11633158 0.009562843
286  0.05598870 0.004136161
287  0.62009789 0.023749987
288  1.11476000 0.042056791
")

A: It's just a simple programming mistake. The row numbers don't correspond to
the row names. For example, row number 258, containing the outlier,
has row name 262:
> data[258,]
    VeDBA.V13AP  VeDBA.X16
262  0.08008333 0.07891688

In your code, you turn the row names into numbers and use the numbers
as if they were row numbers. If you used either the rows names directly
(i.e., without as.numeric()) or extracted the row numbers,
everything would work fine. So either
of these options will work (I prefer the second one):
influential_obs <- names(cooksD)[(cooksD >= (4/n))] # Row names
influential_obs <- which(cooksD >= 4/n)             # Row numbers

And here are the points which your Cook's distance 'test' thinks are outliers:
plot(VeDBA.X16 ~ VeDBA.V13AP, data = data)
points(VeDBA.X16 ~ VeDBA.V13AP, data = data[influential_obs,], col="red", pch=19)

A: I think you might be misunderstanding what Cook's D does. Influential observations are those that, when removed from the sample, cause a noticeable change in the parameter of interest. In this case, it's the slope of the regression line. It would appear from your plot that there is a greater concentration of data points in the lower left quadrant, and so it's feasible that the upper left "outlier" does not sufficiently leverage the slope, whereas the lower right points do because of the relative sparseness of data in that region.


text:
Q: Best practices for using docker in an air-gapped environment I'm new to Docker, and would like to use it in an air-gapped environment.  I understand I can set up my own repository inside my isolated system, but I don't know how to get the many docker images I need from the docker hub into the environment. If I could download them to a .zip or .tgz archive, that would be great, but don't see a way to do that from the hub.  I can't use Docker outside the isolated environment.  I may be able to use git outside my air-gapped environment, but getting .zip archives would be much better. Advice on how to get started will be appreciated.

A: You can do the following to produce an archive file for any image on the Hub:
docker pull image:tag
docker save image:tag -o file.tar

Then transfer file.tar to the air-gapped machine and just do:
docker load -i file.tar

If you actually have an air-gapped network, rather than a single machine, it's probably a better idea to set up your own registry within the network that contains your curated images.


text:
Q: How to get a \mid binary relation that grows in LuaTeX Same question as this one: How to get a \mid binary relation that grows, except in luatex.
The answer to the question in pdflatex is to use \mathrel{}\middle|\mathrel{}, which produces too much space on the right when compiled with lualatex.
MWE:
\documentclass{article}

\begin{document}

  Consider the expression: $\left(a\mathrel{}\middle|\mathrel{}b\right)$.
  Compile this with `pdflatex` and `lualatex` and compare spacing.

\end{document}

Compiled with lualatex/ pdflatex:

Is this a bug and/or how do I fix this?  I'm using texlive 2017.
Edit:  I asked this question on the LuaTeX mailing list and got some interesting replies.  In particular: http://tug.org/pipermail/luatex/2017-November/006645.html.  While editing this egreg updated his answer with a solution based on the linked email ;-)

A: If I compile the simpler
$\left(a\mathrel{}\middle|\mathrel{}b\right)\showlists$\showlists

I get the following in the log file
\mathinner
.\leftheight=0.00052 depth=0.00256 class=172 "28300
.\mathord
..\fam1 a
.\mathrel
..{}
.\middleheight=0.00682 depth=0.00638 "26A30C
.\mathrel
..{}
.\mathord
..\fam1 b
.\right"29301

which seems OK, but is translated into boxes and glue as
\mathon
\hbox(7.5+2.5)x28.46626, direction TLT
.\hbox(7.5+2.5)x3.8889, direction TLT
..\OT1/cmr/m/n/10 (
.\OML/cmm/m/it/10 a
.\glue(\thickmuskip) 2.77771 plus 2.77771
.\hbox(0.0+0.0)x0.0, direction TLT
.\hbox(7.5+2.5)x2.77779, direction TLT
..\OMS/cmsy/m/n/10 j
.\glue(\thickmuskip) 2.77771 plus 2.77771
.\hbox(0.0+0.0)x0.0, direction TLT
.\glue(\thickmuskip) 2.77771 plus 2.77771
.\OML/cmm/m/it/10 b
.\hbox(7.5+2.5)x3.8889, direction TLT
..\OT1/cmr/m/n/10 )
\mathoff

There is a mysterious box which causes two \thickmuskip glues to be inserted.
Solution:
$\left(a\mathrel{}\middle|\mathopen{}\mathrel{}b\right)$

which works also with pdflatex.

Addendum
As explained by Hans on the thread starting at http://tug.org/pipermail/luatex/2017-November/006642.html at the luatex mailing list, there is a simpler workaround:
\documentclass{article}

\newcommand{\relmiddle}{\Umiddle class 5 }

\begin{document}

$\left(a \relmiddle| b\right)$

$(a\mid b)$

\end{document}

The class numbers to be used are different from the standard math classes in legacy TeX (section 7.1.3.3.1 in the LuaTeX manual):
 0  ord
 1  op normal
 2  op limits
 3  op no limits
 4  bin
 5  rel
 6  open
 7  close
 8  punct
 9  inner
10  under
11  over
12  vcenter

We can make it work with the other engines by doing
\documentclass{article}

\ifdefined\Umiddle
  \newcommand{\relmiddle}{\Umiddle class 5 }
\else
  \newcommand{\relmiddle}[1]{\mathrel{}\middle#1\mathrel{}}
\fi

\begin{document}

$\left(a \relmiddle| b\right)$

$(a\mid b)$

\end{document}


text:
Q: How do I access tkinter for a class instantiated in another class? I am following the tutorial (more or less) at this site. I am able to copy and paste the code from the tutorial and modify it with the Python 3 module names (Tkinter becomes tkinter, Queue becomes queue, etc.) and the code runs fine.
However, my code creates widgets in a method.
import tk inter as tk
class ClientUI:
    def __init__(self, master, queue, send_command):
        self.queue = queue
        self.send_command = send_command
        self.master = master
        menu_bar = tk.Menu(master)
        menu_file = tk.Menu(menu_bar, tearoff=0)
        menu_file.add_command(label="Preferences", command=self.show_preferences)
        menu_file.add_command(label="Quit", command=master.destroy)
        menu_bar.add_cascade(label="Client", menu=menu_file)
        master.config(menu=menu_bar)
        master.grid()
        self.create_widgets()
        ...

    def create_widgets(self):
        output = tk.Text(self.master, state=tk.DISABLED, name="output")
        output.grid(row=0)

        input_area = tk.Entry(self, name="input")
        input_area.bind("<Return>", self.send_command)
        input_area.focus()
        input_area.grid(row=1, sticky=tk.W+tk.E)

    ...

class Client:
    def __init__(self, master):
        # super(Client, self).__init__()
        self.master = master
        self.queue = Queue()
        self.ui = ClientUI(master, self.queue, self.send)
        ...

    ...

root = tk.Tk()
client = Client(root)
root.mainloop()

When I try to run this I get the error
    output = tk.Text(self.master, state=self.master.DISABLED, name="output")
AttributeError: 'ClientUI' object has no attribute 'tk'

I don't understand why he sets root = tk.Tk() and how I can access the tkinter module to create widgets.

A: Your error message (but oddly, not your code) shows the error is on this line:
output = self.master.tk.Text(...)

Assuming that you imported tkinter as tk, you want to do this:
output = tk.Text(...)

A: The problem lies in the following function, or similar usages. @bryan helped me to determine it by looking for incorrectly assigned variables.
def create_widgets(self):
    output = tk.Text(self.master, state=tk.DISABLED, name="output")
    output.grid(row=0)

    // This line:
    input_area = tk.Entry(self, name="input")
    input_area.bind("<Return>", self.send_command)
    input_area.focus()
    input_area.grid(row=1, sticky=tk.W+tk.E)

The line input_area = tk.Entry(self, name="input) is passing in self which is of the ClientUI class, and does not have a tk method. Why the global tk was not used I cannot be sure. However, passing self.master which is of the Tk class as the first argument and does have such attribute. This resolved the error message.


text:
Q: How to join Linq entity grouped results I have a list of 114 ISO Controls. Each control joins to a "Control to Documents mapping entity". I need help please to show the documents related to each control. I can achieve what I need with the code below but not at all good practice.
               var items = from d in AnnexAControls.GetAll() // there are 114 controls
                            join e in db.ControlToDocumentMaps on d?.ControlId equals docm.ControlId into grp // one control maps to multiple documents
                            select new
                            {
                                Control = d,
                                MappedDocuments = grp
                            };

                foreach (var item in items) // loops 114 controls
                {
                    var documents = from d in item.MappedDocuments
                                    join e in db.Documents on d.DocumentId equals e.DocumentID into doc
                                    select new { doc };

                    // Shows the documents related to each AnnexAControl
                    foreach (var document in documents)
                    {
                        var documentTitle += $"{document.doc.First().DocumentTitle}{Environment.NewLine}";
                    }

                    //...
                }

A: The key here would be to utilize navigation properties between your controls and documents:
As a basic example:
public class Control
{
    [Key]
    public int ControlId { get; set; }
    // ....
    public virtual ICollection<ControlDocument> Documents { get; set; } = new List<ControlDocument>();
}

public class ControlDocument
{
    [Key, Column(0)]
    public int ControlId { get; set; }
    [Key, Column(1)]
    public int DocumentId { get; set; }
    [ForeignKey("ControlId")]
    public virtual Control Control { get; set; }
    [ForeignKey("DocumentId")]
    public virtual Document Document { get; set; }
}

public class Document
{
    [Key]
    public int DocumentId { get; set; }
    // optionally can have a virtual ICollection<ControlDocument> Controls {...}
}

This will likely need additional configuration to map out the many-to-many relationship but should serve as a starting point to compare to your existing schema. If your entities have navigation properties for the DocumentControl available in the Control and/or Document entities already then you should be good to go. If not, I would highly recommend adding them as this represents a lot of the capability that EF can provide for building queries vs. treating EF & Linq like a substitute for SQL querying with manual joins etc.
To display documents per control if you wanted to project those into a :
var controlDocuments = db.Controls
    .Select(c => new
    {
       c.ControlId,
       c.ControlName,
       Documents = c.Documents.Select(d => new
       {
            d.Document.DocumentId,
            d.Document.DocumentTitle
       }).ToList()
    }).ToList();

This would return a structure of anonymous types containing a list of Controls /w Id and Name, and each control a list of applicable Documents with Id, and Title. From that you could consume the data and generate strings or whatever is needed, or for simple string building expressions these could be written into the Select expressions directly.
AFAIK EF Core still requires that the ControlDocument joining entity is declared and mapped in the relationships. With EF6, if the ControlDocument table merely contains the ControlId and DocumentId as a composite key then you can simplify the mapping so that Control contains an ICollection<Document> and EF can be configured to use a joining table without a matching entity.