text:
Q: Tikz: locally overwrite style I want to locally overwrite a global style.
For the MWE: In the second picture "t=2" should be right of node c respectively d.
MWE:
\documentclass[tikz]{standalone}

\tikzset{%
one/.style args = {#1}{label=right: o{=}#1},%
two/.style args = {#1}{label={[yshift=-1em]right: t{=}#1}}%
}

\begin{document}

\begin{tikzpicture}
\node at (0,0) [one=1,two=2] {a};
\node at (2,0) [one=1,two=2] {b};
\end{tikzpicture}

%locally shift the label up again
\begin{tikzpicture}
\node at (0,0) [two=2] {c};
\node at (2,0) [two=2] {d};
\end{tikzpicture}

\end{document}

A: This answer bases on JouleV's comment to my question.

Instead of trying to edit the global style (which was my idea beforehand) by something like
\begin{tikzpicture}[two/.append style = {label={[yshift=0]}}]

or
\node at (0,0) [two={[yshift=0]2}] {c};

which both does not work, simply literally overwrite the style by:
\begin{tikzpicture}[two/.style args = {#1}{label={right: t{=}#1}}]

Full code:
\documentclass[tikz]{standalone}

\tikzset{%
one/.style args = {#1}{label=right: o{=}#1},%
two/.style args = {#1}{label={[yshift=-1em]right: t{=}#1}}%
}

\begin{document}

\begin{tikzpicture}
\node at (0,0) [one=1,two=2] {a};
\node at (2,0) [one=1,two=2] {b};
\end{tikzpicture}

%locally shift the label up again
\begin{tikzpicture}[two/.style args = {#1}{label={right: t{=}#1}}]
\node at (0,0) [two=2] {c};
\node at (2,0) [two=2] {d};
\end{tikzpicture}

\end{document}


text:
Q: Marshalling C# from DLL to WPF form It is possible to "Marshalling" from DLL to WPF Form? For example I like to update Listbox. Which will be the better way to do it?
Before (when I have everthing in one app) I have so defined:
MyMarshalDataToForm(FormActions.AddItemToListBox, "Handle obtained to my device:");

Where,
private enum FormActions
{
    AddItemToListBox,
    DisableInputReportBufferSize,
    EnableGetInputReportInterruptTransfer,
    EnableInputReportBufferSize,
    EnableSendOutputReportInterrupt,
    ScrollToBottomOfListBox,
    SetInputReportBufferSize
}

Where,
private void MyMarshalDataToForm(FormActions action, String textToDisplay)
{
    try
    {
        object[] args = { action, textToDisplay };

        //  The AccessForm routine contains the code that accesses the form.

        MarshalDataToForm marshalDataToFormDelegate = AccessForm;

        //  Execute AccessForm, passing the parameters in args.

        Dispatcher.Invoke(marshalDataToFormDelegate, args);
    }
    catch (Exception ex)
    {
        DisplayException(Name, ex);
        throw;
    }
}

Sorry for so few information in my first post. Now I want to leave Mashal data in .dll and update (for example) ListBox in Main Form. How to do it?

A: Lacking a good, minimal, complete code example that clearly illustrates your scenario, it's not possible to know what the best approach would be.
However, a common approach for separating concerns between main program and DLL like this would be for the DLL to declare an event that the main program can subscribe to.
For example, in the DLL:
public delegate void FormActionHandler(FormActions action, string textToDisplay);

public event FormActionHandler FormAction;

private void MyMarshalDataToForm(FormActions action, String textToDisplay)
{
    try
    {
        object[] args = { action, textToDisplay };

        //  The AccessForm routine contains the code that accesses the form.

        MarshalDataToForm marshalDataToFormDelegate = FormAction;

        //  Execute AccessForm, passing the parameters in args.

        if (marshalDataToFormDelegate != null)
        {
            Dispatcher.Invoke(marshalDataToFormDelegate, args);
        }
    }
    catch (Exception ex)
    {
        DisplayException(Name, ex);
        throw;
    }
}

Then in your main program where, presumable, the AccessForm() method is declared, you would have some code like this:
myDllObject.FormAction += AccessForm;

In this way, when the DLL needs to call the AccessForm() method, it need not actually know about the method per se. Instead, it uses the delegate already created by the main program to call that method, which has been subscribed to the FormAction event.

Note that the above uses a non-standard event signature. This is perfectly legal, but if you want to follow the .NET standard EventHandler<T>-based convention, you can do that too. It involves more code, but has the advantage of being a more-readily-recognizable event pattern.
For example:
class FormActionEventArgs : EventArgs
{
    public FormActions Action { get; private set; }
    public string TextToDisplay { get; private set; }

    public FormActionEventArgs(FormActions action, string textToDisplay)
    {
        Action = action;
        TextToDisplay = textToDisplay;
    }
}

public event EventHandler<FormActionEventArgs> FormAction;

private void MyMarshalDataToForm(FormActions action, String textToDisplay)
{
    try
    {
        FormActionEventArgs args = new FormActionEventArgs(action, textToDisplay);

        //  The AccessForm routine contains the code that accesses the form.

        EventHandler<FormActionEventArgs> marshalDataToFormDelegate = FormAction;

        //  Execute AccessForm, passing the parameters in args.

        if (marshalDataToFormDelegate != null)
        {
            Dispatcher.Invoke(marshalDataToFormDelegate, this, args);
        }
    }
    catch (Exception ex)
    {
        DisplayException(Name, ex);
        throw;
    }
}

Then your main program would subscribe like this:
myDllObject.FormAction += (sender, e) =>
{
    AccessForm(e.Action, e.TextToDisplay);
};

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to avoid java.util.NoSuchElementException The code below is giving me the error java.util.NoSuchElementException right after I Ctrl+Z
to indicate that the user input is complete. By the looks of it seems as if it does not know how to just end one method without messing with the other scanner object.
I try the hasNext method and I ended up with an infinite loop, either way is not working. As a requirement for this assignment I need to be able to tell the user to use Ctrl+Z or D depending on the operating system. Also I need to be able to read from a text file and save the final tree to a text file please help.
    /* sample input:
       CSCI3320
       project
       personal
       1 HW1
       1 HW2
       1 2 MSS.java
       2 p1.java

        */

    import java.util.Scanner;
    import java.util.StringTokenizer;

    public class Directory {

        private static TreeNode root = new TreeNode("/", null, null);

        public static void main(String[] args) {
            userMenu();
            System.out.println("The directory is displayed as follows:");
            root.listAll(0);

        }

        private static void userMenu(){         //Displays users menu
            Scanner userInput = new Scanner(System.in);//Scanner option
            int option = 0;
            do{ //I believe the problem is here since I am not using userInput.Next()
                System.out.println("\n 1. add files from user inputs ");
                System.out.println("\n 2. display the whole directory ");
                System.out.println("\n 3. display the size of directory ");
                System.out.println("\n 0. exit");
                System.out.println("\n Please give a selection [0-3]: ");
                option = userInput.nextInt();
                    switch(option){
                        case 1: addFileFromUser();
                                break;
                        case 2: System.out.println("The directory is displayed as follows:");
                                root.listAll(0);
                                break;
                        case 3: System.out.printf("The size of the directory is %d.\n", root.size());
                                break;
                        default:
                                break;
                        }
            }while( option !=0);
            userInput.close();

        }
        private static void addFileFromUser() {

            System.out.println("To terminate inp1ut, type the correct end-of-file indicator ");
            System.out.println("when you are prompted to enter input.");
            System.out.println("On UNIX/Linux/Mac OS X type <ctrl> d");
            System.out.println("On Windows type <ctrl> z");
            Scanner input = new Scanner(System.in);

                while (input.hasNext()) { //hasNext being used Crtl Z is required to break
                    addFileIntoDirectory(input); // out of the loop.
                }
                input.close();
        }

        private static void addFileIntoDirectory(Scanner input) {

            String line = input.nextLine();
            if (line.trim().equals("")) return;

            StringTokenizer tokens = new StringTokenizer(line);

            int n = tokens.countTokens() - 1;

            TreeNode p = root;
            while (n > 0 && p.isDirectory()) {

                int a = Integer.valueOf( tokens.nextToken() );
                p = p.getFirstChild();

                while (a > 1 && p != null) {
                    p = p.getNextSibling();
                    a--;
                }
                n--;
            }

            String name = tokens.nextToken();

            TreeNode newNode = new TreeNode(name, null, null);
            if (p.getFirstChild() == null) {
                p.setFirstChild(newNode);
            }
            else {
                p = p.getFirstChild();
                while (p.getNextSibling() != null) {
                    p = p.getNextSibling();
                }
                p.setNextSibling(newNode);
            }

        }

        private static class TreeNode {

            private String element;
            private TreeNode firstChild;
            private TreeNode nextSibling;

            public TreeNode(String e, TreeNode f, TreeNode s) {
                setElement(e);
                setFirstChild(f);
                setNextSibling(s);
            }

            public void listAll(int i) {

                for (int k = 0; k < i; k++) {
                    System.out.print('\t');
                }

                System.out.println(getElement());

                if (isDirectory()) {
                    TreeNode t = getFirstChild();

                    while (t != null) {

                        t.listAll(i+1);
                        t = t.getNextSibling();
                    }

                }
            }

            public int size() {

                int s = 1;

                if (isDirectory()) {
                    TreeNode t = getFirstChild();

                    while (t != null) {
                        s += t.size();
                        t = t.getNextSibling();
                    }
                }

                return s;
            }

            public void setElement(String e) {
                element = e;
            }

            public String getElement() {
                return element;
            }

            public boolean isDirectory() {
                return getFirstChild() != null;
            }

            public void setFirstChild(TreeNode f) {
                firstChild = f;
            }

            public TreeNode getFirstChild() {
                return firstChild;
            }

            public void setNextSibling(TreeNode s) {
                nextSibling = s;
            }

            public TreeNode getNextSibling() {
                return nextSibling;
            }

        }

    }

Exception Details:
    /*Exception in thread "main" java.util.NoSuchElementException
            at java.util.Scanner.throwFor(Scanner.java:907)
            at java.util.Scanner.next(Scanner.java:1530)
            at java.util.Scanner.nextInt(Scanner.java:2160)
            at java.util.Scanner.nextInt(Scanner.java:2119)
            at Directory.userMenu(Directory.java:36)
            at Directory.main(Directory.java:21)*/

A: Your problem is this line:
option = userInput.nextInt();  //line 24

If you read the Javadoc, you will find that the nextInt() method can throw a NoSuchElementException if the input is exhausted. In other words, there is no next integer to get. Why is this happening in your code? Because you this line is in a loop once that first iteration completes (on the outer while loop) your initial input selection has been consumed. Since this is a homework, I am not going to write the code. But, if you remove the loop, you know this works at least once.  Once you try to loop, it breaks. So I will give you these hints:

*

*Change the do/while to a while loop.

*Prompt the user once outside the loop.

*Recreate the prompt and recapture the user input inside the loop.

For example, the code below can be used for the basis of your outer loop.
import java.util.Scanner;

public class GuessNumberGame {

    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.println("Guess the secret number: (Hint: the secret number is 1)");
        int guess = input.nextInt();

        while (guess != 1) {
            System.out.println("Wrong guess. Try again: ");
            guess = input.nextInt();
        }
        System.out.println("Success");
        input.close();
    }
}

The reason why this works is because I don't reuse the same, exhausted, scanner input object to get the next integer. In your example, the initial input is inside the loop. The second time around, that input has already been consumed. Follow this pattern and you should be able to complete your assignment.


text:
Q: how to use tamil font in android this is my tamil UTF-8 unicode string
"\u00e0\u00ae\u009c\u00e0\u00af\u0086\u00e0\u00ae\u00a9\u00e0\u00ae\u00bf\u00e0\u00ae\u00b2\u00e0\u00ae\u00bf\u00e0\u00ae\u00af\u00e0\u00ae\u00be \u00e0\u00ae\u00aa\u00e0\u00af\u0081\u00e0\u00ae\u0095\u00e0\u00af\u0088\u00e0\u00ae\u00aa\u00e0\u00af\u008d\u00e0\u00ae\u00aa\u00e0\u00ae\u009f\u00e0\u00ae\u00ae\u00e0\u00af\u008d"
i want to decode it and display the tamil font
in android is this posible,how to do ?
please help me

A: You can save the tamil (ttf) font in the assets folder, and use it like this:
TextView text; // initialize to your textview
Typeface tf = Typeface.createFromAsset(this.getAssets(),"fonts/tamil.ttf");
text.setTypeface(tf);

A: Step 1: Download a tamil font .ttf file. (For example say kanchi.ttf).
Step 2: Now create a directory "fonts"  in your assets folder in the android project.
Step 3: Now copy the kanchi.ttf file into assets/fonts folder in you Android project.
Step 4: Add these lines to your onCreate()
protected static Typeface tamil = null;
tamil= Typeface.createFromAsset(getAssets(),"fonts/kanchi.ttf");

Step 5: Now provide this typeface to your TextView you want.
    textview= (TextView) findViewById(R.id.tipstext);
    textview.setTypeface(tamil);
    textview.setTextSize(20);
    textview.setText( "nkZk;");

A: The best way to display tamil in android is to use TSCII font as described here. Unicode is not yet fully supported.

A: if you are using webview, place the your font file 'tamilfont.ttf' in the assets folder.
and the java code will be similar to this. notice the font is applied in the css
    data = "
தமிழன்!
 ";
    WebView wv = (WebView)findViewById(R.id.webview);
    wv.loadDataWithBaseURL(null, data, "text/html", "UTF-8", null);

this approach does not work in android 2.0 and 2.1.

A: I Have one to open Tamil font convert doc to pdf and then try to open in android phones


text:
Q: In Visual Studio 2008 using C# how do I set a watch on a property? In Visual Studio 2008, I am using C# if that matters, how do I set a watch on a property so I see whenever the value changes during execution?

A: If you have set a breakpoint, then you can right-click on the "breakpoint dot" and select "Condition". Here you can specify that the breakpoint is only hit when some value (you need to type in the variable name) changes.
A "watched" value will show in red when the value changes.

A: In debug mode set a breakpoint, right click on the property you want to analyze and click "Add watch". The value will be shown in Watch window

A: You need to enter debug mode, so if you're running an application, run in debug. Otherwise, if you're running a web service, you need to attach to the process (like aspnet_wp.exe).
Then, you should have a watch window in the bottom of visual studio, where you can see the value of the property. (you get the property in this window by either typing the name in one of the spaces, or by clicking add to watch for the variable)
The last step is to place break points (stopping points) in your program where you want to see the value that you're watching.

A: While you are debugging you can right click on any variable and choose add watch. Also you can pull up the watch window and manually type it in the name column. I usually set a breakpoint at the start of my program so I can add watches, also they should be there the next time you debug project so you don't have to do it each time.


text:
Q: including controller files from external script in codeIgniter I've the following directory structure.
application
|
| -----> controller
            |
            | ------> profie_control.php
assets
|
| ------> Others
             |
             |---> uploadify
                     |
                     | --> uploadify.php

Now in my uploadify.php I am doing all the stuff that I want to perform.Then after everything is done I want to call a function and pass data to it in profile_control.php.Now I dont know how to access the functions.
I tried to use the following code
include_once("http://localhost/php/ci/index.php/profile_control/myfunction");

in uploadify.php but it gives me the following error
Warning: include_once() [function.include-once]: http:// wrapper is disabled in the server configuration by allow_url_include=0 in C:\wamp\www\php\ci\assets\Others\uploadify\uploadify.php on line 8

And I've read in some forums that this approach is not good as it can cause security issues.Now how I can send data from uploadify.php to profile_control.php securely or what would be a better alternative ???

A: You can't include/require by URL, but you can include/require by path, and it's what you want to do. In your controller:
include_once("../../assets/Others/uploadify/uploadify.php");
some_func(); // function from file 'uploadify.php'


text:
Q: The uncertainty principle of computer science When I work on an algorithm to solve a computing problem, I often experience that speed can be increased by using more memory, and memory usage can be decreased at the price of increased running time, but I can never force the product of running time and consumed memory below a clearly palpable limit. This is formally similar to Heisenberg's uncertainty principle: the product of the uncertainty in position and the uncertainty in momentum of a particle cannot be less than a given threshold.
Is there a theorem of computer science, which asserts the same thing? I guess it should be possible to derive something similar from the theory of Turing Machines.

A: I am not personally familiar with a description of it that parallels Heisenberg's uncertainty principle, per se, but this sounds to me to be closely related to Computational Complexity Theory. Problems can be classified according to some inherent, irreducible complexity, and I think that's what you're getting at with your limit of "the product of running time and consumed memory".


text:
Q: Remainder and quotient of polynomial division in $\mathbb Z_7[x]$ Find the quotient and remainder of:
$$ \frac {x^4 + [3]x^3 + [5]x} {x^2 + [2]} ; \mathbb Z_7[x]$$
Would the answer be the same if  it wasn't in  $\mathbb Z_7[x]$.  Namely:
Quotient: $x^2 +[3]x - [2]$
Remainder: $[-1]x+[4], or, [6]x + [4]? $


text:
Q: How to wake up APP from sleeping (ActionScript 3 - AIR for Android) I use Flex SDK + ActionScript 3.0 to develop APP for Android.
I need a function to wake up my APP when OS is sleeping.
For example, an alarm clock, it counts time in background and "wake up" to ring the bell when specific time matches.
I need the same action to "wake up" my APP from sleeping. I did some google search like "Native Extension" or "NativeProcess class" but it seems can't afford my goal.
I need some suggestion.
anyone ?

A: Yes you will need an ANE (Adobe Native Extension). There are loads out there by now.
this is one of them -> onglongfei/ANE-ALARM-Service


text:
Q: Use string as Apache Camel endpoint? Requisite disclaimer about being new to Camel--and, frankly, new to developing generally. I'd like to have a string generated as the output of some function be the source of my camel route which then gets written to some file. It's the first part that seems challenging: I have a string, how do I turn it into a message? I can't write it into a file nor can I use JMS. I feel like it should be easy and obvious, but I'm having a hard time finding a simple guide to help.
Some pseudo-code using the Java DSL:
def DesiredString() {return "MyString";}

// A camel route to be implemented elsewhere; I want something like:

class MyRoute() extends RouteBuilder {
  source(DesiredString())
  .to("file://C:/out/?fileName=MyFileFromString.txt");
}

I vaguely understand using the bean component, but I'm not sure that solves the problem: I can execute my method that generates the string, but how do I turn that into a message? The "vague" is doing a lot of work there: I could be missing something there.
Thanks!

A: Not sure if I understand your problem. There is a bit of confusion about what the String should be become: the route source or the message body.
However, I guess that you want to write the String returned by your method into a File through a Camel route.
If this is correct, I have to clarify first the route source. A Camel Route normally starts with
from(component:address)

So if you want to receive requests from remote via HTTP it could be
from("http4:localhost:8080")

This creates an HTTP server that listens on port 8080 for messages.
In your case I don't know if the method that returns the String is in the same application as the Camel route. If it is, you can use the Direct component for "method-like" calls in the same process.
from(direct:input)
.to("file:...");

input is a name you can freely choose. You can then route messages to this route from another Camel route or with a ProducerTemplate
ProducerTemplate template = camelContext.createProducerTemplate();
template.sendBody("direct:input", "This is my string");

The sendBody method takes the endpoint where to send the message and the message body. But there are much more variants of sendBody with different signatures depending on what you want to send it (headers etc).
If you want to dive into Camel get a copy of Camel in Action 2nd edition. It contains everything you need to know about Camel.

A: Example:Sending String(as a body content)to store in file using camel Java DSL:
        CamelContext context = new DefaultCamelContext();

        context.addRoutes(new RouteBuilder() {
            public void configure() {
                from("timer:StringSentToFile?period=2000")
                        .setBody(simple(DesiredString()))
                        .to("file:file://C:/out/?fileName=MyFileFromString.txt&noop=true")
                        .log("completed route");
            }
        });

        ProducerTemplate template = context.createProducerTemplate();
        context.start();


text:
Q: Zero-dispersion wavelength Please help me understanding the zero-dispersion wavelength in fibers.
I found this wiki-article on the topic. Accordingly:

"In a single-mode optical fiber, the zero-dispersion wavelength is the wavelength or wavelengths at which material dispersion and waveguide dispersion cancel one another."

Does the zero-dispersion wavelength only exist in single mode fibers?
Does it depend on the length of the fiber? Will two single mode fibers with identical step-profile, but different length (5o km and 300 km) have the same zero-dispersion wavelength?

A: Dispersion, $D$ is defined as:
\begin{equation}
D=\frac{\partial^2k}{\partial \omega^2}
\end{equation}
for the whole system, which is length independent (answering second question).
For the first question, then you can see that for highly multimode fibres, waveguinding will not affect propagation much, and the dispersion relation is that of the core's medium. So if it is made of fused silica, then the zero dispersion wavelength will be at approximately $1250\:nm$.
Edit: From what I remember, fibres with big cores just approach the core's propagation, but I might be wrong, after giving it a bit of thought, and multimode fibres might display a stronger dispersion. In any case, the first definition applies, and as you can see its about the dispersion relation of the system.

A: Does the zero-dispersion wavelength only exist in single mode fibers?
In general, the zero-dispersion wavelength does not exist in multimode fibers. This is because the core of multimode fibers is typically much larger than that of single-mode fibers, which causes light to travel through the fiber in many different modes. This results in a wide range of group velocities for different wavelengths of light, which means that there is no single wavelength at which the group velocity dispersion is zero.
Only MMF to have zero-dispersion wavelength that are specially designed to minimise the dispersion might have ZDW like Graded-index multimode fibers (GI-MMF), Large core multimode fibers (LC-MMF), and Dispersion-flattened multimode fibers (DF-MMF)
Does it depend on the length of the fiber?
The zero-dispersion wavelength (ZDW) of a single-mode fiber is determined by the material properties and the refractive index profile of the fiber. It is not dependent on the length of the fiber. Therefore, two single-mode fibers with identical step-profile and material properties, but different lengths (50 km and 300 km), will have the same ZDW.
Dispersion depends on both distance and wavelength. However, zero dispersion wavelength doesn't depends on distance. It's a constant value of any manufactured fiber with a dispersion coefficient D in terms of ps/nm/km @1550 nm
Dispersion will be more in longer fiber.
This zero-dispersion wavelength is shifted in dispersion-shifted fibers and highly-nonlinear fibers. As dispersion directly related to occurance of nonlinear effects in fiber useful/harmful for different applications


text:
Q: Rails Capistrano rbenv Puma bundle: Command not found I'm trying to run cap staging deploy to an AWS instance, which is our staging server. Everything works, including bundle install... But when it gets to running the Puma server it fails:
Command: cd /home/ubuntu/medcordance/current && ( export RBENV_ROOT="$HOME/.rbenv" RBENV_VERSION="2.5.0" RACK_ENV="staging" ; bundle exec puma -C /home/ubuntu/app_name/shared/puma.rb --daemon )

 DEBUG [02658949]   bash: bundle: command not found

I've checked high and low for a solution. I can't find one. I ran gem install bundler, I confirmed that bundler is installed, I've configured Capistrano with every setting I know should work, and I still can't find a solution to this.
Capfile:
# Load DSL and set up stages
require "capistrano/setup"

# Include default deployment tasks
require "capistrano/deploy"

# Load the SCM plugin appropriate to your project:
#
# require "capistrano/scm/hg"
# install_plugin Capistrano::SCM::Hg
# or
# require "capistrano/scm/svn"
# install_plugin Capistrano::SCM::Svn
# or
require "capistrano/scm/git"
install_plugin Capistrano::SCM::Git

# Include tasks from other gems included in your Gemfile
#
# For documentation on these, see for example:
#
#   https://github.com/capistrano/rvm
#   https://github.com/capistrano/rbenv
#   https://github.com/capistrano/chruby
#   https://github.com/capistrano/bundler
#   https://github.com/capistrano/rails
#   https://github.com/capistrano/passenger
#
require 'capistrano/rails'
# require "capistrano/rvm"
require "capistrano/rbenv"
require "capistrano/bundler"
# require "capistrano/chruby"
require "capistrano/rails/assets"
require "capistrano/rails/migrations"

require "capistrano/puma"
install_plugin Capistrano::Puma  # Default puma tasks

# Load custom tasks from `lib/capistrano/tasks` if you have any defined
Dir.glob("lib/capistrano/tasks/*.rake").each { |r| import r }

Deploy:
lock "~> 3.10.1"

set :application, "app_name"
set :repo_url, "my bitbucket"
set :branch, 'master'

set :use_sudo, true

set :rbenv_type, :user
set :rbenv_ruby, '2.5.0'
set :rbenv_prefix, "RBENV_ROOT=#{fetch(:rbenv_path)} RBENV_VERSION=#{fetch(:rbenv_ruby)} #{fetch(:rbenv_path)}/bin/rbenv exec"
set :rbenv_map_bins, %w{rake gem bundle ruby rails}
set :rbenv_roles, :all # default value

# Default branch is :master
# ask :branch, `git rev-parse --abbrev-ref HEAD`.chomp

# Default deploy_to directory is /var/www/my_app_name
set :deploy_to, "/home/ubuntu/app_name"

A: Figured it out. Turned out to be this single line in my config/deploy.rb file:
set :rbenv_map_bins, %w{rake gem bundle ruby rails}

By removing that it works...

A: For me, adding the following line to config/deploy.rb
append :asdf_map_ruby_bins, 'puma', 'pumactl' # I use asdf to manage ruby plugins

# Or
# append :rbenv_map_bins, 'puma', 'pumactl' if you're using Rbenv, like OP

solved the issue. Hope it helps someone!
Reference: https://github.com/seuros/capistrano-puma/issues/188
NB* append is the new Capistrano syntax, set still works though


text:
Q: using nlsLM() and < length of 'dimnames' not equal to array extent> error The measurment points (y_i, t_i) are given (whereas in this minimal example the y_i is only 3-dim vector (originally from R^6) and t_i fixed time point. I had to (Not sure if the code, the way it is right now, expresses it) to apply the Gauss-Newton-method, so as to minimize the (double) sum of squared errors and find functions parameters aj, cj in the fitting system (in code  represented by the function fitFunc()).
As I kept getting an Inf small entries of the Jacobian matrix in my C++ implementation,  I googled for an alternative and stumbled across the nls() function in R (As I got the'singular gradient matrix' error when using nls(),I switched to nlsLM())
Here is the minimal example (only with N_0 and N_r, whereas the original system has 3 different sumExp-like functions, N_0c and N_c called in fitfunc()):
library(stats)
a_param<-c(0.0294, 0.296, 0.0959)
c_param<-c(0.0574, 0.2960142, 0.3199)
time<-c(0,36,48,60,72,96)
N_srt<-55827

N_0 <- function(ti,cj) {N_srt*exp(-cj[1]*ti)}

prod_a<-function (i, aj){ #input i>=2
                         p<-1
                         j<-1
                         while (j<=i-1){
                                       p <-p*aj[j]
                                       j<-j+1
                                       }
                         p
                         }

PaarProdukt<-function (j, i, cj){
                       p<-1
                       k<-1
                       while (k<=i){
                                   if (k!=j){
                                          p<-p*1/(cj[k]-cj[j])
                                          }
                                k<-k+1
                                }
                        p
                        }

 sumExp<-function(i, cj, ti){ #input i>=2
                             s<-0
                             j<-1

                             while (j <= i){
                                s<-s+exp(cj[j])*PaarProdukt(j,i,cj)
                                j<-j+1
                              }
                              s
                            }

 N_r <- function(ti, i, cj, aj ){#i >2
                                P<-prod_a(i,aj)
                                S<-sumExp(i,cj,ti)
                                2^(i-1)*N_srt*P*S
                            }

      #-------------------
      givendata<-c(55827,0,0,
                   18283,12197,0,
                   11678,15635,19550,
                   6722,8315,13609,
                   5104,3316,6282,
                   715,915,1418)

# as I was annoyed with the fact, that R repliates the vector "time"    3 times so as to match its size with the size of "givendata", I introduced
zeitSpane<-c(0,0,0,36,36,36,48,48,48,60,60,60,72,72,72,96,96,96)

  fitliste<-rep(0,18)

  fitFunc<-function(t,cj,aj){ #t muss be of length 18
  counter<-1

  while (counter <= 18){
    i <- counter %% 3
    if (i == 1){

      fitliste[counter]<-N_0(t[counter],cj)
      }else{
        if (i==0) {i<-3
        }else{i<-2}

      fitliste[counter]<-N_r(t[counter],i,cj,aj)+counter
      }
    counter<-counter+1
  }
  fitliste
}
df<- data.frame(givendata=givendata, t=zeitSpane )

nlsLM(givendata~fitFunc(t,cj,aj), data =df, start=list(t=zeitSpane,cj=c_param,aj=a_param))

I now got this

Error in colnames<-(*tmp*, value = c("t", "cj", "aj")) :
length of 'dimnames' [2] not equal to array extent
In addition: Warning message:In matrix(out$hessian, nrow =length(unlist(par))) :
data length [9] is not a sub-multiple or multiple of the number of rows [24]

Q: Do you know how to fix this error? From where comes this 9 in the warning message?


text:
Q: Reuse existing classes in an ontology I design my own ontology and I reuse items from other ontologies. Is it good or bad practice to subclass an item from another ontology under an existing one? Or should I define my own subclass?
Classes in my ontology
<http://schema.org/Place> a owl:Class .

<http://OtherOntology/Area> a owl:Class;
  rdfs:subClassOf <http://schema.org/Place> .

<http://MyOntology/TinyPlace> a owl:Class;
  rdfs:subClassOf <http://schema.org/Place> .

A: RDF data in general is about "facts" asserted by a particular graph, including facts about a particular ontology. At this level, it doesn't matter which ontology a vocabulary item is part of, since the URI is not relevant and all ontologies stay in "your" graph.
This is different however when your ontology becomes a part of the linked data network. There are no particular guidelines as for what you should be publishing, but I think a good rule of thumb is "don't speak for others", i.e. don't publish facts about entities in other datasets in the same place as facts about entities in your dataset (concretely, at least one node in a triple should be "yours"). This pertains to this part:
<http://OtherOntology/Area> a owl:Class;
  rdfs:subClassOf <http://schema.org/Place> .

You are stating something about a foreign class, but what if a user or importer of your ontology has a different idea about it? There are vocabularies which don't have a unique OWL ontology, so there is a potential for contradictions in some situations. It's probably fine here, but you can never be sure.
It is better to use owl:imports to import http://OtherOntology/ if possible, assuming it is published using OWL. If not, you may publish the relevant part yourself separately, and import it externally, or refer to that document using rdfs:isDefinedBy.
You are however encouraged to use existing classes for maximum interoperability, so using http://schema.org/Place and http://OtherOntology/Area is perfectly fine.


text:
Q: How to check if a module is available for import? I am using a module in a script but one action inside the host application doesn't load this module so the script fails. It's fine if it fails because it doesn't need to run, but I don't want to see the error message box.
Is there a way to check if the module is available, like:
isavailable ( mymodule )

# safe to use the module

But I also want the function to early return, break the execution if it's not available.

A: try:
    import my_module
except ImportError:
    available = False
else:
    available = True

A: You can do the following:
import importlib

def import_if_available(name, package=None):
    try:
        return importlib.import_module(name, package)
    except ImportError:
        return None

print import_if_available('os.path')

From importlib documentation.
The purpose of the importlib package is two-fold. One is to provide an implementation of the import statement (and thus, by extension, the import() function) in Python source code. This provides an implementation of import which is portable to any Python interpreter. This also provides a reference implementation which is easier to comprehend than one implemented in a programming language other than Python.
Two, the components to implement import are exposed in this package, making it easier for users to create their own custom objects (known generically as an importer) to participate in the import process. Details on custom importers can be found in PEP 302.

A: The easiest way to check if a module is available is to import it. And this is almost always what you want, as well. If the module isn't available, this will fail. If the module is available… well, the reason you're checking is because you need to verify that you will be able to import it, so you're not wasting any time importing it now.
More generally, in Python, it's easier to ask forgiveness than permission. If you want to know whether you can do something, just try to do it.
So, this is almost an answer on its own:
import mymodule

The code will "early return, break the execution if it's not available." The only problem is that you don't want to see the error message.
There are two ways around this.

First, you could wrap the code up like this:
try:
    import mymodule
except ImportError:
    pass
else:
    # everything else you were going to do.

Whether "the code" is the whole function body, or the line of code that calls the function, or a chunk of top-level code in your script or module, or whatever, it makes no difference.

If you want to avoid the extra block indent, you can "return early" in various different ways. (Although really, it's almost always trivial to just extract all the indented code out into a new function, which means you end up with just a one-line function call being in the else block.)
How you do that depends on what level you're trying to return from, and that isn't clear from your question. If you want to return early from a function, just return (possibly with an appropriate value). If you want to return early from the whole program, just sys.exit(0). So:
try:
    import mymodule
except ImportError:
    sys.exit(0)
# the rest of your code

You could also exit with a positive value, which is a way to tell the shell or whoever else called your program that it "failed", without printing out an error traceback.

A: Although it's a little unusual to want a called function to halt execution, you can do it, as shown below. You'll have to pass the module's name as a string to the function, since presumably the variable mymodule won't exist yet when it's called. If it's successful it will return the imported module so the result can be assigned to variable name for subsequent use.
import sys

def isavailable(modulename):
    try:
        module = __import__(modulename)
    except ImportError:
        sys.exit(1)  # stop execution
    else:
        return module

Sample usage:
mymodule = isavailable('mymodule')  # program will terminate if not found
mymodule.method()

A: I am not sure if this comes late, but I believe that an easy way to check for this would be using the sys.modules dict:
import sys

if 'my_module' in sys.modules:
    print ('Module available')
else:
    print ('Module not available')

If you want to put this in a function:
import sys

def isavailable(m):
    if m in sys.modules:
        return True
    else:
        return False

isavailable('mymodule')

A: sys.modules check appears to be more elegant? Unfortunately while working in notebook, does not seem to work when used in py file when run as
python mycode.py.
Have no idea why - I guess "replace user and press anykey?"
import sys

# https://stackoverflow.com/questions/20957811/how-to-check-if-a-module-is-available-for-import
if 'geopandas' in sys.modules:
    print ('geopandas is available')
else:
    print ('geopandas is not available') # for whatever reason prints this when in fact is available

# redundant, just for the record

try:
    import geopandas as gpd
except ImportError:
    print('Geopandas is not available. Please "conda install geopandas",\n \
    or switch environment where geopandas is installed "conda activate geopandas_env_name"')
    sys.exit(0)
# the rest of your code

import numpy as np
import pandas as pd


text:
Q: Accquiring network location of a Infopath form using vba I have a network published infopath 2010 form.
I would like this form to display the actual network location it is located in when it loads directly in the form. Right now, the form location is displayed at the bottom of the screen as a part of the Infopath window.
I know how do to do everything else besides getting the network file location using vba. Any ideas? As far as I can tell I can only pull the URI of the form which is specific to SharePoint deployments not Network deployment.
Any ideas would be greatly appreciated! :)

A: I ran a quick test and found that when I opened a network published template, this code:
this.Template.Uri.ToString()

Returned the published location in this format:
file:///D:/Documents/Temp/test.xsn

So, you'd need to clean the string up a bit - but this appears to work with network published templates. Were you getting a different result?


text:
Q: Работа с объектами Подскажите как переделать код так чтобы console.log('object is full of properties') выводилась только тогда, когда в объекте два и более свойства?

const testObject = {
    name: 'Dmitriy',
    age: 99,
    location: 'Monaco'
};
function isEmpty (object) {
    for (let key in object) {
        if (object.hasOwnProperty(key)) {
            return console.log('object is full of properties');
        }
    }
    return console.log('object is empty');
}
isEmpty(testObject);

A: Object.keys(obj) возвращает массив собственных итерируемых строковых свойств. Как раз то, что хочется пересчитать в задаче.
Из названия функции "isEmpty" следует, что она возвращает Булево значение (true / false).
const isEmpty = obj => Object.keys(obj).length <= 2;

Использование:
console.log( isEmpty({ a: "AAA" }) ? 'object is empty' : 'object is full of properties' );
// выведет "object is empty"

console.log( isEmpty({ a: "AAA", b: "BB", c: "C" }) ? 'object is empty' : 'object is full of properties' );
// выведет "object is full of properties"

A: Вот так это можно сделать:

const testObject = {
  name: 'Dmitriy',
  age: 99,
  location: 'Monaco'
};

const testObject1 = {
  name: 'Dmitriy'
};

const testObject2 = {};

function isEmpty(object) {
  let count = 0;
  for (let key in object) {
    if (object.hasOwnProperty(key)) {
      ++count;
    }
    if (count > 1)
      return console.log('object is full of properties');
  }
  return console.log('object is empty');
}

isEmpty(testObject);
isEmpty(testObject1);
isEmpty(testObject2);


text:
Q: Update if not exists, if exists check if code is different from 1 and update I'm trying to build a SQL command to update my table
Update a row in myProduct if it does not exists in table order, or if it exists, check in table order if the code is != 1 to update
UPDATE myProduct
SET statut = 3
WHERE
    myProduct_id NOT IN (SELECT myProduct_id
                         FROM order
                         WHERE code != 1
                           AND myProduct.myProduct_id = order.myProduct_id)
    OR NOT EXISTS IN (SELECT myProduct_id FROM order)

Thank you in advance

A: use the below code..
UPDATE p
    SET statut = 3
FROM myProduct p
WHERE NOT EXISTS
        (SELECT 1
        FROM order o
        WHERE code != 1
        AND p.myProduct_id = 0.myProduct_id)

A: I believe the logic is:  Update all rows where the corresponding row in order is not 1 (or none exists).
If so, you can do this with a simpler statement:
UPDATE myProduct p
    SET statut = 3
WHERE NOT EXISTS (SELECT 1
                  FROM orders o
                  WHERE o.code = 1 AND p.myProduct_id = o.myProduct_id);

You don't specify the database, but the above is standard SQL.
Note:  order is a really bad name for a table, because it is a SQL keyword.  That is why I used orders instead of order.

A: UPDATE myProduct SET statut = 3
WHERE NOT EXISTS(SELECT 1 FROM order WHERE code != 1 AND myProduct.myProduct_id = order.myProduct_id )


text:
Q: Why is averaging count metric showing different result according to time frames in Datadog? I'm having trouble with configuring defining monitor in Datadog (Or maybe it can be alert in Prometheus, I'm not sure).
I have a metric named trace.servlet.request.hits, which is a COUNT metric. Datadog shows me that the interval for this metric is 10 (seconds). I wanted to receive alerts whenever drastic change happens regarding this metric. The metric I defined is diff(avg:trace.servlet.request.hits{cluster_name:$MY_CLUSTER}.as_count()).
However, I thought that configuring time frames (https://docs.datadoghq.com/dashboards/guide/custom_time_frames/) would just change the period (or time window), but changing the time frames always show different result for my metric, and thus I'm having hard time how to configure the threshold to get alerts on.
From my understanding, COUNT metric (https://docs.datadoghq.com/metrics/types/?tab=count#metric-types) is just an addition of all values in one time interval, which I thought that is independent from the time frame. In the case above, one time interval would be 10 seconds.
However, every time I change the time frame, I'm getting different result for the metric. Any help on understanding why? Thanks a lot!

A: Datadog aggregates what you are seeing based on the selected interval. You can use the rollup method for a bit more control, but there are still enforced limits to avoid having more points on the graph than pixels. Longer intervals will always have less granularity.


text:
Q: Does using service worker in Polymer app interfer with Firebase Hosting rewrites? I try to add some rewrites to my firebase.json to invoke some functions at some paths but the functions are called only once or sometimes at some seemingly random times. My Polymer app uses service worker to pre-cache all the views.
I can only think that caching is somehow the reason that my rewrites are not invoking the Firebase functions all the time? Any solution to this?
Also, does login status have anything to do with this?
Here's my firebase.json:
{
  "database": {
    "rules": "database.rules.json"
  },
  "hosting": {
    "public": "build/es5-bundled",
    "rewrites": [
      {
        "source": "**",
        "function": "test"
      }
    ]
  }
}

and my test function :
const fs = require('fs');
exports.test = functions.https.onRequest((req, res) => {
    let indexHTML = fs.readFileSync('./hosting/index.html').toString();
    //I tried to limit cache hoping this might solve the issue, don't see any difference
    res.set('Cache-Control', 'public, max-age=10, s-maxage=10');
    res.status(200).send(indexHTML);
})

Edit
I can confirm that when I use incognito in Chrome my function is called each time as long as I use a new window. So I'm inclined to think the issue is the cache. How to solve it through such that the service worker purpose is not defeated, I'm not sure.


text:
Q: Batch check for whitespace I want to name my batch logfile with the timestamp were it was created. But there is a problem if the time is < 10am. Then I get a whitespace and the filename will be corrupted. I tried to catch that via IF but somehow its not working and the cmd window is closing immediately:
set f_null=%time:~-11,1%
If /i %f_null% == " " (set zeitstempel_start=%DATE:~-4%%DATE:~-7,-5%%DATE:~-10,-8%0%time:~-10,1%%time:~-8,2%%time:~-5,2%) else
                      (set zeitstempel_start=%DATE:~-4%%DATE:~-7,-5%%DATE:~-10,-8%%time:~-11,2%%time:~-8,2%%time:~-5,2%)

set startzeit=Start: %date% %time:~-11,2%:%time:~-8,2%:%time:~-5,2%
set datei_name=%zeitstempel_start%
echo %startzeit% > %def_log_dir%\%datei_name%.log

Any idea what  the problem is?

A: set zeitstempel_start=%DATE:~-4%%DATE:~-7,-5%%DATE:~-10,-8%%time:~-11,2%%time:~-8,2%%time:~-5,2%
set zeitstempel_start=%zeitstempel_start: =0%

replaces any space with 0.
Your problem with the if is twofold:

*

*If /i %f_null% == " " when f_null is Space is resolved as If /i == " " which is a syntax error. If /i "%f_null%" == " " work work - the comparison is very literal.

*The sequence ) else ( must all be on the same line, not split across two as you have posted. It's possible (in fact common) to have ) else ( on its own separate line.
If you run the batch from the prompt, you could see the error messages that are being generated.


text:
Q: Regex for first element of word as Uppercase but in brackets should be Lowercase I want to create regex which should work with  tag. Example code is as follows:

                    Total time(s)

If I use css text-transform: capitalize then output follows:
Total Time(S)

I want the text as follows:
Total Time(s)

Note :
"time(s)" comes dynamically from database.
Thanks in advance for your answers.

A: As, I was using angularjs so I created custom filter and remove text css.
Angular custom filter:
app.filter('capitalize', function() {
        return function(input) {
            return (!!input) ? input.charAt(0).toUpperCase() + input.substr(1).toLowerCase() : '';
        }
    });

Html:

    Total {{challenge.unit  | capitalize}}


text:
Q: Reading a excel CSV file I have a CSV file with exactly the following data:
Fecha,"Último","Apertura","Máximo","Mínimo","Vol.","% var."
01.05.2020,"51,62","51,82","52,21","50,14","161,14K","-2,92%"
30.04.2020,"53,17","51,78","53,83","51,26","185,33K","0,47%"
29.04.2020,"52,92","51,00","54,55","50,88","249,92K","5,27%"

How can I import the file correctly? Import[name,"CVS"] does not recognize the different data fields.
Any suggestion? Thanks.

A: Your data is not well formatted for a simple "one line" Import. The best you can manage with focus on simplicity is:
Import[filename,"CSV","DateStringFormat"->{"Day",".","Month",".","Year"},"NumberPoint"->","]

Assuming you want to replace the numbers containing K with the value times 1000 and the numbers containing % with the value divided by 100, then I suggest using Dataset with the following line of code:
Import[filename,"Dataset",HeaderLines->1,"DateStringFormat"->{"Day",".","Month",".","Year"},"NumberPoint"->","][
All,{
"Vol."->(ToExpression[StringReplace[#,{","->".","K"->"*1000"}]]&),
"% var."->(ToExpression[StringReplace[#,{","->".","%"->"/100"}]]&)
}]


text:
Q: Firestore create collection in console or add doc not working I'm trying to create a collection on firestore within the console, but it doesn't let me move forward. It's asking to add the first document, but the save button is still disabled even tho I added an ID with Auth-ID as you can see in the picture below

I've red a lot of conversations on the web, and they all say we need to set an ID but nothing seems to work for me.
On another hand, I've tried to add a new document straight from my ReactJS app following the documentation example, but same thing here, there are no errors but nothing happens.
import { collection, addDoc } from "firebase/firestore";

try {
   const docRef = await addDoc(collection(db, "users"), {
       first: "Ada",
       last: "Lovelace",
       born: 1815
   });
      console.log("Document written with ID: ", docRef.id);
 } catch (e) {
      console.error("Error adding document: ", e);
}

In the code above, docRef.id is undefined and nothing is added to the collection. The console prints the following:
Document written with ID:  undefined

My rules are set to "production" as follow:
  `rules_version = '2';
   service cloud.firestore {
       match /databases/{database}/documents {
       match /{document=**} {
       allow read, write: if false;
      }
    }
   }`

The documentation states that Cloud Firestore creates collections and documents implicitly the first time you add data to the document. So it should be there
thanks for the help


text:
Q: Unable to read a number from a text file I am using Fortran to make a subroutine to use in a CFD shallow water software.
I have written this code to read and use the values stored.
PROGRAM hieto

! Calcula la precipitacion efectiva en funcion del tiempo
!IMPLICIT NONE

real::a

!Abrir CSV
!OPEN(UNIT=10,FILE="datos.txt",FORM="formatted",STATUS="replace",ACTION="readwrite",ACCESS='sequential')
open(unit=10, file='datos.txt')

!Leer el archivo
read(10, *, iostat=ios)a
print*,ios
print*, a
close (UNIT=10)

END PROGRAM hieto

My text file datos, looks like this
1

2

3

When I run the code as is, I get the following output
-1
0.0000000000
Process return 0 (0x0) execution time: 0.002 s

the first number in the row one is one not zero, so I don't know why this happens.
And if I remove the iostat=ios from the read statement, I get the following error:
At ine 13 (the line od the read stament) of file /home/Dropbox/scripts_tesis/fortran/hieto_telemac.f90 (unit=10, file=datos.txt')
Fortran runtime error: end of file.
Proceess returned 2 (0x2)

I have read some answers here so I tried adding end=3 in the  read statement, and also to end my text file with a blank line at the end.
The end=3 gives an error saying 3 is not a defined label and putting a blank row in the text file  does nothing.
I am using ubuntu 16.04 LTS and Gfortran compiler.

A: What happens is that your file is empty.
Make sure that there is indeed a file called datos.txt in that directory. Pay attention to the exact name. datos.txt and just datos is not the same thing.
If you tried to open it before with the commented command that includes STATUS="replace" your old file would have been replaced.
And because the file is empty, you didn't real anything useful. If iostat is non-zero, and your is -1, then the value of the variable being read is undefined. So your a is undefined. Again, because your file is empty.
Additionally, you cannot just blindly put end=3 in your code because you saw it somewhere on Stack Overflow. You must first understand what it is supposed to do. There is no reason to combine iostat= and end=. The iostat is perfectly sufficient.


text:
Q: Getting the Cell Address of Checkbox when ticked Hy, I am working on Excel VBA which will get me the Cell Address of the Checkbox I tick at the moment. I am able to get the cell address using following code.
Sub test()

    Dim ws As Worksheet
    Set ws = Sheets("Sheet 1")
    Dim chk As CheckBox

For Each chk In ws.CheckBoxes
          Debug.Print chk.TopLeftCell.Offset(0, 0).Address
Next chk

End Sub

This code returns the Cell address of all Check-boxes but I only want one cell address of the checkbox I tick. How can I achieve this.  Currently I am trying events to achieve this but have no success so far.

A: Use the next way, please:

*

*Copy the next Sub in a standard module:

Sub GetChkBoxAddress()
  MsgBox ActiveSheet.Shapes(Application.Caller).TopLeftCell.Address
End Sub

*Copy the next code, too, and run it:

Sub textAssignMacroChkBox()
  Dim sh As Worksheet, s As Shape, chkB As CheckBox

  Set sh = ActiveSheet
  For Each s In sh.Shapes
     If TypeName(s.OLEFormat.Object) = "CheckBox" Then
        s.OnAction = "GetChkBoxAddress"
     End If
  Next
End Sub

*Try checking and unchecking the check boxes...

If you need to return the cell address only when the check box is checked (not for unchecking) the code can be adapted...
Edited:
In order to retrieve the cell address only for checking, you can use the next adapted Sub:
Sub GetChkBoxAddress()
 If ActiveSheet.Shapes(Application.Caller).OLEFormat.Object.Value = 1 Then
    MsgBox ActiveSheet.Shapes(Application.Caller).TopLeftCell.Address
 End If
End Sub


text:
Q: Blocking method of waiting for input and outputting I'm writing a messaging app in node for the command line. It needs be able to print newly received messages while allowing the user to type a message to send whenever they want.
Can you help me figure out how to create a blocking method that exits after receiving a specific input like "EXIT", but allows printing to the console and can receive and handle input that doesn't match the exit case? Thanks in advance.

A: You can't do that in node.js.  If you want to receive other types of events, you can't be blocking the main JS thread.  Javascript in node.js is single threaded and event driven.  The only way to get the next event is to be non-blocking so the main JS thread can fetch the next event in the event queue.
You can very likely deliver the desired functionality you want with non-blocking I/O.  You would have to show us the code you have so far for us to give you further advice on how to accomplish that with the code you have.
Keep in mind that you can exit a node.js process at any time with process.exit() so you could just have asynchronous, event driven input handler and whenever it found specific input like EXIT, it would then call process.exit() to exit the process.  For other input, it would dispatch to the appropriate handler based on what was typed.


text:
Q: Flutter : Bad state: Stream has already been listened to
    class MyPage extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        return DefaultTabController(
          length: 2,
          child: new Scaffold(
            appBar: TabBar(
              tabs: [
                Tab(child: Text("MY INFORMATION",style: TextStyle(color: Colors.black54),)),
                Tab(child: Text("WEB CALENDER",style: TextStyle(color: Colors.black54),)),
              ],
            ),
            body:PersonalInformationBlocProvider(
              movieBloc: PersonalInformationBloc(),
              child: TabBarView(
                children: [
                  MyInformation(),
                  new SmallCalendarExample(),
                ],
              ),
            ),
          ),
        );
      }
    }

    class MyInformation extends StatelessWidget{
      // TODO: implement build
      var deviceSize;

      //Column1
      Widget profileColumn(PersonalInformation snapshot) => Container(
        height: deviceSize.height * 0.24,
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceEvenly,
              children: <Widget>[
                Container(
                  decoration: BoxDecoration(
                    borderRadius:
                    new BorderRadius.all(new Radius.circular(50.0)),
                    border: new Border.all(
                      color: Colors.black,
                      width: 4.0,
                    ),
                  ),
                  child: CircleAvatar(
                    backgroundImage: NetworkImage(
                        "http://www.binaythapa.com.np/img/me.jpg"),
                    foregroundColor: Colors.white,
                    backgroundColor: Colors.white,
                    radius: 40.0,
                  ),
                ),
                ProfileTile(
                  title: snapshot.firstName,
                  subtitle: "Developer",
                ),
                SizedBox(
                  height: 10.0,
                ),
              ],
            )
          ],
        ),
      );
      Widget bodyData(PersonalInformation snapshot) {
        return SingleChildScrollView(
            child: Column(
              children: <Widget>[
                profileColumn(snapshot)
              ],
            ),
        );
      }

      @override
      Widget build(BuildContext context) {
        final personalInformationBloc = PersonalInformationBlocProvider.of(context);

        deviceSize = MediaQuery.of(context).size;
        return StreamBuilder(
            stream: personalInformationBloc.results,
            builder: (context,snapshot){
              if (!snapshot.hasData)
                return Center(
                  child: CircularProgressIndicator(),
                );
              return bodyData(snapshot.data);
            }
        );
      }
    }

I am using Bloc Pattern for retrieving data from Rest API (just called the whole object from JSON and parsed user name only). The Page consists of two tabs MyInformation and SmallCalendar. When the app runs the data are fetched correctly and everything is good. When I go to tab two and return to tab one then the whole screens in tab one goes to red showing error:
Bad state: Stream has already been listened to.

A: The most common form of Stream can be listened only once at a time. If you try to add multiple listeners, it will throw

Bad state: Stream has already been listened to

To prevent this error, expose a broadcast Stream. You can convert your stream to a broadcast using myStream.asBroadcastStream
This needs to be done inside your class that expose Stream. Not as parameter of StreamBuilder. Since asBroadcastStream internally listen to the original stream to generate the broadcast one, this imply you can't call this method twice on the same stream.

A: You could use broadcast, which allows to listen stream more than once, but it also prevents from listening past events:

Broadcast streams do not buffer events when there is no listener.

A better option is to use BehaviorSubject from rxdart package class as StreamController. BehaviorSubject is:

A special StreamController that captures the latest item that has been added to the controller, and emits that as the first item to any new listener.

The usage is as simple as:
StreamController<...> _controller = BehaviorSubject();

A: In my case, I was getting this error because the same line of code myStream.listen() was being called twice in the same widget on the same stream. Apparently this is not allowed!
UPDATE:
If you intend to subscribe to the same stream more than once, you should use a behavior subject instead:

// 1- Create a behavior subject
final _myController = BehaviorSubject<String>();

// 2- To emit/broadcast new events, we will use Sink of the behavior subject.
Sink<String> get mySteamInputSink => _myController.sink;

// 3- To listen/subscribe to those emitted events, we will use Stream (observable) of the behavior subject.
Stream<String> get myStream => _myController.stream;

// 4- Firstly, Listen/subscribe to stream events.
myStream.listen((latestEvent) {
   // use latestEvent data here.
});

// 5- Emit new events by adding them to the BehaviorSubject's Sink.
myStreamInputSink.add('new event');

That's it!
However, there is one final important step.
6- We must unsubscribe from all stream listeners before a widget is destroyed.
Why? (You might ask)
Because if a widget subscribes to a stream, and when this widget is destroyed, the destroyed widget stream subscription will remain in app memory causing memory leaks and unpredictable behavior.:
_flush() {
  _myController.close();
  _myController = StreamController<String>();
}

###############################
###############################
Old Answer:
What fixed it for me is to both create a my stream controller as a broadcast stream controller:
var myStreamController = StreamController<bool>.broadcast();

AND
use stream as a broadcast stream:
myStreamController.stream.asBroadcastStream().listen(onData);

A: I have had the same issue when I used a result of Observable.combineLatest2 for StreamBuilder into Drawer:

flutter: Bad state: Stream has already been listened to.

As for me, the best solution has added the result of this combine to new BehaviorSubject and listen new one.
Don't forget to listen old one !!!
class VisitsBloc extends Object {
    Map<Visit, Location> visitAndLocation;

    VisitsBloc() {
        visitAndLocations.listen((data) {
            visitAndLocation = data;
        });
    }

    final _newOne = new BehaviorSubject<Map<Visit, Location>>();

    Stream<Map<Visit, Location>> get visitAndLocations => Observable.combineLatest2(_visits.stream, _locations.stream, (List<vis.Visit> visits, Map<int, Location> locations) {
        Map<vis.Visit, Location> result = {};

        visits.forEach((visit) {
            if (locations.containsKey(visit.skuLocationId)) {
                result[visit] = locations[visit.skuLocationId];
            }
        });

        if (result.isNotEmpty) {
            _newOne.add(result);
        }
    });
}

I didn't use .broadcast because it slowed my UI.

A: Just to sum up:
The main difference is broadcast() creates a Stream listenable for multiple sources but it needs to be listened for at least one source to start emitting items.

A Stream should be inert until a subscriber starts listening on it (using the [onListen] callback to start producing events).

asBroadcastStream turns an existing Stream into a multi listenable one but it doesn't need to be listened to start emitting since it calls onListen() under the hood.

A: I think not all of the answers take into account the situation where you do not want or simply can't use broadcast stream.
More often than not, you have to rely on receiving past events because the listener might be created later than the stream it listens to and it's important to receive such information.
In Flutter what will often happen is that widget listening to the stream ("listener") gets destroyed and built again. If you attempt to attach listener to the same stream as before, you will get this error.
To overcome this, you will have to manage your streams manually. I created this gist demonstrating how that can be done. You can also run this code on this dartpad to see how it behaves and play with it. I have used simple String ids to refer to specific StreamController instances but there might be better solutions too (perhaps symbols).
The code from the gist is:
/* NOTE: This approach demonstrates how to recreate streams when
         your listeners are being recreated.
         It is useful when you cannot or do not want to use broadcast
         streams. Downside to broadcast streams is that it is not
         guaranteed that your listener will receive values emitted
         by the stream before it was registered.
*/

import 'dart:async';
import 'dart:math';

// [StreamService] manages state of your streams. Each listener
// must have id which is used in [_streamControllers] map to
// look up relevant stream controller.
class StreamService {
  final Map<String, StreamController<int>?> _streamControllers = {};

  Stream<int> getNamedStream(String id) {
    final controller = _getController(id);
    return controller.stream;
  }

  // Will get existing stream controller by [id] or create a new
  // one if it does not exist
  StreamController<int> _getController(String id) {
    final controller = _streamControllers[id] ?? _createController();

    _streamControllers[id] = controller;

    return controller;
  }

  void push(String id) {
    final controller = _getController(id);

    final rand = Random();
    final value = rand.nextInt(1000);

    controller.add(value);
  }

  // This method can be called by listener so
  // memory leaks are avoided. This is a cleanup
  // method that will make sure the stream controller
  // is removed safely
  void disposeController(String id) {
    final controller = _streamControllers[id];

    if (controller == null) {
      throw Exception('Controller $id is not registered.');
    }

    controller.close();
    _streamControllers.remove(id);
    print('Removed controller $id');
  }

  // This method should be called when you want to remove
  // all controllers. It should be called before the instance
  // of this class is garbage collected / removed from memory.
  void dispose() {
    _streamControllers.forEach((id, controller) {
      controller?.close();
      print('Removed controller $id during dispose phase');
    });
    _streamControllers.clear();
  }

  StreamController<int> _createController() {
    return StreamController<int>();
  }
}

class ManagedListener {
  ManagedListener({
    required this.id,
    required StreamService streamService,
  }) {
    _streamService = streamService;
  }

  final String id;
  late StreamService _streamService;
  StreamSubscription<int>? _subscription;

  void register() {
    _subscription = _streamService.getNamedStream(id).listen(_handleStreamChange);
  }

  void dispose() {
    _subscription?.cancel();
    _streamService.disposeController(id);
  }

  void _handleStreamChange(int n) {
    print('[$id]: streamed $n');
  }
}

void main(List<String> arguments) async {
  final streamService = StreamService();

  final listener1Id = 'id_1';
  final listener2Id = 'id_2';

  final listener1 = ManagedListener(id: listener1Id, streamService: streamService);
  listener1.register();

  streamService.push(listener1Id);
  streamService.push(listener1Id);
  streamService.push(listener1Id);

  await Future.delayed(const Duration(seconds: 1));

  final listener2 = ManagedListener(id: listener2Id, streamService: streamService);
  listener2.register();

  streamService.push(listener2Id);
  streamService.push(listener2Id);

  await Future.delayed(const Duration(seconds: 1));

  listener1.dispose();
  listener2.dispose();

  streamService.dispose();
}

A: The problem was due to not disposing the controllers in bloc.
  void dispose() {
    monthChangedController.close();
    dayPressedController.close();
    resultController.close();
  }

A: You should use the following.
StreamController<...> _controller = StreamController<...>.broadcast();

A: For those of you running into this while doing Future.asStream(), you'll need Future.asStream().shareReplay(maxSize: 1) to make it a broadcast/hot stream.

A: For me defining my stream as a global variable worked
Stream infostream (was inside the ...State in a stateful widget i defined it outside the widget and it worked
(not sure if the best solution but give it a try)

A: Call .broadcast() on your stream controller
example:
StreamController<T> sampleController =
      StreamController<T>.broadcast();

A: StreamSplitter.split() from the async can be used for this use case
import 'package:async/async.dart';
...

main() {
  var process = Process.start(...);
  var stdout = StreamSplitter<List<int>>(process.stdout);
  readStdoutFoo(stdout.split());
  readStdoutBar(stdout.split());
}

readStdoutFoo(Stream<List<int>> stdout) {
  stdout.transform(utf8.decoder)...
}

readStdoutBar(Stream<List<int>> stdout) {
  stdout.transform(utf8.decoder)...
}

A: In my case I was Using the Package Connectivity while on flutter web.
Commenting all Connectivity calls solved the issue.
I'm now just using Connectivity while only on Android/iOS.
So maybe check your Packages im you are using some packages that have some issues on Web in case you are developing for web.
Hopefully I could help someone with this Information.

A: This is a problem for the provider, I solved it by change provider initialization
Eg
locator.registerSingleton<LoginProvider>(LoginProvider());

TO
 locator.registerFactory(() => TaskProvider());

Where locator is
GetIt locator = GetIt.instance;

A: This could help any other person. In my case i was using two StreamBuilder one in each tab. So when i swipe to above the tab and back. The other stream was already listened so i get the error.
What i did was to remove the StreamBuilder from the tabs and put it on top. I setState each time there is a change. I return an empty Text('') to avoid showing anything. I hope this methods

A: For other case scenarios. Watch out if you are somehow using a stream inside a stateless class. This is one of the reasons you get the above error.
Convert the stateless class to stateful and call init and dispose method on the streamController:
 @override
 void initState() {
   super.initState();
   YourStreamController.init();
 }

 @override
 void dispose() {
   YourStreamController.dispose();
   super.dispose();
 }

A: make sure you dispose controllers!
@override
  void dispose() {
    scrollController.dispose();
    super.dispose();
  }

A: I was getting this error when navigating away and then back to the view listening to the stream because I was pushing a new instance of the same view into the Navigator stack, which effectively ended up creating a new listener even though it was the same place in code.
Specifically and in more detail, I had a ListItemsView widget which uses StreamBuilder to show all the items in a stream. User taps on the "Add Item" button which pushes the AddItemView in the Navigator stack, and after  submitting the form, the user is brought back to the ListItemsView, where the "Bad state: Stream has already been listened to." error happens.
For me the fix was to replace Navigator.pushNamed(context, ListItemsView.routeName) with Navigator.pop(context). This effectively prevents the instantiation of a new ListItemsView (as the second subscriber to the same stream), and just takes the user back to the previous ListItemsView instance.

A: I experienced this because, i was using a stream builder to create a list for  tabs of tabview and anytime i switch tabs and come back to the previous i get this error. "wrapping the stream builder with a builder widget" did the magic for me.

A: i have experienced this, always closing the streamcontroller worked for me.


text:
Q: How can I create an Accordion List within ionic 2? I want to integrate an accordion in my project using expandable groups but for a recent project, I was needing a rendition of an accordion that expanded text or more precisely overflowed content.

Can you tell me how it will done within ionic 2 ?

A: EDIT:
Ok, I think I've figured it out. This tutorial helped me a lot, so I would recommend reading it also.
I've split my code up into components, where
@Component({
    directives: [DataCards],
    templateUrl: 'build/pages/data-list/data-list.html'
})

export class DataList {

    public dataList: Data[];

    constructor() {
        this.dataList = [
            new Data('Test title', 'Test Details 1, 2, 3, 4, 5', false),
            new Data('Second title', 'These are the details for my second title :)', false)
    ];
}

}
and the corresponding HTML
<ion-content class="cards-bg">
   <data-cards [data]="dataList"></data-cards>
</ion-content>

contain my custom component data-cards. data-cards has an input parameter data, through which the list of data is passed. To be able to use the data-cards component, you need to set the directives attribute. Data is a class containing everything you need in an item of your list.
export class Data {
    constructor(public title: string, public details: string, public showDetails: boolean) {}
}

The component data-cards itself has the selector and inputs attributes set, so the component can be used from the data-list HTML. The function toggleDetails is used to toggle whether the detail part of a list entry is shown.
@Component({
    selector: 'data-cards',
    inputs: ['data'],
    templateUrl: 'build/pages/data-cards/data-cards.html'
})

export class DataCards {
    public data: Data[];
    constructor() {}

    toggleDetails(data: Data) {
        if (data.showDetails) {
            data.showDetails = false;
        } else {
            data.showDetails = true;
        }
    }
}

Finally, in the data-cards template file, I build up the list of data using *ngFor and make the details
 element's visibility dependent on the data showDetails attribute with *ngIf.
<ion-card *ngFor="let d of data">

{{d.title}}

    <button (click)="toggleDetails(d)">+</button>

{{d.details}}

</ion-card>

To get everything to work you will need to add some imports to my code, since e.g. the DataList class depends on DataCards and Data.
I also recommend changing the style of the data-cards template... Without being styled, it doesn't look beautiful exactly :)
UNEDITED ORIGINAL ANSWER:
I'm working on something similar right now. I think this can be implemented by using cards and *ngIf.
So I think I will do something like
<ion-card>

Card Title

    <button (click)="toggleDetails()">+</button>

        Here are some details for the title.

</ion-card>

In the toggleDetails() i would set the showDetails variable to true...
This is just my approach (and untested), I'm going to edit my answer when I'm done implementing it.

A: Check the demo of accordion list within ionic 2 on Github :
https://github.com/mahmoudissmail/ionic2Accordion
.html
<ion-content padding>
  <ion-list>
    <ion-list-header>
      Ionic 2 Accordion Example.
    </ion-list-header>
    <ion-item padding *ngFor="let d of data" (click)="toggleDetails(d)"><ion-icon color="primary" item-right [name]="d.icon"></ion-icon>
      {{d.title}}

{{d.details}}

    </ion-item>
  </ion-list>
</ion-content>

.ts
export class HomePage {

  data: Array<{title: string, details: string, icon: string, showDetails: boolean}> = [];

  constructor(public navCtrl: NavController) {
    for(let i = 0; i < 10; i++ ){
      this.data.push({
          title: 'Title '+i,
          details: 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.',
          icon: 'ios-add-circle-outline',
          showDetails: false
        });
    }
  }

  toggleDetails(data) {
    if (data.showDetails) {
        data.showDetails = false;
        data.icon = 'ios-add-circle-outline';
    } else {
        data.showDetails = true;
        data.icon = 'ios-remove-circle-outline';
    }
  }

thanks for @LPeteR90.


text:
Q: Columns aren't showing in a calculated table, in SSAS Tabular Editor v 2.16.1 I created calculated table in SSAS Tabular Editor (version 2.16.1 if that's important)
But I can only see my calculated column which I created separately
No summarized columns from the code below are shown in my new table in SSAS Tabular Editor, why?
Is there a settings I have to change in order to see the columns?
After I deploy, I can see my new tbl and columns in Power BI (but not in SSAS Tabular)
here is my code in DAX, in SSAS Tabular Model:
      SUMMARIZE (
                 'zzParam_DiagnosisGrp',
                 'zzParam_DiagnosisGrp'[EHRProgramWHID],
                 'zzParam_DiagnosisGrp'[ClientWHID],
                 'zzParam_DiagnosisGrp'[Date],
                 'zzParam_DiagnosisGrp'[Diagnosis Category],
                 'zzParam_DiagnosisGrp'[Diagnosis Classification]
              )

Here is what I see in SSAS Tabular after the code, and after I created 1 more calculated column:

Here is what I see in Power BI:
(These fields I am expecting to see in SSAS Tabular)

Please HELP!

A: The columns won't show up until you deploy.
Here is what I see after creating the table with Tabular Editor 2.16.4 and SSAS Tabular 2017:

The blue question mark icon indicates that you need to deploy.
After I click the save icon to deploy, the icon changes and the columns show up:


text:
Q: NFC card reader which can communicate with a mobile device Hi can anyone suggest me a NFC card reader whose sdk is available and using that we can communicate with the mobile device and transfer data scanned by the reader.
Thanks in advance.

A: ACR 122U is a good solution with SDK. I used it in both android phone and desktop. Host Card Emulation mode is also supported by this device.


text:
Q: Cloud Run as a proxy I am using Cloud Run as a proxy.
I am using NGINX image as a reverse proxy for my Kubernetes Services. Previously I was hitting my External Load Balancer IP. Now I want to hit my Internal Load Balancer IP with the same. I have created an Internal Load Balancer and set up my serverless VPC but while trying running my Cloud Run it is giving me 501 error.
My configuration for Docker file is below:
              server {

            listen 80;

             location / {

                proxy_pass [InternalIp];

                   }
                 }

nginx.conf file
FROM nginx
                  COPY ./nginx.conf /etc/nginx/conf.d/default.conf

my Dockerfile.
Any help is appreciated.


text:
Q: Batch Script To Combine Multiple Files With Same String (but a wildcard!) Into A Zip I'm looking for a way of using 7Z to zip several files with the same into a .7z/.zip file.
Within my directory I have hundreds of files with differing amounts of 'tracks' like so;
Zebrafile.cue
Zebrafile (Track 1).bin
Zebrafile (Track 2).bin

Donkeyfile.cue
Donkeyfile (Track 1).bin
Donkeyfile (Track 2).bin
Donkeyfile (Track 3).bin

Extradonkeyfile.cue
Extradonkeyfile (Track 1).bin

And I need a way of zipping these files together automatically so I just end up with
Zebrafile.zip
Donkeyfile.zip
Extradonkeyfile.zip

I guess the script would have to match the whole filename from the start UP TO the space before the opening bracket "(" somehow! The only variable after that match would be the number of the track "(Track X)"
Would anybody be able to point me in the right direction? I have seen other batch files which get close, but I'm still unsure of how to get the batch file to take into account the changing Track #. Many thanks!

A: Something like the following might work. If it is in a .bat script, double the '%' on the 'f' variable. This will put the .cue and .bin files into one archive file. If you want a .zip format file, use -tzip.
FOR /F "tokens=*" %f IN ('DIR /B /A:-D "*.cue"') DO (7z a -tzip "%~nf.zip" "%~f" "%~nf (*.bin")


text:
Q: Point on a line closest to the origin, general formula using linear algebra only Given a line $\ell$ in $\mathbb R^2$ containing points $p, q$, find point $r$ on $\ell$ closest to the origin, using linear algebra only (no calculus).
My answer is below, but I seem to have made a mistake.  Can you help me find my mistake?
Answer: The point $r$ is given by the formula
$$t = \frac{||q||^2}{||q - p||^2} \\
r = tp +(1-t)q
$$
Notation: We use $x$ to indicate both the point $x$ and a vector from the origin to the point, and don't always distinguish the two.
Proof: A line is an affine combination of its points, so that the points on the line are precisely $tp + (1-t)q$ for $t \in \mathbb R$.  The closest point on line is the unique point on the line whose dot product with a vector parallel to the line is zero.  The vector $q - p$ is parallel to the line. So we need to find a $t$ such that $[tp +(1-t)q] \cdot [q-p] = 0$:
$$[tp +(1-t)q] \cdot [q-p] = 0 \\
2t(p\cdot q) -t||p||^2 - t||q||^2 + ||q||^2 = 0\\
t(||p||^2 + ||q||^2 - 2p \cdot q) = ||q||^2 \\
t = \frac {||q||^2}{||q-p||^2} \\
$$
Problem Example: Let $p=(1,3,3)$ and $q = (0,2,1)$.  Then $t= \frac {||q||^2}{||q-p||^2} = \frac{5}{4}$ and $r = tp + (1-t)q = \frac 5 4 (1,3,3) - \frac {1}4 (0,2,1) = (\frac 5 4, \frac {13}4, \frac {14}{4})$.  However, this does not seem to be the answer calculus gives, so I must be making a mistake.

A: By the use of pseudo inverse:
Your line is $\ell(t)=(p-q)t+q$ and you are seeking $t_0$ such that
$$(p-q)t_0+q\approx\vec0,$$
so $(p-q)^{\top}(p-q)t_0+(p-q)^{\top}q\approx0$.
Hence
$$t_0=\dfrac{(q-p)\bullet q}{\|p-q\|^2}.$$
Addendum
Let's straighten a bit your idea:
\begin{eqnarray*}
[tp+(1-t)q]\cdot[q-p]&=&tp\cdot[q-p]+(1-t)q\cdot[q-p]\\
&=&tp\cdot q-tp\cdot p+(1-t)q\cdot q-(1-t)q\cdot p\\
&=&tp\cdot q-t||p||^2+(1-t)||q||^2-p\cdot q+tp\cdot q\\
&=&2tp\cdot q-t||p||^2+||q||^2-t||q||^2-p\cdot q\\
&=&-t(||q||^2-2p\cdot q+||p||^2)+||q||^2-p\cdot q\\
&=&-t||p-q||^2+||q||^2-p\cdot q\\
&=& .\ .\ .
\end{eqnarray*}

A: Your formula for $t$ is incorrect.Write the position vector as $\mathbf {r=q}+t(\mathbf{p-q})$ The equation $\mathbf{r \bullet (p-q)}=0$ gives$$t=\frac{\mathbf{-q\bullet(p-q)}}{\mathbf{(p-q) \bullet (p-q)}}$$


text:
Q: how to access my personal file in unbunto I'm new to programming, i start use windows-subsystem-for-linux and I don't know how to find my personal documents, my downloads, etc. I tried the path "env" "find" with a path but it didn't work, any suggestions?
"sunny" is the name of my pc, and I can't find my user sessions in the path
any help is welcome thank you


text:
Q: Issue with using wildcards with lucene .net QueryParser I have following code for Lucene .Net search:

If I use query like:
AccountId:1 AND CompanyId:1 AND CreatedOn:[636288660000000000 TO 636315443990000000] AND AuditProperties.FriendlyName.NewValue:CustomerId|235

It works fine with exact match with CustomerId = 235.
However, if I try to search for a wildcard match like for example:
AccountId:1 AND CompanyId:1 AND CreatedOn:[636288660000000000 TO 636315443990000000] AND AuditProperties.FriendlyName.NewValue:CustomerId|*235*

it doesn't fetch me any results. I think it is still going for an exact match with value "*235*" Am I missing anything here?
Thanks!

A: As per the QueryParser syntax documentation, the character | is not supported. However, it is not very clear whether you intended it to be a logical OR or a literal character.
Logical OR
The correct syntax for logical OR is either CustomerId OR *235*, CustomerId *235* or CustomerId||*235*.
Also, if this is meant to be a logical OR, you have to allow for a leading wildcard character as pointed out in Howto perform a 'contains' search rather than 'starts with' using Lucene.Net.
parser.AllowLeadingWildcard = true;

Literal |
To search for a literal pipe character, you should escape the character so the parser doesn't confuse it with a logical OR.
CustomerId\|*235*


text:
Q: Raphael element doesn't transform when passed to a function in a loop I was trying to rotate the object by a variable number of degrees to represent a dial. As the first step I tried doing the following:
window.onload = function() {
    var paper = new Raphael(document.getElementById('canvas_container'), 500, 500);
    var circle = paper.circle(100, 100, 80);
var arrow = paper.path("M 100 100 l -56.5 56.5 z");
    arrow.attr({stroke: '#0a0', 'stroke-width': 3});

    for(var i=0;i<=100; i+=1){
         rotate_cw(arrow);
    }

}

function rotate_cw (element){
element.animate({transform:"r-1,100,100"}, 10);
}

The animate works by itself but I am unable to make it work with an external function.
Any solutions or workarounds?

A: Your code works - the animation is happening and the function works - but it doesn't look like it works for two reasons:

*

*Raphael transforms are absolute, not relative. So, it rotates to one degree, then rotates to the same position. You're not telling it to rotate by one degree 100 times, you're telling it to rotate to one degree 100 times.

*

*Fix this by keeping track of the rotation position, and incrementing it.

*The for loop just happens, more or less instantaneously. So after you fix the first problem, you'll find the animations just jump to the end, regardless of the 10 milisecond delay, because they are all called at more or less the same time. It calls the function 100 times in the space of barely 1 milisecond, and each function call takes 10 ms to animate, so it's reached the end of the 100th rotation in less than 11 miliseconds - not the 1000 miliseconds you probably want.

*

*Fix this by calling the next animation in Raphael's animate callback parameter

Here's an example that I think is more like what you were hoping for:
http://jsbin.com/oxufuh/1/edit


text:
Q: How to ask Mathematica to do the given operation for a set of parameters? I have a set of numbers like this
 s = {a, b, c, d, e, f, ..., g, h}
and I would like to ask Mathematica to do the following operation (to sum the subtractions of adjacent numbers)
 (a - b) + (c - d) + (e - f) + ... + (g - h)
Is it possible to do that?

A: Some more options
Clear[a, b, c, d, e, f, g, h];
s = {a, b, c, d, e, f, g, h};

Total[Table[s[[n]] - s[[n + 1]], {n, 1, Length[s] - 1, 2}]]

Sum[s[[n]] - s[[n + 1]], {n, 1, Length[s] - 1, 2}]

Total[SequenceCases[s, {j_, k_} :> j - k]]

Total[Subtract @@@ Partition[s, 2]]

All give

a - b + c - d + e - f + g - h

A: A mathematical approach: $\sum_{k=1}^n (-1)^{k+1} s_k$ translates as follows
s = {a, b, c, d, e, f, g, h};
Sum[(-1)^(k+1) s[[k]], {k, 1, Length[s]}]
(* a - b + c - d + e - f + g - h *)

A: ☺ = +## & @@ (#[[;; ;; 2]] - #[[2;; ;; 2]]) &;

☺ @ {a, b, c, d, e, f, g, h}

 a - b + c - d + e - f + g - h


text:
Q: How to Get data from nested LinkedHashMap How to get the "test" data from this linkedHashMap
Map<String, Object> response = new LinkedHashMap<String, Object>() {{
    put("data", new LinkedHashMap<String, Object>() {{
        put("images", new LinkedHashMap<String, Object>() {{
            put("original", new LinkedHashMap<String, Object>() {{
                put("url", "test");
            }});
        }});
    }});
}};

response.get("url") = null
response.get("data.images.original.url") = null
response.get("data").get("images").get("original").get("url")
Compilation failed:
cannot find symbol
symbol:   method get(java.lang.String)
location: class java.lang.Object

toString();
result{data={images={original={url=test}}}};

A: The "right" way would be
Object url = ((Map<String,Object>) ((Map<String,Object>) ((Map<String,Object>) response.get("data")).get("images")).get("original")).get("url");

And yes, this is ugly as all heck. Mostly because of the types you've chosen.
By making the value of your maps Object you've gained flexibility on what to put in, but you put the burden on the "reader" of the map to actually cast to whatever they want. And since generics are involved all of these casts are unchecked (i.e. the runtime can check that the returned objects are in fact Map but it can't verify that they are really Map<String, Object>.
Additionally, you also make use of double brace initialization, which I'd strongly discourage, because it's an ugly hack. If you're using Java 9 or later, then simply use Map.of() instead:
Map<String, Object> response = Map.of(
    "data", Map.of(
        "images", Map.of(
            "original", Map.of(
                "url", "test"
            )
        )
    )
);

The indentation here is only there to visualize the structure of those calls, it's absolutely not necessary.


text:
Q: how to add hyperlink to text in dart I am trying to add an anchor tag to the message I want to display but I am getting an error message. Am I not doing this right?
String browserRequirementsUrl = "https://test.testing.com";
var someText = new ParagraphElement()
  ..innerHtml = "Link can be found here[1].";

But I get an error message saying
  html_dart2js.dart:3614 Removing disallowed attribute

Any suggestions, how I can do this?

A: By default in dart:html, for security purposes, this is disallowed.
You can use the .setInnerHtml method:
..setInnerHtml("Link can be found...", treeSanitizer: NodeTreeSanitizer.trusted);

Note that this can potentially be insecure (i.e. inject


text:
Q: Xcode 12 deployment warnings 'IPHONEOS_DEPLOYMENT_TARGET' I installed react-native-maps and started getting the following warnings:

warning: The iOS Simulator deployment target
'IPHONEOS_DEPLOYMENT_TARGET' is set to 8.0, but the range of supported
deployment target versions is 9.0 to 14.1.99. (in target 'Flipper'
from project 'Pods') warning: The iOS Simulator deployment target
'IPHONEOS_DEPLOYMENT_TARGET' is set to 7.0, but the range of supported
deployment target versions is 9.0 to 14.1.99. (in target
'Google-Maps-iOS-Utils' from project 'Pods') warning: The iOS
Simulator deployment target 'IPHONEOS_DEPLOYMENT_TARGET' is set to
8.0, but the range of supported deployment target versions is 9.0 to 14.1.99. (in target 'react-native-google-maps' from project 'Pods')

I saw some online suggestions like the one below:
post_install do |installer|
     installer.pods_project.targets.each do |target|
         target.build_configurations.each do |config|
             config.build_settings['DEBUG_INFORMATION_FORMAT'] = 'dwarf'
             config.build_settings.delete 'IPHONEOS_DEPLOYMENT_TARGET'
             config.build_settings['ONLY_ACTIVE_ARCH'] = 'YES'
         end
     end
  end

However, my podfile looks like the following (this was how it looked when I installed react-native)
require_relative '../node_modules/react-native/scripts/react_native_pods'
require_relative '../node_modules/@react-native-community/cli-platform-ios/native_modules'

platform :ios, '10.0'

target 'allocentric' do
  config = use_native_modules!

  use_react_native!(:path => config["reactNativePath"])
  # React Native Maps dependencies
  rn_maps_path = '../node_modules/react-native-maps'
  pod 'react-native-google-maps', :path => rn_maps_path
  pod 'GoogleMaps'
  pod 'Google-Maps-iOS-Utils'
  pod 'RNVectorIcons', :path => '../node_modules/react-native-vector-icons'
  target 'allocentricTests' do
    inherit! :complete
    # Pods for testing
  end

  # Enables Flipper.
  #
  # Note that if you have use_frameworks! enabled, Flipper will not work and
  # you should disable these next few lines.
  use_flipper!
  post_install do |installer|
    flipper_post_install(installer)
  end
end

target 'allocentric-tvOS' do
  # Pods for allocentric-tvOS

  target 'allocentric-tvOSTests' do
    inherit! :search_paths
    # Pods for testing
  end
end

I can't seem to run the solutions posted online before "post_install" already exists, I have already tried to remove the first post_install or putting the above solution in that post_install but neither works.

A: Try this adding in pod file
post_install do |pi|
    pi.pods_project.targets.each do |t|
      t.build_configurations.each do |config|
        config.build_settings['IPHONEOS_DEPLOYMENT_TARGET'] = '9.0'
      end
    end
end

Ref: Range-of-supported

A: Comment the below lines
add_flipper_pods!
post_install do |installer|
  flipper_post_install(installer)
end

Also add the following lines at the end of Pod file
post_install do |installer|
  installer.pods_project.targets.each do |target|
      target.build_configurations.each do |config|
         if config.build_settings['IPHONEOS_DEPLOYMENT_TARGET'].to_f < 9.0
           config.build_settings['IPHONEOS_DEPLOYMENT_TARGET'] = '9.0'
         end
      end
  end
end


text:
Q: Missing "Access-Control-Allow-Methods" header for CORS in IIS Express I know similar questions have been asked many times but after hours of using any suggestion I can find it still does not resolve.
This is ASP.Net Core 3.1 web app which serves a web API, which I need to have accessible in development with Visual Studio - usual debug mode which runs IIS Express. Another web app is accessing the API (both on localhost, but different port numbers). GET and POST works, PUT does not work.
I know that no preflight requests get sent for GET, HEAD and POST requests, so the error seems to occur only when IIS (or Asp.Net?) has to handle the preflight request.
Browser shows the error
    Access to ... from origin ... has been blocked by CORS policy: Method PUT
    is not allowed by Access-Control-Allow-Methods in preflight response.

Both the preflight request and the actual PUT request are being performed, visible in the browser, but fail.
The response headers of the preflight request contain:
    access-control-allow-headers: *
    access-control-allow-origin: *

They NEVER contain an "access-control-allow-methods" header, no matter what I tried. It seems obvious that the PUT request won't work because the preflight request SHOULD contain this header with "PUT" specified as allowed method.
What I Tried

*

*Controlling CORS from AspNetCore web app

(This would require that the preflight request actually reaches the app and isn't caught by IIS and never forwarded - which I don't know, however)
Installed Microsoft.AspNetCore.Mvc.Cors package, then in Startup.cs:
        services.AddCors(options =>
        {
            options.AddDefaultPolicy(
                policy =>
                {
                    policy.WithOrigins("http://localhost:8080").AllowAnyMethod().AllowAnyHeader();
                });
        });

plus the corresponding UseCors() entry lower in Startup.cs (after Routing and before Authorization, as it should be).
Also tried
     services.AddCors();

in services, and then the following in the Configure section:
        app.UseCors(x => x
            .AllowAnyMethod()
            .AllowAnyHeader()
            .SetIsOriginAllowed(origin => true) // allow any origin
            .AllowCredentials()); // allow credentials

Same result - no "access-control-allow-methods" header.

*IIS Express configuration

In case IIS is doing the preflight job, it should be configurable directly there.
Curiously, IIS Express has 5 locations with configuration files:

*

*C:\Users<username>\Documents\IISExpress\config\

*C:\Program Files\IIS Express (x86)\config\templates\PersonalWebServer\

*C:\Program Files\IIS Express (x86)\AppServer\

*C:\Program Files\IIS Express\config\templates\PersonalWebServer\

*C:\Program Files\IIS Express\AppServer\

None of these contained anything related to CORS in my case (but the two headers shown above nevertheless show). So I tried adding custom headers:
    <httpProtocol>
        <customHeaders>
            <clear />
        <add name="access-control-allow-origin" value="*" />
        <add name="access-control-allow-headers" value="*" />
    <add name="access-control-allow-methods" value="GET,POST,PUT,PATCH,DELETE,OPTIONS" />
       </customHeaders>
        <redirectHeaders>
            <clear />
        </redirectHeaders>
    </httpProtocol>

I added these to EVERY "applicationhost.config" file in above locations. Same result - nothing changes.

*web.config in AspNet Core web app
 <system.webServer>
   <httpProtocol>
     <customHeaders>
       <add name="Access-Control-Allow-Origin" value="http://localhost:8080" />
       <add name="Access-Control-Allow-Methods" value="GET,PUT,POST,DELETE" />
       <add name="Access-Control-Allow-Headers" value="*" />

Same result.
(I did restart the computer after every one of these changes, just for good measure.)
At this stage, I am out of options.
Why would 3 different ways to configure CORS have literally NO EFFECT on what the server sends at all?
Is there a way to find out whether the preflight request gets handled by IIS or by ASP.NET Core? At least then I would know where I have to put the configuration.

A: Thanks to the comment of LexLi I found my own answer.
My use case was, as mentioned for Visual Studio debugging to work with CORS, and for that, there is yet another location for a IIS-Express configuration file:
    $(SolutionDir)\.vs\$ProjectName)\config

I put the above-mentioned custom header lines into this file (plus an additional "access-control-max-age" header).
This alone did not work - the C# UseCors() code in the web app was needed as well. Then it works perfectly.
So in fact my code was all correct - just missing know-how on VS.
I agree with Lex Li that one should rather use the IIS CORS module - yet this has to be configured and IIS Express does not provide a config tool.