Q:

Can I remove any implicitly imported Java library?

Can I remove any implicitly imported Java library?
It may not seem useful.
But I think it may reduce some execution time!

A:

Imports are just syntactic sugar. All they do is let you access things in other packages without having to state their fully qualified name. The code that is produced is exactly the same as if you fully-qualified everything. So there is no runtime performance penalty to having imports.
This also goes for the "implicit imports" (ie: java.lang): you don't pay any price for the classes you don't actually use.

A:

This will have no effect on execution type - I think I'm correct in saying that, by default, classes are only loaded as and when they are needed, not on mass at start-up.
To improve performance you need to profile your application with a tool like Visual VM and address the bottlenecks it identifies (which will never be where you'd expect).

A:

Java doesn't include all of the classes in java.lang.* in your program.  The compiler only includes the ones you explicitly use (or are used by classes you use, etc.).


Q:

Time series data representation in MarkLogic

Time-series data such as historical stock prices are usually stored in an RDBMS.
I am evaluating various options to use this data, possibly store it in doc store or triple store in MarkLogic, and build some use cases on this data and/or along with the other kind of data stored in the doc/triple store.
Essentially, I am looking for ways to

Store time series data such as historical stock prices in a MarkLogic database.
Ways to query this data (stored in ML or queried across the RDBMS), through XQuery for example.
Ways to query this data, along with the other data stored in the doc/triple store.

I would appreciate any recommendations in this regard.

Added some more info...
I am trying to figure a neat way of capturing this data as triples. The idea being that it would be nice to link this data with other related data. For example, if the historical stock price we are trying to store is for HSBC listed on NYSE, then we can in some way define resources for HSBC and NYSE and also capture the stock price as literals (perhaps) and then link the resource HSBC with for example, the company information stored in dbpedia.
Essentially, I am talking about creating linked data, such that it is easy to query across data fetched from different sources and also if possible, try to use inferencing. For example, if I use this approach, it would be possible for me to run a query such as 'Get me the stock price of the companies headquartered in London, whose turnover is greater than $1billion'.

A:

I would recommend storing time-series data in a time-series database: https://en.wikipedia.org/wiki/Time_series_database
Update 1:
You can define HSBC as an entity, specify meta-data for the entity such as location or headcount, and then store quarterly revenue and traded tick prices as separate time-series. Then you can run queries that a) filter by meta-data tag such as Location and filter by aggregation, e.g. MAX(price). I would store headcount as series as well actually. This way I can investigate correlations between different series for research and analytics.


Q:

How to declare a array , then assign it later?

class M{
    string s[5];
    M(){
        s = ["abc","abc","abc","abc","abc"]; // error, how i solve it?
    }
};

I want to declare a array as a private variable, then assign a value to it.

A:

Either you can use the mem-initializer list. For example
class M
{
    string s[5];
pyblic:
    M() : s{ "abc", "abc", "abc", "abc", "abc" }
    {
    }
};

Or instead of the array you could use standard class std::array. For example
#include <array>

class M
{
    std::<string, 5> s;
pyblic:
    M()
    {
         s = { "abc", "abc", "abc", "abc", "abc" };
    }
};


Q:

How would I fit a 4 chord progression into 3 bars?

I'm programmatically trying to create a song. If I have a 4 chord progression that i'm trying to fit into 3 bars, what rules of thumb should i be following to make it sound not terrible?
If we have a example scenario that I'm in the key of C, and my chord progression is I–V–vi–IV. So that leaves us with the chords of C–G–Am–F. What I would do is just shorten the bar the minor chord is in and leave all the major chords longer. Is this a good rule to follow? Will this be ok for other scales, like minor scales?
Sorry if i'm not using the correct terminology, my music theory knowledge is lacking.

A:

Chords conventionally change on the bar, on the half bar or on the beat.   Assuming we're in 4/4 time, you could just choose one pair of chords to fill half-a-bar each instead of a full bar.  No reason to treat minor chords any less favourably than major ones!


Q:

How to keep currency (keeping it localized) independent from system locale on android app?

I've been researching for a solution to this issue for a while and could not find a proper solution. The closest I've got was this entry from stackoverflow. But since this was asked 4 years ago (and is not actually my issue although it could help to solve my problem), I 'll ask again to see if now there is a better workaround.
Context:
I want to release my android app in several countries. Currently only available in Spain. I've read all android developers documentation about localization. It is pretty clear that all dynamic localized information on code should be based on "system locale" when presenting it to the user.
Problem:
Problem comes when user changes language on settings manually and I want to display a price (generated by the app) that bases it's currency on system locale preference. For example lets say I live in Spain and I set up my device Language & input/Language to English(United States). When I do this my app shows prices in US dollars ($) but I want it to keep showing EUR (€) since I'm in Spain. How do I achieve this?
This is mi actual code for showing a "localized" price to the user based on system locale:
    Locale currentLocale = Locale.getDefault();
    priceFormat = NumberFormat.getInstance(currentLocale);
    localCurrency = Currency.getInstance(current);
    //...

    //doubleValueCost is independent from currency but the I want to add the proper currency symbol
    costTextView.setText(priceFormat.format(doubleValueCost) + " " + localCurrency.getSymbol());

This code will add the currency symbol for the system locale selected by user on preferences and not the actual currency symbol of the country where the device is.
Any advice is welcomed. Thanks in advance.

A:

After all the research I decided to use TelephonyManager simCountryIso to localize currency in the concrete scenario I mention in my problem. Not sure if it is the best solution to solve my proble but is the best option I've found. This would be the code to get the currency I need:
        String countryIso = telephonyManager.getSimCountryIso();
        localCurrency = Currency.getInstance(new Locale(countryIso,countryIso));
        //doubleValueCost is independent from currency but the I want to add the proper currency symbol ...
        costTextView.setText(priceFormat.format(doubleValueCost) + " " + localCurrency.getSymbol());

If anyone comes up with a better solution, I would be glad to hear.
Thanks


Q:

How do I set file.encoding for a junit test in ant?

I'm not quite done with file.encoding and ant.   How do I set the file.encoding for junit tests in ant?  The junit ant task doesn't support the encoding attribute like the javac task does.
I've tried running «ant -Dfile.encoding=UTF-8» and «ANT_OPTS="-Dfile.encoding=UTF-8" ant» without success.  System.getProperty("file.encoding") within a test still returns MacRoman.

A:

JUnit supports a child element <jvmarg ...> which should do what you want.
<junit fork="yes">
  <jvmarg value="-Dfile.encoding=UTF-8"/>
  ...
</junit>

I assume you were using the fork=yes attribute since this starts a new JVM for the test run, thus the parameters you send into ant at the command line ant -Dfoo=bar do not necessarily propagate to the JVM running the tests.


Q:

ThreeJS CSS 3D Sprite Randomize

I'm having a little bit of trouble; I am trying to adapt ThreeJS CSS 3D Sprite so that it use an array of images for the sprites. The original is here. Here is my code:
  ...
  var image = document.createElement( 'img' );
  image.addEventListener( 'load', function ( event ) {
    for ( var i = 0; i < particlesTotal; i ++ ) {
      var object = new THREE.CSS3DSprite( image.cloneNode() );
      object.position.x = Math.random() * 4000 - 2000,
      object.position.y = Math.random() * 4000 - 2000,
      object.position.z = Math.random() * 4000 - 2000;
      scene.add( object );
      objects.push( object );
    }
    transition();
  }, false );
  // image.src = 'assets/img/textures/sprite.png';

  /* Randomize Images
  ============================================= */
  var imagesArray = ['assets/img/textures/orb_makro.png','assets/img/textures/orb_tiger_brands.png','assets/img/textures/orb_unilever.png'];)
  var num = Math.floor(Math.random() * 3) + 1 ;
  image.src = imagesArray[num];

  ...

I think part of the problem is that takes an instance of one image and then multiplies it, that's where I am getting stuck. Many thanks!!

A:

To pick a random image for the 3D sprite you would first preload all the images:
var imagesArray = [];
var urlArray = ['assets/img/textures/orb_makro.png',
                'assets/img/textures/orb_tiger_brands.png',
                'assets/img/textures/orb_unilever.png'];
var count = urlArray.length;

// load all images asynchronously
urlArray.forEach(function(url) {
  var img = new Image;
  img.onload = handler;   // todo: also add handler for onerror/onabort
  img.src = url;
  imagesArray.push(img);  // store image to preloaded array
});

function handler() {
  if (!--count) setup();  // when all images are loaded, go to setup
}

In the setup section we can now pick a random image from the preloaded array just adding and modifying a line:
// ...
for ( var i = 0; i < particlesTotal; i++ ) {
  var index = (Math.random() * imagesArray.length)|0; // random index
  var object = new THREE.CSS3DSprite( imagesArray[index].cloneNode() );
  object.position.set(Math.random() * 4000 - 2000,
                      Math.random() * 4000 - 2000,
                      Math.random() * 4000 - 2000);
  scene.add( object);
  objects.push( object );
}
// ...

You could as an option skip the random index step since the positions are random and just cycle through the array:
var object = new THREE.CSS3DSprite( imagesArray[i % imagesArray.length].cloneNode() );


Q:

Document of Laravel about strange syntax

I saw this in the template:
{!! test() !!}

Please help to show me a document of this syntax.
I searched and I didn't know Laravel allow this syntax.

A:

By default, Blade {{ }} statements are automatically sent through PHP's htmlspecialchars function to prevent XSS attacks. If you do not want your data to be escaped, you may use the following syntax:
{!! $name !!}

That is, if I pass data through a variable named name to the view and {{ $name }} is used to display it, It will display as it passed because statements are automatically sent through PHP's htmlspecialchars function to prevent XSS attacks. For example,
return view('welcome')->with('name','');

is used to return view with data in variable named name and

    {{$name}}

is used to disply my data. The output will be

And if I use

    {!!$name!!}

to display the data, The output will be


Q:

Declaration of variable causes segmentation fault

I don't understand the reason for a segmentation fault error in my program.
The code is available here
At line 29 I declare a PclImage variable, defined with typedef like an array of struct.
The definition of PclImage type is the following (from src/libMyKinect.h file):
typedef struct {
    int valid;
    float x;
    float y;
    float z;
    unsigned char blue;
    unsigned char green;
    unsigned char red;
} Point3d;

typedef Point3d PclImage[480][640];

The program works well, but when I declare a second PclImage, I get a segmentation fault as soon as I launch the program.
For example, if at line 30 of the first file I add PclImage bgPcl; the program immediately crashes.
Can anyone help me?

A:

If you declare a PclImage as a local variable (on the stack), you are likely to get a segmentation fault due to a stack overflow.
PclImage is an array with 307,200 elements, each of which is (likely) about 20 bytes in size, so the whole array is something around 6MB in size.  It's highly unlikely that the stack is large enough to contain two of those arrays; it might not even be large enough to contain one (as a very general rule, it's usually safe on most desktop OSes to assume that you have at least 1MB of stack space available).
When you have such large objects, you should allocate them dynamically (using malloc and friends) or, if you aren't concerned with reentrancy, statically.


Q:

PS Old Gen is full and my application slows down

During medium user load, my Tomcat application slows down very much and I am forced to restart Tomcat in order to permit users to work.
The specs of the system are:

Centos 5.4 64bit with 8GB RAM
Tomcat 6
A Bonita BPM webapp - which utilizes many Groovy calls / scripts

The system is running just the Tomcat, no DB or anything else.
When the application turns REALLY slow, a snapshot of the java memory is shown here.
Have you any ideas to help me fine tune the java memory parameters to help the system work?
The current memory ops in Tomcat are these:
MEMORY_OPTS="-Xshare:auto -Xms3072m -Xmx6144m -XX:MaxPermSize=1536m"`

Should I use -XX: UseCompressedOops or any other parameter to prevent this memory exhaustion?

A:

I suggest you memory profiler your application to see how much memory is being retained and where garbage is being produced.  For most web applications, GC is not much of an issue, but if the amount of garbage gets to excessive levels and there isn't much free memory it can slow down the system significantly.


Q:

Some operators on $\ell^2$ of a discrete group: are they a von Neumann algebra?

Caution: Written while trying to turn some vague confusion I was having into precise questions. A bit long and rambling. An appropriate way to answer may just be to point me toward references.
Let $G$ be a discrete group with identity $e$ and let $H$ be the Hilbert space $\ell^2(G)$.  Let $g \mapsto \lambda_g$ and $g \mapsto \rho_g$ be the left and right regular representations of $G$ on $H$.  These are determined on the canonical orthonormal basis $(\delta_x)_{x \in G}$ by the formulae:
$$ \lambda_g \delta_x = \delta_{gx} \\ \rho_g \delta_x = \delta_{xg^{-1}} $$
Let $W$ be the set of operators $T \in B(H)$  such that
$$\rho_x T \delta_x = T \delta_e$$
for all $x \in G$.  Notice an operator $T \in W$ is completely determined by the vector $T \delta_e$ since the formula $T \delta_x = \rho_x^* T \delta_e$ tells $T$ what to do on an orthonormal basis.  In fact, if $\eta = \sum_{x \in G} \eta_x \delta_x$ is any element of $\ell^2(G)$ and $T \in W$ has $T \delta_e = \xi = \sum_{x \in G} \xi_x \delta_x$, then
$$ T\eta = \sum_{s \in G} \eta_s \rho_s^* \xi = \sum_{s \in G} \eta_s \sum_{t \in G} \xi_t \rho_s^* \delta_t = \sum_{t,s \in G} \xi_t \eta_s \delta_{ts} = \xi * \eta \in \ell^2(G)$$
where $\xi * \eta$ is the standard convolution product.
Remark:  Concerning the above convolution, when $\xi, \eta \in \ell^2(G)$, we will have $\xi * \eta \in c_0(G)$. It is not generally the case that $\xi * \eta \in \ell^2(G)$.
It is simple to see that each of the identities $\rho_x T \delta_x = T \delta_e, x\in G$ which define $W$ is linear and strongly continuous in $T$. Thus $W$ is strongly closed subspace of $B(H)$.
Question 1: Is $W$ a von Neumann algebra?
Question 2: If $\xi \in \ell^2(G)$ is such that $\xi * \eta \in \ell^2(G)$ for all $\eta \in \ell^2(G)$, does $T \eta  = \xi * \eta$ define a bounded operator (which is then in $W$)? Loosely, can $W$ be identified with the set of "convolvers" in $\ell^2(G)$?
To motivate the definition of $W$, note that, if $T \in B(H)$ commutes with the right representation of $G$ on $H$, then
$$ \rho_x T \delta_x = T \rho_x \rho_x^* \delta_e = T \delta_e$$
so $T \in W$. In particular, since the left and right representations commute, $W$ contains the reduced group algebra $C^*_r(G)$ which we can define as the norm closure of the linear span of $\lambda(G)$.
Question 3: Does $W$ equal the strong-operator closure of $C^*_r(G)$?
Question 4: Does $W$ equal the commutant of $\rho(G)$? (it is clearly larger).
Thanks for reading.

A:

It is not true in general that $\xi * \eta \in \ell^2(G)$ when $\xi, \eta \in \ell^2(G)$.  There are easy examples to find when $G = \mathbb Z$.
The answer to all four of your questions is yes.
The fourth (and hence also first) question you basically answer yourself noting that $T \in W$ is completely determined by $T \delta_e$.  From this it is not hard to see that $W = \{ \rho(G) \}'$: $T \rho(g) \delta_x = T \delta_{xg^{-1}} = \rho(gx^{-1}) T \delta_e = \rho(g) T \delta_x$, for each $x, g \in G$.
The easiest way to prove your second question is to first show that convolvers give rise to operators with closed graphs, and then apply the closed graph theorem.
Question 3 basically follows from the other questions.  By symmetry from above we have that $\{ \lambda(G) \}'$ is the space of right convolvers $R_\xi \eta = \eta * \xi$.  But left convolution commutes with right convolution hence $\{ \rho(G) \}' \subset \{ \lambda(G) \}'' \subset \{ \rho(G) \}''' = \{ \rho(G) \}'$.  (Note: $\{ \lambda(G) \}''$ is the strong operator closure of $C_r^*(G)$ by von Neumann's double commutant theorem.)


Q:

Error message when trying to run javafx application in netbeans using maven

I am getting an error message when attempting to run a simple javafx application. Using netbeans 11.0, openjdk 12, openjfx12.
Can't extract module name from javafx-12.0.1.pom: Only outputDirectories and jars are accepted on the path
I had similar problems to Alex on this question, as I wanted to be able to debug:
I can't debug an application using netbeans 11 with JavaFX 12
I previously to use the javafx-archetype-fxml as suggested by https://openjfx.io/openjfx-docs/
but had difficulty running.
I tried to follow the steps suggested by Jose.
Using the pom (with the application name changed):-
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.kev</groupId>
    <artifactId>MavenFX</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>MavenFX</name>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

    <organization>
        <!-- Used as the 'Vendor' for JNLP generation -->
        <name>Your Organisation</name>
    </organization>

    <dependencies>
        <!-- JavaFx 12 dependancies -->
        <dependency>
            <groupId>org.openjfx</groupId>
            <artifactId>javafx</artifactId>
            <version>12.0.1</version>
            <type>pom</type>
        </dependency>
        <dependency>
            <groupId>org.openjfx</groupId>
            <artifactId>javafx-controls</artifactId>
            <version>12.0.1</version>
        </dependency>
        <dependency>
            <groupId>org.openjfx</groupId>
            <artifactId>javafx-fxml</artifactId>
            <version>12.0.1</version>
            <type>jar</type>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.8.0</version>
                <configuration>
                    <source>12</source>
                    <target>12</target>

                </configuration>
            </plugin>
            <plugin>
                <groupId>org.openjfx</groupId>
                <artifactId>javafx-maven-plugin</artifactId>
                <version>0.0.2</version>
                <executions>
                    <execution>
                        <!-- Default configuration for running -->
                        <id>default-cli</id>
                        <configuration>
                            <mainClass>org.kev.mavenfx.MainApp</mainClass>
                        </configuration>
                    </execution>
                    <execution>
                        <!-- Configuration for debugging -->
                        <id>debug</id>
                        <configuration>
                            <options>
                                <option>-agentlib:jdwp=transport=dt_socket,server=y,suspend=y,address=*:8000</option>
                            </options>
                            <mainClass>org.kev.mavenfx.MainApp</mainClass>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>
</project>

I then modified the nbactions.xml as suggested:-
<actions>
    <action>
        <actionName>run</actionName>
        <goals>
            <goal>clean</goal>
            <goal>javafx:run</goal>
        </goals>
    </action>
    <action>
        <actionName>jlink</actionName>
        <goals>
            <goal>clean</goal>
            <goal>javafx:jlink</goal>
        </goals>
    </action>
    <action>
        <actionName>debug</actionName>
        <goals>
            <goal>clean</goal>
            <goal>javafx:run@debug</goal>
        </goals>
    </action>
</actions>

The project will happily build with no errors.
However on trying to run the project I get the following error message:-
cd G:\OneDrive\Documents\NetBeansProjects\MavenFX; "JAVA_HOME=C:\\Program Files\\OpenJDK\\jdk-12.0.1" cmd /c "\"\"C:\\Program Files\\Netbeans 11\\java\\maven\\bin\\mvn.cmd\" -Dmaven.ext.class.path=\"C:\\Program Files\\Netbeans 11\\java\\maven-nblib\\netbeans-eventspy.jar\" -Dfile.encoding=UTF-8 clean javafx:run\""
Scanning for projects...

------------------------------------------------------------------------
Building MavenFX 1.0-SNAPSHOT
------------------------------------------------------------------------

--- maven-clean-plugin:2.5:clean (default-clean) @ MavenFX ---
Deleting G:\OneDrive\Documents\NetBeansProjects\MavenFX\target

--- javafx-maven-plugin:0.0.2:run (default-cli) @ MavenFX ---
Using 'UTF-8' encoding to copy filtered resources.
Copying 2 resources
Changes detected - recompiling the module!
Compiling 2 source files to G:\OneDrive\Documents\NetBeansProjects\MavenFX\target\classes
Can't extract module name from javafx-12.0.1.pom: Only outputDirectories and jars are accepted on the path
Error: Could not create the Java Virtual Machine.
Error: A fatal exception has occurred. Program will exit.
Unrecognized option: --module-path
Command execution failed.
org.apache.commons.exec.ExecuteException: Process exited with an error: 1 (Exit value: 1)
        at org.apache.commons.exec.DefaultExecutor.executeInternal(DefaultExecutor.java:404)
        at org.apache.commons.exec.DefaultExecutor.execute(DefaultExecutor.java:166)
        at org.openjfx.JavaFXBaseMojo.executeCommandLine(JavaFXBaseMojo.java:447)
        at org.openjfx.JavaFXBaseMojo.executeCommandLine(JavaFXBaseMojo.java:409)
        at org.openjfx.JavaFXRunMojo.execute(JavaFXRunMojo.java:97)
        at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo(DefaultBuildPluginManager.java:134)
        at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:207)
        at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:153)
        at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:145)
        at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:116)
        at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:80)
        at org.apache.maven.lifecycle.internal.builder.singlethreaded.SingleThreadedBuilder.build(SingleThreadedBuilder.java:51)
        at org.apache.maven.lifecycle.internal.LifecycleStarter.execute(LifecycleStarter.java:128)
        at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:307)
        at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:193)
        at org.apache.maven.DefaultMaven.execute(DefaultMaven.java:106)
        at org.apache.maven.cli.MavenCli.execute(MavenCli.java:863)
        at org.apache.maven.cli.MavenCli.doMain(MavenCli.java:288)
        at org.apache.maven.cli.MavenCli.main(MavenCli.java:199)
        at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.base/java.lang.reflect.Method.invoke(Method.java:567)
        at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced(Launcher.java:289)
        at org.codehaus.plexus.classworlds.launcher.Launcher.launch(Launcher.java:229)
        at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode(Launcher.java:415)
        at org.codehaus.plexus.classworlds.launcher.Launcher.main(Launcher.java:356)
org.apache.commons.exec.ExecuteException: Process exited with an error: 1 (Exit value: 1)
        at org.apache.commons.exec.DefaultExecutor.executeInternal(DefaultExecutor.java:404)
        at org.apache.commons.exec.DefaultExecutor.execute(DefaultExecutor.java:166)
        at org.openjfx.JavaFXBaseMojo.executeCommandLine(JavaFXBaseMojo.java:447)
        at org.openjfx.JavaFXBaseMojo.executeCommandLine(JavaFXBaseMojo.java:409)
        at org.openjfx.JavaFXRunMojo.execute(JavaFXRunMojo.java:97)
        at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo(DefaultBuildPluginManager.java:134)
        at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:207)
        at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:153)
        at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:145)
        at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:116)
        at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:80)
        at org.apache.maven.lifecycle.internal.builder.singlethreaded.SingleThreadedBuilder.build(SingleThreadedBuilder.java:51)
        at org.apache.maven.lifecycle.internal.LifecycleStarter.execute(LifecycleStarter.java:128)
        at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:307)
        at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:193)
        at org.apache.maven.DefaultMaven.execute(DefaultMaven.java:106)
        at org.apache.maven.cli.MavenCli.execute(MavenCli.java:863)
        at org.apache.maven.cli.MavenCli.doMain(MavenCli.java:288)
        at org.apache.maven.cli.MavenCli.main(MavenCli.java:199)
        at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.base/java.lang.reflect.Method.invoke(Method.java:567)
        at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced(Launcher.java:289)
        at org.codehaus.plexus.classworlds.launcher.Launcher.launch(Launcher.java:229)
        at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode(Launcher.java:415)
        at org.codehaus.plexus.classworlds.launcher.Launcher.main(Launcher.java:356)
------------------------------------------------------------------------
BUILD FAILURE
------------------------------------------------------------------------
Total time: 2.827 s
Finished at: 2019-08-07T23:18:12+01:00
Final Memory: 19M/70M
------------------------------------------------------------------------
Failed to execute goal org.openjfx:javafx-maven-plugin:0.0.2:run (default-cli) on project MavenFX: Error: Command execution failed. Process exited with an error: 1 (Exit value: 1) -> [Help 1]

To see the full stack trace of the errors, re-run Maven with the -e switch.
Re-run Maven using the -X switch to enable full debug logging.

For more information about the errors and possible solutions, please read the following articles:
[Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoExecutionException

I can't understand the line:
Can't extract module name from javafx-12.0.1.pom: Only outputDirectories and jars are accepted on the path

A:

As discussed in the comments:
If you get the error Unrecognized option: --module-path, it means you are running with Java 1.8.
If you are running your Maven project from an IDE, it also means that your IDE is using JDK 1.8 as well.
There are two options to fix this issue:
In case of NetBeans, with the IDE closed, you can edit C:\path\to\NetBeans11.1\etc\netbeans.conf, and add the JDK 12 path, like documented here:
netbeans_jdkhome="C:\path\to\jdk-12.0.2"

Save, close the file, and open NetBeans again, and run the project, it should work. Note this is a permanent solution.
If still doesn't work, make sure you don't have in your PATH variable an older JDK. It is frequent to have the JDK bin path added to the Path environment variable, and if that is the case, that will be still chosen by your IDE.
The other option is to use <executable> in your JavaFX Maven plugin, like:
<configuration>
    <executable>C:\path\to\jdk-12.0.2\bin\java</executable>
    ...
</configuration>

Now, regardless the JDK of your IDE, it will pick the one in that path. Obviously, this makes your pom less portable.


Q:

Looking for a probability distribution

Recently I discussed an experiment with a friend. Assume we start a random experiment. At first there is an array with size 100 000, all set to 0. We calculate at each round a random number modulo 2 and select one random position in that array. If the number in the array is 1, nothing is changed and otherwise the pre-computed value is set. The question is: how many distinct hash values would we have added in 1%, 5%, 50%, 95%, 99% of all cases?
Example: 4 rounds with array of size 10:
Array                     Position   random number
[0,...,0]                    5              0
[0,...,0]                    7              1
[0,...0,1,0,0,0]        6              1
[0,..0,.1,1,0,0,0]     6              0
[0,..0,.1,1,0,0,0]     2              0

First we considered this a somehow simple problem. But after thinking about for some hours, searching the web and asking some math students we couldn't find a solution.So do you know a probability distribution for this problem?

A:

This is equivalent to (among other names) the Coupon Collector problem.  Your are asking about the distribution of the number of coupons collected after $t$ steps, when the total number of possible coupons is $n$.
http://en.wikipedia.org/wiki/Coupon_collector%27s_problem
ADDED:  this and related distributions are also studied under other names such as Birthday Problem, random mappings, and random hashing.  Kolchin-Sevastyanov-Chistyakov Random Allocations, Knuth The Art Of Computer Programming, vol. 2, and Flajolet & Sedgwick Analytic Combinatorics all discuss these problems and may contain the precise asymptotics of the distribution you are looking for.


Q:

a system of nonlinear equations (power sum)

greetings . is there a general method-algorithm to solve the following system !?
$\sum_{n=1}^{m} {x_{n}}^{j}= {k}_{j} $
$j=1,2,...,m$
$k_{j}$ are constants
thanks in advance

A:

Solution of this system are  ALL m roots of the polynomial equation P(x) = 0 in ONE variable.
Where P(x) is defined as follows.
Power sum related to elementary symmetric functions by the so-called Newton formulas.
$\sigma_i = Newton (p_i)$
http://en.wikipedia.org/wiki/Newton's_identities
So define $c_i= Newton(k_j)$.
And write polynom $P(x) = \sum_i c_i x^i$
Its zeros are yours numbers $x_i$.
To solve polynomial equation you may use Newton method or any other method.


Q:

Active constraints in UITableViewCell don't get updated when updated from cellForRowAt

I have a view with two leading constraints that conflict each other. One with leading offset, other without. The 'constant' property works for active constraint. But I want to enable/disable constraints to fit my needs. It works in every place except UITableViewCell, when called from tableView:cellForRowAtIndexPath:.
Here is my cell:
class WowCell: UITableViewCell {
    @IBOutlet weak var myView: UIView!
    @IBOutlet var leading: NSLayoutConstraint!
    @IBOutlet var leadingSpace: NSLayoutConstraint!

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }

    func setup(ye:Bool) {
        setActiveConstraint(ye: ye)

        //doesn't help
        setNeedsLayout()
        layoutIfNeeded()
        needsUpdateConstraints()
        setNeedsUpdateConstraints()
        needsUpdateConstraints()
        setNeedsLayout()
        setNeedsDisplay()
    }

    func setActiveConstraint(ye:Bool){
        leading.isActive = !ye
        leadingSpace.isActive = ye
    }

    override func layoutSubviews() {
        //when called from here, it does work
    }
}

Thanks in advance
Edit: As Prashant Tukadiya advised, it works by changing priorities of both active constraints. But be aware that both constraint have to be lower than 1000.
func setActiveConstraint(ye:Bool){
    leading.priority  = UILayoutPriority(rawValue: !ye ? 999 : 250)
    leadingSpace.priority = UILayoutPriority(rawValue: ye ? 999 : 250)
}

A:

Try with priority  as active / deactivate constraint call addConstraint and removeConstraint  internally
func setActiveConstraint(ye:Bool){
    leading.priority  = !ye ? 999 : 250
    leading.priority = ye ? 999 : 250
}


Q:

how do you set the background of the screen when you popup a jquery ui dialog

in this example, the background of the screen changes when you load up the dialog.  How can i set this on my jquery dialog.  i dont see anywhere in the API where i can set this background behavior when the dialog opens.

A:

Define ui-widget-overlay in your CSS.


Q:

Search in TCL expect using variable name doesn't fetch answer

I doing telnet via an Expect script, and send some command and expect the the below.
expect -re {02 : (.*?)\s}
set output $expect_out(1,string)
puts "output is $output"

=> output is 3  (this is the right answer)

set tests "02 : "

expect -re {"$tests"(.*?)\s}
set output $expect_out(1,string)
puts "output is $output"

=> output is 2 (some other value, this value is the older value present in $expect_out(1,string) that was used to search other text)

Can I save the text to be searched in a variable and pass to expect-re {....} ?
I want the text to be searched in a variable, and then pass that variable in expect..
I tried this, but it didn't work.
expect -re {($tests)(.*?)\s}

A:

I believe your issue is that the variable is not being expanded within the braces. Try this instead:
expect -re "${tests}(.*?)\\s"

Compare the difference between:
puts {"$tests"(.*?)\s}
# Output: "$tests"(.*?)\s
puts "${tests}(.*?)\\s"
# Output: 02 : (.*?)\s

The braces prevent substitution of the value of $tests and instead just puts a literal $tests as the regular expression. The quotes ensure that you actually get the value of $tests. I have added additional braces (to make it ${tests}) because otherwise the parens are treated as part of the variable expansion.


Q:

What is the sum of the angles of a triangle on Earth orbit?

Gauss went out and measured triangles made up of mountain peaks to show that the angles sum up to 180 degree.
However, general relativity leads to non-Euclidian space and I would like to get a better feeling for it.
What would be the sum of angles in a triangle that has all corners on earth's orbit (and with sides of equal length)? The sides are defined by light beams traveling between the corners.

A:

Calculating the sum of the interior angles precisely woud be a big task as we'd need to compute the trajectory of the light ray and there isn't a convenient analytic expression for this. However we can easily calculate an upper limit for the interior angles.
The key fact we need to know is that the deflection angle $\theta$ of a light ray in the Schwarzschild metric is given by:

$$ \theta = \frac{4GM}{c^2r} \tag{1} $$
Strictly speaking this is an approximation that fails when the curvature is high, but at the Earth-Sun distance the curvature is so small the the approximation is essentially exact.
The reason this applies to your question can be seen by drawing out the experiment you describe:

We take three points around the Earth's orbit that form the corners of an equilateral triangle and shine the light ray between the corners. Because the light ray is deflected by the Sun we have to shine the light ray outwards a bit (I've grossly exaggerated in the diagram!). Equation (1) gives us the total deflection of a light ray that comes in from infinity and departs to infinity. Our light ray will have a deflection smaller than this because it neither comes from infinity nor ends up at infinity, but we can use equation (1) as an upper limit for the deflection angle we observe. So let's calculate that upper limit.
The angle between the light ray and the side of the triangle is just $\theta/2$, and there are six such angles, so the sum of the interior angles exceeds $\pi$ by $3\theta$. The upper limit for the sum $\Theta$ is therefore:
$$ \Theta \le \pi + \frac{24GM}{c^2r} $$
where $r$ is the radius of the Earth's orbit and I've made the approximation that the distance of closest approach is $r/2$. It remains only to feed in the values for the various parameters, which gives us:
$$ \Theta \le \pi + 0.00000024 $$


Q:

A function returning the string of

I'm getting setup in mongodb, was looking into using the greater than hash parameter and I get an error. However, when I use a hashrocket it works. Why is this?
require 'rubygems'
require 'mongo'
require 'pry'
require 'win32ole'

db = Mongo::Connection.new.db("test")
x = db['text']

y = x.find({a: {$gt: 0}})
y.each {|y| puts y }

Data
{"_id"=>BSON::ObjectId('51630eea5a8d7b8a8be738c0'), "a"=>1.0}
{"_id"=>BSON::ObjectId('51632de8583be71698000001'), "a"=>1}
{"_id"=>BSON::ObjectId('51632de8583be71698000002'), "a"=>1, "b"=>2}

The Error
syntax error, unexpected ':', expecting tASSOC

for this line at the $gt: part
    y = x.find({a: {$gt: 0}})
This while
y = x.find({'b' =>  {'$gt' => 0}})
y.each {|y| puts y }

A:

I think that $gt is being interpreted as a reference to global variable $gt, not a symbol :$gt. And since you can't use colonized hash syntax with variables, it rightfully expects a hashrocket. The query should work with both string and symbol:
y = x.find({'b' =>  {'$gt' => 0}})
y = x.find({'b' =>  {:$gt => 0}})


Q:

cannot able to get values using any = {} in typescript angular8

import { Component, OnInit  } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { enableProdMode } from '@angular/core';
enableProdMode();

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {
   values: any = {};

  constructor(private http: HttpClient) { }

  ngOnInit() {
    this.getValues();
    console.log(this.values);
  }

   getValues()
   {
     this.http.get('http://localhost:5000/api/values').subscribe(Response => { this.values = Response},error => {console.log(error);
     });
   }

}

I can able to get values from HTTP response.but I cannot able to store those values in 'values' object. getting empty array.

A:

You need to place console.log within the subscribe, As it is getting called asynchronously by the time your console.log gets executed there is no result.
getValues()
{
     this.http.get('http://localhost:5000/api/values').subscribe(Response => {
        this.values = Response;
        console.log("##Got values", this.values);
        },error => {console.log(error);
   });
}


Q:

How to show Highstock tooltip to nearest point in 2-D distance?

When plotting many series on the same graph, is it possible for the tooltip to snap to the closest point in 2-d distance as opposed to the closest in x-axis value only. In this situation, it's impossible to tell which series is which from the color alone and snapping to the closest x-axis value is pretty useless as it basically hops randomly among the many series all having a data point around the same x-value.
I didn't find a way to set up the tooltip this way, but algorithmically it's really not that expensive as one can simply pick out for each series the closest x-value data point and then pick among these the point with the shortest 2-d distance (or even just the closest y-value point as usually x-values are much more densely packed than y-values).
Update I played with the findNearestPointBy suggested below, which should do what I want except I'm actually using a stockChart. It appears that stockChart behaves differently from a chart - see stockChart vs. chart

findNearestPointBy does not seem to make a difference. If you place mouse directly above either of the two points next to the "bump" but at the height of the bump, the tooltip snaps to the bump on chart but to the lower points on stockChart.
when hovering near the points from both series at the same x-value, stochChart tooltip shows both series whereas chart tooltip only shows the series whose nearest point is closer - I much prefer the latter as I want the tooltip to tell me which series the nearest point belongs to.

Update 2 I asked the same question at Highcharts support page, and was pointed to the solution. Adding tooltip: {shared: false} solves both of my issues stockChart v2.

A:

Set Series.findNearestPointBy option to 'xy'.
From API:

findNearestPointBy: String
Determines whether the series should look for the nearest point in
  both dimensions or just the x-dimension when hovering the series.
  Defaults to 'xy' for scatter series and 'x' for most other series. If
  the data has duplicate x-values, it is recommended to set this to 'xy'
  to allow hovering over all points.
Applies only to series types using nearest neighbor search (not direct hover) for tooltip.
src: http://api.highcharts.com/highcharts/plotOptions.area.findNearestPointBy

example: http://jsfiddle.net/gh/get/library/pure/highslide-software/highcharts.com/tree/master/samples/highcharts/series/findnearestpointby/


Q:

Как просуммировать списки разных размеров?

def suma(x,y):
    i = 0
    z=[]
    while i< len(x)<len(y):
        z.append(x[i]+y[i])
        i+=1
    return z

print(suma([1,2,3],[1,2,3,4]))

A:

воспользуйтесь функцией itertools.zip_longest():
from itertools import zip_longest

res = [a+b for a,b in zip_longest(x, y, fillvalue=0)]

результат:
In [58]: res
Out[58]: [2, 4, 6, 4]


Q:

Какую среду разработки стоит взять начинающему в C#?

Среда нужна для ознакомительных целей: посмотреть на язык и сопутствующие библиотеки.

A:

Стоит загрузить и установить Visual C# 2010 Express. Из плюсов:

эта IDE доступна для свободного скачивания с сайта Microsoft;
есть локализанная версия на русском языке.

A:

Лучше установи Visual Studio 2010 C# + ReSharper 2010.
Сама студия как IDE будет на родном языке и помогать с синтаксисом и командами Решарпер.

A:

Если только для ознакомления с языком и библиотеками - возьми любую доступную для тебя visual studio начиная с 2008.


Q:

Why GCP Pricing Calculator Interface is not showing completely?

I'm trying to use the GCP pricing calculator but when the page is loaded I'm unable to view the entire interface to use the calculator. The only bottom part of the page is showing completely.
I've tried loading the page with and without sign-in, even loaded in incognito window but the problem is same. What I'm getting every time on loading the GCP pricing  calculator can be found in this image link:

What's the solution to this problem?

A:

This is not really a solution but I can not comment due to low point ;(
You can try this link rather than this link
From console message this seems to be possibly related with ISP.
I could not produce this in any browser in my pc though (ubuntu18.04, chrome81.0.4044.122 (Official Build) (64-bit), firefox75.0), except slow loading of the app while using this link to access.


Q:

Is the tag word-difference useful since we already have the tag difference?

I saw that we have both word-difference and difference.

Is word-difference useful since we already have difference?

A:

Actually, to me it seems that difference is too broad to be useful; I am not sure word-difference is useful too. At least the latter seems to suggest it applies to words, but in both the cases, they are not defining exactly what difference the tags are for.
word-choice is much more useful, IMO, since it says the question is about which word should be used in a specific context; in other words, it specifies to which difference the OP is interested.

A:

It looks like there isn't enough interest in the merge to do it or kill it, so we'll just keep things the way they are.
The tag difference is used three times more than word-difference. In my opinion, word-difference doesn't have a meaningful distinction from difference and the tags should be merged.
The description of word-difference is:

For questions about differences in meaning or use between related words or words with similar meanings.

The description of difference is:

This tag is for questions about the difference in meaning between certain words, or phrases.

I think we should rewrite the description of the difference tag to be:

For questions about differences in meaning or usage between words or phrases with similar meanings.

If you agree that word-difference should be merged into difference, up-vote this answer. If you disagree, please leave a comment or answer explaining why and down-vote this answer.


Q:

Find and remove nested level

I want to find and remove the value, where my id is "5cc6d9737760963ea07de411"
my data:
[
    {
        "products" : [ {
                    "id" : "5cc6d9737760963ea07de411",
                    "quantity" : 1,
                    "totalPrice" : 100,
                },
                {
                    "id" : "5cc6d9737760963ea07de412",
                    "quantity" : 2,
                    "totalPrice" : 200,
                }
        ],
        "isCompleted" : false,
        "_id" : "5cc7e4096d7c2c1f03570a2f"
    },
    {
        "products" : [{
                    "id" : "5cc6d9737760963ea07de414",
                    "quantity" : 1,
                    "totalPrice" : 100,
                },
                {
                    "id" : "5cc6d9737760963ea07de4133",
                    "quantity" : 2,
                    "totalPrice" : 200,
                }
        ],
        "isCompleted" : false,
        "_id" : "5cc7e4096d7c2c1f03570a2f"
    }

]

i tried:
Schema.findOneAndUpdate({"products.id": "5cc6d9737760963ea07de411"},
{ $pull:  {"products.$.id": "5cc6d9737760963ea07de411"  })

but it's not working.

A:

Now you don't need to use .dot notation. Instead you need to use "absolute" object structures:
Schema.findOneAndUpdate(
  { "products.id": "5cc6d9737760963ea07de411" },
  { "$pull": { "products": { "id": "5cc6d9737760963ea07de411" }}}
)


Q:

The device, \Device\Ide\iaStor0, did not respond within the timeout period

On my Windows Server 2008 R2 Enterprise system I have a bunch of hard drives. The disk mode is set to 'RAID' in bios and I have 2 disks set as RAID 1. I also have a couple of other disks without any raid to store other data.
On random occasions a certain drive (always the same one) disconnects with the following event entry:

The device, \Device\Ide\iaStor0, did not respond within the timeout period

I have the latest Intel Rapid Storage software, I tried disabling LPM, switching cable, switching sata port but without any results. Does anyone have another suggestion for me?
Hardware:

Motherboard: Asus P8H67-M PRO
Disk: Samsung HD154UI

EDIT
Apparently this disk had a ATAPI standard instead of an ATA standard. So it might nog have supported all the AHCI functions. Enabling hotswap in the bios DID solve the problem (I think) but I have swapped the disk with an ATA one to get the system fully stable for sure.

A:

Try enabling hot plug in the bios for the drives.
"Asus H67/P67 owners: Asus has confirmed that hot-swapping should be set to enabled for most drive configurations, especially SSDs. Because of the number of issues reported using SSDs or newer model conventional drives the default setting will most likely be set to enabled in a future BIOS release across all platforms."
http://www.ocztechnologyforum.com/forum/showthread.php?87197-SOLVED-Vertex-3-Huge-Windows-freezes-due-to-iaStor0-device-problem


Q:

Record sound and play simultaneously in iphone SDKs programmatically

How to record sound and play simultaneously in iphone SDKs programmatically? If anybody have links and source code then please help me. Thank You very much in advance!

A:

Check out this sample from Apple.
http://developer.apple.com/library/ios/#samplecode/aurioTouch/Introduction/Intro.html
It should get you started.


Q:

SQL2005 vs SQL2008

We are investigating replacing an existing SQL2000 server on Windows2003 (32Bit) with new hardware and a newer version.
We are looking at an application that requires at least SQL2005, but will run on SQL2008 as well.  Our other DB's should run on either as well.
Has anyone had any experiences good or bad with either version?
The Hardware we are likely to get will be 64bit capable, so running SQL2008 64 bit is an option as well.
Thanks

A:

They're both rock-solid.  If you have the choice, go straight to SQL Server 2008 - there are improvements with each release, and even if you're one of the sort of folks that like to wait until a service pack is released before installing an application, SQL Server 2008 SP1 has been out for over a month now.
Here is a directory of the new features in SQL Server 2008.  Also inherent in every release (but harder to spot) are improvements to the storage engine that enable SQL Server to perform more optimally and reliably.

A:

You should have no trouble transferring databases from SQL2000 to 2005 or 2008, but you will be wanting to do a proper test of the applications before doing so in a live environment (just in case).
I have no experience of SQL2008 yet, but we have moved many DBs from 2000 to 2005 with only one small issue with some code in an old app. That issue was due to how some views were defined/called in that project. If a view defines a field like "SELECT [somefield]=NULL, [and], [the], [rest] FROM [sometable]" then the app running "SELECT * FROM [theview] WHERE [somefield]='value'" would cause a cast-of-varchar-to-int error sometimes (but not in all cases) in SQL2005 where it never did in SQL2000. The simple solution was to change the view to [somefield]=CAST(NULL AS NVARCHAR). You probably won't run into this particular issue, and we've had no others, but it proves the point that you need to do a full application test in a dev/test environment before making the jump for a live service.
We have moved DBs from 32 bit SQL2005 to 64 bit SQL2005 servers without any issues at all, and I expect going from 64 back to 32 would work just as well.
Take note though that once moved to SQL2005 moving a database back to SQL2000 is a considerable pain so to labour my main point make sure you test thoroughly before moving your own apps. Also make sure you get clear written word from any external vendors involved that their DBs/code have been tested against the version of SQL Server you select.
Edit: one other relevant point: our apps we have moved this way do not make use of extra services like full-text indexing, reporting services, and so on - just the main SQL database service - so I can't comment on whether apps that use such extra features migrate smoothly or not.

A:

Talk to your application vendor. If they can't tell you, I'd do a pilot test on SQL Server 2008 and see if it works. Odds are good it will. (And say nasty things to your vendor for not know what platforms their application will work on.)


Q:

Vim plugin for adding external links

Now, this may be something obvious and already solved and known to everyone, but I just thought of it, so have mercy ...
Is there a Vim plugin for (when writing markdown texts) that enables you to insert links in a way that Ctrl-L in here (StackOverflow) does it. Or something similar to it.
For example, I write in a link, http://www.google.com, press Ctrl-L, and it moves that link to the bottom of the page replacing it with [description][28] where 28 is the current (increase by one from last) identifier.
Anyone? Anything similar?

A:

I use a custom macro to insert links from the system clipboard (Tested with Vim 7.3 on OS X and Windows, should work with Linux, too) and use formd to convert the resulting inline-style links to reference-style when I see fit.
I got these macros in my .vimrc:
" Create a Markdown-link structure for the current word or visual selection with
" leader 3. Paste in the URL later. Or use leader 4 to insert the current
" system clipboard as an URL.
nnoremap <Leader>3 ciw[<C-r>"]()<Esc>
vnoremap <Leader>3 c[<C-r>"]()<Esc>
nnoremap <Leader>4 ciw[<C-r>"](<Esc>"*pli)<Esc>
vnoremap <Leader>4 c[<C-r>"](<Esc>"*pli)<Esc>

And use these to invoke formd which lives in my ~/bin/ folder:
" Use formd to transfer markdown from inline to reference links and vice versa
" see: http://drbunsen.github.com/formd/
nmap <leader>fr :%! ~/bin/formd -r<CR>
nmap <leader>fi :%! ~/bin/formd -i<CR>

So, I just copy the needed link, navigate to the word (or use visual mode to select more words) to turn into a link and hit ,4. If I know I'll link a word or selection but don't have the URL yet, I hit ,3 and the macro inserts the needed parentheses empty.
Hitting ,fr produces the reference-style. If needed, ,fi returns to inline-style links.


Q:

Android what widget is this

Check the integer spinner in the picture. Can someone tell me what widget it is?

A:

That would be a NumberPicker.
Note that you can use uiautomatorviewer to examine the UI of a running application and learn what widgets are used.


Q:

Java: Detect if image isGIF or isTIFF and convert to JPG

I have a Java website, now Ive build an uploader, the validation for JPG images is done and a way to save it into the server it is too.
But now I need to create an utility class using isGIF and isTIFF validated them by byte[] and convert that byte[] to java.awt.Image to save as JPG
So basically I need boolean isGIF(byte[]), boolean isTIFF(byte[]), java.awt.Image convertGIF(byte[]) and java.awt.Image convertTIFF(byte[]).
But I have no idea how to do it, could someone help me please?
Thank you!

A:

You could consider using mime-utils. It basically gives you the mime type for a given byte[] or stream source using the same detection that the unix file command uses.
http://www.medsea.eu/mime-util (seems to be unavailable currently, try looking at the google cache for info).
You could also consider simply parsing every image using ImageIO.read and then rewriting them all using ImageIO.write. This will work for jpeg images too, althogh it isn't totally efficient. It would be an appropriate solution if you wanted to scale, crop or watermark your images at the same time. Since this is web submitted data, there is a certain argument for attempting to parse the file as image to make sure that it really is an image, and not a malicious file type.
ImageIO is smart so you don't have to know what type the data is to begin with. And it will through an exception if the data is malformed, so this makes sure that your image data is valid.
JPEG files apparently start with 0xFFD8, so you can just check for that in your code.
For example, to simply recode every image that doesn't look like a jpeg:
byte[] bytes = new byte[1024]; //your input
byte[] result = bytes;
if( bytes[0] != 0xFF || bytes[1] != 0xD8 )
{
    BufferedImage image = ImageIO.read( new ByteArrayInputStream( bytes ) );
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ImageIO.write( image, "jpeg", baos );
    result = baos.toByteArray();
}


Q:

ナビゲーションバーに画像をボタンとして追加し、動作させないまま半透明にもしない方法

ナビゲーションバーの右端にアイコンのように画像を貼り付けたいです。
今考えられる実現方法としては、iPhoneアプリのアイコンに使用する
画像をボタンとして下記のコードに組み込むことです。
- (void)viewDidLoad {
    [super viewDidLoad];

    // ナビゲーションバー右端にボタンの追加及び設定
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    [button setImage:[UIImage imageNamed:@"Icon-Small@2x.png"] forState:UIControlStateNormal];
    [button sizeToFit];
    [button addTarget:self action:@selector(hoge) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:button]; //右側に設定する場合

    button.enabled = NO; // disableに設定。これで押せなくなる。
}

画像（ボタンとしてですが）が追加され、ボタンとしての挙動もしなくなりましたが、
enabledにした為にアイコン画像が半透明になってしまいました。
ボタンとしての挙動をさせず、かつ、アイコン画像を半透明にしない方法を
ご教示いただけないでしょうか。以上、何卒よろしくお願いいたします。

A:

- (void)viewDidLoad {
    [super viewDidLoad];

    // ナビゲーションバー右端にボタンの追加及び設定
    UIImage *anImage = [UIImage imageNamed:@"Icon-Small@2x.png"];
    UIImageView *imageView = [[UIImageView alloc] initWithImage: anImage];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView: imageView]; //右側に設定する場合
}

わざわざボタンを持ってくることはないと思います。ご確認ください。
ただ、ナビゲーションバーにある「なにか」をタップしても、なにも起こらないというのは、ユーザインターフェイスとしては、まずいと思うのですが、いかがですか？自己満足なアプリ、ユーザに不親切なアプリは、Appleの審査でリジェクトされる可能性があります。


Q:

How to build rs fie in AndroidStudio

I am using AndroidStudio. I want to develop with RenderScript, when I create a file hello.rs and build the project，then I try to use ScriptC_hello in java file,but the compiler cannot
find ScriptC_hello class，I think ScriptC_hello.class did not create，but how to create it?

A:

Make sure your .rs file is in the app/src/main/rs directory in your project.  Unlike Eclipse based projects, all your .rs files need to reside here by default rather than alongside the Java files from the same package.


Q:

JavaFx TextArea Prompt Text

I am trying to get the TextArea's prompt text to display in a certain format. I am able to achieve the format I want, but it requires me to add lots of white space between text. I was thinking \n would do the trick, but it did not. Is there a way to get to the prompt text to go to the next line without wrapText="true" and lots of white space?
<?xml version="1.0" encoding="UTF-8"?>

<?import de.jensd.fx.glyphs.fontawesome.FontAwesomeIconView?>
<?import javafx.geometry.Insets?>
<?import javafx.scene.control.Button?>
<?import javafx.scene.control.Label?>
<?import javafx.scene.control.TextArea?>
<?import javafx.scene.control.TextField?>
<?import javafx.scene.layout.HBox?>
<?import javafx.scene.layout.StackPane?>
<?import javafx.scene.layout.VBox?>
<?import javafx.scene.text.Font?>

<VBox alignment="TOP_CENTER" maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="400.0" prefWidth="600.0" spacing="10.0" xmlns="http://javafx.com/javafx/8.0.141" xmlns:fx="http://javafx.com/fxml/1" fx:controller="ez_proxy_2.toolbar_buttons.AddStanzaController">
    <children>
        <StackPane>
            <children>

                    <padding>
                        <Insets top="10.0" />
                    </padding>

                <FontAwesomeIconView fx:id="faQuestionMark" glyphName="QUESTION_CIRCLE" size="32" StackPane.alignment="CENTER_RIGHT">
                    <StackPane.margin>
                        <Insets right="10.0" />
                    </StackPane.margin>
                </FontAwesomeIconView>
            </children>
        </StackPane>
        <TextField fx:id="tfTitle" alignment="CENTER" promptText="Enter Title Here">
            <VBox.margin>
                <Insets left="20.0" right="20.0" />
            </VBox.margin>
        </TextField>

        <TextArea fx:id="taStanzaInfo" promptText="Title Fake Title                                                                                URL https://www.example.com                                                                                HJ www.example.com                                                                                DJ example.com" wrapText="true">
            <VBox.margin>
                <Insets left="20.0" right="20.0" />
            </VBox.margin>
        </TextArea>
        <Button fx:id="btnOff" mnemonicParsing="false" onAction="#handleBtnOff" prefHeight="25.0" prefWidth="52.0" text="Off" />
        <HBox alignment="CENTER_RIGHT" prefHeight="100.0" prefWidth="200.0" spacing="10.0">
            <children>
                <Button fx:id="btnExit" mnemonicParsing="false" onAction="#handleBtnExit" prefHeight="25.0" prefWidth="52.0" text="Exit" />
                <Button fx:id="btnAdd" mnemonicParsing="false" onAction="#handleBtnAdd" prefHeight="25.0" prefWidth="52.0" text="Add" />
            </children>
            <VBox.margin>
                <Insets left="20.0" right="20.0" />
            </VBox.margin>
        </HBox>
    </children>
</VBox>

A:

You can try using XML syntax for \r\n -
 (in my test example, for some reason, just
 doesn't work for promptText attribute, but it works fine with text):
<TextArea promptText="Title Fake Title
URL https://www.example.com
HJ www.example.com
DJ example.comButton" />


Q:

regex awk match between pattern, skipping first occurrence of endpat

I have a problem. I want to match lines between two patterns, inclusive. I can do that. Let's say this is what I've got:
art
subject

Course Material
paint
brush
easel
beret

art

Skills learned
oil
pastel
ink
chalk

math
subject

Course Material
book
calculator
etc...

I'll use the standard  awk '/^art/ , /subject/' file  and get
art
subject

art

Skills learned
oil
pastel
ink
chalk

math
subject

This is the best I can do. The problem is that it cuts the art description into two parts.  The question I have is:

How do I use the first art match, skip the first discipline match and then use the second discipline match?

A:

This code seems to work as desired, but I can't help feel that it would be better to create a more easily parsed output format.
script.awk
/art/       { print; art++; next }
/subject/   { if (art < 3 && subject < 2) { print; subject++ } next }
            { if (art < 3 && subject < 2) print }

If the line contains art, print it and increment the 'art' count, and jump to the next line.  If the line contains 'subject' — then if the art count is less than 3 and the subject count is less than 2, print the line and increment the subject count, and jump to the next line.  Otherwise, if the art count is less than 3 and the subject count is less than 2, print the line.
Sample run
$ awk -f script.awk data
art
subject

Course Material
paint
brush
easel
beret

art

Skills learned
oil
pastel
ink
chalk

math
subject
$

This code is a little too well attuned to the sample data.
The 'art < 3' conditions should be 'art > 0 && art < 3'.  You also want to be able to choose the keywords.
BEGIN       { kw1 = "art"; kw2 = "subject" }
$1 ~ kw1    { print; nkw1++; next}
$1 ~ kw2    { if (nkw1 > 0 && nkw1 < 3 && nkw2 < 2) { print; nkw2++ } next }
            { if (nkw1 > 0 && nkw1 < 3 && nkw2 < 2) print }

And it would be nice to eliminate the math and subject lines at the end too.  For that, we need a more complex script that saves a line before printing it, remembering that the blank lines need printing too.
Revised script.awk
BEGIN       { kw1 = "art"; kw2 = "subject" }
$1 ~ kw1    { old = $0; nkw1++; next}
$1 ~ kw2    { if (nkw1 > 0 && nkw1 < 3 && nkw2 < 2)
              { if (nkw2 == 0) print old; old = $0; nkw2++ }
              next
            }
            { if (nkw1 > 0 && nkw1 < 3 && nkw2 < 2) { print old; old = $0 } }

Extended data file
english
subject

Course material
To Kill a Mockingbird
To Set a Watchman
Huckleberry Finn
Tom Sawyer

english

Skills learned
comprehension
dialectical analysis

art
subject

Course Material
paint
brush
easel
beret

art

Skills learned
oil
pastel
ink
chalk

math
subject

Course Material
book
calculator
etc...

Revised sample output
$ awk -f script.awk data
art
subject

Course Material
paint
brush
easel
beret
art

Skills learned
oil
pastel
ink
chalk

$

The revised script will only print out the first art block.  If there are other such blocks in the file, they are not printed (but no superfluous material is printed either).
You could arrange for the keywords to be passed to the script by revising the BEGIN block to check that kw1 and kw2 were set on the command line, for example, with:
awk -v kw1=art -v kw2=subject -f script.awk data


Q:

md-nav-bar not rendering, only showing plain text

I have a problem with the Angular Material directive "md-nav-bar". It is not rendering in my code. I tried copying various working pieces of code, but I didn't manage to get it running.
HTML

<md-content layout="row">
    <md-toolbar class="md-hue-2">

            <md-button class="md-icon-button" aria-label="Home" href="#/welcome">
                explore
            </md-button>

                md-nav-bar Test

            <md-button class="md-icon-button" aria-label="Coontact Us" href="mailto:info@osterdach.de">
                email
            </md-button>
            <md-button class="md-icon-button" aria-label="Call Us" href="tel:+4915732224836">
                phone
            </md-button>

    </md-toolbar>
</md-content>

<md-content>
    <md-nav-bar md-selected-nav-item="currentNavItem" nav-bar-aria-label="navigation links">
        <md-nav-item md-nav-href="#/holzbau" name="page5">Holzbau</md-nav-item>
        <md-nav-item md-nav-href="#/dach" name="page5">Dach</md-nav-item>
      <md-nav-item md-nav-href="#/fassade" name="page5">Fassade</md-nav-item>
      <md-nav-item md-nav-href="#/erhaltUndEnergie" name="page5">Erhalt und Energie</md-nav-item>
    </md-nav-bar>
</md-content>

<md-content>

The Routing is working properly, so I am not including it completely here!

    Holzbau |
    Dach |
    Fassade |
    Erhalt und Energie
</md-content>

<md-content ng-view layout="row" layout-align="center"></md-content>

app.js
var app = angular.module("app", ["ngRoute", "ngMaterial"]);

/* ROUTING & THEMING */
app.config(function ($mdThemingProvider, $routeProvider) {

    /* ROUTING */
    $routeProvider
        .when("/holzbau", {
            templateUrl : "views/holzbau.html"
        })
        .when("/dach", {
            templateUrl : "views/dach.html"
        })
        .when("/fassade", {
            templateUrl : "views/fassade.html"
        })
        .when("/erhaltUndEnergie", {
            templateUrl : "views/erhaltUndEnergie.html"
        })
        .when("/welcome", {
            templateUrl : "views/welcome.html"
        })
        .otherwise({
            templateUrl : "views/welcome.html"
        });
    /* END ROUTING */

    /* THEMING */
    var customPrimary = {
        '50': '#3defff',
        '100': '#24ecff',
        '200': '#0aeaff',
        '300': '#00dcf0',
        '400': '#00c4d6',
        '500': '#00ADBD',
        '600': '#0096a3',
        '700': '#007e8a',
        '800': '#006770',
        '900': '#005057',
        'A100': '#57f1ff',
        'A200': '#70f3ff',
        'A400': '#8af5ff',
        'A700': '#00383d'
    };
    $mdThemingProvider
        .definePalette('customPrimary',
            customPrimary);

    var customAccent = {
        '50': '#68070b',
        '100': '#80090d',
        '200': '#970b10',
        '300': '#af0c12',
        '400': '#c70e15',
        '500': '#df1017',
        '600': '#f13138',
        '700': '#f2494f',
        '800': '#f46166',
        '900': '#f6787d',
        'A100': '#f13138',
        'A200': '#EF1921',
        'A400': '#df1017',
        'A700': '#f79094'
    };
    $mdThemingProvider
        .definePalette('customAccent',
            customAccent);

    var customWarn = {
        '50': '#949eb6',
        '100': '#8590ab',
        '200': '#7582a1',
        '300': '#677496',
        '400': '#5c6987',
        '500': '#525D78',
        '600': '#485169',
        '700': '#3d465a',
        '800': '#333a4b',
        '900': '#292e3b',
        'A100': '#a3abc0',
        'A200': '#b2b9ca',
        'A400': '#c1c7d5',
        'A700': '#1e222c'
    };
    $mdThemingProvider
        .definePalette('customWarn',
            customWarn);

    var customBackground = {
        '50': '#ffffff',
        '100': '#ffffff',
        '200': '#ffffff',
        '300': '#f4fbfb',
        '400': '#e1f5f4',
        '500': '#CEEEED',
        '600': '#bbe7e6',
        '700': '#a8e1df',
        '800': '#95dad8',
        '900': '#82d4d1',
        'A100': '#ffffff',
        'A200': '#ffffff',
        'A400': '#ffffff',
        'A700': '#6fcdca'
    };
    $mdThemingProvider
        .definePalette('customBackground',
            customBackground);

    $mdThemingProvider.theme('default')
        .primaryPalette('customPrimary')
        .accentPalette('customAccent')
        .warnPalette('customWarn')
        .backgroundPalette('customBackground')
    /* END THEMING */

});
/* END app.config */

app.controller("MainController", function($scope, $route) {

});

See this Pen with my code: http://codepen.io/anon/pen/pbBOdv

A:

You need to load the Angular Material CSS file and update the JS file - CodePen
CSS: https://cdn.gitcdn.link/cdn/angular/bower-material/v1.1.0/angular-material.css
JS: http://ajax.googleapis.com/ajax/libs/angular_material/1.1.0-rc.5/angular-material.min.js
You also need to make the name of each md-nav-item unique:
<md-nav-item md-nav-href="#/holzbau" name="page1">Holzbau</md-nav-item>
<md-nav-item md-nav-href="#/dach" name="page2">Dach</md-nav-item>
<md-nav-item md-nav-href="#/fassade" name="page3">Fassade</md-nav-item>
<md-nav-item md-nav-href="#/erhaltUndEnergie" name="page4">Erhalt und Energie</md-nav-item>


Q:

loadMovie issue actionscript 2

Has anybody ever had any issues with loadMovie in as2?
I have inherited some horrific code and need to solve an issue, if you imagine a gallery and clicking back and forward would call loadMovie and get the URL address from an array, each time the back and forward buttons are pressed the number is increased and references to a different image url in the array - pretty straight forward stuff.
For some reason when I load the image for the first time, it's fine after that loadMovie refuses to work, even any requests to get an image doesn't trigger. Has anybody had this problem before?
Here's a short example:
var currentImage:Number = 0;
load_image(currentImage);
function load_image(_num:Number):Void {
  container.loadMovie(images[_num].img);
  trace('loading ====== ' + images[_num].img);
}
next_btn.onRelease = function():Void {
  currentImage ++;
  load_image(currentImage);
}
prev_btn.onRelease = function():Void {
 currentImage --;
 load_image(currentImage);
}
It's seriously weird and I haven't experienced it before. I wouldn't mind guessing that some of the code in the side is interferring with it. If anybody has any suggestions, that would be great. I'm open to any ideas!
Thanks in advance!
Will

A:

I've tested your code - these's no definition included for images, so I have assumed the following:
var images:Array = new Array({img:"0.jpg"}, {img:"1.jpg"}, {img:"2.jpg"});

... and it works fine for me, so perhaps the problem is in another area of the code?
Also, currentImage -- and currentImage ++ don't protect against running into invalid values (eg currentImage = -1), is this a problem for you?


Q:

Getting A Garbage Value In Bubble Sorting for the Highest Value in C

I am facing a problem that the Highest value in the array is getting replaced by a random garbage negative value. I am not able to locate the problem. Here is the full source code to the program -
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>
#include<conio.h>

int main()
{
int num[10],i,choice,counter=1;
printf("\n\n=====Program To Sort Integer Array=====\n\n");
printf("\nPlease Enter 10 Array Elements = \n");
for (i = 0; i < 10; i++)
{
    printf("\nPlease Enter The %d Element Of The Array\n", i);
    scanf("%d", &num[i]);

}
printf("\n\nHow Would You Like To Sort The Entered Array?\n1. Bubble Sort\n2. Selection Sort\n3. Insertion Sort\n\n");
scanf("%d", &choice);
switch (choice)
{
case 1:{

           printf("\nYou Have Selected Bubble Sort\n");
           while (counter != 0)
           {
               counter = 0;
               for (i = 0; i < 10; i++)
               {

                   if (num[i]>num[i + 1])
                   {
                       int temp=0;
                       temp = num[i];
                       num[i] = num[i + 1];
                       num[i + 1] = temp;
                       counter++;
                       break;
                    }
               }
           }
           printf("\n\nThe Array In Ascending Order Is =\n");
           for (i = 0; i < 10; i++)
           {
               printf("\n%d", num[i]);
           }

           break;
}
default:
    break;
}
_getch();
}

The array is getting sorted partially but the highest number is getting replaced. Also, I am using Visual Studio.
Thanks In Advance

A:

for (i = 0; i < 10; i++)
{
    if (num[i]>num[i + 1])
    {
        int temp=0;
        temp = num[i];
        num[i] = num[i + 1];
        num[i + 1] = temp;
        counter++;
        break;
    }
}

What happens here when i gets to 9? You compare num[9] and num[10] - the 10th and 11th elements.
I'll assume you already know what happens if you try to access an out-of-bounds array element. If the out-of-bounds value happens to be greater than num[9], you swap it with num[9] - so now the array has a garbage value, and you just overwrote that wasn't part of the array.
Solution: change i < 10 to i < 9. There are only 9 pairs of elements to check (0/1, 1/2, 2/3, ..., 8/9).


Q:

who owns and is responsible for the truck?

My husband's ex girlfriend signed a loan for him to purchase a vehicle before we got married. Since then, he has continued paying on the vehicle the entire time we have been married. He is now in jail. Do I have the rights to the vehicle. Should I be making the payments? Or does she still legally own the vehicle and is held responsible? (My husband and I have been married for 4 years in which he has been the one making the payments.) Also, due to him being in jail, if we proceed with a divorce, will the truck be an asset in the divorce hearing?

A:

Whoever signed the loan owes the money to the bank for the truck. So, in this case it is probably both your husband and his ex girlfriend.
Whoever is listed on the title of the vehicle as the registered owner has the full exclusive use of the vehicle. That is probably your husband.
Any person who co-signed for a loan owns nothing and has rights to nothing. Co-signing a loan just means that the signer agrees to pay off the loan. In this case the girlfriend does not, nor has ever owned the vehicle.
If payments are not made on the vehicle, the owner of the loan (probably a bank) will repossess the vehicle and take ownership of it. At that point they will become the registered owner.
Your main options are:

Refinance the car. You take your own loan and buy out your husband and his girlfriend. Both of them and the bank would have to agree to this. You would become the registered owner of the car.
Make a set-off agreement. In this case, you offer your husband a deal: you will make the payments on the car, if you get the use of the car and a percentage of the sale price in the event the car is sold.
Try to get a judge to award you the car in the divorce. In this scenario, the judge would order that you become the registered owner of the car, but the girlfriend and your husband would still be responsible for paying the loan. The risk here is that both will default on the loan and the car will get repossessed.


Q:

Check if user exists and return user + roles EF6

I'm trying to figure out how can i retrieve roles with Any and check if user exists on the same query and return as SingleOrDefault() but doesn't seem to work.
private User Authenticate(LoginViewModel model)
{
     using (HutLogisticaContext context = new HutLogisticaContext())
     {
         return context.Users.Where(u => u.Username.Contains(model.Username)).SingleOrDefault();
     }
}

However it won't let met add single or default if i add Any. How can i do both on same query?
EDIT
I forgot to mention but I want to return the user object with all the roles related to it, not sure if it's possible without navigation property because i could not use include
public class Role
{
    public int Id { get; set; }
    public string Nome { get; set; }

    public ICollection<User> Users { get; set; }
    public ICollection<Claim> Claims { get; set; }
}

public class User
{
    public int Id { get; set; }
    public string Username { get; set; }
    public DateTime? DataSessao { get; set; }
    public bool IsActivo { get; set; }

    public virtual Colaborador Colaborador { get; set; }

    public ICollection<Role> Roles { get; set; }
    public ICollection<App> Apps { get; set; }
}

i'm using EF 6 so this created automatically the join table with UserId and RoleId as PK and FK

A:

After the long discussion on chat the below code works for OP.
private User Authenticate(LoginViewModel model)
{
    using (HutLogisticaContext context = new HutLogisticaContext())
    {
        return context.Users
                      .Include(u => u.Roles)
                      .Where(u => u.Id == 123)
                      .SingleOrDefault();
    }
}


Q:

How to screen record using AppleScript on Catalina?

So I've been using a script before I updated to Catalina that worked fine for screen recording. It's based on another user's SE question, but ever since the update, it looks like there is a new step.
Basically, you tell "QuickTime Player" to start (new screen recording).
But instead of a screen recording starting, it just opens a new menu which lets you select some settings, or click the screen to record using the last used settings.
I've tried using System Events to click to screen, even after a 1s delay, but it's not working.
Anyone know how to either:
1) Bypass the new menu and just start recording right away
2) Start recording once the menu has popped up (System Events doesn't detect window 1, so I'm not even sure how to navigate the UI)
3) Click the screen/UI using System Events
* Update to question *
I've edited my AppleScript code since user3439894 wrote a response. It seems to work for what I've asked. The only problem now is that I'm not sure how to save to file to a specific path. Below, I've added some code snippets of what I currently have since making edits (it just saves the screen recording to the Desktop based on the date for the time. Below that, I have my original code which saves it on the Desktop as test.mov.
My code now, after edits
1) Starting recording
tell application "QuickTime Player" to activate
tell application "QuickTime Player" to start (new screen recording)
tell application "System Events" to tell process "Screen Shot"
  repeat until exists its front window
    delay 0.1
  end repeat
  if not (exists button "Record" of its front window) then
    click checkbox "Record Entire Screen" of its front window
  end if
  click button "Record" of its front window
end tell

2) end recording
tell application "System Events" to click menu bar item 1 of menu bar 1 of application process "screencaptureui"

My Code Before Edits
3) Old way I used to start my recording before Catalina for screen recording (still works for webcam (aka Movie) recording)
tell application "QuickTime Player" to activate
tell application "QuickTime Player" to start (new screen recording)

4) Old way I used to stop and save my screen recording that doesn't work in Catalina
set filePath to "Users:mini:Desktop:test.mov"
set f to a reference to file filePath
tell application "QuickTime Player"
  pause document "screen recording"
  save document "screen recording" in f using settings preset "1080p"
  stop document "screen recording"
  close document "screen recording"
end tell

A:

Without seeing your AppleScript code, all I can say is that for me, as an example, on macOS High Sierra doing a screen recording requires different coding then on macOS Catalina, as the latter no longer actually uses QuickTime Player to do the actual screen recording.
This may also hold true for macOS Mojave, however, the following example AppleScript code was only tested under macOS Catalina:
--  # Setup to do a screen recording.

tell application "QuickTime Player" to new screen recording

--  # Start the screen recording.

tell application "System Events" to tell process "Screen Shot"
    repeat until exists button "Record" of its front window
        delay 0.1
    end repeat
    click button "Record" of its front window
end tell

--  # Set the time in seconds you want the recording to be.

delay 2

--  # Stop the recording.

tell application "System Events" to ¬
    click menu bar item 1 ¬
        of menu bar 1 ¬
        of application process "screencaptureui"

At this point, by default, when the screen recording is stopped, it is saved to the Desktop as e.g. Screen Recording 2019-11-01 at 3.38.00 PM.mov on my system and opened in QuickTime Player.
Additional coding can be included to do whatever else one would like to do with the screen recording (within the limits of the target app and AppleScript).
That all said, since macOS Catalina is actually using a different application to do the actual screen recording and not QuickTime Player, one could skip the use of QuickTime Player and create the screen recording using the following example AppleScript code, which uses the system default keyboard shortcut ⇧⌘5:
--  # Setup to do a screen recording.

tell application "System Events" to keystroke "%" using {shift down, command down}

--  # Start the screen recording.

tell application "System Events" to tell process "Screen Shot"
    repeat until exists its front window
        delay 0.1
    end repeat
    if not (exists button "Record" of its front window) then
        click checkbox "Record Entire Screen" of its front window
    end if
    click button "Record" of its front window
end tell

--  # Set the time in seconds you want the recording to be.

delay 2

--  # Stop the recording.

tell application "System Events" to ¬
    click menu bar item 1 ¬
        of menu bar 1 ¬
        of application process "screencaptureui"

Note the use of % instead of 5 in keystroke "%" as the shift key is pressed and I'm on a US English keyboard.
The usual caveats, regarding System Preferences > Security & Privacy > Privacy, apply.

Note: The example AppleScript code is just that and does not contain any additionally error handling as may be appropriate. The onus is upon the user to add any error handling as may be appropriate, needed or wanted. Have a look at the try statement and error statement in the AppleScript Language Guide. See also, Working with Errors.


Q:

How to give access to inactive user profile?

I guess the title is obvious. I have built a Drupal 7 website showing a view of the previous Users (inactive profiles).
As an admin, I can access these profiles but I need anonymous users to have that permission too (view "previous" or "old" members profiles).
Is there any module to add that kind of permission?
Thanks and sorry for my English ;)

A:

The View Profiles Permissions module will work for that purpose: https://www.drupal.org/project/view_profiles_perms.
In order for this to work, you will also need to give your blocked users a Role.
It is not the primary function of the View Profiles Permissions module, but there is more information about this specific issue here: https://www.drupal.org/node/2490934
Additionally, You can use the Rules module to automatically assign a role to users when they become blocked.
Steps:

Install and Enable the View Profiles Permissions module
Create a role called "Blocked"
Give permissions to anonymous users to "Access to Blocked profiles"
Assign the "Blocked" role to all users who are blocked (aka Inactive, Old, Disabled)
Extra Credit: Install/Enable the Rules module and a new Rule that automatically assigns the Blocked" role to users when they become blocked.


Q:

How to handle server responses with AngularJs $resource promises

I am starting to learn AngularJs.
Using AngularJs, I have the following factory called "datacontext" which exposes a function for getting a person resource with a specific id:
function datacontext($resource, common) {
    var $q = common.$q;
    var People = $resource('/api/people/:id', { id: '@id' });

    var service = {
        getPerson: getPerson
    };

    return service;

    function getPerson(id) {
        var p = People.get({ id: id });

        return $q.when(p);
    }
}

and inside my controller I use it as follows:
function getPerson(id) {
    return datacontext.getPerson(id).then(onSuccess, onError);

}
function onSuccess(data) {

    return vm.person = data;
}
function onError(data) {
    alert("A");
}

My service works by returning the correct resource for the particular id and returns a 404 not found if its not found.
In the code block above, its seems like it always calls the onSuccess callback even if there is a 404 response.
What am I doing wrong? Any help would be appreciated.

A:

Why you don't use $q service for promises? What about:
    function getPerson(id) {
        var defer = $q.defer();
        People.get({ id: id }, function() {
             //success
        },
        function(){
            //fail
        });
        return defer.promise;
}

Don't forget to inject $q to your service


Q:

Maximal ideal of ring of matrices

Let $R=M_n(\mathbb F_q )$ be the ring of $n\times n$ matrices over the finite field $\mathbb F_q$. I want to show that every matrix of rank $n-1$ in any maximal left ideal of $R$ generates that maximal left ideal.

I know that $R$ is semi-simple ring. I deduce that every ideal of $R$ was generated by idempotent element, but I don't know how do I use this fact.
Any suggestion?

A:

Finally, I found the solution of my question in Jacobson's book (page 232 of Lectures in Abstract Algebra). However Jacobson used old literature and I restate with modern literature.

Let $D$ be a division ring and n be a natural number. If $H_r$, $0 \leq r \leq n$, denotes the left ideal of $M_n(D)$ containing all matrices whose $d_{ij} = 0$, for every $r \leq j \leq n$, then every left ideal of $M_n(D)$ is similar to $H_r$, for some $r$, $0 \leq r
\leq n$ (there exists an invertible matrix $P$, so that every matrix in the left ideal of $M_n(D)$ is of the form $PKP^{−1}$, where $K\in H_r$).


Q:

How to structure my iOS code?

I have quite a complex setup, and am looking for advice in how to structure my code. What I'm trying to do is something similar to twitter when you press one of a users images and can swipe through them. This is what I have at the moment:

A UIViewController subclass that gathers data from a server, and passes it to a UITableViewController subclass through a variable called theData
This UITableViewController subclass also gathers more data as the users scrolls to the bottom of the table view and appends it to theData (i.e. uses pagination). This UITableViewController subclass is reused throughout the app so that data from a different source can be passed to it.
When a user clicks on a UITableViewCell, a UIWindow is created which has a UIPageViewController inside it. The window uses the UITableViewController as a delegate to access theData, and passes the theData from the delegate to the UIPageViewController in a variable called pageData
Each page of the UIPageViewController is a UIViewController that loads images from the pageData

The next stage is to do pagination as the user swipes to the end of the pageData in the UIPageViewController. However I don't think my code is structured well enough to reuse the pagination code from the UITableViewController. Please could someone give me advice on how to improve this code structure?
Thank you
EDIT
The UIViewController in the first bullet point does more than just downloading data (it has other views within it).
I use a UIWindow to encapsulate the UIPageViewController because I want it to expand from the frame of the UITableViewCell and "take over" the full screen - covering the status bar.

A:

My advice would be to create simple service which you can use for communication with the server. You don't need View controller for that.
Further more you can create static methods that will give you theData without passing it all over the application.
Regarding the swipe, you can take 3 users in an array, and corresponding to scroll, load additional one, and release unnecessary one. That would help you with memory usage ( if users swipes through 50 or more users ).
Instead of UIWindow, create simply segue from UITableViewController to DetailView, or in your situation, UIPageViewController.


Q:

How can I add a tag to a tag set?

Using CiviCRM 4.7.16. I create a new tag and I want to add it to a tag set. But when I click on the Parent Tag pull down menu, it only shows tags that have not been assigned to a set. Tag sets are not shown. This is the case when both creating a new tag and editing a tag. I can't see another way to add a tag to a tag set.
Is this a bug?

A:

You may be right that this is a bug in 4.7.16. Fortunately it has been solved in 4.7.17.
This release includes a redesigned tag management screen with numerous improvements.

Update: 4.7.17 has been released.


Q:

¿Por qué algunos miembros de aquí son arrogantes?

Soy miembro en esta comunidad y en ocasiones veo que algunos usuarios son bien criticones o arrogantes y no piensan que algunas preguntas son algo tonta para ellos porque para ellos es fácil o ya lo conocen pero no entienden que hay programadores que son nuevos y novatos y no conocen bien algunos conceptos o algún tema pero ahí van y los critican o algo parecido así obvio. Yo no rompo las reglas.

¿Y quién es el moderador en este sitio?

A:

Gilberto, me llamo la atención tu pregunta y quiero externar mi punto de vista acerca de esto, creo que esto forma parte de situaciones que varios de nosotros hemos experimentado en la vida, entiendo que en ocasiones para alguien puede ser molesto, para otros no tanto el recibir una critica, esto también dependiendo del tipo de critica la cual puede ser constructiva pero en otras ocasiones la critica tiene otra connotación muy diferente.
Como recomendación te sugiero enfocarte en el objetivo que es obtener información que te ayude a solucionar el problema que publicas en tu pregunta.
Poner atención a las personas que en verdad cumplen el objetivo de ayudarte y aprender de ellos. En cambio evitar discusiones con quien va a buscar un detalle para hacerte ver miles de detalles.
Mis sugerencias se basan en que soy alguien que en ocasiones desconozco muchas cosas, pero se que es muy importante preguntar, así sea algo muy básico, seguramente habrá quien considere risible o tonto como lo comentas, pero no te preocupes tal vez estas personas ya pasaron esta etapa que fue desgraciadamente de esta forma.

¿Qué es lo que siempre le has querido preguntar a una mujer o a un
  hombre y no te atreves? ... Si te quedas con la duda, nunca lo sabrás!

Solo recuerda que cuando tengas el conocimiento y veas que alguien pregunta algo que sea básico para ti,  trata de ayudarlo y no realices la misma conducta, mientras tanto cuando desconozcas algo no dejes de externar tus dudas para obtener el conocimiento.
Sigue aportando a la comunidad preguntando (tratando como ya lo han comentado otros compañeros de mejorar la calidad de las preguntas, agregar código de lo que hayas tratado o documentar fuentes que hayas tratado) y respondiendo, con esto aportas a que otros nuevos usuarios que tengan dudas encuentren la respuesta a lo que tu alguna vez buscabas.

A:

Tienes ejemplos de comentarios de lo que consideras rudos o arrogantes?
Lo adecuado es reportar ese contenido como Irrespetuoso u Ofensivo y si un usuario en particular es el que se comporta así, avisar a los moderadores.
Los moderadores son: Miquel Coll, Luiggi Mendoza y  Konamiman  (ya no lo es, es empleado de SO) y tienen un diamante ♦
En las preguntas tienes un boton de reportar. Le das a "se necesita la intervencion de un moderador" y explicas lo sucedido.
Nota: Recuerda que tambien tienes el chat para discutir temas e incluso invocar (con @) a usuarios.

A:

En el asunto de la arrogancia hay que considerar varias cosas.
SO es un sitio en que que tiene su cantidad significativa de informáticos como usuarios.
No es un secreto que informáticos no son exactamente famoso por sus habilidades sociales o diplomáticos. Eso no significa que no lo pueden tener, pero que no necesariamente se puede esperar que los tienen. Ten paciencia.
Arrogancia no siempre lo es.
Cada uno tiene su propia forma de comunicarse. Algunos tienen un sentido de humor excéntrico, otros simplemente no sienten que tienen tempo para ser amable, otros más tratan ser amable, pero alguien se ganó una medalla borrándoles todo que escribieron que podría haber suavizado un poco una crítica valida. Ten paciencia.
A nadie le pagan aquí
La gente que se toman el tiempo para responderte a tus preguntas lo hacen gratis. Eso no es una excusa para falta de cortesía, pero al otro lado es difícil de exigir dado las circunstancias. Ten paciencia y disfruta la gente que se toman el tiempo y más encima te tratan amable y con paciencia.
¿La respuesta o el comentario arrogante me ayudó?
Yo prefiero una respuesta útil pero arrogante cualquier día sobre una respuesta que no me enseña nada pero eso con mucha empatía (Mi navegador me marca empatía como palabra desconocida/falta de ortografía - véase "informáticos").
Muchos consideran djb arrogante por ejemplo, sin embargo yo sería más feliz que perro con dos colas recibiendo una respuesta arrogante de el (si logro inventar una pregunta suficientemente interesante para llamar su atención).
SO trata implementar meritocracia
Si sientes que faltan gente amable y cortes aquí, trata dar un mejor ejemplo, y usa tus votos para fomentar el estilo de moderación y respuestas que a ti conviene. Eso es el impacto que tienes. Pero ¡ojo!, no olvides que lo más importante aquí es el contenido de las publicaciones, menos el estilo, mientras tanto no queda ofensivo. Haces un flaco favor a todos si terminas fomentando blabla, solamente porque fue entregado en forma amable.
Puedes dar un mejor ejemplo
Si tu ves respuesta que te parecen arrogante, poco paciente y tu sientes que el OP necesita un poco más información, escribe una respuesta más explicativa. Si resulta que la gente prefieren las respuestas más amigables y menos bruscas, se va reflejar en votos y aceptación. Eso probable es la única forma como enfrentar un exceso de arrogancia, porque es dentro de la naturaleza de la arrogancia que es muy difícil de cambiar un arrogante. ;)
Ahora, si la arrogancia llega al punto que es una falta de respeto, ofensivo o humillante, debes reportarlo, independiente de quien se trata.


Q:

Why can't I "edit" (open in Interface Builder) a carbon .nib in Xcode 4.6.1?

I can't believe I need to ask this...
I'm upgrading a Carbon app from Xcode 3.4.x to Xcode 4.6.1.
When I select a .nib file in the Project Navigator, it only wants to open/ display with "Preview".  I can't get the Interface Builder Editor to display -- at all!
Obviously, there is some magic here.  Do the .nib files need to be converted to .xib first?  Or is there some component that needs to be installed that wasn't?  (I think the command line tools may not be installed).
UPDATE: I've converted one of the .nib files to .xib, and dropped it back into the project.  No difference: I still cannot bring up Interface Builder (at all).

A:

Xcode 4 does not support editing Carbon nibs, though you can build an app using them.  For editing the nibs, you'd better have a Mac that can run Snow Leopard, or Snow Leopard Server in a virtual machine, with Xcode 3.2.6 installed on it.


Q:

OpenCV - suitable implementation for Thin - Plate Spline Warping

I have the shape of a face with together with the reconstruction of that face and I want to model the corresponding image of the initial shape.
Basically, I want to move the points from the original shape to the position indicated by the reconstruction of the face. I have tried to do this by using thin plate spline warping, this implementation of it : http://ipwithopencv.blogspot.ro/2010/01/thin-plate-spline-example.html.
However, it's not working as I would want. I want to have the corners of the image fixed and just to move the corresponding points which define the face. I can illustrate this with 2 pictures. In the first picture I have the shape of the original face with the reconstructed shape.

In here I have the picture which I want to modify and the resulted picture by using the code from the link mentioned above. The green points mark the original face points and the blue points mark their new position and where I want to reposition them and stretch my face.

All I want is just to move the green points to the blue points so that it looks deformed. Do you know of any method to do this which you have tested?

A:

Getting the corners fixed is quite easy. Just add four additional correspondencies for the four image corners. In terms of your example:
iP.push_back(cv::Point(0, 0));
iiP.push_back(cv::Point(0, 0));
iP.push_back(cv::Point(0, height-1));
iiP.push_back(cv::Point(0, height-1));
iP.push_back(cv::Point(width-1, 0));
iiP.push_back(cv::Point(width-1, 0));
iP.push_back(cv::Point(width-1, height-1));
iiP.push_back(cv::Point(width-1, height-1));

Where, of course,  width is the image width and height is the image height