text:
Q: Android, How to send HTML email and force Android to send it through G-Mail not other applications? I want to send email through my application. I need to send HTML based email just through G-Mail. I found following solutions that each of them has pros and cons.
1) Using Intent (Intent.ACTION_SEND). This is very simple way and I can see my body in HTML format but the problem is when I click on "Send email" button, so many applications like Facebook and Google+ pop up which are useless and I shouldn't show it in that list. This is its code:
String html = "<!DOCTYPE html>Visit W3Schools.com!" + "
If you set the target attribute to \"_blank\", the link will open in a new browser window/tab.
";

Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("text/plain");
intent.putExtra(Intent.EXTRA_EMAIL, new String[] {"MY EMAIL ADDRESS"});
intent.putExtra(Intent.EXTRA_SUBJECT, "subject here");
intent.putExtra(Intent.EXTRA_TEXT, Html.fromHtml(html));
startActivity(Intent.createChooser(intent, "Send email..."));

2)  Using Intent (Intent.ACTION_SENDTO). This way Filters useless applications and shows me just mail clients. But it doesn't display my email in HTML format in gmail client. When i send the email some clients show the body in HTML format while others doesn't identify HTML and my link behaves like plain text. This code is like:
String html = "<!DOCTYPE html>Visit W3Schools.com!" + "
If you set the target attribute to \"_blank\", the link will open in a new browser window/tab.
";
Intent send = new Intent(Intent.ACTION_SENDTO);
String uriText = "mailto:MY EMAIL ADDRESS" + "?subject=subject here" + "&body=" + html;
uriText = uriText.replace(" ", "%20");
Uri uri = Uri.parse(uriText);
send.setData(uri);
startActivity(Intent.createChooser(send, "Send mail..."));

3) Sending mail using JavaMail API which adds so much complexity to application and I didn't test it so far.
What is your suggestion? I need a way to have advantages of first and second ways. I need when user click on button it shows Gmail client and I can show him/her html content in body part of client.
any suggestion would be appreciated. Thanks
======================
Update
Something about code 2 is wrong. The code is like this:
String html = "<!DOCTYPE html>Visit W3Schools.com!" + "
If you set the target attribute to \"_blank\", the link will open in a new browser window/tab.
";
Intent send = new Intent(Intent.ACTION_SENDTO);
String uriText = "mailto:MY EMAIL ADDRESS" + "?subject=subject here" + "&body=" + Html.fromHtml(html);
uriText = uriText.replace(" ", "%20");
Uri uri = Uri.parse(uriText);
send.setData(uri);
startActivity(Intent.createChooser(send, "Send mail..."));

A: Try the following -
Intent shareIntent = new Intent(Intent.ACTION_SENDTO,Uri.parse("mailto:"));
shareIntent.putExtra(Intent.EXTRA_TEXT,Html.fromHtml(body));
shareIntent.putExtra(Intent.EXTRA_SUBJECT, subject);
startActivity(shareIntent);

This will only present email applications.

A: If you want only one application to handle your intent then you need to remove Intent.createChooser(), rather jst use startActivity()---> it send the mail using default email client, if not set then will ask to do so... tat can be changed anytime

A: To get only email applications, use
Intent.setType("message/rfc822")


text:
Q: Creating custom android dialer I am working on the new phone app for Android. Obviously it needs to make and receive phone calls.
My first problem is how to place a phone call from the app without invoking System default dialer. Making calls using Intent is very easy. However when I try to place a call without using Intent then that's entirely different ball of wax.
It seems that I need to use android.telephony but I can't find any good resources that could tell me where to start. Simple tutorial would be nice.
If you could point me to a resource that would help me that will be really appreciated.

A: From Android 10 onwards the only way to handle phone calls is by using the InCallService APIs. I have made a basic dialer app that explains basics of how to handle calls as a default dialer app. https://github.com/adnan-creator/java-custom-dialer

A: Create an app that responds to Intent.ACTION_DIAL. In the AndroidManifest.xml you need to add the following to that Activity:
<intent-filter>
    <action android:name="android.intent.action.DIAL" />
    <category android:name="android.intent.category.DEFAULT" />
</intent-filter>

You can read more in:

Android dialer application

A: i faced same problem
couldn't ask default dialer in phone os >= Q android
check my asnwer
https://stackoverflow.com/a/71094871/15072590

redpajama_set_name: RedPajamaStackExchange


text:
Q: Error with assigning a value to an element of an array of characters once initialised inside a function So here's what I am trying to do; connect two arrays of characters together through using memcpy. Part of this is because I am using u_chars but for this example, we will just use characters and use strlen to get the length of a string for simplification's sake.
Essentially, the steps that steps I take are:

*

*Create a new pointer that will represent my combined strings (char* name)

*Pass the address of the pointer into a function (so a reference to a pointer) along with the two pointers that I want to add together

*Set a dereferenced uninitialised pointer to be the memory address of a new memory allocation of the size I want (this works fine)

*Copy the first set of data into this new location (this also works fine)

*Copy the second set of data into this new location, plus a few places that represent the lengthof the first set's data (this also works fine)

*Set the last character of this pointer's data to be a null-terminating character ('\0)

...and this is where everything dies. I get an access violation error when trying to write to location 0x00000000. However, the pointer definitely exists. Below is the code (written in Visual C++ using VS2013)
#include "stdafx.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

char * name;
char * firstpart;
char * lastpart;

void addstrings(char ** result, char * body, char * prefix)
{
   int x = strlen(prefix);
   int y = strlen(body);

   *result = (char *)malloc((x + y + 1) * sizeof(char));

   memcpy(*result,      prefix,  x);
   memcpy(*result + x,  body,    y);

   *result[x + y] = '\0';     // Exception is thrown writing to memory address 0x00000000
}

int _tmain(int argc, _TCHAR* argv[])
{
   firstpart = "stack";
   lastpart = "overflow";

   addstrings(&name, firstpart, lastpart);
   return 0;
}

The following replacement allows the program to continue, which on inspection shows me that the string exists
result[x + y] = '\0';

But this will not set any value; which is probably correct as "result" in this instance is still only the reference to the pointer and not the pointer itself (I want to modify the contents at the address of this pointer, which itself is a pointer, but I need to de-reference it by one level first).
To be clear; I know that there are ways around this (strcpy if I am using string.h) but this wouldn't work if I am using u_char types or something like this. Additionally, I could modify the above as follows, which works fine:
char * addstrings(char * result, char * body, char * prefix)
{
   int x = strlen(prefix);
   int y = strlen(body);

   result = (char *)malloc((x + y + 1) * sizeof(char));

   memcpy(result,      prefix,  x);
   memcpy(result + x,  body,    y);

   result[x + y] = '\0';

   return result;
}

*

*Return type is now char *

*Takes a pointer to the output string rather than a reference to the pointer

*Removed all dereferencing in the function

*Returns the pointer

The function call now looks like:
name = addstrings(name, firstpart, lastpart);

And this will work fine. But I am just curious as to what the issue really is and why I could not assign a value to an element in the array that the pointer is pointing to (yet I can in the second example).
Any comments or thoughts are greatly appreciated,
Thanks!

A: Just add this
(*result)[x + y] = '\0';

array subscript [] operator has higher precedence than dereference operator *.
Also notice that the second version of your function is ok, but you don't need to pass
char *result

as a parameter.
In the first case the indirection is performed first by the [] operator and then you are left with an invalid pointer.


text:
Q: https, a subdomain and an iframe: Any alternative to purchasing an additional SSL certificate? I have a website example.com and an SSL certificate for this domain only. No subdomains except www are included. The site is based on Typo3.
On example.com/map is an iframe (note the subdomain):
<iframe src="https://map.example.com" width="400" height="300">

This doesn't work with all browsers. Some browsers show an error (SSL_ERROR_BAD_CERT_DOMAIN) because the subdomain is not covered by the certificate.
The subdomain contains rather complex content which I wouldn't know how to built in Typo3, that's why I used an iframe.
Question:
Is there any way to insert the contents of map.example.com into the page example.com/map without purchasing an additional SSL certificate for the subdomain?
Thanks
Pida

A: I see the following solutions:

*

*Get a certificate for map.example.com

*

*Buy one

*Use an ACME client, for example Let's Encrypt

*Link: Instead of using an iFrame just link to the site map.example.com

*Set up a reverse proxy

*Server side include: Write an extension for the website example.com/map which includes the content from map.example.com

*Rebuild the solution as TYPO3 extension

It is difficult to say which one fits best for you.
A server side include may be easy in some cases, but in most cases it requires a lot of search an replace for the content which is going to be pasted. It also requires to include asset files (images, javascript, css) either in the TYPO3 template or dynamically by parsing the whole include content.
A reverse proxy is easy to set up in case you have the required software components already installed an the required knowledge. Otherwise it requires some reading and some hours to set up.


text:
Q: Sitecore 9.2 (002893) equivalent DLLs for Sitecore 8.1 rev. 151207 I was using a sitecore 8.1 151207 instance and Now I'm upgrading the solution to a 9.2 002893
In my 8.1 solution I have called following methods
 WorkflowCounters.ActionsExecuted.IncrementBy(int amount)
 Factory.GetMessage(Item item)

I've removed 8.1 dlls and added 9.2 dlls. Now some of the methods are not working due to unavailability of the dll references or due to some other issue(may be they have changed the method name, class name etc)
Here are the name spaces of those classes.
 WorkflowCounters >> Sitecore.Diagnostics.PerformanceCounters
 Factory >> Sitecore.Modules.EmailCampaign

Can someone help me by mentioning what the new method/class is to be used or the namespace to be used?

A: 1)
The Sitecore.Diagnostics.PerformanceCounters.WorkflowCounters.ActionsExecuted.IncrementBy namespace is now:

Sitecore.Diagnostics.PerformanceCounters.DataCount.WorkflowActionsExecuted.IncrementBy

Inside Sitecore.Kernel
2)
In Sitecore 8.1 there was an option module, Email Experience Manager. In Sitecore 9.2 this module is part of the core product. So this is why EmailCampaign related namespaces are changed. Also some things are changed in the architecture. The introduction of service bus implementation, The Sitecore Message bus runs on Rebus.
Looks like you try to use some functionality replaced by the new service bus. so it is not just change a namespace, I suppose you want to send an EXM email. The new way is documented on https://doc.sitecore.com see
https://doc.sitecore.com/developers/exm/92/email-experience-manager/en/sending-email-campaigns-programmatically.html


text:
Q: Unit test static method with dependency I have not much experience in unit testing, especially with Mockito and now I have encountered the following situation.
class A {

    void setField(String obj) {
    }

    Object execute() {
        throw new RuntimeException("Meh!");
    }

}

class B {
    //function to be tested
    static Object someMethod() {

        A a = new A();
        a.setField("test");
        Object response = a.execute();
        //logic here

        return response;
    }
}

class BTest() {

   A aInstance = mock(A.class);

   @Test
   public void test_someMethod_when_exec_returns_X() {
      when(aInstance.execute()).thenReturns("X");// doesn't work
      assertTrue("X", B.someMethod());
   }
}

I want to test the someMethod static method when a.execute() returns specific value.
I know, I can create a mock object of A and pass it to someMethod function, which is not a good solution as I should change the signature of someMethod.
What is the correct solution in this case?

A: If you check out PowerMockito's documentation you'll realize that the following is what you need:
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;

import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.powermock.api.mockito.PowerMockito.mock;
import static org.powermock.api.mockito.PowerMockito.whenNew;

// execute the test with the appropriate runner
@RunWith(PowerMockRunner.class)

// prepare B for instrumentation so we can hack stuff inside
@PrepareForTest(B.class)
public class MyTest {

    @Test
    public void bShouldCallA() throws Exception {
        // create a mock for A and configure its behaviour
        A aMock = mock(A.class);
        when(aMock.execute()).thenReturn("X");

        // make sure that when A's constructor is called in the static method, the mock above is returned
        whenNew(A.class).withNoArguments().thenReturn(aMock);

        // do the actual invocation
        Object actualResult = B.someMethod();

        // check result and interactions
        assertEquals("X", actualResult);
        verify(aMock).setField("test");
    }
}

A: As I mentioned, the PowerMockito doesn't work in android, you can just mock android object with that. And here comes engineering solution :)
Factory class to create object A.
public class AFactory {

  static private AFactory sInsntance = new AFactory();

  public static AFactory createObject() {
      return sInsntance.createInternally();
  }

  protected TMMethodBuilder createInternally() {
     return new A();
  }

  //This function is only for testing, in order to inject factory
  @Deprecated
  public static void setFactory(AFactory mock) {
      sInsntance = mock;
  }
}

And create object A:
A a = AFactory.createObject();

In Test project extend AFactory and override createInternally() method to return mocked object.
public class AFactoryTest extends AFactory {

  private static A a = mock(A.class);

  @Override
  protected TMMethodBuilder createInternally()  {
      return a;
  }
}

So in test class just do the following:
    factory = new AFactoryTest();
    a = factory.createInternally();
    AFactory.setFactory(factory);
    //
    when(..).thenReturn();


text:
Q: Determine thickness, head and tail of a snake in OpenCV C++ I'm trying to analyze an image of a snake and determine the thickest point and which end is the head and which end is the tail.  Here is the original image.

So far I have processed the image through grayscale, binary and processed the canny contours of the snake.

I also have the skeleton of the canny via thinning algorithm which is roughly the center line of the snake.

Now that I have the Canny contours and skeleton contours what techniques could be used to determine the pixel width of the fattest part of the snake body and also determine the head and tail?

I havent been able to find any techniques with OpenCV C++ that I can use to create these measurements or determine head from tail.
Any help and guidance would be greatly appreciated.

A: Here is my suggestion, assuming computational cost is not a problem:

*

*Thickness: for each point of the skeleton, the local thickness can be approximated by computing the distance from the current point of the skeleton and each point of the contour and keeping the smallest distance. Then the thickest point is simply the one where the local thickness is maximal.
thickness(x_skelet) = min([distance(x_skelet, x_contour) for x_contour in countour]) (yeah I know this is bad python style pseudo code, hope it make sense)

*Hear/Tail differentiation: The main difference between head and tail is the average thickness. First off I would define which percentage of the body the tail and head are (at first glance I'd say 5%). Then, using the local thickness defined above I'd compute the average thickness over the 5% points of each side of the serpent. The head should be the side with the highest average thickness. And by definition the tail is the other.

From looking at your image, this should be robust enough to overlook the small artifacts in your image. Know that this implementation of local thickness is a little off close to the extremities but it should be good enough for what you described.
Hope this is useful to you.

A: A more general approach would result in widths orthogonal to and along the skeleton, or even better, orthogonal to and evenly spaced along the (smoothed) medial axis. Ortho-medial widths can then be plotted or, to obtain the head and tail position, easily be analyzed.


text:
Q: Parse custom binary protocol from inputstream I have a couple of questions regarding a custom binary protocol.
Our server is connected to a CCT (Custom Command Terminal) which is controlled by the user and can send binary commands to this central unit. The communication between the CCT and the server is a standard ethernet socket on a certain port.
All commands and messages in both directions will use the same frame format:

*

*STX: 0x02 - byte indicating the start of the command

*Length: The length of the messages including the STX and length bytes but not the checksum byte

*Command: The type of command

*Parameter 1-n: the data bytes for the given command number

*ChkSm: A checksum byte

When the server receives a message with a valid checksum or a first connection, it will send a single acknowledge byte back.
For the communication, I'm using a standard Java socket with a DataInputStream and DataOutputStream.

*

*How I can correctly read in the bytes from the DataInputStream and cast these back to their original values (integer, booleans, ...). I know there are the readByte(), readShort() and readbyte(byteArr, offsett, length) methods but why would I prefer the one over the other.

*readbyte(byteArr, offsett, length) returns the number of bytes read. Why would I use this value is my scenario. What size should the byteArr be as my parameter?
 byte[] responseBytes = new byte[5];
 int bytesRead = 0;
 try {
     bytesRead = mInputStream.read(responseBytes, 0, 4);
 } catch (IOException e1) {
     e1.printStackTrace();
 }

*When I receive data from the inputstream and I use readByte(), would this be the STX (the start of the command)?

*How are binary protocols handled? Is there any best practice on getting started on this? Maybe an example based on what I am trying to achieve?

A:
How I can correctly read in the bytes from the DataInputStream

Don't use DataInputStream. Just use the plain InputStream.

readbyte(byteArr, offsett, length) returns the number of bytes read. Why would I use this value is my scenario. What size should the byteArr be as my parameter?

Since the Length is only a single byte, a command can be at most 256 bytes long (255 + 1 byte ChkSm), so use a byte[256].
The value returned by read(responseBytes) then tells you how many bytes you actually received, so you know whether you got all the bytes (compare with Length).

When I receive data from the inputstream and I use readByte()

You probably wouldn't use read() to read a single byte, only read(responseBytes).

How are binary protocols handled?

Depends on the protocol. There is no single good answer.


text:
Q: Mail rejected using phpmailer on GoDaddy.com host Using this:
require("lib/class.phpmailer.php");
$mail = new PHPMailer();
$mail->Username = "XXX@validGoDaddyAccount.com";
$mail->Password = "xxx";
$mail->Subject = $subject;
$mail->Body= $message;
$mail->AddAddress($toAddr);
$mail->FromName = "XXXXXXXXXXXX";

$mail->IsSMTP();
$mail->SMTPDebug = 2;
$mail->Host = "smtpout.secureserver.net";
$mail->Port = 465;
$mail->SMTPSecure = "ssl";
$mail->SMTPAuth = true;
$mail->From = $mail->Username;
$mail->IsHTML(true);
if(!$mail->Send()) {
    echo "Mailer Error: " . $mail->ErrorInfo;
} else {
   return true;
}

I get this response:
SMTP -> FROM SERVER:220 p3plsmtpa07-05.prod.phx3.secureserver.net ESMTP
SMTP -> FROM SERVER: 250-p3plsmtpa07-05.prod.phx3.secureserver.net hello     [00.00.0.0], secureserver.net 250-HELP 250-AUTH LOGIN PLAIN 250-SIZE 31457280 250-PIPELINING 250-8BITMIME 250 OK
SMTP -> FROM SERVER:550 User XXX has exceeded their send quota
SMTP -> ERROR: MAIL not accepted from server: 550 User XXX has exceeded their send quota
The following From address failed: XXX : MAIL not accepted from server,550,User XXXm has exceeded their send quota
SMTP server error: User XXX has exceeded their send quota

Mailer Error: The following From address failed: XXX : MAIL not accepted from server,550,User XXX has exceeded their send quota
SMTP server error: User XXX has exceeded their send quota

I know about setting the SMTP Relays for GoDaddy accounts and they are set right. I can send email from this account all day long as long as I don't use PHPmailer.

A: see the following line
SMTP -> FROM SERVER:550 User XXX has exceeded their send quota

That's why it is rejecting.

A: The solution is that I needed to pre-authorize with POP prior to starting the SMTP operation:
require("lib/class.phpmailer.php");
require_once('lib/class.pop3.php');
$pop = new POP3();
$pop->Authorise('pop.server.net', 110, 30, 'username', 'password', 1);
$mail = new PHPMailer();
...


text:
Q: UTF-8 issue with Soft Hyphen (U+00AD) in both LuaLaTeX and XeLaTex I have a very simple test case that displays all of the Latin-1 printable characters (U+0021 - U+007e, U+00A1 - U+00ff). It works correctly for every UTF-8 character except U+00AD. It fails with both LuaLaTeX and XeLaTex.
It does not matter if I use unicode-math, nor does it matter if I set the monospace font. If I open the source file in Notepad, everything displays correctly, no matter which font I choose (as long as Latin-1 is supported by the font). If I do set a font using setmonofont it doesn't make any difference.
Here is the test case:
\documentclass[10pt]{article}
\begin{document}
\begin{verbatim}
! " # $ % & ' ( ) * + , - . /
0 1 2 3 4 5 6 7 8 9 : ; < = > ?
@ A B C D E F G H I J K L M N O
P Q R S T U V W X Y Z [ \ ] ^ _
` a b c d e f g h i j k l m n o
p q r s t u v w x y z { | } ~

¡ ¢ £ ¤ ¥ ¦ § ¨ © ª « ¬  ® ¯
° ± ² ³ ´ µ ¶ · ¸ ¹ º » ¼ ½ ¾ ¿
À Á Â Ã Ä Å Æ Ç È É Ê Ë Ì Í Î Ï
Ð Ñ Ò Ó Ô Õ Ö × Ø Ù Ú Û Ü Ý Þ ß
à á â ã ä å æ ç è é ê ë ì í î ï
ð ñ ò ó ô õ ö ÷ ø ù ú û ü ý þ ÿ
\end{verbatim}
\end{document}

This does not show correctly in the question, so an image of the source is also included in a monospace font.

And here is the output. It can be seen that on the first line above the ASCII range (starting with the inverted !) that following the "not" symbol, the hyphen is omitted. This may be correct in non-verbatim mode, since it is a "weak" hyphen if it were embedded in a word. However, that processing should not occur in verbatim mode. Note that it also fails when not in verbatim mode, and since the weak hyphen is not embedded in a word, it should not be omitted (as Notepad shows).

A: Whatever Notepad shows should not be taken as an absolute rule. For instance, the editors I have on my machine don't show U+00AD.

Not even if I ask to show invisible characters

However, you might decide to show the character inside verbatim and it's not difficult: hook into the code to add your personal stuff when initiating verbatim.
\documentclass[10pt]{article}
\usepackage{etoolbox}

\makeatletter
\patchcmd{\@verbatim}{\@noligs}{\@noligs\@otherstuff}{}{}
\def\@otherstuff{\catcode"AD=\active}
\begingroup
\catcode"AD=\active
\gdef^^ad{{\ooalign{-\cr\hidewidth?\hidewidth\cr}}}
\endgroup

\begin{document}
\begin{verbatim}
  ! " # $ % & ' ( ) * + , - . /
0 1 2 3 4 5 6 7 8 9 : ; < = > ?
@ A B C D E F G H I J K L M N O
P Q R S T U V W X Y Z [ \ ] ^ _
` a b c d e f g h i j k l m n o
p q r s t u v w x y z { | } ~

  ¡ ¢ £ ¤ ¥ ¦ § ¨ © ª « ¬  ® ¯
° ± ² ³ ´ µ ¶ · ¸ ¹ º » ¼ ½ ¾ ¿
À Á Â Ã Ä Å Æ Ç È É Ê Ë Ì Í Î Ï
Ð Ñ Ò Ó Ô Õ Ö × Ø Ù Ú Û Ü Ý Þ ß
à á â ã ä å æ ç è é ê ë ì í î ï
ð ñ ò ó ô õ ö ÷ ø ù ú û ü ý þ ÿ
\end{verbatim}
\end{document}

Decide about the appearance, here a question mark superimposed to a hyphen.

A: This is expected behavior. Notepad might be showing you the character as a hyphen, but my editor for one does not: It displays <0xad> to denote an unprintable character.
You see, back in 2002 when Unicode 4.0 first came out, the category of U+00AD SOFT HYPHEN was changed from the previous "Pd" (punctuation, dash) to "Cf" (other, format), following HTML 4.0's lead, where  has always behaved that way.
This means that the sole purpose of this character is to mark an invisible hyphenation opportunity, which only becomes a visible hyphen at the end of a line after formatting, if and when needed. Really just like \- in TeX, all things considered.

A: A regular expression can find formatting characters and replace them with something visible:

MWE
\documentclass{article}
\usepackage{xparse}
\usepackage{xcolor}

\ExplSyntaxOn

\NewDocumentCommand { \showAD } { +m } {
    \tl_set:Nn \l_tmpa_tl { #1 }
    \regex_replace_all:nnN
                { \xAD }
                { \cB\{ \c{color} \cB\{ red \cE\} A \cE\} \c{llap}\cB\{ D \cE\} }
                \l_tmpa_tl
    \tl_use:N \l_tmpa_tl
}

\ExplSyntaxOff

\begin{document}

abcxyz (invisible)

\showAD{abcxyz} (visible)

\ttfamily
\showAD{¡ ¢ £ ¤ ¥ ¦ § ¨ © ª « ¬  ® ¯}

\end{document}


text:
Q: SQL Dependency Tracking Not Working I am having some issues with SQL dependency tracking. On some of our developer machines SQL dependencies are recorded as expected, on some they are not. We cannot locate the setting on the machine that is preventing the SQL dependency from being tracked. When the same code and configuration is run on our UAT and Production machines we get the same issue, no SQL dependency tracking.
It seems to be machine or user specific. Is there a permission, firewall or some other such setting that may be preventing the SQL dependency tracking from working within certain environments?
Thanks for all your help.

A: are some devs building / running against .NET 4.5 and some .NET 4.6?
if you are using .NET 4.6+, you get more dependency tracking "for free", but on 4.5 and earlier you need to use Status Monitor to turn on additional profiling to get sql dependencies collection at runtime.
The instructions for installing status monitor are here:
https://azure.microsoft.com/en-us/documentation/articles/app-insights-asp-net-dependencies/


text:
Q: Two-step verification for microsoft company account? I have a MS company account using Office 365 (so myname@mydomain.com is my account), and I use Office, Azure, and Visual Studio Team Services.
However, I cannot find anywhere how to enable 2FA for this account. I can set up 2FA for my normal, personal, windows live Id using this page:
http://windows.microsoft.com/en-US/windows/two-step-verification-faq.
But that doesnt work for company accounts.
Anyone knows if this is possible? thanks!

A: What you need is Multi-Factor Authentication for Azure Active Directory. It is part of AAD Premium features.
You can read how to enable and configure it here. And more info on it here.
UPDATE
As per documentation:

Multi-Factor Authentication is now included with Premium and can help
  you to secure access to on-premises applications (VPN, RADIUS, etc.),

As well as per this documentation:

Azure Multi Factor Authentication is included in Azure Active
  Directory Premium and as a result it is also included with the
  Enterprise Mobility Suite

Note: MFA is (at least was) possible with the free AAD but only for the Global Admins in the directory, or for Subscription Administrators within an Azure Subscription.


text:
Q: create variable from annotation argument I'm trying to save the argument from an custom annotation ( UrlAnnotation ) to be able to use it across classes.
But unfortunately I cannot make it to work in a simple way :/
This is how I'm trying to solve it.
Test.cs
[UrlAnnotation("customer"])
[TestMethod]
public void Smoke(){
 ....
}

UrlAnnitation.cs
public class UrlAnnotation : Attribute
 {
  private string baseUrl;

  public UrlAnnotation(string baseUrl)
  {
   this.baseUrl = baseUrl;
  }
 }

Later I'm trying to access baseUrl (annotation argument) like this.
**Uri.cs**

public class Uri {

   private UrlAnnotation urlAnnotation;

   public Uri()
    {
      urlAnnotation = new UrlAnnotation();
    }
 }

The error that is thrown is from
    urlAnnotation = new UrlAnnotation();
because It wants an argument, make sense but I don't really know how to add the argument from the annotation.
Thanks in advance


text:
Q: Javascript/HTML mobile browser emulator Looking for an html/js solution/package to display a website preview on my site, where the previewed site is rendered as if it was viewed by a mobile browser.
Currently I am using a solution based on an iFrame, however this does not allow me to set the user agent to a mobile one, so it is not an optimal solution.
Suggestions appreciated.
EDIT:
I don't think I made myself clear enough, I want to embed such an emulator on my webpage, I am not looking for a browser extension or for a desktop software solution.

A: you can use Ripple Emulator it emulates many devices and many platforms.
first open chrome(chrome adds on) ,open this URL on chrome :
add it on chrome ,
you can then enable it on disable it as you need,
(write click enable/disable)
see how it looks:

A: There are a lot of emulators available for mobile devices. Some prominent ones are:

*

*Ripple Emulator for Chrome

*Opera Mobile Emulator

*Also checkout, this page on MobileX for a complete catalog.

A: OK,
Just to update and specify what I eventually did:
What I needed to do is embed some kind of iframe which emulates webpages as if they were viewed from a mobile device. The biggest problem was to set the user agent to be a mobile one (which you cannot do with an iframe).
What I ended up doing is set up another php-based server running a glype proxy.
The Glype proxy allows to emulate different user agents, I hard coded it to be an android browser user agent.
I then inserted an iframe pointing to my other proxy server, and it works nice.
I still had a problem with some websites which implement and iframebuster script, and I had to manage that.
Ilan


text:
Q: Error while running apache tika and vision server i am trying out capabilities of apache tika and got the following error after setting up and running tika and tensor flow recognition server.
I installed using docker and followed these instructions from the documentation
a. Using docker (Recommended)

*

*git clone https://github.com/USCDataScience/tika-dockers.git && cd
tika-dockers

*docker build -f InceptionRestDockerfile -t
uscdatascience/inception-rest-tika .

*docker run -p 8764:8764 -it uscdatascience/inception-rest-tika

*Once it is done, test the setup by visiting http://localhost:8764/inception/v4/classify/image?topn=2&min_confidence=0.03&url=https://upload.wikimedia.org/wikipedia/commons/f/f6/Working_Dogs%2C_Handlers_Share_Special_Bond_DVIDS124942.jpg in your web browser.

and got following error

Traceback (most recent call last):

File "/usr/bin/inceptionapi", line 237, in <module>

app = Classifier(__name__)

File "/usr/bin/inceptionapi", line 194, in __init__

self.names = create_readable_names_for_imagenet_labels()

File "/usr/bin/inceptionapi", line 138, in create_readable_names_for_imagenet_labels

assert num_synsets_in_ilsvrc == 1000

AssertionError

It is breaking with the same error for tika vision video too but image captions API is working fine, can someone please help me in solving this issue

A: The Assertion error is because it cannot download some of the imagenet data due to the Tensorflow project moving where they reside, and therefore the data isn't there to be loaded at runtime. Both InceptionVideoRestDockerfile and InceptionRestDockerfile are impacted.
I've created a Fork with the required changes and submitted a pull request here to the team at USC. Using the updated URLs allows these Docker images to load the model. This in turn allows them to be used in Apache Tika.


text:
Q: How to show only message from log (hide time ,pid etc.) in Android Studio I haven't use Android Studio (IntelliJ IDEA) before the logcat that show in Android Studio also show time and pid etc. on the left side of logcat. I want to hide those stuff (time and pid) I wanna see only message form Log.
Is there any suggestion?

A: You can use PID Cat from Jake Wharton.
pidcat.py com.health.main

A: Now on Android Studio you can config the logcat

A: I'm stuck on the same problem. As you pointed out this is a missing feature, I hope that it will be added in the future.
For now, I've mitigated the problem by enabling the "Use Soft Wraps" option that allow multiline logging in order to avoid the horizontal scrolling.

UPDATE
As reported in the official issues tracker, there should be more formatting options starting from Android Studio 1.4 beta 3

Good news, this should be out now with 1.4 beta 3 which we just
  released today.

A: Batter You can use monitor.
.
set the path in environment variable C:\Program Files\Android\android-sdk\tools; . and type monitor.and you can filter any type of messages however you want. :)


text:
Q: AttributeError: module 'rest_framework.serializers' has no attribute 'as_view' in django i already import and install djangorestframework in my project and import it to my settings, how do i call or import my serializers to my urls.py, i am getting this error AttributeError: module 'rest_framework.serializers' has no attribute 'as_view'
this is my serializers.py
from rest_framework import serializers
from .models import register

class registerSerializer(serializers.ModelSerializer):
    class Meta:
        model = register
        field = ('username', 'password', 'email')

this is my urls.py
from rest_framework import serializers
urlpatterns = [
    path('admin/', admin.site.urls),
    path('', serializers.as_view(), name='serializers')
]

this is my settings.py
INSTALLED_APPS = [
    'rest_framework',
    'registrationApp',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
]

A: views.py
from .serializers import *
# PARA el uso del API (al final)
from rest_framework import viewsets
from .models import *
class RegisterViewSet(viewsets.ModelViewSet):
    queryset = register.objects.all()
    serializer_class = registerSerializer

urls.py
from rest_framework import routers
router = routers.DefaultRouter()
router.register('register', RegisterViewSet)
urlpatterns = [
    path('', include(router.urls), name='api-rest'),
]

documentation rest-framework


text:
Q: Good historical books on projective geometry Can you suggest some good book for newbies which gives a solid historical background and good understanding in projective geometry ?
(I have zero background in projective geometry, and the only geometry I know is some rudimentary Eucledian Geometry. I was learning projective goemetry from EGMO Chapter 9, but I couldn't properly understand "projective plane", "points at infinity" etc)

A: A good reference is Coxeter's book Projective Geometry. The first chapter should provide enough orientation to get you started, should you choose then to go elsewhere. But you might as well stick with the entire book, if you want to learn the subject.
Other good discussions of the history are in Jeremy Gray's Worlds Out of Nothing and the last chapter of Cornelius Lanczos's Space Through the Ages.


text:
Q: Center an image with CSS (horizontal and vertical) This is a basic question that i couldn't find answer to .
I would like to take a logo image, centre it exactly in the middle of the screen ,when keeping the image in its original size .
Than right under that image(- 5px down), put a small text line, where i choose its font .
Everything is messed up when i am trying to do that , so i will put the basic ,and if you can help me achieve this simple goal, that would be great .

A: You could achieve this by using css transform and absolute position like this:
JSFiddle - DEMO

<!DOCTYPE html>

    <meta charset="utf-8">

MY TEXT

A: Improved - now with image re-sizing
Building Blocks

*

*The image and text are wrapped in a div.

*The div is centered thanks to the right combination of position: absolute, top, right, bottom, left and margin: auto.

*The container will re-size to its max width and height with height: 100% and width: 100%

*max-height: 100% and max-width: 100% ensures that the image width height ratio remains 1:1 when re-sizing.
IE 8 needs a fixed pixel height for the container.
Change max width and height to match the image.
Demo

* {
  margin: 0;
  padding: 0;
}
.centered {
  position: absolute;
  top: -4em;
  /* change top unit size to get desired vertical placement */
  right: 0;
  bottom: 0;
  left: 0;
  margin: auto;
  height: 100%; /*IE 8 Needs px height */
  width: 100%;
  max-height: 300px;
  max-width: 300px;
  min-width: 100px;
  text-align: center;
}
.centered img {
  max-height: 100%;
  max-width: 100%;
  min-width: 100px;
}

Green Eggs and Ham


text:
Q: How to hide a section and show another section in one click in elementor? I want to hide a section and show another section in one click.... is there any way to do that in elementor.
I searched on google but I get the result that only hide a  section and show it again on another click.
But I want to hide a section and show a hidden section in one click....
please, help me with the solution.
thank you.

A: *

*make sure to set a classname/id for each of your sections and also for your button.
eg. let's say i have set .sc1 and .sc2 for sections and .btn for the button.

*drag and drop HTML widget to your header template or the page/template you want the results in.

*copy the following javascript code to your html, make sure to put it between script tag:

var btn = document.querySelector('.btn');
    var sc1 = document.querySelector('.sc1');
    var sc2 = document.querySelector('.sc2');
    btn.addEventListener("click", function() {
    if (sc1.style.display === "none") {
    sc1.style.display = "block";
    sc2.style.display = "none";
    } else {
    sc1.style.display = "none";
    sc2.style.display = "block";
    }
    });
.sc1, .sc2 {
  width: 50px;
  height: 50px;
}
.sc1 {
  background: #000;
  display: block;
}
.sc2 {
  background: #e2062c;
  display: none;
}

<button class="btn">click</button>


text:
Q: Linux stuck one hour ahead (CentOS) I use CentOS, and for some reason, one of the servers I bought (amongst a network of other servers I do not own) is off by one hour. The time is one hour ahead no matter what time zone I set it to.
[root@adventurelobbies5 ~]# mv /etc/localtime /etc/localtime.bak
[root@adventurelobbies5 ~]# ln -s /usr/share/zoneinfo/America/New_York /etc/localtime
[root@adventurelobbies5 ~]# date
Mon May 14 18:24:23 EDT 2012

Right now, it's actually Mon May 14 17:24:23 EDT 2012
Any ideas? I've heard things about setting the hardware clock? I'm not sure if I have access to that as this is a VPS.


text:
Q: Spring Boot Microservices Saga example I am looking to learn the Spring Boot Microservices Saga based project. I went through web and found many theoretical links like https://www.baeldung.com/cs/saga-pattern-microservices and https://microservices.io/patterns/data/saga.html, but I don't find the simple source code witch depicts the working code.
Can anyone please share the link to source code which is working POC?

A: You can try the following if it helps:
https://github.com/berndruecker/trip-booking-saga-java
Although I would suggest you using the Axon framework. It is designed for an event-driven system. You can easily find many examples related to the saga in axon as well. May be something like this:   https://github.com/dashsaurabh/saga-pattern-axon-spring-boot-sample


text:
Q: java comparator on multidimensional array Is there a better way to write this comparator? I have an equivalent of multidimensional array where columns are Object's. The actual objects are String and BigDecimal 99% of the time. I am sorting "rows" on a given column index.
I want to avoid instanceof.
protected static class MyComparator implements Comparator<DataRow> {
    private int idx;

    public MyComparator(int idx) {
        this.idx = idx;
    }

    @Override
    public int compare(DataRow r1, DataRow r2) {
        Object o1 = r1.getColumns()[idx];
        Object o2 = r2.getColumns()[idx];
        if (o1 instanceof String){
            return ((String)o1).compareTo((String)o2);
        }else if (o1 instanceof BigDecimal){
            return ((BigDecimal)o1).compareTo((BigDecimal)o2);
        }else{
            throw new UnsupportedOperationException("comparison cannot be performed");
        }
    }

A: Since both String and BigDecimal are Comparables:
return ((Comparable)o1).compareTo(o2);

A: I think since you only depend on the type Comparable you could rewrite it as:
public int compare(DataRow r1, DataRow r2) {
        Comparable o1 = (Comparable) r1.getColumns()[idx];
        Comparable o2 = (Comparable) r2.getColumns()[idx];
        return o1.compareTo(o2);
}

If you carefully populate the table you shouldn't face the UnsupportedOperationException situation.

A: If the colum types are not comparable, I would implement separate comparators and make the Column class a factory for the correct comparator that should be used.


text:
Q: SVN Switch to new repositary is not working My current repository is : /var/www/svn/project.all my files within project folder.it doesn't have trunk,branches,tags structure as of now.
Now i have created new project as "/var/www/svn/projectnew" with trunk,branches,tags.
I took the Dump of "/var/www/svn/project" and loaded to "/var/www/svn/projectnew/trunck" and created one branch in "/var/www/svn/projectnew/branches/site1" from trunk.
Currently my Working copy pointing "/var/www/svn/project". i tried to switch my working copy from "/var/www/svn/project" to "/var/www/svn/projectnew/branches/site1" but it saying,
Repository UUID 'd3f06af7-c344-2d45-b1bd-7799e0e99d7a' doesn't match expected UID 'f5f9f6ac-3f50-7e4d-a9d4-0bc9a9b443b8'.
Help me on how i can go with this?

A: You should relocate your current working copy. Command svn relocate will help you.


text:
Q: tmux script to launch several commands How can I write the following in a bash script?
tmux # Start tmux session.
compass watch /path/to/project1/compass/ # Run the first process.
Ctrl + B, " # Split the pane.
compass watch /path/to/project2/compass/ # Run the second process.
Ctrl + B, D # Exit the session.

A: tmux \
    new-session  'compass watch /path/to/project1/compass/' \; \
    split-window 'compass watch /path/to/project2/compass/' \; \
    detach-client

The new-session command (which creates a new tmux session) and the split-window command (which splits the current window into two panes) in tmux takes optional shell commands to run. The detach-client does the obvious at the end.
If you want a horizontal split (two panes side by side), use split-window -h in the command above.
When sending multiple tmux commands to tmux you need to separate them by ;. The ; needs to be protected from the shell by quoting/escaping it (';', ";" or \;), to stop the shell from interpreting it as the end of the tmux command.
I've split the whole thing into separate lines for readability. If you do this in a script (which I recommend), make sure there's nothing after the final \ on each line.
Reattach to the session with tmux a, tmux attach, or tmux attach-session (these are all equivalent).
The tmux session will end once both commands have finished executing.

A: To run a short command without exiting at the end:
tmux \
    new-session  'ls ; bash' \; \
    split-window 'ls ; bash'

or
tmux \
    new-session  'ls ; bash' \; \
    new-window   'ls ; bash'

A: This didn't work for me ( I was trying to do something like 'ls -la'). What did was:
tmux new-session -d bash
tmux split-window -h bash
#sends keys to first and second terminals
tmux send -t 0:0.0 "<my-first-command>" C-m
tmux send -t 0:0.1 "<my-second-command>" C-m
tmux -2 attach-session -d

This allowed me to run pretty generic stuff and although it looks ugly, it is pretty functional.
Just leaving it here in case other people are looking for the same thing.
Source: https://gist.github.com/kizzx2/4739236


text:
Q: how to display a view in Django? I'm totally new to Django, and I'm trying to understand how does it work (I'm more used to PHP and Spring frameworks.
I have a project called testrun and inside it an app called graphs, so my views.py looks like:
#!/usr/bin/python
from django.http import HttpResponse

def index(request):
   return HttpResponse("Hello, World. You're at the graphs index.")

then, in graphs/urls.py:
from django.conf.urls import patterns, url, include
from graphs import views

urlpatterns = patterns(
   url(r'^$', views.index, name='index'),
)

finally, at testrun/urls.py:
from django.conf.urls import patterns, include, url
from django.contrib import admin

admin.autodiscover()

urlpatterns = patterns('',
    # Examples:
    # url(r'^$', 'testrun.views.home', name='home'),
    # url(r'^blog/', include('blog.urls')),
    url(r'^graphs/', include('graphs.urls')),
    url(r'^admin/', include(admin.site.urls)),
)

However, when I try to access http://127.0.0.1:8000/graphs/ I get:
Page not found (404)
Request Method: GET
Request URL:    http://127.0.0.1:8000/graphs/
Using the URLconf defined in testrun.urls, Django tried these URL patterns, in this order:
^admin/
The current URL, graphs/, didn't match any of these.
You're seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page.

What am I doing wrong that I can't get that simple message to be displayed in the browser?

A: To expand on my comment, the first argument to patterns() function is

a prefix to apply to each view function

You can find more information here:
https://docs.djangoproject.com/en/dev/topics/http/urls/#syntax-of-the-urlpatterns-variable
Therefore in graphs/urls.py you need to fix the patterns call like so:
urlpatterns = patterns('', # <-- note the `'',`
   url(r'^$', views.index, name='index'),
)


text:
Q: Convert from curl to ajax I would like to get some help with my ajax code. I want to move the curl code in the index.html to work with ajax but I don't know how I can convert from curl to ajax code.
Index.html:
<script>
$button.click(function(e)
{
   e.preventDefault();
   var emptyMail = true;
   var email = $emailInput.val().trim();
   var $emailInput_1 = $("#email").val();

   $(document).ready(function()
       $(this).val("SUBMITTING...");
       $("form").submit();

       $.ajax({
         url: "post.php",
         type: 'POST'
        });
    });
</script>

Here is the post.php
<?php
function _curl($url, $post = "", $headers = "")
{
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36");
    curl_setopt($ch, CURLOPT_REFERER, $url);
    curl_setopt($ch, CURLOPT_POST, ($post && is_array($post))? 1 :0);
    if ($post && is_array($post))
    {
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post));
    }
    if ($headers && is_array($headers))
    {
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    }
    curl_setopt($ch, CURLOPT_COOKIESESSION, true);
    curl_setopt($ch, CURLOPT_COOKIEFILE, "/dev/null");
    curl_setopt($ch, CURLOPT_COOKIEJAR, "/dev/null");
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    $result = curl_exec($ch);
    return $result;
    curl_close($ch);
}
if ($_POST)
{
    _curl("http://example.com/land/formFillReturnV5b.php", array(
    "name"=>"groups_name",
    "email"=>$_POST['email'],
    "phone"=>"",
    "ip"=> $_SERVER['SERVER_ADDR'],
    "reff"=>"",
    "page"=>"Q6",
    "link"=>"https://example.com/meme",
    "notes"=>"",
    "MID"=>"39918",
    "LID"=>"",
    "ARData"=>"meme",
    "cookie"=>""), array("X-NewRelic-ID" => "VQQBVl9aDRABUFJbAQkOUQ==", "X-Requested-With" => "XMLHttpRequest", "Content-Type" => "application/x-www-form-urlencoded; charset=UTF-8"));
}
?>

I want to make it like this:
<script>
    $button.click(function(e)
    {
       e.preventDefault();
       var emptyMail = true;
       var email = $emailInput.val().trim();
       var $emailInput_1 = $("#email").val();

       $(document).ready(function()
           $(this).val("SUBMITTING...");
           $("form").submit();

           $.ajax({
             url: "http://example.com/land/formFillReturnV5b.php",
             type: 'POST',
             "name"=>"groups_name",
             "email"=>$_POST['email'],
             "phone"=>"",
             "ip"=> $_SERVER['SERVER_ADDR'],
             "reff"=>"",
             "page"=>"Q6",
             "link"=>"https://example.onlinesalespro.com/meme",
             "notes"=>"",
             "MID"=>"39918",
             "LID"=>"",
             "ARData"=>"meme",
             "cookie"=>""), array("X-NewRelic-ID" => "VQQBVl9aDRABUFJbAQkOUQ==",      "X-Requested-With" => "XMLHttpRequest", "Content-Type" => "application/x-www-form-urlencoded; charset=UTF-8"));
            });
        });
    </script>

When I tried it, it won't work. If you can show me an example how I can use ajax code to send the data to the server that would be great.

A: Used Documentation
Example code
<script>
$button.click(function(e)
{
   e.preventDefault();
   var emptyMail = true;
   var email = $emailInput.val().trim();
   var $emailInput_1 = $("#email").val();

   $(document).ready(function()
       $(this).val("SUBMITTING...");
       $("form").submit();

       $.ajax({
         url: "http://example.com/land/formFillReturnV5b.php",
         type: 'POST',
         data: {name: "groups_name", email: "text@email.ru" /* and other parametrs*/ }
         success: function(result) {
          console.log(result);
         }
        });
    });
</script>


text:
Q: iText XFA Worker on OSGI (Karaf) I'm currently trying to deploy an XFA form rendering solution to Karaf. All my code works nicely when testing locally (no OSGi), but when I try to deploy to Karaf I get various errors. I believe the root cause here is that thge XFAWorker jars are not compiled as OSGi bundles. So I used the Karaf wrap protocol to import the bundles, but am still not succeeding. I've tried quite a few things and will try to document them as fully as possible below. However, it's super long to describe the various roadblocks I rand into, so in simple terms, the summary of my questions is:
How does one go about using iText XFA Worker in an OSGi container? (Karaf/Felix preferably)
Herewith the full sad story of what I tried:
First, the piece of code that requires the XFA Worker jars:
private byte[] flattenXfa(byte[] sourceXfaBytes) throws RuntimeException {

    // Create an output stream for the flattened doc
    ByteArrayOutputStream flattened = new ByteArrayOutputStream();

    try {
        Document document = new Document();
        PdfReader reader = new PdfReader(sourceXfaBytes);
        PdfWriter writer = PdfWriter.getInstance(document, flattened);
        XFAFlattener flattener = new XFAFlattener(document, writer);
        flattener.flatten(reader);
        document.close();
    } ... various catches
}

This method is called (via another class) on the start method of my bundle Activator, so that means I try to render (and flatten) the PDF on bundle start-up. This is really just for testing purposes - 've created a totally seperate project that really just has the little bundle and rendering code, to make sure nothing else can cause trouble.
Here's the start method of my activator (just in case it's important)
public void start(BundleContext context) {
    System.out.println("Starting the bundle");
    System.out.println("Rendering PDF");
    Renderer rend = new Renderer();
    String templatePath = "Path/to/xfa/file";
    String renderPayload = "<form1><Name>MyName</Name><Surname>MySurname</Surname></form1>";
    String xfaPdfPath = "Path/to/output/interactive/form";
    String flatPdfPath = "Path/to/output/flat/pdf";
    String licenseFilePath = "Path/to/itext/license/file";

    boolean flatten = true;
    rend.renderDoc(flatten, templatePath, renderPayload, xfaPdfPath, flatPdfPath, licenseFilePath);
}

As you can see, I've got a boolean flag that allows me to skip the flattenXfa method under certain circumstances.
In my Maven POM, I'm using the following dependencies:
    <dependency>
        <groupId>com.itextpdf</groupId>
        <artifactId>itextpdf</artifactId>
        <version>5.5.11</version>
    </dependency>
    <dependency>
        <groupId>com.itextpdf.tool</groupId>
        <artifactId>xfaworker</artifactId>
        <version>5.5.11</version>
    </dependency>
    <dependency>
        <groupId>com.itextpdf.tool</groupId>
        <artifactId>xmlworker</artifactId>
        <version>5.5.11</version>
    </dependency>
    <dependency>
        <groupId>com.itextpdf.tool</groupId>
        <artifactId>itext-licensekey</artifactId>
        <version>1.0.4</version>
    </dependency>

Take note: the itextpdf and xmlworker jars are available as OSGi bundles. Only the xfaworker and itext-licensekey cause issues
As stated earlier, when I run the code outside of OSGi it works fine - it renders and flattens the PDF like a champion.
When I try to run from OSGi it gives various issues, depending on my approach. So here's a trace of the things I've tried. I'll explain what problems I get with each:
Try 1: Use the wrap protocol to install the non-OSGi bundles.
After starting Karaf I run the following commands in sequence, i.e. simulating what my eventual feature file will do:
bundle:install -s mvn:com.itextpdf/itextpdf/5.5.11
bundle:install -s mvn:com.itextpdf.tool/xmlworker/5.5.11
bundle:install -s wrap:mvn:com.itextpdf.tool/xfaworker/5.5.11
bundle:install -s wrap:mvn:com.itextpdf.tool/itext-licensekey/1.0.4
bundle:install mvn:com.testing/xfa-test/0.0.1-SNAPSHOT (I specifically don't start it yet)

When I now start my bundle I get the following issue:
Starting the bundle
Rendering PDF
java.lang.NoClassDefFoundError: com/itextpdf/tool/xml/html/CssAppliersAware
    at java.lang.ClassLoader.defineClass1(Native Method)
    at java.lang.ClassLoader.defineClass(ClassLoader.java:763)
    at org.apache.felix.framework.BundleWiringImpl$BundleClassLoader.defineClass(BundleWiringImpl.java:2370)
    at org.apache.felix.framework.BundleWiringImpl$BundleClassLoader.findClass(BundleWiringImpl.java:2154)
    at org.apache.felix.framework.BundleWiringImpl.findClassOrResourceByDelegation(BundleWiringImpl.java:1542)
    at org.apache.felix.framework.BundleWiringImpl.access$400(BundleWiringImpl.java:79)
    at org.apache.felix.framework.BundleWiringImpl$BundleClassLoader.loadClass(BundleWiringImpl.java:2018)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
    at org.apache.felix.framework.BundleWiringImpl.getClassByDelegation(BundleWiringImpl.java:1415)
    at org.apache.felix.framework.BundleWiringImpl.searchImports(BundleWiringImpl.java:1595)
    at org.apache.felix.framework.BundleWiringImpl.findClassOrResourceByDelegation(BundleWiringImpl.java:1525)
    at org.apache.felix.framework.BundleWiringImpl.access$400(BundleWiringImpl.java:79)
    at org.apache.felix.framework.BundleWiringImpl$BundleClassLoader.loadClass(BundleWiringImpl.java:2018)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
    at com.testing.xfa.Renderer.flattenXfa(Renderer.java:123)
    at com.testing.xfa.Renderer.renderDoc(Renderer.java:52)
    at com.testing.xfa.Activator.start(Activator.java:34)
    at org.apache.felix.framework.util.SecureAction.startActivator(SecureAction.java:697)
    at org.apache.felix.framework.Felix.activateBundle(Felix.java:2226)
    at org.apache.felix.framework.Felix.startBundle(Felix.java:2144)
    at org.apache.felix.framework.BundleImpl.start(BundleImpl.java:998)
    at org.apache.karaf.bundle.command.Start.executeOnBundle(Start.java:38)
    at org.apache.karaf.bundle.command.BundlesCommand.doExecute(BundlesCommand.java:64)
    at org.apache.karaf.bundle.command.BundlesCommand.execute(BundlesCommand.java:54)
    at org.apache.karaf.shell.impl.action.command.ActionCommand.execute(ActionCommand.java:83)
    at org.apache.karaf.shell.impl.console.osgi.secured.SecuredCommand.execute(SecuredCommand.java:67)
    at org.apache.karaf.shell.impl.console.osgi.secured.SecuredCommand.execute(SecuredCommand.java:87)
    at org.apache.felix.gogo.runtime.Closure.executeCmd(Closure.java:480)
    at org.apache.felix.gogo.runtime.Closure.executeStatement(Closure.java:406)
    at org.apache.felix.gogo.runtime.Pipe.run(Pipe.java:108)
    at org.apache.felix.gogo.runtime.Closure.execute(Closure.java:182)
    at org.apache.felix.gogo.runtime.Closure.execute(Closure.java:119)
    at org.apache.felix.gogo.runtime.CommandSessionImpl.execute(CommandSessionImpl.java:94)
    at org.apache.karaf.shell.impl.console.ConsoleSessionImpl.run(ConsoleSessionImpl.java:274)
    at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.ClassNotFoundException: com.itextpdf.tool.xml.html.CssAppliersAware not found by wrap_mvn_com.itextpdf.tool_xfaworker_5.5.11 [61]
    at org.apache.felix.framework.BundleWiringImpl.findClassOrResourceByDelegation(BundleWiringImpl.java:1574)
    at org.apache.felix.framework.BundleWiringImpl.access$400(BundleWiringImpl.java:79)
    at org.apache.felix.framework.BundleWiringImpl$BundleClassLoader.loadClass(BundleWiringImpl.java:2018)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
    ... 35 more
Error executing command: Error executing command on bundles:
    Error starting bundle 65: Activator start error in bundle xfa-test [65].

For interest's sake, if I set the flatten attribute to false (i.e. I just render the interactive form without flattening) then it works fine, even in OSGi. That scenario, however, does not use the XFA Worker jar.
Try 2 - Use the Private-Package configuration of the maven-bundle-plugin
From the error message in Try 1, it seems that the issue has something to do with bundle wiring. So then I thought: Why not simply embed all the non-OSGi stuff directly in my bundle as private packages
So I edit the maven plugin as follows:
        <plugin>
            <groupId>org.apache.felix</groupId>
            <artifactId>maven-bundle-plugin</artifactId>
            <version>${maven-bundle-plugin.version}</version>
            <extensions>true</extensions>
            <configuration>
                <instructions>
                    <Bundle-SymbolicName>${project.artifactId}</Bundle-SymbolicName>
                    <Bundle-Version>${project.version}</Bundle-Version>
                    <Bundle-Activator>com.testing.xfa.Activator</Bundle-Activator>
                    <Export-Package>
                        com.testing.xfa*;version=${project.version}
                    </Export-Package>
                    <Import-Package>
                        *
                    </Import-Package>
                    <Private-Package>com.itextpdf.*</Private-Package>
                </instructions>
            </configuration>
        </plugin>

Now when I install and try to start my bundle I get the following  (typical OSGi) message:
Error executing command: Error executing command on bundles:
    Error starting bundle 66: Unable to resolve xfa-test [66](R 66.0): missing requirement [xfa-test [66](R 66.0)] osgi.wiring.package; (osgi.wiring.package=org.antlr.v4.runtime) Unresolved requirements: [[xfa-test [66](R 66.0)] osgi.wiring.package; (osgi.wiring.package=org.antlr.v4.runtime)]

Which leads me down a trial-and-error rabbit hole of adding more and more private packages to the bundle until my Private-Package tags looks like this:
    <Private-Package>com.itextpdf.*;org.antlr.*;org.abego.treelayout.*</Private-Package>

At this stage I get the following error (and it doesn't go away, even if I add "org.apache.jcp.*" to the list of private packages
Error executing command: Error executing command on bundles:
    Error starting bundle 69: Unable to resolve xfa-test [69](R 69.0): missing requirement [xfa-test [69](R 69.0)] osgi.wiring.package; (osgi.wiring.package=org.apache.jcp.xml.dsig.internal.dom) Unresolved requirements: [[xfa-test [69](R 69.0)] osgi.wiring.package; (osgi.wiring.package=org.apache.jcp.xml.dsig.internal.dom)]

Try 3 - Install all the bundles that cause issues that Private-Package doesn't solve.
This was another trial-and-error rabbit hole, but my approach was to:
 - Keep all non-osgi jars in my private packages tag
 - Remove the wrapped jars altogether (since they are now embedded in my bundle)
 - Add the following Karaf bundles, one by one:
bundle:install -s mvn:com.itextpdf/itextpdf/5.5.11
bundle:install -s mvn:com.itextpdf.tool/xmlworker/5.5.11
bundle:install -s mvn:org.apache.directory.studio/org.apache.commons.codec/1.8
bundle:install -s mvn:org.apache.santuario/xmlsec/2.0.2
bundle:install -s mvn:org.bouncycastle/bcprov-jdk15on/1.56
bundle:install -s mvn:org.bouncycastle/bcpkix-jdk15on/1.56
bundle:install -s mvn:org.bouncycastle/bcprov-jdk15/1.45
bundle:install -s wrap:mvn:org.apache.xmlbeans/xmlbeans/2.6.0

In between the addition of each bundle, I try to start my own and check what errors I get. Wash, rinse, repeat.
After an hour or two I've got a Private Packahe tag that looks like this:
<Private-Package>com.itextpdf.*;org.antlr.*;org.abego.treelayout.*;org.bouncycastle.*;org.mozilla.*</Private-Package>

At this stage Karaf no longer throws osgi wiring exceptions, but gives me the following NullPointerException
karaf@root()> start 87
Starting the bundle
Rendering PDF
java.lang.NullPointerException
    at com.itextpdf.tool.xml.xtra.xfa.positioner.Positioner.<init>(Positioner.java:190)
    at com.itextpdf.tool.xml.xtra.xfa.positioner.SubFormPositioner.<init>(SubFormPositioner.java:50)
    at com.itextpdf.tool.xml.xtra.xfa.pipe.FormBuilder.buildSubForm(FormBuilder.java:215)
    at com.itextpdf.tool.xml.xtra.xfa.pipe.FormBuilder.buildSubForm(FormBuilder.java:152)
    at com.itextpdf.tool.xml.xtra.xfa.pipe.FormBuilder.getFormDom(FormBuilder.java:566)
    at com.itextpdf.tool.xml.xtra.xfa.XFAFlattener.flatten(XFAFlattener.java:901)
    at com.itextpdf.tool.xml.xtra.xfa.XFAFlattener.flatten(XFAFlattener.java:491)
    at com.itextpdf.tool.xml.xtra.xfa.XFAFlattener.flatten(XFAFlattener.java:359)
    at com.itextpdf.tool.xml.xtra.xfa.XFAFlattener.flatten(XFAFlattener.java:329)
    at com.itextpdf.tool.xml.xtra.xfa.XFAFlattener.flatten(XFAFlattener.java:300)
    at com.testing.xfa.Renderer.flattenXfa(Renderer.java:124)
    at com.testing.xfa.Renderer.renderDoc(Renderer.java:52)
    at com.testing.xfa.Activator.start(Activator.java:35)
    at org.apache.felix.framework.util.SecureAction.startActivator(SecureAction.java:697)
    at org.apache.felix.framework.Felix.activateBundle(Felix.java:2226)
    at org.apache.felix.framework.Felix.startBundle(Felix.java:2144)
    at org.apache.felix.framework.BundleImpl.start(BundleImpl.java:998)
    at org.apache.karaf.bundle.command.Start.executeOnBundle(Start.java:38)
    at org.apache.karaf.bundle.command.BundlesCommand.doExecute(BundlesCommand.java:64)
    at org.apache.karaf.bundle.command.BundlesCommand.execute(BundlesCommand.java:54)
    at org.apache.karaf.shell.impl.action.command.ActionCommand.execute(ActionCommand.java:83)
    at org.apache.karaf.shell.impl.console.osgi.secured.SecuredCommand.execute(SecuredCommand.java:67)
    at org.apache.karaf.shell.impl.console.osgi.secured.SecuredCommand.execute(SecuredCommand.java:87)
    at org.apache.felix.gogo.runtime.Closure.executeCmd(Closure.java:480)
    at org.apache.felix.gogo.runtime.Closure.executeStatement(Closure.java:406)
    at org.apache.felix.gogo.runtime.Pipe.run(Pipe.java:108)
    at org.apache.felix.gogo.runtime.Closure.execute(Closure.java:182)
    at org.apache.felix.gogo.runtime.Closure.execute(Closure.java:119)
    at org.apache.felix.gogo.runtime.CommandSessionImpl.execute(CommandSessionImpl.java:94)
    at org.apache.karaf.shell.impl.console.ConsoleSessionImpl.run(ConsoleSessionImpl.java:274)
    at java.lang.Thread.run(Thread.java:745)
Error executing command: Error executing command on bundles:
    Error starting bundle 87: Activator start error in bundle xfa-test [87].

At which point I believe I'm doing something VERY WRONG, so I'm hoping to get some assistance here at SO.
Any pointers would be appreciated


text:
Q: Unique arrays in a multidimensional array I have a multidimensional array and I'm looking for a way to get only unique elements in the array.
use strict;
use feature 'say';
use List::Util 'shuffle';
#use List::MoreUtils 'uniq';

my @array = shuffle (
    [4, 10],
    [5, 6],
    [1, 2],
    [1, 2],
    [1, 2]
);

sub uniq {
    my %seen;
    grep !$seen{$_}++, @_;
};
my @unique = uniq(@array);
foreach (@unique) {say "@$_";};

And this doesn't work. It seems like each array in a multidimensional array is a different reference.
I  tried to use uniq from MoreUtils but it also doesn't work.
Please help.
P/s: I'm looking for a way to produce [4, 10] [5, 6] [1, 2].

A: You have to reference both array values in your %seen hash:
#!/usr/bin/perl
use strict;
use warnings;
use feature 'say';
use List::Util 'shuffle';

my @array = shuffle (
    [4, 10],
    [5, 6],
    [1, 2],
    [1, 2],
    [1, 2]
);

sub uniq {
    my %seen;
    grep !$seen{$_->[0]}{$_->[1]}++, @_;
};
my @unique = uniq(@array);
foreach (@unique) {say "@$_";};

Instead of a nested hash, you could stringify the two elements like so:
grep !$seen{"$_->[0],$_->[1]"}++, @_;

For the general case of an array of arbitrary data structures you can serialize the elements. This example uses Storable::freeze for serialization. $Storable::canonical needs to be set to true to allow for comparison of data structures. See documentation.
As @Ikegami points out, this will still cause problems with float values...
#!/usr/bin/perl
use strict;
use warnings;
use feature 'say';
use List::Util 'shuffle';
use Data::Dumper;
use Storable qw/freeze/;
#use List::MoreUtils 'uniq';

my @array = shuffle (
    [4, 10],
    [5, 6],
    [1, 2],
    [1, 2],
    [1, 2],
    [1,2,3],
    [1,2,{foo=>'bar'}],
    [1,2,{foo=>'bar'}],
    [1,2,{foo=>'baz'}],
);

sub uniq {
    my %seen;
    local $Storable::canonical = 1;
    grep !$seen{freeze( $_ )}++, @_;
};
my @unique = uniq(@array);
say Dumper \@unique;


text:
Q: how to use os.listdir sorted by first directorys and then files in python? I use os.listdir() and This code can traverse system directory structure, then generate a json file to django front-end of easyui call display tree UI:
def CreateDirTree(path,file_json):
    global id_num
    id_num=0
    def createDict(path):
            global id_num
            tree_list=[]
            pathList = os.listdir(path)
            for i,item in enumerate(pathList):
                    id_num+=1
                    children_map={}
                    children_map['id']=id_num
                    children_map['text']=item
                    if os.path.isdir(os.path.join(path,item)):
                            path = os.path.join(path,item)
                            print "directory:",path
                            tmp_listdir=os.listdir(path)
                            if  len(tmp_listdir) != 0:
                                    children_map['state']='closed'
                                    children_map['children'] = createDict(path)
                            tree_list.append(children_map)
                            path = '\\'.join(path.split('\\')[:-1])
                    else:
                        tree_list.append(children_map)
                        print children_map
            return tree_list

    tree_list=createDict(path)
    fjson = json.dumps(tree_list,ensure_ascii=False,sort_keys=False)
    with open(file_json,'w') as lf:
            lf.write(fjson)
    ##end
CreateDirTree("D:\\all_source\\somesite","123.json")

run and result is:
directory: D:\all_source\somesite\a

file is: b.txt

file is: oo.txt

file is: a.txt

directory: D:\all_source\somesite\b

file is: 123.txt

file is: b.txt
directory: D:\all_source\somesite\c

file is: yyt.txt

directory: D:\all_source\somesite\c\z

file is: c.txt

file is: e.txt

But I want to effect is:
directory: D:\all_source\somesite\a

a subdir files: 123.txt

a subdir files: abc.txt

directory: D:\all_source\somesite\b

directory: D:\all_source\somesite\c

directory: D:\all_source\somesite\c\z

file is: a.txt

file is: b.txt

file is: c.txt

file is: e.txt

first sorted by directory then sorted by files, How to do? please help me,thanks!

A: Create a list for directories and another for files and iterate over their concatenation. Adjusting from your code:
(...)
# List of directories only
dirlist = [x for x in os.listdir(path) if os.path.isdir(os.path.join(path, x))]
# List of files only
filelist = [x for x in os.listdir(path) if not os.path.isdir(os.path.join(path, x))]
for i,item in enumerate(dir_list + filelist):
(...)

This will start with directories and their subdirectories, and then move to the files

A: Here is a function to create the structure without a global variable and without calling os.listdir() twice for each directory:
import os
from itertools import count

def create_dir_tree(path):
    ids = count(0)
    def recurse(path):
        names = list()
        for name in os.listdir(path):
            full_name = os.path.join(path, name)
            names.append((os.path.isdir(full_name), name, full_name))
        names.sort(key=lambda n: (not n[0], n[1]))
        result = list()
        for is_dir, name, full_name in names:
            item = {'id': next(ids), 'text': name}
            if is_dir:
                children = recurse(full_name)
                if children:
                    item['state'] = 'closed'
                    item['children'] = children
            result.append(item)
        return result
    return recurse(path)

Like the original code one can't tell if an entry is a filename or an empty directory from the created data structure.


text:
Q: EF code first migrations, DB generated GUID keys The question as a one liner
How do I get EF to generate as part of a code first migration
ALTER TABLE [DMS].[Forms] ADD  CONSTRAINT [DF_DMS.Forms_Id]  DEFAULT (newid()) FOR [Id]
GO

More detail of the problem
I'm to build out a simple table to store information about forms, as it happens I already have this working for another table in my db but if I show you the code (see below) you'll realise the issue I'm hitting is stranger than it might seem ...
First the working example entity:
[Table("Files", Schema = "DMS")]
public class File
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public Guid Id { get; set; }
    ...
}

ok, now the not working one ...
[Table("Forms", Schema = "CMS")]
public class Form
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public Guid Id { get; set; }
    ...
}

As stated in the question, I'm using EF code first, so here's the migration code:
The working one:
CreateTable(
    "DMS.Files",
    c => new
        {
            Id = c.Guid(nullable: false),
            ...
        })
    .PrimaryKey(t => t.Id)
    ...;

... and the non working one ...
CreateTable(
    "CMS.Forms",
    c => new
        {
            Id = c.Guid(nullable: false),
            ...
        })
    .PrimaryKey(t => t.Id)
    ...;

So all is good ... then I migrate my db with an "update-database" command and script the two tables ...
The working one:
...
CREATE TABLE [DMS].[Files](
    [Id] [uniqueidentifier] NOT NULL,
    ...
 CONSTRAINT [PK_DMS.Files] PRIMARY KEY CLUSTERED
(
    [Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

GO

ALTER TABLE [DMS].[Files] ADD  CONSTRAINT [DF_DMS.Files_Id]  DEFAULT (newid()) FOR [Id]
GO
...

... and the non working one ...
...
CREATE TABLE [CMS].[Forms](
    [Id] [uniqueidentifier] NOT NULL,
    ...
 CONSTRAINT [PK_CMS.Forms] PRIMARY KEY CLUSTERED
(
    [Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

GO
...

A: I have no idea why but this works and fixes the problem ...
The working one (no changes):
CreateTable(
    "DMS.Files",
    c => new
        {
            Id = c.Guid(nullable: false),
            ...
        })
    .PrimaryKey(t => t.Id)
    ...;

... and the non working one (with fix applied)...
CreateTable(
    "CMS.Forms",
    c => new
        {
            Id = c.Guid(nullable: false, defaultValueSql: "newid()"),
            ...
        })
    .PrimaryKey(t => t.Id)
    ...;

I figure I must have come across some sort of bug in EF that results in it generating the migration correctly in some cases.


text:
Q: How can I cancel a scheduled gift delivery on steam? I've set up a scheduled gift on steam. Now I want to recall it. How can I do that?

A: EDIT: This answer is outdated. You'll find the late 2017 version of it here.

Old answer:

*

*You go into your steam inventory.

The game should still be in your inventory, because it's not accepted yet. (It can't because it is scheduled) so:

*You click on the game that is planned to be gifted

*You click on "manage gift..."

*Select "Return the gift to your account" and press "Next"

The result: The gift is back in your inventory and wont be gifted.


text: Q: How do I set a toolbar/menu action to use the relevant system default icon in Qt 5? I'm using Qt Designer to design a GUI for a PyQt5 app. The app implements a number of actions that are common among most of the apps, namely "New", "Open", "Save", "Save As", "Undo", "Redo", "Cut", "Copy", "Paste" and "Delete". All the Qt apps I run on my [KDE5] system use the same icons for these so I conclude they are included in the system Qt theme (and the majority if not all of Qt themes probably) and the apps just display the system default icons instead of shipping their own as bundled resources. How do I implement the same in my app design?


text:
Q: How can I format only part of a word in a comment? Since comments gained the ability of some very limited formatting that's also a source of frustration involved. The syntax is, while similar to the main post syntax, still different enough that you stumble over the discrepancies every now and then.
Something like *foo*-bar works in normal posts but not in comments.
Case in point here: How the hell does the parser work?
Or rather: What do I need to do to the string to work? Adding a space after the interior * does work. But that's sort of a non-solution. Adding U+200B in there does not work (would have been too easy, I presume).
ETA: Ok, in the comments I've been doing some testing. It appears that everything that's a space seems to work (suggests \s is used somewhere). Since the zero-width space isn't a space it doesn't work. While I used foo-bar as a test string I also sometimes wanted to emphasize part of a non-hyphenated word, something like *un*foo (which works in Markdown, even though it doesn't appear to work in the JS preview. However, I would have expected the hyphen-minus at least to count as a delimiter. Looks like the hair space is the best option so far.

A: Intra word styling is not supported in comments.
Your workarounds using thin word separators work, and is likely to be the only thing you can do to get the effect.


text:
Q: Read and parse more than one text file matlab I have four .txt files. Each one has 250 lines, where each line has 4 values separated by commas as shown below are the first 5 lines in one of the file, but all are of the same structure:
NaN,NaN,NaN,-1
792.98,419.48,333.35,245.63
787.13,408.59,345.05,251.48
798.3,414.17,333.36,245.63
803.61,414.43,333.35,239.78

One of the four files is the reference file, named groundtruth.txt I want to read each line from the three files and compare it with the values found in the same line number in the groudtruth.txt file. And after that save the difference between the values of the ground_truth and each one in a file for further processing, so the result will be that I'll have 3 new different files holding the differences where each file will have 250 lines and each line holds the difference such as the first line of the result file having the difference between the ground_truth and the first file will be like this :79.8,9.42,22.35,10.63
So if anyone could please advise.

A: If I understand correctly, this should be the thing you are after:
groundtruth = dlmread('groundtruth.txt');

file1 = dlmread('file_01.txt');
file2 = dlmread('file_02.txt');
file3 = dlmread('file_03.txt');

dlmwrite('diff_01.txt', file1 - groundtruth);
dlmwrite('diff_02.txt', file2 - groundtruth);
dlmwrite('diff_03.txt', file3 - groundtruth);


text:
Q: Needed help why background image doesn't show up on the div? HELP
I dont know really what to do, I did review everything on the W3 schools website about CSS and HTML but nothing works.
File paths are correct but the background of that div  class = "mainBanner" is not functioning.

Welcome to The Travellers Website

You're all in one solution for perfect travels. Make memories and take          step across
    islands you've never seen before.

A: Presuming the image is in the correct location, you are likely receiving issues as you haven't set a height/width of the image itself. You can do this by using background-size

 * {
    background-color: black;
    margin: 0;
    padding: 0;
    }

    .mainBanner {
    background-image: url(https://i.imgur.com/7a4DOBA.jpg);
    background-size:100% 100%;
    color: #ffffff;
    text-align: center;
    height: 700px;
    }

Welcome to The Travellers Website

You're all in one solution for perfect travels. Make memories and take          step across
    islands you've never seen before.

Is the background image covered by the * selector when the bg color is applied? This imgae from the .mainBanner class doesnt load even the file is correct

As .mainBanner is more specific than *, css specified under the .mainBanner will take precedence.

A: background: url(/images/background.jpg) center no-repeat ;


text:
Q: How to distinguish field that requires null=True when blank=True is set in Django models? Some model fields such as DateTimeField require null=True option when blank=True option is set.
I'd like to know which fields require that (maybe dependent on backend DBMS), and there is any way to do this automatically.

A: null=True is used to tell that in DB value can be NULL
blank=True is only for django , so django doesn't raise error if field is blank e.g. in admin interface
so blank=True has nothing to do with DB
NULL requirement will vary from DB to DB, and it is upto you to decide if you want some column NULL or not

A: This post should help to understand the difference on blank and null in Django


text:
Q: Extracting ArcGIS REST Server from Webmap URL I would like to view certain Webmap information in my desktop GIS software, and I'm looking for a way to extract a REST server (or, in future situations, WMS/WFS/WCS URLs) from a webmap website.
I reviewed these two posts:

*

*Find out ESRI REST URL for web map which is hiding it

*Adding ArcGIS webappviewer to QGIS?
It's clear that you need to inspect the website/use developer tools to find the feature service URL from the Network Tab... and this is where I run into problems. For example, I'm trying to get the REST URL for this website https://tpwd.maps.arcgis.com/apps/webappviewer/index.html?id=f5e8debeaa994abe888d86a7112649ff. But when I analyze the network tab, I can't find the REST server URL.
How do I find this URL using inspect element?
See picture below:

A: The first thing to do is get the application's configuration. Do this by searching the Network tab in the browser's Developer Tools.
If you filter on f5e for instance (which is part of the ID in your URL), you will find a request to the Web Mapping Application: https://tpwd.maps.arcgis.com/sharing/rest/content/items/f5e8debeaa994abe888d86a7112649ff/data?f=json
The response is a JSON file which has a map attribute that in turn has an ItemID of ef0d5fe1a5f841ffb432445b1913cb55:

Now, search the Network tab for that ID. You will find two items, you need this one: https://tpwd.maps.arcgis.com/sharing/rest/content/items/ef0d5fe1a5f841ffb432445b1913cb55/data?f=json
This is also a JSON file, of the Web Map this time, containing all used layers and basemaps.


text:
Q: Why wont this code take the database schema using flyway and migrate it to docker container database? I have the following code to take an existing schema "config_data" and apply it to a docker container database "db":
here is my code, it all happens inside the docker-compose.yaml file:
  flyway:
    image: flyway/flyway
    network_mode: bridge
    restart: always
    command: -url=jdbc:mysql://localhost:3311/db -schemas=config_data -user=root -password=P@ssw0rd -connectRetries=60 migrate

    volumes:
      - ./flyway:/flyway/sql
    depends_on:
      - db
  db:
    image: mysql
    network_mode: bridge
    restart: always
    environment:
      - MYSQL_ROOT_PASSWORD=P@ssw0rd
    command: --character-set-server=utf8mb4 --collation-server=utf8mb4_unicode_ci
    ports:
      - 3311:3306

My understanding is that flyway can copy the schema of one db "config_data" and apply that to a docker container db.
When I run docker-compose up I log into mysql workbench with those credentials, the problem is, it's a generic db with none of the tables/schema I need to have.
What is causing this and how can I fix it?
Thanks


text:
Q: Cannot store the answer to memory in MIPS I'm trying to write a function in MIPS that would take in a string and return the number of character inside the string. This is what I have so far
# Program to calculate string length of any given string

            .data
mystring:   .asciiz "Hello, World!"
answer:     .word 0

            .text
            .globl main
main:       la      $a0, mystring   # Load base adress of the string into function argument

            jal     strlen          # jump to strlen and save position to $ra

            sw      $vo, answer     # Store the answer to memory

            li      $v0, 10         #exit
            syscall

strlen:     li      $v0, 0          # Initialize counter = 0

stringLoop: lb      $t0, 0($a0)     # Load first word of the string

            beq     $t0, $zero, end # if $t0 == '\0' then exit the loop

            addi    $a0, $a0, 1     # Increment the address (go to the next character)

            addi    $v0, $v0, 1     # Increment the counter

            b       stringLoop

end:        jr      $ra             # Return to main program

Everytime I try to run it with QtSpim, it gives me a syntax error at the line "sw      $vo, answer". Could someone please tell me what is wrong with my program? Thanks

A: Syntax errors are often caused by typos as in your case. You accidentally wrote vo instead of v0.


text:
Q: Spring MVC Rest Application on Weblogic throwing java.lang.StackOverflowError my company is shifting from tomcat to WebLogic 12.1.3, So I am trying to create a sample Spring MVC rest application on WebLogic.
I clone a sample project from here https://github.com/hasanozgan/spring-mvc-akka-maven-weblogic-demo which is working fine, then modified few files accordingly.
POM
changed spring version to 4.2.1.RELEASE
add Jackson dependency
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.hasanozgan.common</groupId>
    <artifactId>akka-demo</artifactId>
    <packaging>war</packaging>
    <version>1.0-SNAPSHOT</version>
    <name>Spring Akka Maven Webapp</name>
    <url>http://maven.apache.org</url>
    <properties>
        <spring.version>4.2.1.RELEASE</spring.version>
        <akka.version>2.3.0</akka.version>
        <scala.version>2.10</scala.version>
    </properties>
    <dependencies>
        <!-- Spring 3 dependencies -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.9.7</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <!-- AKKA Version -->
        <dependency>
            <groupId>com.typesafe.akka</groupId>
            <artifactId>akka-actor_${scala.version}</artifactId>
            <version>${akka.version}</version>
        </dependency>
        <dependency>
            <groupId>cglib</groupId>
            <artifactId>cglib</artifactId>
            <version>2.2.2</version>
        </dependency>
        <dependency>
            <groupId>javax.inject</groupId>
            <artifactId>javax.inject</artifactId>
            <version>1</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>servlet-api</artifactId>
            <version>2.5</version>
            <scope>provided</scope>
        </dependency>
    </dependencies>
    <repositories>
        <repository>
            <id>com.typesafe.repo-releases</id>
            <name>Typesafe Maven Releases Repository</name>
            <url>http://repo.typesafe.com/typesafe/releases</url>
            <releases>
                <enabled>true</enabled>
            </releases>
            <snapshots>
                <enabled>true</enabled>
            </snapshots>
        </repository>
    </repositories>
    <build>
        <finalName>akka-demo</finalName>
        <plugins>
            <plugin>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>1.6</source>
                    <target>1.6</target>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

mvc-dispatcher-servlet.xml
commented InternalResourceViewResolver because it's a rest application.
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-3.0.xsd">
    <context:component-scan base-package="com.hasanozgan.demo" />
    <!-- <bean  class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix">
            <value>/WEB-INF/pages/</value>
        </property>
        <property name="suffix">
            <value>.jsp</value>
        </property>
    </bean> -->
</beans>

a sample data pojo class with 3 variables.
    package com.hasanozgan.demo.controllers;
import java.util.Date;
public class Data {
    int rollNo;
    String name;
    Date d;
    public int getRollNo() {
        return rollNo;
    }
    public void setRollNo(int rollNo) {
        this.rollNo = rollNo;
    }
    public Date getD() {
        return d;
    }
    public void setD(Date d) {
        this.d = d;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
}

Controller
replaced @Controller with @RestController and add pojo class as return type
    package com.hasanozgan.demo.controllers;
import java.util.Date;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.hasanozgan.demo.controllers.Data;
@RestController
@RequestMapping("/")
public class HelloController {
    @RequestMapping(method = RequestMethod.GET)
    public Data home() {
        Data d = new Data();
        d.setName("hello");
        d.setRollNo(1);
        d.setD(new Date());
        return d;
    }
}

Deployment is successful on weblogic but when I am hitting rest url

http://localhost:7001/akka-demo with postman its saying

Root cause of ServletException.
java.lang.StackOverflowError
    at org.springframework.context.event.AbstractApplicationEventMulticaster$ListenerCacheKey.hashCode(AbstractApplicationEventMulticaster.java:312)
    at java.util.concurrent.ConcurrentHashMap.get(ConcurrentHashMap.java:936)
    at org.springframework.context.event.AbstractApplicationEventMulticaster.getApplicationListeners(AbstractApplicationEventMulticaster.java:169)
    at org.springframework.context.event.SimpleApplicationEventMulticaster.multicastEvent(SimpleApplicationEventMulticaster.java:125)
    at org.springframework.context.support.AbstractApplicationContext.publishEvent(AbstractApplicationContext.java:380)
    at org.springframework.context.support.AbstractApplicationContext.publishEvent(AbstractApplicationContext.java:334)
    at org.springframework.web.servlet.FrameworkServlet.publishRequestHandledEvent(FrameworkServlet.java:1073)
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1005)
    at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:861)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:731)

What am I doing wrong?


text:
Q: Why is closing resources important when you have finalize() Alright, so I know that you should always close your streams and other native resources, but I am currently not sure why.
I see one reason for why and that is because of the limited amount of resources available and you want to release them as soon as you are done with them.
But lets assume that your application doesn't use that many resources, then there shouldn't be a need to close the resource right?
Especially since you have the finalize() block that should close all native resources when the GC gets to it.

A: Simple: you always strive to do the right thing.
Building an application on assumptions such as "it doesn't use many resources" is a wrong approach. Instead: you focus on getting your logic right.
You see: the thing with real world application is: when they are helpful, they will be used. And as soon as you have users, you will be dealing with additional requirements. That results in you enhancing and maintaining your code. And as a result of that, any "compromise" that you made earlier on ("it's just a small thing, so who cares") has the potential to make such activities much harder than the ought be.
In other words: you should strive to build applications that are "correct". You don't write sloppy code because it "doesn't matter". Because you very often can not predict if your code doesn't become "important" at some point - and then your sins will come back biting you.
And no, finalize isn't the answer to anything ( see here ). You care about all resources that your code is using, and you carefully make sure that resources have a well defined life cycle.

A: Firstly finalize is never guaranteed to be called by the GC, so you cannot rely on it.
Secondly, in a real world application the amount of resources needed by your application changes, hence you shouldn't rely on assumptions and you should free up as many resources as you can to provide the best possible performance.
In my opinion the key words are performance, availability, scalability.

A: The assumption that "you have the finalize() block that should close all native resources when the GC gets to it" is wrong in the first place. There is no guaranty that every object representing a native resource has such a finalize() method.
Second, a resource isn't necessarily a native resource.
When you have, e.g. a BufferedOutputStream, an ObjectOutputStream, or a ZipOutputStream wrapping a FileOutputStream, the latter likely has a finalize() method to free the underlying native resource (that's implementation dependent), but that doesn't write any pending data of the wrapper stream needed to have correctly written data. Closing the wrapper stream is mandatory to ensure that the written output is complete.
Naively adding a finalize() method to these wrapper stream classes to close them would not work. When the stream object gets collected, it implies that there is no reference to it, in other words there is no directed application→wrapper stream→native stream graph anymore. Since object graphs could be cyclic, there is no guaranty that an expensive search for an order among dead objects would succeed, and that's why the JVM doesn't even try.
Or, as the specification puts it:

The Java programming language imposes no ordering on finalize method calls. Finalizers may be called in any order, or even concurrently.

Therefore, a finalize() method of a wrapper would not be guaranteed to be called before the finalize() method of underlying native stream, thus, the underlying native stream might have been finalized and closed before the wrapper stream making it impossible to write the pending data.
And the rabbit hole goes even deeper. Object instances are maintained by the JVM as needed by the code, but the code can get optimized to use encapsulated data directly. If the wrapper stream class had a finalize() method, you might find out that the wrapper instance can be freed even earlier than expected, as discussed in finalize() called on strongly reachable object in Java 8.
Or, in short, explicit closing is the only way to ensure that it happens exactly at the right point of time.

A: As a Java developer, you have little control over when, or even if, finalizers are invoked. If your resources are in limited supply (database connections, for example), or create additional threads that have to be serviced, or hold locks, or use substantial memory, then you need to exercise control over when they are allocated and freed. It isn't always obvious what the implications are for keeping a resource allocated, and it's always safer to minimize the scope and duration of your resource usage, so far as the logic of the application allows.


text:
Q: How can i set a placeholder when redirecting my url with wildfly standalone handlers? I'm trying to redirect my URL with the following settings in the standalone.xml:
<server name="default-server">
            <http-listener name="default" socket-binding="http" redirect-socket="https" enable-http2="true"/>
            <https-listener name="https" socket-binding="https" security-realm="ApplicationRealm" enable-http2="true"/>
            <host name="default-host" alias="localhost">
                <location name="/en/" handler="en"/>
                <location name="/de/" handler="de"/>
                <location name="/" handler="de"/>
                <filter-ref name="server-header"/>
                <filter-ref name="x-powered-by-header"/>
            </host>
        </server>
        <servlet-container name="default">
            <jsp-config/>
            <websockets/>
        </servlet-container>
        <handlers>
            <file name="en" path="${jboss.home.dir}/standalone/deployments/en"/>
            <file name="de" path="${jboss.home.dir}/standalone/deployments/de"/>
        </handlers>

My handlers point on to the matching angular frontend-projects in the deployments folder of my wildfly-server, where also my EAR-file is deployed.
This works fine except for one case: If i refresh my detail-page, which looks like this: localhost:8080/en/details/1234 i get an error

404 - Page not found
  I already tried <location name="/en/details/1234" handler="en"/> which works, but obviously only for that specific id.

In my understanding this could be solved by adding something like
<location name="/en/details/(.*)" handler="en"/>
My problem is that I can't figure out how to put a placeholder like a regular expression after "details/". Is that even possible? Or is there a better way of handling this redirection/rewriting problem?
I already gave undertow-handlers.conf a shot, but it felt like it never really triggered the rewrite rules I implemented there.