text:
Q: Why is flatlist unable to fit in container - React Native My flatlist is wrapping, but I don't want it to. Is this specific to the data type?
Here is the relavant code if I use flatlist:
<View>
                                <Text style={styles.statLabel}>
                                    Habilidad(es)
                                </Text>
                                <FlatList
                                    data={ this.state.pokemonAbilities }
                                    renderItem={({item}) => <Text style={styles.statData}>{item.node}</Text>
                                    }
                                    keyExtractor={(item) => item.id}
                                />
                            </View>

When I render this code, the "Habilidades" is not under the other two stats as it should be. Instead, it wraps and ends up on the right:
Render with FlatList
When I remove the flatlist and instead use placeholder text, it works:
<View>
                                <Text style={styles.statLabel}>
                                    Habilidad(es)
                                </Text>
                                <Text>
                                    Placeholder
                                </Text>
                            </View>

The above code renders the following:
Code with placeholder
The styles for abilityContainer, statsLabel, and statsData are here:
statLabel: {
    color: 'white',
    fontSize: 20,
},
stateData: {
    marginBottom: 20
},

A: You should add a View of the FlatList, after that you should add the style container like this:
 container: {
    flex: 1
 },
  item: {
    backgroundColor: '#f9c2ff',
    padding: 20,
    marginVertical: 8,
    marginHorizontal: 16,
   }


text:
Q: How to access client's appData folder in node.js I want to be able to find out if the client system has a dropbox folder with a business account and then move a file into that folder. I know from this link that the information is available in AppData\Dropbox\info.json
https://www.dropbox.com/en/help/4584
The challenge I am facing is reading this file.
First I am not able to find any code to get the path of appdata and second there would most likely be security issues.
I want to know if this is even doable. I am very new to node.js and am not able to find much help online.
Thanks,
Arshya

redpajama_set_name: RedPajamaStackExchange


text:
Q: Matplotlib subplot2grid packing with axes labels Any help in getting the subplot2grid and the axes labels to work nicely together will be so much appreciated. As you can see in the picture attached some of the axes labels overlap the surface of the neighbouring subplots.
Attached some code as well in case it helps.
def init_plot(self):

    self.f0 = plt.figure(num = 0, figsize = (12, 8))#, dpi = 100)
    self.f0.suptitle("CFM diffusion", fontsize=12)
    self.ax01 = plt.subplot2grid((2, 3), (0, 0))
    self.ax02 = plt.subplot2grid((2, 3), (0, 1))
    self.ax03 = plt.subplot2grid((2, 3), (1, 0))
    self.ax04 = plt.subplot2grid((2, 3), (1, 1))
    self.ax05 = plt.subplot2grid((2, 3), (0, 2))
    self.ax06 = plt.subplot2grid((2, 3), (1, 2))

    self.ax01.set_ylim((300, 0))
    self.ax02.set_ylim((300,0))
    self.ax03.set_ylim((230, 250))
    self.ax04.set_ylim((0.08, 0.22))
    self.ax02.set_xlim((230, 250))
    self.ax03.set_xlim((self.model_time[0], self.model_time[-1]))
    self.ax04.set_xlim((self.model_time[0], self.model_time[-1]))
    self.ax05.set_ylim((300,0))
    self.ax05.set_xlim((0, 0.125))
    self.ax06.set_xlim((self.model_time[0], self.model_time[-1]))
    self.ax06.set_ylim((0.08, 0.125))

    self.ax01.set_ylabel(r"Depth [m]")
    self.ax01.set_xlabel(r"Density [$\mathrm{kgm}^{-3}$]")
    self.ax02.set_ylabel(r"Depth [m]")
    self.ax02.set_xlabel(r"Temperature [K]")
    self.ax03.set_ylabel(r"Temperature Forcing [K]")
    self.ax03.set_xlabel(r"Model Time [y]")
    self.ax04.set_ylabel(r"Accumulation Forcing [$\mathrm{my}^{-1}$ ice eq.]")
    self.ax04.set_xlabel(r"Model Time [y]")
    self.ax05.set_ylabel(r"Depth [m]")
    self.ax05.set_xlabel(r"Diffusion Length [m]")
    self.ax06.set_ylabel(r"$\sigma'_{18}$ [m]")
    self.ax06.set_xlabel(r"Model Time [y]")

    # self.ax01.set_title('Density profile')
    # self.ax02.set_title('Temp. profile')
    # self.ax03.set_title('Temperature Forcing')
    # self.ax04.set_title('Accum Forcing')
    # self.ax05.set_title('Diffusion Length')
    # self.ax06.set_title('Diffusion Length at CO')

    self.hlp011 = self.ax01.plot(self.rho_hl*1000, self.z_hl, "r--")
    self.p011, = self.ax01.plot(self.rho[0][1:], self.z[0][1:],'b-')
    self.p012, = self.ax02.plot(self.temperature[0][1:], self.z[0][1:], 'k-')
    self.p021, = self.ax03.plot(self.climate[0,0], self.climate[0,2],'k-')
    self.p022, = self.ax04.plot(self.climate[0,0], self.climate[0,1], 'k-')
    print(self.climate[0,1])
    self.p023, = self.ax05.plot(self.iso_sigmaD[0][1:], self.z[0][1:], 'r-')
    self.p024, = self.ax05.plot(self.iso_sigma18[0][1:], self.z[0][1:], 'b-')
    self.iso_sigma18_co = np.array((self.iso_sigma18[0][1:][self.rho[0][1:]>804.3][0],))
    self.p025, = self.ax06.plot(self.climate[0,0], self.iso_sigma18_co[0], 'b-')

    return

Best
Vas

A: Try tight_layout with guide here.
In your code just add this line after creating self.f0:
self.f0.tight_layout()

A: Final answer here:
self.f0.tight_layout() takes care of things with some padding to account for the title on top.
class CfmPlotter():

def __init__(self, fpath = None):

    hl_inst = herron_lang.HL(temp = -40.0+273.15, accu= 0.0917, rho_o=350.)

    self.z_hl, self.rho_hl = hl_inst(np.arange(0,400, 0.01))
    # fpath = "./DO_results/DO_tests_vary_tr_time/cfm_DO_trtime_1500/Goujon_DO_trtime_1500.hdf5"
    self.fpath = fpath
    f = h5py.File(fpath)
    self.fs = os.path.split(fpath)[1]
    print f.keys()
    self.z = f["depth"][:]
    self.rho = f["density"][:]
    self.temperature = f["temperature"][:]
    self.age = f["age"][:]
    self.climate = f["Modelclimate"][:]
    self.iso_sigmaD = f["iso_sigmaD"][:]
    self.iso_sigma18 = f["iso_sigma18"][:]
    self.iso_sigma17 = f["iso_sigma17"][:]
    self.model_time = np.array(([a[0] for a in self.z[:]]))

    f.close()
    return

def init_plot(self):

    self.f0 = plt.figure(num = 0, figsize = (10, 6))#, dpi = 100)
    self.f0.tight_layout(pad = 2.8)
    self.f0.suptitle("CFM diffusion", fontsize=12)
    self.ax01 = plt.subplot2grid((2, 3), (0, 0))
    self.ax02 = plt.subplot2grid((2, 3), (0, 1))
    self.ax03 = plt.subplot2grid((2, 3), (1, 0))
    self.ax04 = plt.subplot2grid((2, 3), (1, 1))
    self.ax05 = plt.subplot2grid((2, 3), (0, 2))
    self.ax06 = plt.subplot2grid((2, 3), (1, 2))

    self.ax01.set_ylim((300, 0))
    self.ax02.set_ylim((300,0))
    self.ax03.set_ylim((230, 250))
    self.ax04.set_ylim((0.08, 0.22))
    self.ax02.set_xlim((230, 250))
    self.ax03.set_xlim((self.model_time[0], self.model_time[-1]))
    self.ax04.set_xlim((self.model_time[0], self.model_time[-1]))
    self.ax05.set_ylim((300,0))
    self.ax05.set_xlim((0, 0.125))
    self.ax06.set_xlim((self.model_time[0], self.model_time[-1]))
    self.ax06.set_ylim((0.08, 0.125))

    self.ax01.set_ylabel(r"Depth [m]")
    self.ax01.set_xlabel(r"Density [$\mathrm{kgm}^{-3}$]")
    self.ax02.set_ylabel(r"Depth [m]")
    self.ax02.set_xlabel(r"Temperature [K]")
    self.ax03.set_ylabel(r"Temperature Forcing [K]")
    self.ax03.set_xlabel(r"Model Time [y]")
    self.ax04.set_ylabel(r"Accumulation Forcing [$\mathrm{my}^{-1}$ ice eq.]")
    self.ax04.set_xlabel(r"Model Time [y]")
    self.ax05.set_ylabel(r"Depth [m]")
    self.ax05.set_xlabel(r"Diffusion Length [m]")
    self.ax06.set_ylabel(r"$\sigma'_{18}$ [m]")
    self.ax06.set_xlabel(r"Model Time [y]")

    # self.ax01.set_title('Density profile')
    # self.ax02.set_title('Temp. profile')
    # self.ax03.set_title('Temperature Forcing')
    # self.ax04.set_title('Accum Forcing')
    # self.ax05.set_title('Diffusion Length')
    # self.ax06.set_title('Diffusion Length at CO')

    self.hlp011 = self.ax01.plot(self.rho_hl*1000, self.z_hl, "r--")
    self.p011, = self.ax01.plot(self.rho[0][1:], self.z[0][1:],'b-')
    self.p012, = self.ax02.plot(self.temperature[0][1:], self.z[0][1:], 'k-')
    self.p021, = self.ax03.plot(self.climate[0,0], self.climate[0,2],'k-')
    self.p022, = self.ax04.plot(self.climate[0,0], self.climate[0,1], 'k-')
    print(self.climate[0,1])
    self.p023, = self.ax05.plot(self.iso_sigmaD[0][1:], self.z[0][1:], 'r-')
    self.p024, = self.ax05.plot(self.iso_sigma18[0][1:], self.z[0][1:], 'b-')
    self.iso_sigma18_co = np.array((self.iso_sigma18[0][1:][self.rho[0][1:]>804.3][0],))
    self.p025, = self.ax06.plot(self.climate[0,0], self.iso_sigma18_co[0], 'b-')

    return


text:
Q: Using thirdparty libraries from dart language How can import and use any third party javascript libraries in dart..?  I want to use snapsvg in my dart application to render svg. But not sure how to add dependencies to add and import it.
I added js: any to my pubspec.yaml and imported packages/browser/interop.js into my html. Where do I place downloaded snapsvg.js and import it to my dart source file to use it.
I am trying to use following javascript code using snapsvg framework from dart.
s = Snap(800, 600);
s.rect(0, 0, 100, 100).attr({
    fill: 'white',
    stroke: 'black'
});

I tried this code from in dart:
  import 'package:js/js.dart' as js;
  void main() {
      var s = js.context.Snap(800, 600);
      s.rect(0, 0, 100, 100);
  }

This works fine in dartium, but when I Run as Javascript after build, I got javascript error "method zm not found in object"
I believe this is not right way and I should use be using callMethod on proxy. So I changed code like this
import 'dart:js' show context, JsObject;
void main() {
     var snap = context['Snap'];
    snap.callMethod('rect', 0,0,100,100);
}

This is not working in Dartium as itself. I would appreciate if someone can provide example of how to  call constructor Snap(800, 600) from dart and also rect and attr methods in my example code.

A: You add them to the HTML file using <script> tags.
You can call JavaScript functions from Dart using dart-js-interop.
There are many examples here on Stackoverflow under this tag - just click on the tag below your question.
When you provide a more concrete example it is easier to help.

A: You can call into JavaScript with the built-in dart:js library. Please try to avoid using /package/ js, which is what you install by adding js: any to your pubspec. The js package is likely to cause the dart2js output to be bloated and we're probably going to deprecate it at some point.
You can reference JavaScript files like you would in any HTML page, via script tags. You don't actually import them into Dart source, you use dart:js to access JavaScript via its top-level context property.


text:
Q: Find coins which sum to target amount with a restricted set Given a sum amount 1.15 Rs. (1 Rs. = 100 Paise), so total 115 paise and given a list of 8 coins with denominations as {1, 2, 5, 10, 20, 25, 50, 100} paise. Find 6 coins which sum to 1.15 Rs. The constraint is that I should not be able to give change from my solution for the amounts given in a restricted set. The restricted set here is {5, 10, 20, 25}.
Appreciate any solutions or pointers.

A: Is this what you are looking for?
import java.util.Arrays;
public class Coining {

public static void getChange(int amount, int[] denomination){
    Arrays.sort(denomination);//sort the array
    for(int coin=denomination.length-1; coin>=0;coin--){
        int coef = amount/denomination[coin];
        amount%=denomination[coin];
        if(coef > 0)
            System.out.format("%d {%d Paise}%n",coef, denomination[coin]);
        if(amount == 0)
            return;
    }
}//

public static void main(String... args){
    //int coins[]={1,2,5,10,20,25,50,100}; THIS IS IRRELEVANT.
    int restricted[]={5,10,20,25};
    int amount = 115;
    getChange(amount,restricted);
}//
}


text:
Q: Haskell using typeclasses inside type signatures Assuming a simple typeclass constrained signature:
f :: (Eq a, Num b) => a -> b
f str = 4

I was wondering why these didn't work
f :: (Eq a) -> (Num b)
f str = 4

f :: Eq -> Num
f str = 4

I know that type classes have the kind * -> Constraint, whereas the type signatures only accept kinds of *.
But my question is why is there this restriction? Why can't typeclasses be used like types? What would be the advantages and disadvantages of allowing the ability to use typeclasses like types?

A: There is (if we neglect unboxed types) only one kind whose types actually have any values: *. All other kinds don't contain types as such, but just "type-level entities". The compiler can use those to determine what to do with the actual types and their values around, but it's never possible to have at runtime a value of a "type" with some kind like * -> Constraint.
That * is the kind for value-types is just a rule of the game. It's a good thing to have, for much the same reason it's a good idea to have a strong static type system which prevents nonsensical conversions at runtime. Wat?? Or, let's take it literally, for the same reason you can't just hop your king over your pawns, no matter how appealing that feature might look in a particular situation you've run into.
If some extension did allow making values from non-*-kinded types, in particular * -> Constraint, we'd need a whole bunch of non-obvious definitions to make it clear how these "class-values" are actually supposed to be used. Likely, it would amount to a record type containing the class' methods as a dictionary. But, how exactly... the specification would be pretty much of a nightmare. And complicating the language itself this way is in no way worth the expenditure, since 1. the standard way of using type classes is just fine for at least 95% of all applications, and 2. when you do need reified type classes, you can quite easily do so with GADTs, ConstraintKinds, or even plain old manually-defined dictionary records. None of that requires distorting the fundamental ideas of how the language treats values, as non-*-types would.

Anyway... let's explore for a moment how this might work. One thing is for sure: it would not allow you to write stuff anything as simple as f str = 4!
Consider
f1 :: forall a, b . Eq a -> Num b

Both Eq a, Num b :: Constraint, so we'd have values of type of kind Constraint. That would basically be a particular dictionary of methods for a given instance. So the implementation of f1 would have to look something like
f1 (EqDict (d_eq :: a -> a -> Bool))
       = NumDict { dict_fromInteger = ??? :: Integer -> b
                 , dict_plus        = ??? :: b -> b -> b
                 , ...
                 , dict_signum      = ??? :: b -> b
                 }

Evidently there is no meaningful way to define all those methods in the result. All you could do with such a "class-function" is to "project" from a stronger class to a weaker one. E.g. you could define
monadApp :: forall m . Monad m -> Applicative m
monadApp (MonadDict {dict_return = d_ret, dict_bind = d_bd})
        = ApplicativeDict { dict_pure = d_ret
                          , dict_app = \fs vs -> d_bd fs (\f -> d_bd vs $ d_ret . f) }

That specific one would be, in fact, somewhat useful, but only because Monad (still, but not for long!) lacks Applicative as a superclass which it should simply have. Normally, there shouldn't be much reason having to explicitly "downgrade" any classes, because superclass-relations (or tuple-ConstraintKinds) do just that automatically.

A: Type variables may appear more than once in a type signature:
f :: Eq a => a -> a -> a -> Bool

Writing the above as
f :: Eq a -> Eq a -> Eq a -> Bool

looks inconvenient. Worse, we might have more than one constraint on a:
g :: (Show a, Eq a) => a -> Bool

How would we write this in the alternative notation?
g :: (Show & Eq) a -> Bool    -- ??

Forgetting the a completely as you suggest in the last example makes signatures
ambiguous: consider
h1 :: (Eq a)       => a -> a -> a -> a -> Bool
h2 :: (Eq a, Eq b) => a -> a -> b -> b -> Bool

These are quite different signatures: you can call h2 1 2 [1] [2] but not h1 1 2 [1] [2]
since the latter requires the four arguments to be of the same type.
After the proposed convention is used, they are reduced to the same signature:
h12 :: Eq -> Eq -> Eq -> Eq -> Bool

Is the call h12 1 2 [1] [2] valid? The above signature is too ambiguous to tell.


text:
Q: Graph query works in console app, fails in azure function I am querying Azure Active Directory using Microsoft.Graph.
My method (shown below) works in a console app i created as a POC.
When i try and use the method in an azure function it returns a HTTP 500 error, but does not give me any information to track down the issue.
The issue occurs on the below line:
IGraphServiceUsersCollectionPage usersPage = await graphClient
    .Users
    .Request()
    .Filter($"Department eq 'Information Technology'")
    .Select("Department,DisplayName,Mail,Id")
    .GetAsync();

The program hangs there for about 5 seconds and then postman shows a 500 internal error.
Appreciate advice on how to troubleshoot or resolve this.
Full Method:
[FunctionName("Function1")]
public static async Task<IActionResult> Run(
    [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
    ILogger log)
{

    string tenantId = "xxxx-xxxx-xxxx-xxxx";
    string clientId = "xxxx-xxxx-xxxx-xxxx";
    string clientSecretValue = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";

    List<User> users = new List<User>();
    var scopes = new[] { "https://graph.microsoft.com/.default" };

    var clientSecretCredential = new ClientSecretCredential(
        tenantId, clientId, clientSecretValue);

    var graphClient = new GraphServiceClient(clientSecretCredential, scopes);

    IGraphServiceUsersCollectionPage usersPage = await graphClient
        .Users
        .Request()
        .Filter($"Department eq 'Information Technology'")
        .Select("Department,DisplayName,Mail,Id")
        .GetAsync();

    users.AddRange(usersPage.CurrentPage);

    return new OkObjectResult(users);
}

** I'm aware hard coding secrets is terrible practice, this was just a proof of concept before investing too much time.
UPDATE:
The function is long running (taking about 3 minutes to run completely). It seems it is running correctly if i get its URL and execute it in a browser, it just does not run correctly in the "Code & Test feature" on the azure portal, functions blade

A: You can run the azure function from Azure protal's function blade and check the error in logs window. Read more details at this Microsoft documentation.
Regarding failure, best guess can be that function itself failing to start due to missing configuration setting like AzureWebJobStorage

A: Could be something related to dll's version. For .netcore 3.1 adding this line under .csproj file fixed the issue.. or upgrade to .Net6.0 (VS2022)
 <PropertyGroup>
        ...
        <_FunctionsSkipCleanOutput>true</_FunctionsSkipCleanOutput>
 </PropertyGroup>


text:
Q: TSLint enforce complete typedef on left side of assignment In all other strongly typed languages I've seen, type definitions precede the value.  I would like to follow the same pattern in TypeScript by forcing a variable definition to have a full type definition preceding the =.
I believe I tried every possible configuration of typedef and no-inferrable-types, but I cannot get the linter to resolve this example as desired:
const f: (x: number) => number = (x) => x * x; // should be valid
const g = (x: number): number => x * x; // should be invalid
const n = 3; // should be valid


text:
Q: How do I create an OpenGL 1.2 context in GLFW 3 I want to create OpenGL 1.2 context, but I get this error: "Failed to open GLFW window".
When I create 3.3 or 4.3 context there is no problem. How can I create 1.2 context?
glfwWindowHint(GLFW_SAMPLES, 4);
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 1);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 2);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);

const GLFWvidmode * mode = glfwGetVideoMode(glfwGetPrimaryMonitor());
WindowWidth = mode->width;
WindowHeight = mode->height;
midWindowWidth = WindowWidth / 2;
midWindowHeight = WindowHeight / 2;

window = glfwCreateWindow(WindowWidth, WindowHeight, "Quadcopter Project", glfwGetPrimaryMonitor(), NULL);
if( window == NULL )
{
    fprintf( stderr, "Failed to open GLFW window. \n" );
    glfwTerminate();
    return -1;
}

A: There are no profiles in OpenGL < 3.2. You cannot create a 1.2 core profile because there is no such thing.
You allso cannot directly force the driver to create a 1.2 context. The afunctionality to request a specific context version was introduced in 3.0. So basically, everything before 3.0 is just some legacy context. You can ask for 1.2, but it might give you a much higher (compatibility profile) context, depending on the platform and the drivers you try this on.


text:
Q: Valorant shows no internet connection I tried to install Valorant but installer shows not able to connect to internet, I have checked the connection and it works fine with others. When I use VPN service it works fine.
So I installed it using VPN (The location of VPN is same as my country)
But how do I use it without VPN.


text:
Q: "Intro to Statistical Learning" Chapter 5 - Resampling p.191 Can someone help with the usage of this line of code:
library(ISLR)
set.seed(1)
train=sample(392,196)
lm.fit=lm(mpg~horsepower,data=Auto,subset=train)
attach(Auto)
mean((mpg-predict(lm.fit,Auto))[-train]^2)

I'm looking for help on last line of code.  Can someone explain what it is doing?
(specifically the syntax "mpg-predict.." and usage of the "-")
For reference this comes from:
"An Introduction to Statistical Learning: with Applications in R".  Chapter 5 - Re-sampling. (p.191)

A:
I think you are referring to this page.
There are two - here.
The first one in mpg-predict is just the ordinary minus sign. predict is the function for model prediction. Read ?predict and ?predict.lm for more. The reason that you can take subtraction between mpg and prediction result, is that you have attach the dataset. Alternatively, use Auto$mpg - predict(lm.fit, Auto).
The second one with -train is for subsetting. Here is a simple example:
x <- 1:5
x[-(2:3)]  ## drop element 2 to 3


text:
Q: Specs for a portable server My question: I would like to buy or build a small, portable server to serve a web application to a very small number of users (as in a dozen or less), as well as some file server functions. Cloud based solutions are out because I won't have internet access at my location, so I need to carry this box with me to the location. What kind of specs do I need for this?
The background. Every year, I help out with a convention for a youth group. There are competitions of various kinds: the kids take tests, they compete in athletic competitions, they make art and submit it for judging, the list goes on. My part in this is I compile the scores in a database and process them to determine the winners. This takes place at a youth camp, and I set up in one of the buildings at the edges of the facility, and other convention helpers bring me the results to process.
Right now, I'm doing this in an Access database running on a decently powered Lenovo laptop. This is fine as far as it goes, but it limits the score entry and processing to only those who have Access on their machines. That means we end up having one, maybe two extra machines if we're lucky, for people to enter contest results. I have been thinking recently that it would be nice move away from that to something that would run in a browser. People submitting scores could use any laptop that was handy or we could potentially just hand them a tablet to use. It could greatly streamline our process.

A: You dont need a "server class" machine to do this.  In reality, any old laptop will support serving a simple web application and will be able to handle a dozen concurrent users with ease.  You didnt go into any detail about your file sharing needs.  However, even an old laptop can serve files under a light load, which is what I am assuming.  As a laptop, it is inherently portable, which is what you wanted.


text:
Q: JavaFX log4j in a textarea with a different thread I'm trying to redirect log4j output to a textarea but this one get filled at the end of the action since I'm using Platform.runLater
Is there any way I can do it with a different thread ?
AppFX.java
public class AppFX extends Application {

public static void main(String[] args) {
    ConfHandler.initConf();
    launch(args);
}

@Override
public void start(Stage primaryStage)throws IOException {
    primaryStage.getIcons().add(new Image("file:src/main/resources/images/frameIcon.png"));
    FXMLLoader loader = new FXMLLoader();
    String currentPath = System.getProperty("user.dir");
    loader.setLocation(new URL("file:\\"+currentPath+"\\src\\main\\resources\\scenes\\TestsFrame.fxml"));
    Parent content = loader.load();
    primaryStage.setTitle("IGED Tests");
    Scene scene = new Scene(content);
    primaryStage.setScene(scene);
    primaryStage.show();
    TextAreaAppender.setTextArea(((EaaSCleanerController)loader.getController()).getLogTextArea());
}}

TextAreaAppender.java
public class TextAreaAppender extends WriterAppender {
private static volatile TextArea textArea = null;

public static void setTextArea(final TextArea textArea) {
    TextAreaAppender.textArea = textArea;
}

@Override
public void append(final LoggingEvent loggingEvent) {
    final String message = this.layout.format(loggingEvent);
    try {
        Platform.runLater(new Runnable() {
            @Override
            public void run() {
                try {
                    if (textArea != null) {
                        if (textArea.getText().length() == 0) {
                            textArea.setText(message);
                        } else {
                            textArea.selectEnd();
                            textArea.insertText(textArea.getText().length(), message);
                        }
                    }
                } catch (final Throwable t) {
                    System.out.println("Unable to append log to textarea:" + t.getMessage());
                }
            }
        });
    } catch (final IllegalStateException e) {
    }
}}

log4j.properties
# Append the logs to the GUI
log4j.appender.gui=com.bp.nest.testauto.gui.TextAreaAppender
log4j.appender.gui.layout=org.apache.log4j.PatternLayout
log4j.appender.gui.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p - %m%n

A: You should put your actions on a separate thread. Then the logging can happen in parallel to your actions. You should never block the GUI-thread.


text:
Q: passing from an input data as an array of images to the api I am trying to pass from an input multiply images to the api as the following:
<el-form-item label="images" prop="images">
  <el-input name="files" type="file" multiple="multiple" v-model="property.images" v-on:input="changed"/>
</el-form-item>

and then passing to the data as:
  data() {
    return {
      property: { title: '', description: '', price: 0, images []},

then passing to api:
  createProperty() {
      WebAppAPI.CreateProperty(this.property).then(response => {

but is only passing one string url, even though I add several images.
Any idea what else do I need to do to pass an array instead of a string?

A: You can refer to this demo fidddle.
https://jsfiddle.net/RiddhiParekh/s8ot36kh/
 <el-upload multiple="multiple" class="upload-demo" action="https://jsonplaceholder.typicode.com/posts/" :on-change="handleChange" :file-list="fileList3">
  <el-button size="small" type="primary">Click to upload</el-button>

jpg/png files with a size less than 500kb

</el-upload>


text:
Q: jQuery Slideshow that supports a table format? I have a client who has a website using CommerceSpace by Network Solutions and would like to have an image fader on the front page. The only issue I run into is I cannot seem to get it to work right because the formatting is in a table. That can't be changed because that's the way this software lays everything out. Does anybody have an idea? I would like to use the jQuery Cycle plugin, but I cannot get it to work right. Help?
It was working with scriptaculous before, but we didn't decide to use that due to jQuery working better for us, and this is what worked before.
var e2; var f2; var g2;
activeImage = 2; paused=0;

if (document.getElementsByClassName('specials')[0] && document.getElementById('ctl00_pageContent_ctl00_productList')) {
trs = document.getElementById('ctl00_pageContent_ctl00_productList').getElementsByTagName('tr');
featcount = 0; colcount = 1;
for (i=0;i<trs.length;i++) {
    if (trs[i].className == "nojs") { continue; }
    featcount++; trs[i].id="featimg"+featcount;
    tds = trs[i].getElementsByTagName('td'); tdnum = 0;
    timeout = "new Effect.Parallel([";

    for (j=0;j<tds.length;j++) {
        if (tds[j].className == "nojs") { continue; }
        tds[j].id=trs[i].id+"td"+tdnum;
        if (tds[j].getElementsByTagName('div')[0]) {
            tds[j].getElementsByTagName('div')[0].id = tds[j].id+"div";
            if (featcount != activeImage) {
                tds[j].style.display='none';
                new Effect.Opacity(tds[j].id+"div", {from: 1, to:0, duration: 0});
            }
        }
        tdnum++;
    }
}
function changeimg(direction,paused) {
    clearTimeout(e2);clearTimeout(f2);clearTimeout(g2);
    for3 = ""; for1 = "";
    oldImage = activeImage;
    if (direction=='previous'){activeImage = (activeImage == 1) ? featcount : activeImage-1;}
    else { activeImage = (activeImage >= featcount) ? 1 : activeImage+1;}

    timeout = "new Effect.Parallel([";
    for (i=0;i<colcount;i++) { timeout+="new Effect.Opacity('featimg"+oldImage+"td"+i+"div', {from: 1, to:0, duration: .5})"; if ((i+1)<colcount) { timeout+=","; }
    }
    e2 = setTimeout(timeout+"], {duration: 0, sync: true})",10);

    timeout = "new Effect.Parallel([";
    for (i=0;i<colcount;i++) { timeout+="new Effect.Fade('featimg"+oldImage+"td"+i+"', {duration: 0}),";}
    for (i=0;i<colcount;i++) { timeout+="new Effect.Appear('featimg"+activeImage+"td"+i+"', {duration: 0})"; if ((i+1)<colcount) { timeout+=","; }
    }
    f2 = setTimeout(timeout+"], {duration: 0, sync: true})",600);

    timeout = "new Effect.Parallel([";
    for (i=0;i<colcount;i++) { timeout+="new Effect.Opacity('featimg"+activeImage+"td"+i+"div', {from: 0, to:1, duration: 1})"; if ((i+1)<colcount) { timeout+=","; }
    }
    g2 = setTimeout(timeout+"], {duration: 0, sync: true})",700);

    if (direction=='auto' && paused==0) {t=setTimeout("changeimg('auto',"+paused+")",10000);}
    else {(pause(0))};
}
var t=setTimeout("changeimg('auto',0)",7000);

}
This is the general format of the table.

  Large Ancient    Egyptian New Kingdom Clear Glass Bead 1500 BC.

$28.00

<input type="image" name="ctl00$pageContent$ctl00$productList$ctl00$imbAdd" id="ctl00_pageContent_ctl00_productList_ctl00_imbAdd" src="/themes/barclay-1-2-1/images/buttons/cart_btn_add.gif" onclick="javascript:WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions("ctl00$pageContent$ctl00$productList$ctl00$imbAdd", "", true, "productList1739", "", false, false))" style="border-width:0px;" />

  Large Ancient Egyptian New Kingdom Clear Glass Bead 1500 BC.

$28.00

<input type="image" name="ctl00$pageContent$ctl00$productList$ctl01$imbAdd" id="ctl00_pageContent_ctl00_productList_ctl01_imbAdd" src="/themes/barclay-1-2-1/images/buttons/cart_btn_add.gif" onclick="javascript:WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions("ctl00$pageContent$ctl00$productList$ctl01$imbAdd", "", true, "productList1736", "", false, false))" style="border-width:0px;" />

 ANCIENT        EGYPTIAN    NEW   KINGDOM   MAGICAL GLASS   BEAD     1500 BC

$24.00

<input type="image" name="ctl00$pageContent$ctl00$productList$ctl02$imbAdd" id="ctl00_pageContent_ctl00_productList_ctl02_imbAdd" src="/themes/barclay-1-2-1/images/buttons/cart_btn_add.gif" onclick="javascript:WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions("ctl00$pageContent$ctl00$productList$ctl02$imbAdd", "", true, "productList1720", "", false, false))" style="border-width:0px;" />

  RARE   ASHANTI  BRACELET C1880

$120.00

<input type="image" name="ctl00$pageContent$ctl00$productList$ctl03$imbAdd" id="ctl00_pageContent_ctl00_productList_ctl03_imbAdd" src="/themes/barclay-1-2-1/images/buttons/cart_btn_add.gif" onclick="javascript:WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions("ctl00$pageContent$ctl00$productList$ctl03$imbAdd", "", true, "productList1714", "", false, false))" style="border-width:0px;" />

    ANCIENT    EGYPTIAN    NEW KINGDOM   MAGICAL GLASS   BEAD   1500 BC

$24.00

<input type="image" name="ctl00$pageContent$ctl00$productList$ctl04$imbAdd" id="ctl00_pageContent_ctl00_productList_ctl04_imbAdd" src="/themes/barclay-1-2-1/images/buttons/cart_btn_add.gif" onclick="javascript:WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions("ctl00$pageContent$ctl00$productList$ctl04$imbAdd", "", true, "productList1697", "", false, false))" style="border-width:0px;" />

A: Have javascript write out a div with your images.
document.write('
');
$('.product-list-img').each( function() {
    document.write('')
});
document.write('
')

window.onload= function() {
  $('.slideshow1').cycle({
        fx:       'fade',
        speed:     1500,
        timeout:   4000,
        next:      'slideshow1'
    });
};


text:
Q: Edge theory of FQHE - Unable to produce Green's function from anticommutation relations and equation of motion? I'm studying the edge theory of the fractional quantum Hall effect (FQHE) and I've stumbled on a peculiar contradiction concerning the bosonization procedure which I am unable to resolve. Help!
In particular, consider the first few pages of X.G. Wen's paper "Theory of the edge states in fractional quantum Hall effects". Here, Wen defines a fermionic field $\Psi(x,t)$ in (1+1) dimensions in terms of a bosonic field $\phi(x,t)$ as
$$ \Psi(x,t) \propto e^{i\frac{1}{\nu}\phi(x,t)} .$$
The number $\nu$ is the filling fraction of the FQHE, which we shall set to $\nu=1/3$ for simplicity. The bosonic field fulfills the somewhat strange commutation relations
$$ [\phi(x,y),\phi(y,t)] = i\pi\nu\,\text{sgn}(x-y) $$
which are necessary to make $\Psi(x,t)$ anticommute like a proper fermion
$$ \lbrace \Psi(x,t), \Psi^\dagger(y,t) \rbrace = \delta(x-y) .$$
Moreover, the bosonic field satisfies the equation of motion
$$ (\partial_t-v\partial_x) \phi(x,t) = 0 .$$
Some operator algebra shows that $\Psi(x,t)$ is also a solution to this equation of motion. However, it appears to me that these two requirements, anticommutation and the equation of motion, already fix the Green's function of the fermion!
However, Wen goes on to note that these fermions have the Green's function (equation (2.12) in the paper)
$$ G(x,t) = \langle T(\Psi^\dagger(x,t) \Psi(0)) \rangle = \exp[\langle\frac1{\nu^2}\phi(x,t)\phi(0)\rangle] \propto \frac{1}{(x-vt)^{1/\nu}} .$$
I do not understand how this can be. After all, from the anticommutation relations and the equation of motion, we can calculate the Green's function to be
$$ G(x,t) \propto \frac{1}{x-vt} .$$
To do this, define Fourier modes $\Psi_k, \Psi^\dagger_k$, obtain the usual anticommutation relations for these, solve the equation of motion, and transform back into real space. The result will be as noted, and the exponent $1/\nu$ will be missing.

Where did the exponent $1/\nu$ go? What's wrong with calculating the Green's function from the anticommutation relations and the equation of motion?

Maybe there's something going on inside the $\delta(x-y)$ part of the anticommutation relations? If so, what exactly? Or maybe something about the ground state? Or something about the bosonization procedure as a whole?

A: I understand that you want to compute the fermion propagator in the
operator formalism (in contrast to the path integral formalism where the
same result can be obtained). Then following José's remark, the
fermionization formula is correct, i.e., gives the canonical
anti-commutation relations iff it is normal ordered:
$\psi(z) = :\exp(i \frac{1}{\nu}\phi(z)): = \exp(i \frac{1}{\nu}\phi_+(z)) \exp(i \frac{1}{\nu}\phi_-(z))  $
where $\phi_+(z)$ ($\phi_-(z)$ ) contains only the  dependence the
creation (anihilation) field components.
The fermion propagator formula given in the question is a consequence of the product formula of two normally ordered exponentials:
$:\exp(ia\phi(z_1))::\exp(ib\phi(z_2)): =:\exp(ia\phi(z_1)+ib\phi(z_2)):exp(-ab\langle \phi(z_1) \phi(z_2)\rangle)$.
This formula can be easily verified independently for each mode using the Baker–Campbell–Hausdorff formula
Now, the computation is with respect to the boson vacuum and this is the
reason that the fermion propagator has the power dependence.

A: Here, I would like to make some additional remarks.
1) In eq (2.11) of the referred paper,  the correlation of the
boson field is given $\langle\phi(x,t)\phi(0)\rangle =-\nu \ln(x-vt)$.
This allows us to calculate
$G(x,t) = \langle T(\Psi^\dagger(x,t) \Psi(0)) \rangle = \exp[\langle\frac1{\nu^2}\phi(x,t)\phi(0)\rangle] \propto \frac{1}{(x-vt)^{1/\nu}}$.
2) It is not correct to write
$\lbrace \Psi(x,t), \Psi^\dagger(y,t) \rbrace = \delta(x-y)$, since here
$\Psi(x,t)$ is not the bare electron operator.
$\Psi(x,t) = exp(i\phi(x,t)/\nu)$ is only the projection of the
bare electron operator into the low energy subspace. So we have
$ \Psi(x,t) \Psi^\dagger(y,t) = (-)^{1/\nu}\Psi^\dagger(y,t)   \Psi(x,t)
=-\Psi^\dagger(y,t)  \Psi(x,t)$ when $1/\nu =$ odd integer.
But $\lbrace \Psi(x,t), \Psi^\dagger(y,t) \rbrace = \delta(x-y)$ is not correct.


text:
Q: Get ACAccount Facebook user full name is null i'm trying to get the user full name of the Facebook account, the app already have the permissione in the Facebook iPhone setting, some day ago this code works, but know doesn't, i can't understand why, this is the code:
ACAccountStore *accountStore = [[ACAccountStore alloc] init];

__block ACAccount *facebookAccount;

ACAccountType *facebookTypeAccount = [accountStore accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierFacebook];

NSDictionary *options = @{ACFacebookAppIdKey:@"mycode",ACFacebookPermissionsKey: @[@"email"]};

[accountStore requestAccessToAccountsWithType:facebookTypeAccount
                                      options:options
                                   completion:^(BOOL granted, NSError *error) {
                                       if(granted){
                                           NSArray *accounts = [accountStore accountsWithAccountType:facebookTypeAccount];
                                           facebookAccount = [accounts lastObject];
                                           NSLog(@"name: %@",[facebookAccount userFullName]);
                                           dispatch_async(dispatch_get_main_queue(), ^{
                                               [self.fb_name setText:[facebookAccount userFullName]];
                                           });

                                       }
                                   }];

this: NSLog(@"name: %@",[facebookAccount userFullName]); is null

A: I believe userFullName is only available since iOS 7. Maybe you tested on iOS 7 and now you are experiencing the issue when you target iOS 6. See iOS: user's full name for an ACAccountTypeIdentifierFacebook for the iOS 6 fallback.


text:
Q: Does Android certificate expired date affect enterprise android app? I have deployed enterprise android application through OTA.
It is signed by the expired Android certificate(keystone).
If it is signed by the expired certificate, is it not performed on user devices?
Is Android certificate expired date only checked by Google Play when i publish it through Google Play?
Doesn't Android OS check the certificate expired date when i install it on Android device?

A: I'm not sure what Android certificate you meant.
But if you mean certificate which used while generate signed apk, it won't affect any functionality with already installed app.


text:
Q: Return value of function variable if function active, else return 0 for variable if function not called, but other function with same variable called I want to be able to return the value assigned to a variable assigned to an active function, but if that function is not active, I want to be able to return 0 for the same variable, but assigned to a different function. The code block below is what I want to do this with:
def draw(x):
    if not hasattr(draw, 'counter'):
         draw.counter = 0
    draw.counter += 1
    global drawing
    q.put(x)
    process = False
    drawingLock.acquire()
    if not drawing:
        process = True
        drawing = True
    drawingLock.release()
    if process:
        if not q.empty():
            x()
        drawingLock.acquire()
        drawing = False
        drawingLock.release()
    print('`draw` has been called {} times'.format(draw.counter))
    h = draw.counter
    def walk():
        if not hasattr(walk, "counter"):
            walk.counter = 0
        walk.counter += 1
        penup()
        forward(letter_width + space_width)
        pendown()
        print('`walk` has been called {} times'.format(walk.counter))
        global w
        w = 0 if walk is False else walk.counter
    onkey(walk, "space")
    def draw_newline():
        # This funtion will pick up the turtle and move it to a second line below HELLO
        penup()
        goto(xcor() -(((space_width + letter_width)*(draw.counter)) + (space_width * w)) , ycor() -(letter_height + letter_height/2))
        pendown()
    def handle_enter():
        draw.counter = 0
        walk.counter = 0
    def Carriage_functions():
        draw_newline()
        handle_enter()
    onkey(Carriage_functions, "Return")

As you can see, this walk() function:
    def walk():
        if not hasattr(walk, "counter"):
            walk.counter = 0
        walk.counter += 1
        penup()
        forward(letter_width + space_width)
        pendown()
        print('`walk` has been called {} times'.format(walk.counter))
        global w
        w = 0 if walk is False else walk.counter
    onkey(walk, "space")

draws a space in the turtle graphics window every time SPACE is pressed on the keyboard, and it also counts how many times it has been executed through:
if not hasattr(walk, "counter"):
        walk.counter = 0
    walk.counter += 1

Then, I assign this value to the globally declared variable 'w' to be used in the next function (draw_newline()) like this:
global w
w = 0 if walk is False else walk.counter

The issue is that whenever I assign the w to the draw newline()'s goto() function, like so:
goto(xcor() -(((space_width + letter_width)*(draw.counter)) + (space_width * w)) , ycor() -(letter_height + letter_height/2))

I get this error:
in draw_newline
goto(xcor() -(((space_width + letter_width)*(draw.counter)) + (space_width * w)) , ycor() -(letter_height + letter_height/2))
NameError: name 'w' is not defined

even though w is globally defined! What am I doing wrong here?
EDIT: I have even tried this:
def walk():
    if not hasattr(walk, "counter"):
        walk.counter = 0
    global counter
    walk.counter += 1
    penup()
    forward(letter_width + space_width)
    pendown()
    print('`walk` has been called {} times'.format(walk.counter))
    global h
    h = walk.counter
if walk == False:
    w = 0
elif walk == True:
    w = h

and still no luck. I am just getting this error:
NameError: free variable 'w' referenced before assignment in enclosing scope

Even when I put the same code block after the draw_newline() function, I still get the same error.


text:
Q: Struggling with foreach I'm rather new and, well, awful at this whole scripting thing: so any help would be appreciated.
Basically I am trying to create a PowerShell script that installs an undefined number of printers on an undefined number of computers. The computer names and printer names will come from local text files.
This is what I have so far:
$credentials = Get-Credential
$printerlist = Get-Content c:\setup\printers.txt
get-content c:\setup\names.txt | foreach-object {foreach($printer in $printerlist){rundll32 printui.dll PrintUIEntry /ge /c $_ /n  $printer}}

EDIT: I am getting the error, unable to enumerate per machine printer connections operation could not be completed (error 0x0000007b) I have tried modifying the script anyway i can come up with, which is probably fewer ways than it should be.

A: I don't think you have an issue with your foreach loop here.
I think it's just the usage of rundll32 printui.dll PrintUIEntry
Install printer:
rundll32 printui.dll,PrintUIEntry /in /c "\\COMPUTER_NAME" /n "\\PRINT_SERVER_NAME\PRINTER_NAME"

Sets default printer:
rundll32 printui.dll,PrintUIEntry /y /c "\\COMPUTER_NAME" /n "\\PRINT_SERVER_NAME\PRINTER_NAME"

Try installing with the /in individually for one computer from powershell console without your script to see if you still get the same error, could be a permission but I don't think so.


text:
Q: is there any cell number limitation when GridView.AutoGenerateColumns false? I have a problem when I am generating a GridView column manually.
my program stops at this line:
e.Row.Cells[42].Text = "x";

and throws the below error:

"Specified argument was out of the range of valid values. Parameter
  name: index    Description: An unhandled exception occurred during the
  execution of the current web request. Please review the stack trace
  for more information about the error and where it originated in the
  code.
Exception Details: System.ArgumentOutOfRangeException: Specified
  argument was out of the range of valid values. Parameter name: index"

My HTML code is:

    <asp:GridView EnableSortingAndPagingCallbacks="true" ID="StationGridView" runat="server"
        GridLines="None" CellSpacing="1" AlternatingRowStyle-Wrap="false"
        Font-Names="tahoma" Font-Size="14px" CellPadding="3"
        AllowSorting="True"
        ViewStateMode="Disabled" EnableViewState="false"
        AllowPaging="True" PageSize="15" dir="rtl" Width="100%"
        OnRowDataBound="StationGridView_RowDataBound">

        <HeaderStyle BackColor="#d7effd" Font-Bold="true" ForeColor="Navy" Font-Size="12px" Font-Underline="false" />

        <FooterStyle BackColor="#d7effd" Font-Bold="true" ForeColor="Navy"
            VerticalAlign="Middle" HorizontalAlign="Center" Font-Size="16px" />

        <AlternatingRowStyle BackColor="#c0c0c0" ForeColor="#000000" Height="25px" />

    </asp:GridView>

My source code is :
protected void Page_Load(object sender, EventArgs e)
{

    if (Page.IsPostBack == false)
    {
        Initialize();
    }

    //Load data

        PortalDataSetTableAdapters.VW_StationTableAdapter stationsAdapter = new PortalDataSetTableAdapters.VW_StationTableAdapter();
        PortalDataSet.VW_StationDataTable Station;
        Station = stationsAdapter.GetData();

        StationGridView.DataSource = Station;
        StationGridView.AutoGenerateColumns = true;

         StationGridView.DataBind();
    }
}

protected void StationGridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
        if (e.Row.RowType == DataControlRowType.Header)
        {
            e.Row.Cells[0].Text = "a";
            e.Row.Cells[1].Text = "b";
            e.Row.Cells[2].Text = "c";
            .
            .
            e.Row.Cells[42].Text = "x";
            e.Row.Cells[43].Text = "x";
            e.Row.Cells[44].Text = "x";
         }
}

When the number of cells are generating goes more than 42 (exactly on the line e.Row.Cells[42].Text = "x";), the error happens. Why does this occur?

A: If you don't have billion of rows, columns count is not the problem here
(source: http://forums.asp.net/post/3380845.aspx )
You certainly have only 42 columns, and when you're trying to reach the 43th, you get the ArugmentOutOfRangeException.


text:
Q: What's the Name of this Natural Disaster Movie? It's possibly a Sci-Fi action Film too The Natural Disaster Action Movie I'm asking about is about a meteor that fell from space to earth. A man and either his daughter or wife stumble upon the meteor and inside they find a plant-like thing (similar to the one in the 2001 comedy movie, Evolution). The man pulls the giant meteor with his truck and takes it to their home. They discover that that plant-like thing grows roots and cures diseases, bruises, etc. It also gives warnings to them that something is going to destroy earth. At the end, the man and the woman survive along with the plant-like thing inside a cement mixer or cement truck. The truck looks like the one from the 2009 movie 2012: SuperNova.
That's all I know because my uncle told me about this movie, but doesn't know the name of it. All I remember is that he said it's around the year 2000 to now, But it's not a comedy movie, it's like a suspenseful and action movie.

A: Your description matches the movie Terminus (2015): extraterrestrial object with healing powers, worldwide apocalypse, shelter made from old machinery.
Trailer (2 minutes; contains brief profanity):

Here's the cement mixer:


text:
Q: How to check for existence of subtree in XML document I need to check if an XML document contains a given XML DOM subtree. I only need to ensure that all the elements and attributes from this subtree are present in the document. However, there can be more elements or attributes in the subtree of the document that matches the given subtree for comparison. And I want them to be skipped from the comparison.
So far I have implemented my own solution which finds a subtree represented by Node class in the given XML document. This Node class contains only the attributes necessary for comparison - element name, text content, list of child nodes and map of attributes. I have implemented my own class and not used org.w3c.dom.Node because it is just too big containing many unnecessary attributes for my test scenario. The subtree represented by the root Node element is iterated one element after another and each its subtree is searched in the given XML document using XPath until the whole tree is checked or any subtree is not found.
This solution works well only when I need to check if the subtree is present there or not. However, I use this to check large configuration files that are often changed and it is quite difficult to find the exact place where the change occurred. That is why I think about using some existing solution which has better output and allows to easily see the differences. Unfortunately, I have not been able to find anything matching my criteria.
Is there any tool that allows this? I have heard about XMLUnit and have a quick look at it but I am not sure if it is capable of finding a subtree in a document ignoring any other elements or attributes. Can you show me an example how to do this in XMLUnit if it is possible?

A: No, this isn't anything XMLUnit 1.x would be well suited for.  You could use XPath to get at the root nodes of your subtrees, import them into fresh Documents and compare those - but would still need to filter out all the differences you are not interested in.
We are currently working on XMLUnit 2.x and it may at one point contain tools to help you (it currently wouldn't work much better than 1.x for you), but it is nowhere close to done, yet.


text:
Q: interactively call SAS script (server based) from server based Python or vice-versa I am trying to call SAS script using server based Python in my organization. SAS I have access is server based as well but have not been able to configure initial setting. When I import saspy and run sas=saspy.SASsession(), I get following error:
Using SAS Config named: default
The OS Error was:
No such file or directory

SAS Connection failed. No connection established. Double check your settings in sascfg_personal.py file.

Attempted to run program /opt/sasinside/SASHome/SASFoundation/9.4/bin/sas_u8 with the following parameters:['/opt/sasinside/SASHome/SASFoundation/9.4/bin/sas_u8', '-nodms', '-stdio', '-terminal', '-nosyntaxcheck', '-pagesize', 'MAX', '']
If no OS Error above, try running the following command (where saspy is running) manually to see what is wrong:
/opt/sasinside/SASHome/SASFoundation/9.4/bin/sas_u8 -nodms -stdio -terminal -nosyntaxcheck -pagesize MAX

Using SAS Config named: default
  SAS Connection failed. No connection established. Double check your settings in sascfg_personal.py file.

Attempted to run program /opt/sasinside/SASHome/SASFoundation/9.4/bin/sas_u8 with the following parameters:['/opt/sasinside/SASHome/SASFoundation/9.4/bin/sas_u8', '-nodms', '-stdio', '-terminal', '-nosyntaxcheck', '-pagesize', 'MAX', '']
Try running the following command (where saspy is running) manually to see if you can get more information on what went wrong:
/opt/sasinside/SASHome/SASFoundation/9.4/bin/sas_u8 -nodms -stdio -terminal -nosyntaxcheck -pagesize MAX

But, even when i submit the above command, I do not get any details.
Being able to run python script from SAS will serve my purpose as well, but I am not sure how to do this as well.

A: When you say SAS is server based, do you mean a remote server, not a local installation of SAS? Have to read the configuration guide to see how to configure saspy to get to your remote server? https://sassoftware.github.io/saspy/install.html#configuration
There is more than one way, depending upon your client and server setup.


text:
Q: Procedure Or Function SpAddDepartment Has Too Many Arguments Specified Problem
I get an error

Procedure or function spAddDepartment has too many arguments specified

How to solve it?
Details: when inserting data into table department using stored procedure spAddDepartment using fluent api in ASP.NET MVC 5, I get that error mentioned above.
Table Departments:
CREATE TABLE [dbo].[Departments]
(
    [DepartmentID] [int] IDENTITY(1,1) NOT NULL,
    [DepartmentName] [nvarchar](50) NULL,
    [IsActive] [bit] NULL
)

Stored procedure spAddDepartment:
ALTER Procedure [dbo].[spAddDepartment]
    @DepartmentName    nvarchar(50)
AS
BEGIN
    INSERT INTO Departments
    VALUES (@DepartmentName, 1)
END

Department model class:
public partial class Department
{
    public Department()
    {
        Employees = new HashSet<Employee>();
    }

    public int DepartmentID { get; set; }

    [StringLength(50)]
    public string DepartmentName { get; set; }

    public bool? IsActive { get; set; }

    public virtual ICollection<Employee> Employees { get; set; }
}

Database context:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Entity<Department>()
                .MapToStoredProcedures(p => p.Insert(sp => sp.HasName("spAddDepartment").Parameter(pm => pm.DepartmentName, "DepartmentName")));
}

DepartmentController:
[HttpPost]
public ActionResult Insert(Department depart)
{
    depart.IsActive = true;

    hr.Departments.Add(depart);
    hr.SaveChanges();

    return View(depart);
}

Department view:

Department

    @Html.ValidationSummary(true, "", new { @class = "text-danger" })

        @Html.LabelFor(model => model.DepartmentName, htmlAttributes: new { @class = "control-label col-md-2" })

            @Html.EditorFor(model => model.DepartmentName, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.DepartmentName, "", new { @class = "text-danger" })

        @Html.LabelFor(model => model.IsActive, htmlAttributes: new { @class = "control-label col-md-2" })

                @Html.EditorFor(model => model.IsActive)
                @Html.ValidationMessageFor(model => model.IsActive, "", new { @class = "text-danger" })

            <input type="submit" value="Create" class="btn btn-default" />

A: When you execute SaveChanges(), it will make this call to the database (assuming the DepartmentName is Dep1:
exec [dbo].[spAddDepartment] @DepartmentName=N'Dep1',@IsActive=1

That is why you are getting the error because your stored procedure only has 1 parameter but EF is looking for a stored procedure with 2 parameters.
You ask why 2 parameters? Because your class has 4 properties: one is virtual so that one is ignored, the DepartmentID is identity column so that one will be auto generated and thus not required, the other 2 properties (DepartmentName and IsActive) are required and therefore it is expecting a stored procedure with 2 parameters as shown above.
Fix
To fix the issue, add another parameter to your stored procedure.


text:
Q: RavenDB query with Linq and enum Given this document class:
public class Tea
{
   public String Id { get; set; }

   public String Name { get; set; }

   public TeaType Type { get; set; }

   public Double WaterTemp { get; set; }

   public Int32 SleepTime { get; set; }
}

public enum TeaType
{
    Black,
    Green,
    Yellow,
    Oolong
}

I store a new Tea with the following code:
using (var ds = new DocumentStore { Url = "http://localhost:8080/" }.Initialize())
using (var session = ds.OpenSession("RavenDBFirstSteps"))
{
    Tea tea = new Tea() { Name = "Earl Grey", Type = TeaType.Black, WaterTemp = 99d, SleepTime = 3 };
    session.Store(tea);
    session.SaveChanges();
    Console.WriteLine(tea.Id);
}

The tea will be successfully saved, but when I try to query all black teas with linq, I am getting no results:
using (var ds = new DocumentStore { Url = "http://localhost:8080/" }.Initialize())
using (var session = ds.OpenSession("RavenDBFirstSteps"))
{
    var dbTeas = from teas in session.Query<Tea>()
                    where teas.Type == TeaType.Black
                    select teas;

    foreach (var dbTea in dbTeas)
    {
        Console.WriteLine(dbTea.Id + ": " + dbTea.Name);
    }
}

I also tried to save the Enum as Integer with the following command:
ds.Conventions.SaveEnumsAsIntegers = true;

But, the result is the same. All works when I use the Name or the WaterTemp. Does RavenDB supports Enums in this way or I am totally wrong?

A: It seemed that I got the answer. It is always not recommended to use properties with a name like Type, which can be a reserved keyword.
I renamed Type and everything works, so the answer is:
public class Tea
{
   public String Id { get; set; }

   public String Name { get; set; }

   public TeaType TeaType { get; set; }

   public Double WaterTemp { get; set; }

   public Int32 SleepTime { get; set; }
}


text:
Q: I'm trying to create a new repository on github but can't get my ssh key I cant make a repository because I don't have an ssh key on git hub but I don't know how to get that I fallowed a video and it was going good until he copy pasted it and that won't work for me. I tried clip < ~/.ssh/id_rsa.pub
 but when I hit CTRL V nothing pastes.

A: In your terminal:
sudo apt-get install xclip

Then:
xclip -sel clip < ~/.ssh/id_rsa.pub

Key should be in your clipboard now.
Log-in to Github > Click on your profile photo > Click Settings > Click on SSH and GPG in your sidebar > Click New SSH key or Add SSH key > Enter a title like "My Linux machine" > Paste your key into the Key field.
Done.


text:
Q: java.net.SocketException: Operation not permitted (select/poll failed) when adding Keen events asynchronously in AWS Lambda Dependency:
<dependency>
    io.keen</groupId>
    keen-client-api-java</artifactId>
    5.2.0</
</dependency>

Bean creation:
@Bean
public KeenClient keenClient() {
    KeenClient keenClient = new JavaKeenClientBuilder().build();
    keenClient.setDefaultProject(new KeenProject(projectId, writeKey, readKey));
    keenClient.setDebugMode(debugMode);

    if (enableLogging) {
        KeenLogging.enableLogging();
    }

    return keenClient;
}

Service definition:
@Service
public class KeenAnalyticsService implements AnalyticsService {
    private static final Logger LOG = LoggerFactory.getLogger(KeenAnalyticsService.class);

    private final KeenClient keenClient;

    public static final String ID = "id";
    public static final String USER_LOGIN_EVENT = "user_login_event";

    @Autowired
    public KeenAnalyticsService(KeenClient keenClient) {
        this.keenClient = keenClient;
    }

    @Override
    public void submitUserLoginEvent(UserLoginAnalyticsEvent userLoginAnalyticsEvent) {
        Map<String, Object> event = Maps.newHashMap();
        event.put(USER_LOGIN_EVENT, userLoginAnalyticsEvent);
        addEvent(USER_LOGIN_EVENT, event);
    }

    private void addEvent(String collection, Map<String, Object> event) {
        addEvent(collection, event, Maps.newHashMap());
    }

    private void addEvent(String collection, Map<String, Object> event, Map<String, Object> keenProperties) {
        if (!event.containsKey(ID)) {
            String id = UUID.randomUUID().toString();
            LOG.info("Adding {} Keen event with ID ({})", collection, id);
            event.put(ID, id);
        } else {
            LOG.info("Adding {} Keen event with existing ID ({})", collection, event.get(ID));
        }

            try {
            keenClient.addEventAsync(keenClient.getDefaultProject(), collection, event, keenProperties, new LoggingKeenCallback());
        } catch (Throwable e) {
            LOG.warn("Unable to add event", e);
        }
    }

    private static class LoggingKeenCallback implements KeenDetailedCallback {
        @Override
        public void onSuccess() {}

        @Override
        public void onFailure(Exception e) {}

        @Override
        public void onSuccess(KeenProject project, String eventCollection, Map<String, Object> event, Map<String, Object>     keenProperties) {
            LOG.info("Successfully processed event asynchronously with ID({}) to Collection({})", event.get(ID),     eventCollection);
        }

        @Override
        public void onFailure(KeenProject project, String eventCollection, Map<String, Object> event, Map<String, Object>     keenProperties, Exception e) {
            LOG.warn("Unable to process event asynchronously with ID({}) to Collection({})", event.get(ID), eventCollection,     e);
        }
    }

}
I'm getting the following stacktrace:
Exception in thread "pool-1-thread-1" java.lang.RuntimeException: java.net.SocketException: Operation not permitted (select/    poll failed)
    at io.keen.client.java.KeenClient.handleFailure(KeenClient.java:1643)
    at io.keen.client.java.KeenClient.addEvent(KeenClient.java:171)
    at io.keen.client.java.KeenClient$1.run(KeenClient.java:243)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)
Caused by: java.net.SocketException: Operation not permitted (select/poll failed)
    at java.net.SocketInputStream.socketRead0(Native Method)
    at java.net.SocketInputStream.socketRead(SocketInputStream.java:116)
    at java.net.SocketInputStream.read(SocketInputStream.java:171)
    at java.net.SocketInputStream.read(SocketInputStream.java:141)
    at sun.security.ssl.InputRecord.readFully(InputRecord.java:465)
    at sun.security.ssl.InputRecord.read(InputRecord.java:503)
    at sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:983)
    at sun.security.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1385)
    at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1413)
    at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1397)
    at sun.net.www.protocol.https.HttpsClient.afterConnect(HttpsClient.java:559)
    at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(AbstractDelegateHttpsURLConnection.java:185)
    at sun.net.www.protocol.http.HttpURLConnection.getOutputStream0(HttpURLConnection.java:1316)
    at sun.net.www.protocol.http.HttpURLConnection.getOutputStream(HttpURLConnection.java:1291)
    at sun.net.www.protocol.https.HttpsURLConnectionImpl.getOutputStream(HttpsURLConnectionImpl.java:250)
    at io.keen.client.java.http.UrlConnectionHttpHandler.sendRequest(UrlConnectionHttpHandler.java:86)
    at io.keen.client.java.http.UrlConnectionHttpHandler.execute(UrlConnectionHttpHandler.java:30)
    at io.keen.client.java.KeenClient.publishObject(KeenClient.java:1436)
    at io.keen.client.java.KeenClient.publish(KeenClient.java:1370)
    at io.keen.client.java.KeenClient.addEvent(KeenClient.java:168)
    ... 4 more

Are there any ideas as to what might be causing the issue? The issue goes away when I add the event in sync rather than async but I'd prefer to add the event async if possible.
I'm 99% sure this is the Lambda cutting off execution to the event mid-send but I wanted to be sure. I don't recognize the stacktrace myself personally so there's only so much I can speculate from it.
Obviously I don't want to delay user login attempts any more than I have to but if I fire off the keen event asynchronously as the last thing I do before returning the login result to the user then there's bound to be some kind of timing issue related to the container closing and the keen event being sent.
Then again, Lambda might be smart enough to wait for child spawned threads to finish. Then again, it might not. It might quit when the main thread finishes executing by design.
Curious if anyone in the Keen team or the Lambda team can shed more light on this.


text:
Q: Can't drop element in previously hidden cdkDropList When I start dragging the element, I show the target container for the drop and change the size of the original container to leave place to the drop zone.
What happens is that the size of the original container that is being considered is the one at the moment of the drag start.
When I drop my element, he's being dropped in the original container.

{{ e }}

    Glissez déposez pour archiver

.list-container {
    min-height: calc(100vh - 325px);
    max-height: calc(100vh - 325px);
    overflow: auto;
}

.dessus {
    background-color: orange;
    min-height: 300px;
    max-height: 300px;
}

.cdk-archive {
    color: white;
    transition: 0.5s;
    text-align: center;
    height: 15vh;
    background-color: rgba(74, 74, 74, 0.8);

    .cdk-drag-placeholder {
        display: none !important;
    }
}

.on-drag {
    min-height: calc(100vh - (325px + 15vh))!important;
    max-height: calc(100vh - (325px + 15vh))!important;
    overflow: auto;
}

drop(event) {
    console.log('drop');
}

dropArchive(event) {
    console.log('dropArchive');
}

dragStart(event: CdkDragStart) {
    this.dragStartEtat = true;
}

dragEnd(event) {
    this.dragStartEtat = false;
}

There is no problems if the target container is shown from the start.
What is expected is for the dropArchive to be triggered when dropping in 'archive' zone. However the drop on 'baseList' is the one still being triggered.
Is there anything I'm doing wrong or a solution to get around this behavior ?
Here's the full working example : https://stackblitz.com/edit/hidden-drop-zone


text:
Q: Twitter bootstrap grid system - 4 span3's results in 2 lines I am using twitter bootstrap and want to have 4 'how it works' sections across a single line within a container.  According to twitter bootstrap, within a container, there are 12 spans so this shouldn't be an issue.
For some reason, when i create 4 div's, it results in the 4th div going to the next line.  My screen width is greater than the width where it should stack it vertically, so that's not the issue.
Any ideas?
CSS HERE
.howitworks{
        text-align: center;
        margin-top: 30px;
        }

.howitworks p{
        margin-left:20%;
        padding-bottom: 40px;}

.howitworks h3{
        padding-top:25px;
            }

#howitworksdetail{
        border: thin solid #0d9e49;
        border-bottom-width: 3px;
        border-bottom: solid #0d9e49;
        min-height: 220px;
        margin-top: 60px;
            }

HTML HERE

header

stuff.

header

stuff

header

stuff

header

stuff

I tried eliminating the border and that did not do it either.  Thanks

A: It looks like you are missing
 in your code. You'll notice on the Bootstrap Grid System page that it requires the class row in order to create a row with those 12 columns.
Also, you have the class span2 on your
 elements, but I believe you only want to apply the grid classes to
 elements. Hope this helps!


text:
Q: How do I get this twitter feed to render in my React component? I'm new to React. I've been using it for about two weeks now.
I'm trying to get this Twitter feed to render on my React component but I'm not sure how.
Problem: When I click on the navbar link to get to this page, all that shows up is my login component.
Heres the code for the twitter feed. Any idea why and how I can fix this to just show the feed?
<a
  class="twitter-timeline"
  data-lang="en"
  data-theme="dark"
  href={"https://twitter.com/MTA?ref_src=twsrc%5Etfw%22%7D%3ETweets"}
>
</a>
<script
  async
  src="https://platform.twitter.com/widgets.js"
  charset="utf-8"
></script>

A: Was actually able to get this fixed. It's still a bit buggy but I realized I was missing a few packages that I should've downloaded


text:
Q: Radio button validation with error handling in c# WPF application Hi I have 3 radio button with 10, 20, 30 value in it and 4th radio button is other with textbox next to it for user to enter any other number value in it.
I would like to show message when user doesn't select any radio button or if they enter wrong data other than number in other radio button text box.
here is my code

A: It is bit unclear, I assume(from comments), you want to show a message when user inputs non  double value in the textbox, UseMessageBox.Show to show the message.


text:
Q: access values from multidimen array in ruby Hi I have an array that i created using push like this
arr.push(h, s.power)

PS: h and s.power both are variables but depends on condition I applied
which ends up something like this
[22,"0.014",22,"0.01",22,"0.01",22,"0.082",22,"0.0002",22,"0.02822",22,"0.0042822",22,"0.041662",21,"0.0042822",21,"0.11107"]

but now I want to create new array for each new value like 22, 21 but I can not access it with  many combinations I tried such as arr[22], with arr.map

A: You should consider using a Hash instead. See ruby hash documentation here.
So instead of pushing h and s.power into an array, you would add them to the hash like this:
my_hash[h] ||= []
my_hash[h].push(s.power)

The first line makes sure you have an array in the hash for the latest value of h. The second adds s.power to that array.
If you run this code repeatedly, you will end up with one array for each unique value of h which you can access like this:
my_hash[22] # <= returns the array of s.power values for h=22
my_hash[21] # <= returns the array of s.power values for h=21

If I understand your question correctly, this should be a clean way to do what you want.


text:
Q: matching 2 dataframes in pandas If I have 2 dataframes in pandas like below
but 2 dataframes don't have same columns, only few columns are same.
df1
no  datas1 datas2 datas3 datas4
 0      a    b      a      a
 1      b    c      b      b
 2      d    b      c      a

df2
no  datas1 datas2 datas3  data4  data 5  data6
 0      c    a      a       a      a       b
 1      a    c      b       b      b       b
 2      a    b      c       b      c       c

I'd like to know how much it's matched for each same column based on "no" filed using pandas functions
the result are below
data3 is 100% match
data4 is 66% match

or

data3 is 3 matched
data4 is 2 matched

What's the best way to make like that ?

A: You can do this - first run equals method and if True then print that dataframes match, otherwise use compare method and then calculate the percentage of rows that matched between dfs:
import pandas as pd

df1 = pd.DataFrame({'a': [1, 2, 3], 'b': [4, 5, 6]})
df2 = pd.DataFrame({'a': [2, 2, 3], 'b': [4, 5, 7]})

if df1.equals(df2):
    print('df1 matched df2')
else:
    comp = df1.compare(df2)
    match_perc = (df1.shape[0] - comp.shape[0]) / df1.shape[0]

print(f'{match_perc * 100: .4f} match')  # Out: 33.3333 match

You can simplify by just using compare and if the dataframes match perfectly then you print that they matched:
df1 = pd.DataFrame({'a': [1, 2, 3], 'b': [4, 5, 6]})
df3 = pd.DataFrame({'a': [1, 2, 3], 'b': [4, 5, 6]})

comp = df1.compare(df3)
match_perc = (df1.shape[0] - comp.shape[0]) / df1.shape[0]
if match_perc == 1:
    print('dfs matched')
else:
    print(f'{match_perc * 100: .4f} match')

# Out: dfs matched


text:
Q: How can I convert double-float to byte array and vice versa in common lisp? For integer (32bit or 4 bytes) I can do as follows;
(defun get-u4 (arr pos)
  (let ((u4 0))
    (setf (ldb (byte 8 0) u4) (aref arr pos))
    (setf (ldb (byte 8 8) u4) (aref arr (+ pos 1)))
    (setf (ldb (byte 8 16) u4) (aref arr (+ pos 2)))
    (setf (ldb (byte 8 24) u4) (aref arr (+ pos 3)))
  u4))

(defun put-u4 (arr pos int)
  (setf (aref arr pos) (ldb (byte 8 0) int))
  (setf (aref arr (+ pos 1)) (ldb (byte 8 8) int))
  (setf (aref arr (+ pos 2)) (ldb (byte 8 16) int))
  (setf (aref arr (+ pos 3)) (ldb (byte 8 24) int)))

However, I cannot figure out how can I do this for 64bit or 8byte
double-float? Little-Endianess is assumed.
=============
I found one solution (using external library);
https://www.quicklisp.org/beta/UNOFFICIAL/docs/ieee-floats/doc/index.html
using this one, I can encode/decode double-float to/from integer with proper
size.

A: From wikipedia we get this:

You can get the library you mentioned in the comment with quicklisp:
CL-USER> (ql:quickload 'ieee-floats)
To load "ieee-floats":
  Install 1 Quicklisp release:
    ieee-floats
; Fetching #<URL "http://beta.quicklisp.org/archive/ieee-floats/2015-06-08/ieee-floats-20150608-git.tgz">
; 4.92KB
==================================================
5,041 bytes in 0.01 seconds (378.68KB/sec)
; Loading "ieee-floats"
[package ieee-floats]
(IEEE-FLOATS)
CL-USER> (ieee-floats:encode-float32 23d2)
1158660096
CL-USER> (ieee-floats:decode-float32 #b010101)
2.9427268e-44
CL-USER> (ieee-floats:encode-float32 0)
; Evaluation aborted on #<TYPE-ERROR expected-type: FLOAT datum: 0>.
CL-USER> (ieee-floats:encode-float32 0.0)
0
CL-USER> (ieee-floats:encode-float32 0.1)
1036831949

you can use of course iee-floats:encode/decode-float64 of course,
You also need to know that #b010101 is a macro that represents the number in binary you can use in normal math with common lisp:
CL-USER> (+ 2 #b10)
4

so it converts the binary for you to an integer, then you can also have the utility with format
(format nil "~B" 2)
"10"

That you can use to convert integers to binary string, finally the only thing that you may take care is the 0 autocompletion before the number in binary, the ieee library removes them for the representation
CL-USER> (ieee-floats:encode-float64 1.0d0)
4607182418800017408
CL-USER> (format nil "~B" *)
"11111111110000000000000000000000000000000000000000000000000000"
CL-USER> (length *)
62
CL-USER> (ieee-floats:encode-float64 -1.0d0)
13830554455654793216
CL-USER> (format nil "~B" *)
"1011111111110000000000000000000000000000000000000000000000000000"
CL-USER> (length *)
64

CL-USER> (ieee-floats:decode-float64 #b11111111110000000000000000000000000000000000000000000000000000 )
1.0d0
CL-USER> (ieee-floats:decode-float64 #b1011111111110000000000000000000000000000000000000000000000000000 )
-1.0d0
CL-USER> (ieee-floats:decode-float64 #b0011111111110000000000000000000000000000000000000000000000000000 )
1.0d0

With this you can make all your needed transformations, good luck


text:
Q: Hung Glassfish after limited usage, GC? I'm working on the following setup:
OS         CentOS release 6.4 (Final)
Memory     1024MB
CPU        1 × 2.4 Ghz @ 80%
Glassfish  GlassFish Server Open Source Edition 3.1.2.2 (build 5)

I'm aware that this is only a small setup with limited memory, though it should suffice.
Here's my problem (I know, there's written a lot about it already):
After some usage my memory seems to clog up. This leads to a hung Glassfish, meminfo show something like:
MemTotal:        1030772 kB
MemFree:          158488 kB
Buffers:            3204 kB
Cached:            16340 kB
SwapCached:         7100 kB
Active:           413424 kB
Inactive:         410252 kB

top shows:
PID  USER      PR  NI  VIRT  RES  SHR S %CPU %MEM    TIME+  COMMAND
2380 root      20   0  860m 658m 6028 S 99.8 65.4 170:58.30 java

Conclusion
My Glassfish server tends to use all resources after a while. I'm not sure as too why the CPU is clogged, though I'm suspecting this has something to do with Garbage Collection.
My question is, how can I prevent this from happening? Should I configure my GC, if so, how?

A: 1024MB isn't trivial.  I don't know what your app is doing, but it's a respectable start.
Since Java uses a generational memory model, I'd recommend getting a dynamic picture of all the generations: perm gen, eden, etc.
I like Visual VM, with all the plug-ins installed.  It lets me see memory, threads, CPU, objects in real time.  Try it and see if it'll help you.  More information is what you need.


text:
Q: RDTSC equivalent for iOS I'm looking to do high-precision timing in an iOS app. On an Intel x86 chip, I'd use RDTSC to get timestamps, but I can't do that on an ARM device. Is there an equivalent of RDTSC that can be used from an iOS app?

A: There appears to be a clang builtin for this, __builtin_readcyclecounter(). On x86, it compiles to rdtsc; on ARM64, it compiles to mrs x0, PMCCNTR_EL0. On ARM it always returns 0 though. ARM64 is good enough for me though, since 32-bit support was dropped in iOS 11.

A: For high-precision timing, perhaps you could use mach_absolute_time()
Technical Q&A QA1398 Mach Absolute Time Units


text:
Q: Why is my variable undefined inside the Underscore.js each function? Here is my code:
TextClass = function () {
    this._textArr = {};
};

TextClass.prototype = {
    SetTexts: function (texts) {
        for (var i = 0; i < texts.length; i++) {
            this._textArr[texts[i].Key] = texts[i].Value;
        }
    },
    GetText: function (key) {
        var value = this._textArr[key];
        return String.IsNullOrEmpty(value) ? 'N/A' : value;
    }
};

I'm using the Underscore.js library and would like to define my SetTexts function like this:
_.each(texts, function (text) {
    this._textArr[text.Key] = text.Value;
});

but _textArr is undefined when I get into the loop.

A: You have to pass this as context for _.each call like this:
_.each(texts, function (text) {
    this._textArr[text.Key] = text.Value;
}, this);

See the docs for http://underscorejs.org/#each

A: In JavaScript, the function context, known as this, works rather differently.
You can solve this in two ways:

*

*Use a temporary variable to store the context:
SetTexts: function (texts) {
  var that = this;
  _.each(texts, function (text) {
    that._textArr[text.Key] = text.Value;
  });
}

*Use the third parameter to _.each() to pass the context:
SetTexts: function (texts) {
  _.each(texts, function (text) {
    this._textArr[text.Key] = text.Value;
  }, this);
}

A: this in javascript does not work the same way as you would expect. read this article:
http://www.digital-web.com/articles/scope_in_javascript/
short version:
the value of this changes every time you call a function. to fix, set another variable equal to this and reference that instead
TextClass = function () {
    this._textArr = {};
};

TextClass.prototype = {
    SetTexts: function (texts) {
        var that = this;
        for (var i = 0; i < texts.length; i++) {
            that._textArr[texts[i].Key] = texts[i].Value;
        }
    },
    GetText: function (key) {
        var value = this._textArr[key];
        return String.IsNullOrEmpty(value) ? 'N/A' : value;
    }
};

A: Note that you can also pass things other that "this".  For example, I do something like:
var layerGroupMasterData = [[0],[1,2,3],[4,5],[6,7,8,9],[10]];

_.each(layerGroupMasterData,function(layerGroup,groupNum){
    _.each(layerGroup, function (layer, i) {
            doSomethingThatComparesOneThingWithTheOverallGroup(layerGroupMasterData,layer);
    },layerGroups);
},layerGroupMasterData);


text:
Q: How to remove white spaces around img tag? I can't understand, why I should use display: flex; to get the image stretched for the whole space. Even if I set height of the img tag and for its parent (.hey) to 100%, it won't work and would have white space.

Here's the code:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <title>Document</title>

Hey

Lorem ipsum dolor sit, amet consectetur adipisicing elit. Sapiente rerum aliquid tempora ipsum facere
                neque, sint expedita nihil laboriosam accusantium.

Can you please explain why it works that way?

A: You could simply set a display : block on the img like so :
 img {
      display:block;
      /*
         the lines below is for when you want the image
         fills its parent also vertically
         whiteout loosing quality
      */
      height: 100%;
      object-fit:cover;
 }

Your attempt is not working because by default, an img is an inline element, which means width and height set via CSS won't have any effect . Having a display : flex on the parent makes it a flex element, which behaves to a certain point like a block element.

A: img is an inline element. That means you cannot set its width or height. To do that you first need to make it a block or inline-block element, or you could just use display flex and img will now be flex-items. White space is due to margin of p tag
img {
  display: block;
  width: 100%;
  height: 100%;
}

As suggested in a previous answer, you could use this code but it still wont work as you still need to make room for your p tag. You need to first think what you actually want. If you want your p tag to be placed on img then search on this site and there our tons of questions for you. If you want to align them left to right, then use
display: inline-block;
width: 50%;

in both p and img tag. display: flex; is awesome too.


text:
Q: Android with Math Parser I have a problem with my Android Program. I'm using mxparser as my Math Parser. I added it to my Lib. No errors are showing after I typed my program using this but the program gets an error when i click a certain button when running. I tried debugging it many times and I'm sure the error comes from the parser. Any Ideas?
  private OnClickListener ButtonClicked= new OnClickListener()
    {
    @Override
    public void onClick(View v)
    {
        Function f = new Function("f(x) = "+funcText.getText().toString());
        Expression xlexp = new Expression("f("+xlText.getText().toString()+")",f);
        Expression xuexp = new Expression("f("+xuText.getText().toString()+")",f);
        double c = xlexp.calculate();
        double d = xuexp.calculate();
        String xlString = String.valueOf(c);
        String xuString = String.valueOf(d);
        fxlText.setText(xlString);
        fxuText.setText(xuString);

    }

    };

Update:
These are my inputs
This is the Error Message (I think xD)
Thank you LutzL for keeping up with me :D
Update2:
I edited the code:
private OnClickListener ButtonClicked= new OnClickListener()
{
@Override
public void onClick(View v)
{
    xlText.getText();
    xuText.getText();

    String firstString=xlText.getText().toString();
    String secondString=xuText.getText().toString();
    double xl = Double.parseDouble(firstString);
    double xu = Double.parseDouble(secondString);

double f=2*xl+1;
double f2=2*xu+1;
String xlstring = String.valueOf(f);
String xustring = String.valueOf(f2);

    fxlText.setText(xlstring);
    fxuText.setText(xustring);

}

};

This is working. In this code, I get the values of xl and xu then I inserted it in the function I made(2*x+1). But what I need is a code that also gets the function from the user. That's why I used mxparser.
Update3:
I started debugging it and this shows(Source not Found). Don't know what it means. any idea? :(

A: Its three years since this post was made. You could use the open-source ParserNG.
It supports arithmetic operations, equation solving, differential calculus, integral calculus, basic statistics, function/formula definition, can be used for graphing among others.
Evaluating an expression is as simple as:
    MathExpression expr = new MathExpression("(34+32)-44/(8+9(3+2))-22");
    System.out.println("result: " + expr.solve());

    result: 43.16981132075472

Or using variables and calculating simple expressions:
 MathExpression expr = new MathExpression("r=3;P=2*pi*r;");
System.out.println("result: " + expr.getValue("P"));

Or using functions:
MathExpression expr = new MathExpression("f(x)=39*sin(x^2)+x^3*cos(x);f(3)");
System.out.println("result: " + expr.solve());

result: -10.65717648378352

Or to evaluate the derivative at a given point(Note it does symbolic differentiation(not numerical) behind the scenes, so the accuracy is not limited by the errors of numerical approximations):
MathExpression expr = new MathExpression("f(x)=x^3*ln(x); diff(f,3,1)");
System.out.println("result: " + expr.solve());

 result: 38.66253179403897

Which differentiates x^3 * ln(x) once at x=3.
The number of times you can differentiate is 1 for now.
or for Numerical Integration:
MathExpression expr = new MathExpression("f(x)=2*x; intg(f,1,3)");
System.out.println("result: " + expr.solve());

result: 7.999999999998261... approx: 8

This parser is decently fast and has lots of other functionality.
Work has been concluded on porting it to Swift via bindings to Objective C.
UPDATE
Due to requests in the comments, I have created the Android port as a simple dependency for your projects.
You can get that here
Or just add it in your root build.gradle at the end of repositories:
allprojects {
        repositories {
            ...
            maven { url 'https://jitpack.io' }
        }
    }

Also add to your app's build.gradle file, under your dependencies, add:
dependencies {
            implementation 'com.github.gbenroscience:parserng-android:0.1.1'

    }

DISCLAIMER: ParserNG is authored by me.


text:
Q: What is difference between qsize() and queue.unfinished_tasks for a Python Queue object? I discovered I am getting different values when checking qsize() vs the queue's unfinished_size variable.  In what cases would there be a large difference between these results?
   from queue import Queue
   dbjobs = Queue()
   ...
   ...
   ...
   print("qsize() = " + str(dbjobs.qsize()))
   print("unfinished_tasks = " + str(dbjobs.unfinished_tasks))

Example Result 1:
qsize() = 0
unfinished_tasks = 79

Example Result 2:
qsize() = 2
unfinished_tasks = 117

A: I assume you mean the standard library's queue.Queue (not e.g. asyncio.queue.Queue or something else).
As far as I know Queue.unfinished_tasks is not documented, so I would advise against using it on principle.
Assuming it does behave as can reasonably be expected, when reading the documentation for Queue.join, the attribute unfinished_tasks seems to be a counter that goes up by one, whenever a new item is put into the queue and down by one when the Queue.task_done method is called.
As for Queue.qsize, that just returns the (approximate) number of items in the queue. Meaning that number decreases when an item is taken out of the queue (using Queue.get for example). Doing that should have no effect on the unfinished_tasks.
You can think of it as answering different questions. The qsize method answers the relatively straightforward question: "How many items are in the queue right now?"
The unfinished_tasks counter presumably answers the question: "How many items that were put into the queue at some point are still in it or are currently being worked on by consumers of the queue?" Although this is much less precise, since it is entirely possible that a consumer of the queue takes an item out, but never calls task_done afterwards (because he crashed for example).


text:
Q: how get message of error by ajaxError? My php code:
throw Exception("Lorem !", 403);

now I want by ajaxError, get Lorem ! :
$(document).on('ajaxError', function(el, jqxhr) {
  console.log(xhr.statusText);
  console.log(xhr.responseText);
});

that xhr.statusText give me Forbidden message, not Lorem !.
and xhr.responseText give all html code of 403 Page !
How can give Lorem ! text instead?


text:
Q: Error. Docker container mongo-cnt doesn't start Can someone help me? I have dockers files and project that has mongobd and back-end on node.js. I read a lot of articals but can't find any answers that solve this problem. The mongo-cnt container doesn't start and show:
 Error message (] WiredTiger error (1) [1573219560:340726][1:0x7fc183f0fb00], connection: __posix_open_file, 669: /data/db/WiredTiger.wt: handle-open: open: Operation not permitted Raw: [1573219560:340726][1:0x7fc1
83f0fb00], connection: __posix_open_file, 669: /data/db/WiredTiger.wt: handle-open: open: Operation not permitted)

. Also, I must start this project on windows10.
I use for work docker-desktop(version 2.1.0.4).
Please, look at these 2 files and logs.
docker-compose.sh:
    retryOnErr() {
        until $1 2>&1 > /dev/null
        do
            echo "Try again ..."
            sleep 2
        done
    }

    docker-compose down  --remove-orphans --volumes

    rm -rf ./data

    docker-compose up -d --force-recreate --build --renew-anon-volumes

    echo "Waiting for mongo bring up..."
    retryOnErr "docker exec -it mongo-cnt mongo --eval 'rs.status()'"
    echo "Mongo is UP ..."

    docker exec -it mongo-cnt mongo --eval 'rs.initiate({_id:"rs0", members:[{_id:0, host:"mongors:27017"}]});'

    docker-compose restart auditsvc
    docker-compose restart parsersvc

docker-compose.yml:
version: '3.7'
services:

  mongors:
    hostname: mongors
    image: mongors-img
    build: ./mongo-db/
    container_name: mongo-cnt
    restart: on-failure
    ports:
      - 27017:27017
    volumes:
      #- ./data:/data/db
      - mongodata:/data/db
      - ./mongo-db/mongod.conf:/etc/mongod.conf
      - ./mongo-db/mongo-init.sh:/docker-entrypoint-initdb.d/mongo-init.sh
      - ./minuteMedia.postman_collection.json:/minuteMedia.postman_collection.json
    command: ["--config", "/etc/mongod.conf"]

  auditsvc:
    image: auditsvc-img
    build: ./audit-service/
    container_name: auditsvc-cnt
    ports:
      - 5000:5000
      - 5858:5858
    depends_on:
      - mongors

  auditui:
    image: auditui-img
    build: ./audit-ui/
    container_name: auditui-cnt
    volumes:
    - ./audit-ui/nginx-react.conf:/etc/nginx/conf.d/default.conf
    ports:
      - 80:80
    depends_on:
      - mongors

  parsersvc:
    image: parser-img
    build: ./parser/
    container_name: parser-cnt
    volumes:
      - ./out:/app/out
    depends_on:
      - mongors

And logs:
mongo-cnt    | 2019-11-08T13:25:59.807+0000 I  STORAGE  [initandlisten] wiredtiger_open config: create,cache_size=478M,cache_overflow=(file_max=0M),session_max=33000,eviction=(threads_min=4,threads_max=4),config_base=false,statistics=(fast),log=(enabled=true,archive=t
rue,path=journal,compressor=snappy),file_manager=(close_idle_time=100000,close_scan_interval=10,close_handle_minimum=250),statistics_log=(wait=0),verbose=[recovery_progress,checkpoint_progress],
mongo-cnt    | 2019-11-08T13:26:00.323+0000 E  STORAGE  [initandlisten] WiredTiger error (17) [1573219560:323308][1:0x7fc183f0fb00], connection: __posix_open_file, 669: /data/db/WiredTiger.wt: handle-open: open: File exists Raw: [1573219560:323308][1:0x7fc183f0fb00],
connection: __posix_open_file, 669: /data/db/WiredTiger.wt: handle-open: open: File exists
mongo-cnt    | 2019-11-08T13:26:00.325+0000 I  STORAGE  [initandlisten] WiredTiger message unexpected file WiredTiger.wt found, renamed to WiredTiger.wt.162
mongo-cnt    | 2019-11-08T13:26:00.326+0000 E  STORAGE  [initandlisten] WiredTiger error (1) [1573219560:326230][1:0x7fc183f0fb00], connection: __posix_open_file, 669: /data/db/WiredTiger.wt: handle-open: open: Operation not permitted Raw: [1573219560:326230][1:0x7fc1
83f0fb00], connection: __posix_open_file, 669: /data/db/WiredTiger.wt: handle-open: open: Operation not permitted
mongo-cnt    | 2019-11-08T13:26:00.337+0000 E  STORAGE  [initandlisten] WiredTiger error (17) [1573219560:337480][1:0x7fc183f0fb00], connection: __posix_open_file, 669: /data/db/WiredTiger.wt: handle-open: open: File exists Raw: [1573219560:337480][1:0x7fc183f0fb00],
connection: __posix_open_file, 669: /data/db/WiredTiger.wt: handle-open: open: File exists
mongo-cnt    | 2019-11-08T13:26:00.339+0000 I  STORAGE  [initandlisten] WiredTiger message unexpected file WiredTiger.wt found, renamed to WiredTiger.wt.163
mongo-cnt    | 2019-11-08T13:26:00.340+0000 E  STORAGE  [initandlisten] WiredTiger error (1) [1573219560:340726][1:0x7fc183f0fb00], connection: __posix_open_file, 669: /data/db/WiredTiger.wt: handle-open: open: Operation not permitted Raw: [1573219560:340726][1:0x7fc1
83f0fb00], connection: __posix_open_file, 669: /data/db/WiredTiger.wt: handle-open: open: Operation not permitted
mongo-cnt    | 2019-11-08T13:26:00.351+0000 E  STORAGE  [initandlisten] WiredTiger error (17) [1573219560:351210][1:0x7fc183f0fb00], connection: __posix_open_file, 669: /data/db/WiredTiger.wt: handle-open: open: File exists Raw: [1573219560:351210][1:0x7fc183f0fb00],
connection: __posix_open_file, 669: /data/db/WiredTiger.wt: handle-open: open: File exists
mongo-cnt    | 2019-11-08T13:26:00.353+0000 I  STORAGE  [initandlisten] WiredTiger message unexpected file WiredTiger.wt found, renamed to WiredTiger.wt.164
mongo-cnt    | 2019-11-08T13:26:00.354+0000 E  STORAGE  [initandlisten] WiredTiger error (1) [1573219560:354694][1:0x7fc183f0fb00], connection: __posix_open_file, 669: /data/db/WiredTiger.wt: handle-open: open: Operation not permitted Raw: [1573219560:354694][1:0x7fc1
83f0fb00], connection: __posix_open_file, 669: /data/db/WiredTiger.wt: handle-open: open: Operation not permitted
mongo-cnt    | 2019-11-08T13:26:00.356+0000 W  STORAGE  [initandlisten] Failed to start up WiredTiger under any compatibility version.
mongo-cnt    | 2019-11-08T13:26:00.356+0000 F  STORAGE  [initandlisten] Reason: 1: Operation not permitted
mongo-cnt    | 2019-11-08T13:26:00.356+0000 F  -        [initandlisten] Fatal Assertion 28595 at src/mongo/db/storage/wiredtiger/wiredtiger_kv_engine.cpp 786
mongo-cnt    | 2019-11-08T13:26:00.356+0000 F  -        [initandlisten]
mongo-cnt    |
mongo-cnt    | ***aborting after fassert() failure
mongo-cnt    |
mongo-cnt    |

Thank you for your attention!


text:
Q: Changing a Hotseat Human Player to AI If I'm playing a hotseat multiplayer game with a bunch of friends, and one has to leave, is there a way to make AI take over that friend's play, in the middle of the game?

A: I've been playing hotseat games for the last week in service of certain achievements, and I've yet to find a way for the AI to take over a human's slot.  It seems as though once the game is set up, you're stuck with however many humans you expected to play when the game started.


text:
Q: How do I batch encrypt existing passwords in a MySQL db? I am updating a web system for a client, and his 'accounts' table has over 20,000 users, each with a password field of straight text, meaning none of the passwords are encrypted. (I know, scary!) Anyway, I need to know how to take ALL of these passwords and easily encrypt them, preferably in batch style, and import them back into the db. I couldn't find much in searches. I did see B-Crypt, but that looks to be used mostly for files. I'm pretty novice at this so ANY suggestions would be greatly appreciated! Thanks. :)

A: Here is one way to do this.
UPDATE table_Users
SET password = EncryptionFunctionYouChoose(password);

EDIT
 where "table_Users" is the table where your password is held and "password" is the column name for the password.
END EDIT
Although a better idea would be to hash each password with an individual salt value rather than encrypting.  (my opinion)

A: As far as I know MySQL does not provide in-built B-CRYPT function. Refer. If you just want to solve this issue by using MySQL queries you can do something like
update users set password = SHA2(password, 256);

But if you do like to BCrypt, I guess you will have to do it at app level.
There are always interesting discussions on storing password in database. See this list


text:
Q: Difference between random variable and data with measure-theoretic formulation Let's suppose we have some process generating data and we get IID observations $x_1, \dots, x_n$. We know that a random variable is a Borel function $X : \Omega \to \mathbb R$. Is it correct to say that each of these $x_i$ is equal to $X(\omega)$ for various $\omega \in \Omega$, and the same function $X$?
Furthermore, if we say we have random variables $X_1, \dots, X_n$, then each of these is a possibly different function from $\Omega$ to $\mathbb R$, right? But if we then specify that they're identically distributed, we have $n$ copies of the same function, so if we then observe corresponding data $x_1, \dots, x_n$ we can treat $x_i = X_i(\omega_i)$, i.e. we observe each function once, or since all $X_i$ are the same, we have $n$ observations on one function?
Sorry if this is unclear, but my inability to articulate this precisely is exactly why I'm asking this!

A: To your first question:
You could view $x_i=X(\omega_i)$, if $x_i$ denotes results we have from the events in $\Omega$ (but "IID" usually does not apply). If we consider "drawing samples according to some distribution", we usually consider them as "IID" random variables that obeys a certain distrubition - i.i.d. is used for random variables. So if they mention $x_1,\ldots, x_n$ as "IID", they probably mean those observations to be different random variables.

To your second question:
Strictly speaking, "i.i.d" just means that those random variables are "independent and identically distributed", but they are not necessarily the same random variables. So what we know is the following:

*

*They are independent, i.e. events in the $\sigma$-algebra generated by one random variable is independent with events in the $\sigma$-algebra generated by another. Or more intuitively, their joint probability distribution could be decomposed into multiplication of their own distributions, e.g. $f_{X,Y}(x,y)=f_X(x)\cdot f_Y(y)$ for continuous case.

*They have the same probability distribution. But notice that does not mean that the random variables need to be the same. e.g. let $X\sim U_{[0,1]}$, $X$ and $1-X$ have the same distribution, but they are different r.v. Another example could be $\sin(Y)$ and $\cos(Y)$, where $Y \sim  U_{[0,2\pi]}$. Further, if $X$ extends a bit beyond of Borel-measurable, say, Lesbegue-measurable instead, then we might get two random variables to have the same distribution function but not same probability for every event.