text:
Q: Apache/varnish trailing slash with port issue I have a setup (php application) with
:: varnish (port 80) -> apache port (8080)
By default apache adds trailing slashes to directories but when it does it redirect with the port. e.g.
http:/www.domain.com/folder redirect to http:/www.domain.com:8080/folder/
This url with the port causes issues.
So I tried adding the directive
DirectorySlash Off in the .htaccess file but the application doesn't play nice anymore. e.g. broken links etc etc
I then tried to update the VCL as described on
http://danielmiessler.com/blog/adding-a-trailing-slash-to-directories-using-varnish/
sub vcl_recv {
if ((req.url ~ "/directory" ) && (! (req.url ~ "index.php"))){
   set req.url = req.url "/";
}
}

but I get the error
Message from VCC-compiler:
Expected ';' got '"/"'
(program line 174), at
('input' Line 14 Pos 26)
   set req.url = req.url "/";
-------------------------###-

Does anyone have any suggestions?
Thanks

A: I'd recommend keeping the redirect logic out of Varnish; the fundamental problem is that redirects based on the DirectorySlash setting will add the internal Apache port (8080) in the redirect.
To fix, try adding the following Apache setting to your Apache config (won't work in htaccess):
UseCanonicalName Off

Per Apache's documentation on UseCanonicalName:

With UseCanonicalName Off Apache httpd will form self-referential URLs using the hostname and port supplied by the client if any are supplied

Which means that apache should respect the incoming client port (80) forwarded by Varnish, even when doing the DirectorySlash redirect.


text:
Q: Use printf to format floats without decimal places if only trailing 0s Is it possible to format a float in C to only show up to 2 decimal places if different from 0s using printf?
Ex:
12 => 12
12.1 => 12.1
12.12 => 12.12
I tried using:
float f = 12;
printf("%.2f", f)

but I get
12 => 12.00
12.1 => 12.10
12.12 => 12.12

A: From our discussion in the above answer here is my program that works for any number of digits before the decimal.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main() {
    float f1 = 12.13;
    float f2 = 12.245;
    float f3 = 1242.145;
    float f4 = 1214.1;

    int i = 0;
    char *s1 = (char *)(malloc(sizeof(char) * 20));
    char *s2 = (char *)(malloc(sizeof(char) * 20));

    sprintf(s1, "%f", f1);
    s2 = strchr(s1, '.');
    i = s2 - s1;
    printf("%.*g\n", (i+2), f1);

    sprintf(s1, "%f", f2);
    s2 = strchr(s1, '.');
    i = s2 - s1;
    printf("%.*g\n", (i+2), f2);

    sprintf(s1, "%f", f3);
    s2 = strchr(s1, '.');
    i = s2 - s1;
    printf("%.*g\n", (i+2), f3);

    sprintf(s1, "%f", f4);
    s2 = strchr(s1, '.');
    i = s2 - s1;
    printf("%.*g\n", (i+2), f4);

    free(s1);
    free(s2);

    return 0;
}

And here's the output
12.13
12.24
1242.15
1214.1

A: You can use the %g format specifier:
#include <stdio.h>

int main() {
  float f1 = 12;
  float f2 = 12.1;
  float f3 = 12.12;
  float f4 = 12.1234;
  printf("%g\n", f1);
  printf("%g\n", f2);
  printf("%g\n", f3);
  printf("%g\n", f4);
  return 0;
}

Result:

12
12.1
12.12
12.1234

Note that, unlike the f format specifier, if you specify a number before the g it refers to the length of the entire number (not the number of decimal places as with f).

A: For what it's worth, here's a simple ObjC implementation:
// Usage for Output   1 — 1.23
[NSString stringWithFormat:@"%@ — %@", [self stringWithFloat:1],
                                       [self stringWithFloat:1.234];

// Checks if it's an int and if not displays 2 decimals.
+ (NSString*)stringWithFloat:(CGFloat)_float
{
    NSString *format = (NSInteger)_float == _float ? @"%.0f" : @"%.2f";
    return [NSString stringWithFormat:format, _float];
}

%g wasn't doing it for me — this one yes :-) Hope it's useful to some of you.

redpajama_set_name: RedPajamaStackExchange


text:
Q: CSS3 changing background colors I want to have a series of elements, and I want to have incremental background colors, but I also want to not hard-code it in order to allow for future expansion.

one

two

three

I could do something like this:
.container div:nth-child(0) {
    background-color: #0000ff;
}
.container div:nth-child(1) {
    background-color: #000066;
}
.container div:nth-child(2) {
    background-color: #000000;
}

I would rather do that with a single rule, which would allow more succinct code and also allow for more extensibility (for, say, 6 elements). Is this even possible? I am aware that something like this is pretty straightforward with JQuery, but I would rather just use CSS if possible.

A: You can somehow handle this using a gradient, with a very big size, and setting just the position

.container div {
  background-image: linear-gradient(yellow, blue);
  background-size: 20000px 20000px;
  }

.container div:nth-child(1) {
  background-position: 0% 0%;
}

.container div:nth-child(2) {
  background-position: 0% 30%;
}

.container div:nth-child(3) {
  background-position: 0% 100%;
}

one

two

three


text:
Q: how change catalina.properties file if it is read only in embedded tomcat using intellij idea
I am trying to set a property in catalina.properties file but it is read-only file
how to change this file using intellij idea

I want to add following property
tomcat.util.http.parser.HttpParser.requestTargetAllow=|{}

I want to add this because I want to allow pipe and braces as request parameter

Please help me


text:
Q: changing x-axis of FFT plot This is my first post here and im new to coding just to let you know.
i want to make a fft analysis of a time-series dataset spanning one year with datapoints in 15 minute intervals. The dataset I use represents the state of charge of a battery in %. I want to see the different loading cycles (horly, weekly, monthly).
I watched some youtube videos and applied the code of this video to my own data: https://www.youtube.com/watch?v=su9YSmwZmPg
here is my code:
from numpy.fft import fft, fftfreq, ifft
import matplotlib.pyplot as plt, mpld3

# setup domain
# number of points (15 min intervals within 1 year)
nl = 34943

# lengt of watched domain
# 1 year in hours
lx    = 34943/4

# creating x-achsis
x = np.linspace(0, lx, nl)

# full signal
# dataset of different values troughout the year
y = np.array(df['SOC_batt'])

# creating nexessary frequencies
freqs = fftfreq(nl)

# splitting frequencies in half
mask = freqs > 0

# fft values
fft_vals = fft(y)

# true theoretical fft
fft_theo = 2.0*np.abs(fft_vals/nl)

plt.figure(1)
plt.title('original data')
plt.plot(x, y, color='xkcd:salmon')

plt.figure(2)
# fft processed
plt.plot(freqs[mask], fft_theo[mask], label='true fft values')
plt.title('true fft values')
mpld3.display()`

these are the plots i get.
enter image description here
enter image description here
I zoomed in the fft graph and got these x values from the peaks:
# first peack of 4 at 0.01041
# second peak of 5 at 0.02083
# third peack of 1.1 at 0.03125

how can i translate these into more meaningful values regarding im dealing with a whole year of data?
Im not sure how to include data in the post I hope my problem is still understandable though.
thanks in advance


text:
Q: PFSense routing I have PFSense on the following: 192.168.1.1 with machines on the 192.168.1.1/24.
I would like this network to be able to access the 192.168.2.2 network. The WAN on the pfsense is currently 192.168.2.223 and the 192.168.2.0/24 pfsense router with internet access is on 192.168.2.254.
I'm trying without any success in getting the 192.168.1.1/24 network dial out to the 192.168.2.0/24 or the internet.

A: You should not have an Upstream Gateway in you LAN. The Upstream Gateway should be configured in your WAN interface (in this case would be 192.168.2.254 which is, I guess, your internet provider). Looks like you have a wrong network configuration. You should design a simple network diagram with the IP addresses of every device for more info.


text:
Q: Catch all module exceptions to not crash the main app I'm working on a library module (using gradle and proguard) on Android that will be integrated in other application.
Is there a solution to catch all exceptions thrown by a library so if the library have some NPE or exception in other threads (like an OMX exception), the main app will not crash.

A: You can look for any uncaught exception in your liberary project
private Thread.UncaughtExceptionHandler _unCaughtExceptionHandler = new Thread.UncaughtExceptionHandler() {
    @Override
    public void uncaughtException(Thread thread, Throwable ex) {

       //Put a check if it is thrown by your liberary then deal with it.

    }
};

 Thread.setDefaultUncaughtExceptionHandler(_unCaughtExceptionHandler);

A: You can use setDefaultUncaughtExceptionHandler() but if you got uncaught exception then the flow of your app is already interrupted and recovery is usually very hard / impossible. Perhaps the only useful case to catch all the uncaught exceptions is to report it back to developer so you can nail the bug and fix. But if that's your goal, then I'd rather use existing solutions like Crittercism or so.


text:
Q: To use the smartsync to store the data in local soup android native SDK Below is my code for creating the soup on locally and sync down and store  the data in local soup. Below is my code calling onCreate method. Salesforce data is not syncdown. Can anyone help me for this issue.
private void createSoup() {

    IndexSpec[] TMACCOUNTS_INDEX_SPEC = {

            new IndexSpec("product_amount",    SmartStore.Type.floating),
            new IndexSpec("tm_type",      SmartStore.Type.full_text),
            new IndexSpec("Date", SmartStore.Type.full_text),
            new IndexSpec("tm_phone", SmartStore.Type.full_text),
            new IndexSpec("Id",      SmartStore.Type.integer),
            new IndexSpec("OwnerId", SmartStore.Type.string),
            new IndexSpec("User_Name", SmartStore.Type.string)
    };
    mSmartStore.registerSoup(SoupName.TMACCOUNT_SOUP, TMACCOUNTS_INDEX_SPEC);

}

private void syncDownTMAccount() {

    List<String> accountObject =  new ArrayList<>();
    accountObject.add("product_amount");
    accountObject.add("tm_type");
    accountObject.add("Date");
    accountObject.add("tm_phone");

    final SyncOptions options = SyncOptions.optionsForSyncUp(accountObject, SyncState.MergeMode.LEAVE_IF_CHANGED);

    SyncDownTarget target = new SoqlSyncDownTarget("SELECT  product_amount__c, tm_type__c, Date__c, tm_phone__c FROM "+SoupName.TMACCOUNT_SOUP__);

    try {

        DebugLog.d("SyncDownTarget=="+target.asJSON());

       /* syncManager.syncUp(target, options, SoupName.TMACCOUNT_SOUP, new SyncManager.SyncUpdateCallback() {
                    @Override
                    public void onUpdate(SyncState sync) {
                        handleSyncUpdate(sync);
                    }
                });

                JSONArray result = null;
                try {
                    result = mSmartStore.query(QuerySpec.buildSmartQuerySpec("select product_amount__c from {"+ SoupName.TMACCOUNT_SOUP+"}", 10), 0);
                } catch (JSONException e) {
                    e.printStackTrace();
                }

                DebugLog.d("Local DB data= "+result);*/

            }
        });

    } catch (JSONException e) {
        Log.e(TAG, "JSONException occurred while parsing", e);
    }
}


text:
Q: Fetch current location of a Google Plus user's contact I would like to access the location of a User's contact.
Given, that the user is authenticated and the requested contact has granted access to his location data (Location Sharing).
This is basically the same thing as in the Google+ Android App under "Locations" or in the web app, when you open the "About me" information.
I searched the People API, but apparently the "getCurrentLocation" method does not seem to provide that information anymore (delivers NULL).
Thank you for your hints and tips


text:
Q: How to fix decorator mock I have a problem with mocking my decorator in my flask app.
I've tried monkeypatch, mock.patch  and none is working
I'm running with python3.7
Here is my code
in => app/v1/views/user_data.py

@r.route('/myroute/<int:user_id>', methods=['GET'])
@verify_token
def ep_intern_midas_user_data_user_id(user_id):
    # do some stuff here
    return "Done"

in app/v1/decorators/verify_token.py

def verify_token(view_function):
    @wraps(view_function)
    def decorated_function(*args, **kwargs):
        # do decorator stuff

   return decorated_function

in tests/unit_tests/views/user_data.py
from functools import wraps
from app.v1 import decorators

def mock_decorator():
    def decorator(f):
        @wraps(f)
        def decorated_function(*args, **kwargs):
            return 200
        return decorated_function
    return decorator
# !important thing - import of app after replace
decorators.verify_token = mock_decorator

from app import app
app.testing = True

def test_index():
    with app.test_client() as client:
        res = client.get('v1/intern/midas/user_data/1')
        assert res.status_code == 200

(even with monkeypatch)
===== never works

I expected to have the result 200 but I have 401, what is the result if the decorator is called and not its mock.
Thanks for help


text:
Q: How to do synchronous cross-domain call in javascript I am doing cross domain call.
This is taking more time(some ms or 1s).
so below that code is executing.
var xdr;
    if (window.XDomainRequest) // Check whether the browser supports XDR.
    {
        xdr = new XDomainRequest(); // Create a new XDR object.
        if (xdr) {
            xdr.onload = function () {
                var data = $.parseJSON(xdr.responseText);
                AddData(data, link);
            };
            xdr.open("post", urlSearch);
            xdr.send();
        }
        else {
            alert('Server Error!! Try Later.');
        }
    }
    else {
         alert("Not IE 8");
     }

I want to do that synchronous.
So that after that call finished below code will execute
please help
Thanks in advance.

A: Just to clarify, since some "JavaScript" programmers tend to be actually jQuery programmers ( and I doubt that they can even be that, I'm talking about comments ).
Back to the topic. After few minutes of googling it seems that XDomainRequest object does not support synchronous calls.
And this is actually good. What you don't know is that synchronous AJAX ( note that synchronous AJAX is a contradiction on its own - first A stands for Asynchronous ) is the root of all evil in browsers. Why? Because JavaScript is single-threaded, so when user waits for a request to finish he can't do anything - entire page is blocked ( and in some worse cases, like IE8 I believe, entire browser is blocked ).
So what should you do? You should do what every good JavaScript programmer does and write your code in an asynchronous way. For example:
var xdr;
if (window.XDomainRequest) { // Check whether the browser supports XDR.
    xdr = new XDomainRequest(); // Create a new XDR object.
    xdr.onload = function () {
        var data = $.parseJSON(xdr.responseText);
        AddData(data, link);
        // other code goes here
    };
    xdr.onerror = function () {
        alert('Server Error!! Try Later.');
    };
    xdr.open("post", urlSearch);
    xdr.send();
} else {
    alert("Not IE 8");
}

If you have more code that depends on xdr, then simply add it to onload handler ( you can wrap it in a separate function to make it easier to read ).


text:
Q: Can't Create ActiveX Object I am using third party payment gateway for my site.
Once customer fills amount detail and contact detail, page will be redirected to other .asp page.
In that asp page ,i have written below code.
    Dim pipe

    Set pipe = Server.CreateObject("e24PaymentPipe.e24PaymentPipe.1")

    pipe.ResourcePath=resourcePath  'mandatory
    pipe.Alias=aliasName            'mandatory
    pipe.Action=action              'mandatory
    pipe.ResponseURL=receiptURL     'mandatory
    pipe.ErrorURL=errorURL      'mandatory
    pipe.Amt=amount                 'mandatory

    pipe.Currency=curr
    pipe.Language=language
    pipe.TrackId=trackId

    pipe.Udf1=donateamt
    pipe.Udf2=email
    pipe.Udf3=phone
    pipe.Udf4=baddress
    pipe.Udf5=fname

But i am getting error at 2nd line only .
The error says , Can't create Activex Object.
I have successfully registered e24paymentpipe.dll, but still i am getting error.
Can anyone please help me..?

A: IIS 10, example with missing 32-bit 'adrot.dll', used in ASP Classic.
This approach can be applied for another 'old' 32-bit dll-s.

*

*Open installation CD(or DVD, iso, etc.) of Windows XP.

*Be assure of, that folder 'X:\i386'('X' is drive letter)
contains file 'adrot.dl_', where
'dl_' means that this file is compressed 'dll'.

*Open CMD as administrator.

*Expand(decompress) 'adrot.dl_' to 'adrot.dll' by
command in CMD :
X:\i386> expand ADROT.DL_ D:\ADROT.DLL

*Copy/Cut ADROT.DLL to C:\Windows\SysWOW64,
because ADROT.DLL is 32bit component and must to be in 'SysWOW64'.

*In CMD navigate to C:\Windows\SysWOW64 and register dll :
C:\Windows\SysWOW64>regsvr32 adrot.dll

*In IIS, from left pane('Connections'), open(double click) 'Application Pools'

*Find your Application Pool(by column 'Name').

*Right click over name of your Application Pool and open 'Advanced Settings'.

*In 'Advanced Settings', set 'Enable 32-Bit Applications' to 'true'.

A: Finally found my answer.
I did register both dlls (e24payment.dll and e24pipe.dll).
And also check application pool.
In application pool, go to Advanced setting and check that Enable 32 bit application is set to false and that's it.
It worked like a charm.


text:
Q: Existence of measurable set $A\subseteq{\mathbb R}$ which is locally uncountable and so is its complement Is there a measurable set $A\subseteq{\mathbb R}$ such that $|A\cap I|$ and $|A^\complement\cap I|$ are both uncountable for any open interval $I$?

A: The set of real numbers whose decimal representation has a finite number of ones (let's agree a number can't end with infinite 9's, even if it doesn't really change anything.)
It is measurable because you can write it as a countable union of countable intersections of intervals (it's kind of tedious to write down); it is uncountable on every interval because you can truncate the decimal representation and then put only $2$'s and $3$'s as you want; the complement is uncountable because you can truncate the decimal representaiton and then put $1$'s at odd positions and $2$'s or $3$'s at even positions as you want. As a side note this set is of measure zero.

A: Yet another solution:
A rational open interval is an interval of the form $(q_1, q_2)$ for $q_1<q_2$ rationals. There are countably many rational open intervals, and every nonempty open interval contains a rational open interval.
Now for each rational open interval $I$, let $S_I$ be a subset of $I$ which is uncountable but has measure zero - basically, a (thin) Cantor set in $I$. The set $$X=\bigcup_{I\mbox{ a rational open interval}} S_I$$ is then a countable union of measure-zero sets, hence has measure zero and is measurable.

*

*Since $X$ has measure zero, its complement has uncountable intersection with every nontrivial open set.

*On the other hand, by construction $X\cap U$ is uncountable for every nonempty open set $U$: any such $U$ contains a rational open interval $I$, and then $X\cap U\supseteq X\cap I\supseteq S_I$ which is uncountable.

The only weird bit about this is the choice of $S_I$, but this can be done nicely: if $I=(q_0, q_1)$, let $f: x\mapsto (q_1-q_0)x+q_0$. $f$ is a bijection from $(0, 1)$ to $I$. Let $C$ be the usual Cantor set, and let $S_I=f(C\cap (0, 1))$.

A: This construction might be rather tedious but the nice thing is that it works also when 'uncountable' is replaced by 'of positive measure' in the question.
Fix some enumeration $(q_i)_i$ of ${\mathbb Q}$ and define $X_i^j:=B(2^{-2i-j},q_j)$ (where $B(\epsilon,x)$ is the open $\epsilon$-ball around $x$), $X_i:=\cup_j X_i^j$, $Y_0:=\emptyset$ and $$Y_{i+1}:=\begin{cases}Y_i\cup X_{i+1}&i\text{ is even}\\Y_i\setminus X_{i+1}&\text{else.}\end{cases}$$
Then the set $Y:=\liminf_i Y_i$ satisfies our demands.  (Note that $\liminf_i Y_i=\limsup_i Y_i$ almost everywhere since all points outside of $X_i$ become stable after the $i$th construction step and the measure of $X_i$ converges to $0$.)
$Y$ is measureable as $\liminf$ of measurable sets.
Now I want to show that $\mu(Y\cup I)>0$ for any open interval $I$, the proof works analogously for $Y^\complement$ because one can construct $Y^\complement$ analogously to $Y$ by switching $\emptyset$ with ${\mathbb R}$, even with odd and $\liminf$ with $\limsup$.
There exists some odd $m$ and (arbitrary) $n$ with $X_m^n\subseteq I$ and $X_m^n\cap X_{m+1}^j=\emptyset$ for $j<n$.  So $X_m^n\cap Y\supseteq X_m^n\setminus(\cup_{j\ge n} X_{m+1}^j)$ hence $\mu(X_m^n\cap Y)\ge 2^{-2m-n}-2^{-2(m+1)-(n-1)}>0$.


text:
Q: Setup integrated terminal of vs-code with anaconda I have installed the latest anaconda python distribution and as well vs-code editor. When vs-code is used and its terminal prompt invoked I have no Anaconda Prompt available at start respectively integrated terminal has no Anaconda prompt with vs-code environment.
How and where the vs-code editor should be set up with enabled Anaconda prompt terminal?
Moreover, I would like to create a separate python/conda environment within Anaconda and redirect execution there whilst staying with vs-code and its terminal.
I expect the indication for this Anaconda terminal within prompt e.g.
(base) PS C:\Users\

In the vs-code command prompt, I have
PS C:\Users\

A: In Settings.json, add "python.terminal.activateEnvironment": true to make sure when opening a new integrated Terminal, the virtual environment can be activated automatically.
1.Press Ctrl+Shift+` to open an integrated Terminal, run
    conda create -n .venv python=3.8

Then you should get the .venv created successfully:

2.You may see the tips, then activate the .venv:

3.Open Command Palette, select the interpreter by manually entering the path to python.exe, the environment location you can get from the information shown under the create command. Now the python interpreter shown in the left bottom corner should be:
4.Click the green button in the top right corner to Run Python File in Terminal, which will open a new integrated Terminal and environment is activated automatically:

Please follow my steps and have a try. If there's any questions, don't hesitate to let me know.


text:
Q: django.db.utils.ProgrammingError: multiple default values specified for column "_id" of table "Asset_movie" After make migrations , i tried to do migrate, but i am getting the django.db.utils.ProgrammingError: multiple default values specified for column "_id" of table "Asset_movie"
from django.db import models
import date time
from django.contrib import admin

class Movie(models.Model):
        CHOICES_MOVIE_TYPE = (
             ("SF", 'Short-Film'),
             ("P", "Promo"),
             ("OT", 'Other'),
         );
           CHOICES_LANGUAGE_TYPE = (
               (" ", ''),

           );
           CHOICES_ORIGINAL_OWNER_TYPE = (
               ("OT", 'Other'),

           );
           CHOICES_REMARK_TYPE = (

           );
          # _id = models.AutoField(primary_key=True)
           name = models.CharField(max_length = 50, blank = False)
           Movie_Type = models.CharField(max_length = 2, choices = CHOICES_MOVIE_TYPE, default = "OT", blank = False)
           language = models.CharField(max_length = 5, choices=CHOICES_LANGUAGE_TYPE, default = "OT", blank = False)enter code here
           tags = models.TextField()
           original_owner = models.CharField(max_length = 2, choices = CHOICES_ORIGINAL_OWNER_TYPE, default = "OT", blank = False)
           Partner = models.CharField(max_length = 10)
           acquisition_cost = models.DecimalField(max_digits = 5, decimal_places = 4,  blank = True)
           release_date = models.DateField(("Date"), default = datetime.date.today)


text:
Q: Pyspark .startswith reverse does not work I have a dataframe which contains multiple mac addresses. I need to filter out mac adresses starting with 'ZBB'. I am using a solution that makes sense to me:
import pyspark.sql.functions as f
dffinal = df.filter(f.col("mac_address").startswith("ZBB") === false)

unfortunately this solution doesn't work as it does not recognise ===, when I put == then 'false' is not defined. I am trying out solutions from https://sparkbyexamples.com/spark/spark-filter-startswith-endswith-examples/ unfortunately something goes wrong. Can anyone point me towards a working solution?

A: Booleans in python are capitalized, so True & False. Python doesn't know the triple equal ===.
For your problem you can solve it the way you have now.
df.filter(f.col('mac_address').startswith('ZBB') == False)

Or use the tilde ~, which does a bitwise NOT, but can be less readable in my opinion.
df.filter(~f.col('mac_address').startswith('ZBB'))


text:
Q: How to extract filename from string in vimscript? Say we are given this string in a vimscript:
"/home/Linus Torvalds/.vim/bundle/vim-autoformat/formatters/tidy -q --show-errors 0 --show-warnings 0 --indent auto --indent-spaces 2 --vertical-space yes --tidy-mark no --wrap 68".
How do we extract the filename part? In this case that would be:
"/home/Linus Torvalds/.vim/bundle/formatters/tidy".

A: If you can guarantee there are no dashes (-) in the path itself, I would do it like this:
matchstr(input_string,'^.\{-}\ze -')

Explanation: From the beginning of the string (^) match any character non-greedily (.\{-}) until the first occurrence of a space followed by a dash (\ze -).
Or you could just match until the first dash and then trim any trailing whitespace with a substitute() command, which would be less concise, but might be more readable.


text:
Q: How can I add additional dependencies for my maven project without committing it to pom.xml file? I want to add a dependency for example Spring Developer Tools.  I understand that I can add it to the pom.xml file, but that'll make git show the addition as an uncommitted change.  I don't want to commit this, it'll be just for my local testing.
Is there a way I can have a secondary pom.xml file for this dependency and then I can add that to .git/info/exclude so that it can be ignored?

A: do a new git branch and put your changes there for testing. Example
git checkout -b "feature/playground"

Modify your pom, than you can apply your changes to your testing branch.
git add -u
git commit -m "Devtools added"

if you need to go back to your unchanged branch.
git checkout master

if master is your main branch.
This is by far best solution. If you for some un clearly reasons want avoid of pushing devtools into your master branch.
But to answer you Question directly. Depend on your IDE, you can add a Dependencie without to change your pom. For that you need to download the .jar you want to add.
And than add it via UI of your IDE. Here is an example how it looks like in JetBrains IntelliJ IDEA


text:
Q: My query generates an ORA-00933 error, why is that? I'm using php to generate an oracle query like this:
...

$sql = sprintf("INSERT INTO $table_name %s %s ON DUPLICATE KEY UPDATE ",
            $this->prepare_insert_sql("", $fields, false),
            $this->prepare_insert_sql(" VALUES ", $values, true));
    for ($index = 0; $index < count($fields); $index++) {
        if ($index > 0) {
            $sql .= ", ";
        }
        $sql .= $fields[$index] . "='" . $values[$index] . "'";
    }
...

And the result query is:
INSERT INTO TBL_CONFIG(KEY,VALUE)
VALUES ('1_default_meter_type_for_device_type_1','822')
ON DUPLICATE KEY
UPDATE KEY='1_default_meter_type_for_device_type_1', VALUE='822'

It gives an ORA-00933 error.
I really can't seem to find the error. Any tip is appreciated.

A: Using merge instead of insert into worked.
MERGE INTO TBL_CONFIG USING DUAL ON (KEY ='1_default_meter_type_for_device_type_1')
WHEN MATCHED THEN UPDATE SET VALUE = '822'
WHEN NOT MATCHED THEN INSERT (KEY, VALUE) VALUES ('1_default_meter_type_for_device_type_1', '822')

A: Per your posted code KEY is a reserve word and so you need to escape it using "" double quote like below
INSERT INTO TBL_CONFIG("KEY",VALUE)
VALUES ('1_default_meter_type_for_device_type_1','822')
ON DUPLICATE KEY
UPDATE "KEY"='1_default_meter_type_for_device_type_1', VALUE='822'

EDIT:
Totally confused. Oracle doesn't have ON Dulicate Key Update. You have to use MERGE statement as commented by Fred-ii.

A: Try this:
$sql = sprintf(
    "INSERT INTO $table_name %s %s ON DUPLICATE KEY UPDATE ",
    $this->prepare_insert_sql("", $fields, false),
    $this->prepare_insert_sql(" VALUES ", $values, true)
);

for($index = 0; $index < count($fields); $index++) {
    if($index > 0) {
        $sql .= ", ";
    }

    // added " before and after field name
    $sql .= '"' . $fields[$index] . '"=\'' . $values[$index] . "'";
}


text:
Q: Limit scrollbars to content area when static header/footer are present There is this example for a web page with static header and footer:
Site Link
(when looking at this webpage, please remove the transparent archive.org header by clicking on the red "X" top right)
My question is, is it (easily) possible to limit the scrollbar to the actual (scrollable content) area -- in other words, the scrollbar should not extend over the static header and footer (like it does now).
Here is a jsfiddle showing the same: scrollable content with static headers and footers where the scrollbar goes over header and footer, but should be limited to the content box:
#content {
width: 1024px;
margin: 0 auto;
padding: 60px 0;
height:calc(100% - 120px);
}

Here is an example of the current implementation:

html, body {
    height: 100%;
    width: 100%;
    margin: 0;
    padding: 0;
    background-color:#ff00ff;
    margin:0px auto;
}
.wrapper {
    width:100%;
    height:100%;
}
.container {
    width:1024px;
    margin:0px auto;
    height:100%;
}
header {
    width: 1024px;
    height: 60px;
    background: red;
    position: fixed;
    top: 0;
}
#content {
    width: 1024px;
    margin: 0 auto;
    padding: 60px 0;
    height:calc(100% - 120px);
    background-color:#fff;
}
footer {
    width: 1024px;
    height: 60px;
    background: red;
    position: fixed;
    bottom: 0;
}

HELLO

HELLO

HELLO

HELLO

HELLO

HELLO

HELLO

HELLO

HELLO

HELLO

HELLO

HELLO

HELLO

HELLO

HELLO

HELLO

HELLOWEEN

A: You can have a scrollable content pane, by using: overflow: auto; on #content.
Here is an altered version of your css to help you with your current problem:

html, body {
    height: 100%;
}
body {
    margin: 0;
    padding: 0;
    background-color:#ff00ff;
}
.wrapper {
    width:1024px;
    height: inherit;
}
.container {
    margin:0 auto;
    height: inherit;
}
header {
    height: 60px;
    background: red;
}
#content {
    margin: 0 auto;
    padding: 0;
    height:calc(100% - 120px);
    background-color:#fff;
    overflow: auto;
}
footer {
    height: 60px;
    background: red;
}

HELLO

HELLO

HELLO

HELLO

HELLO

HELLO

HELLO

HELLO

HELLO

HELLO

HELLO

HELLO

HELLO

HELLO

HELLO

HELLO

HELLO

HELLO

HELLO

HELLO

HELLOWEEN

And here is the jsFiddle as well: http://jsfiddle.net/7S4Xx/271/


text:
Q: external keyboard: cannot use f1,f2 etc. keys without pressing fn key I am using mba with high sierra and an external keyboard JETech 2156. The problem is I do not want to use fn key, for example F8 key has play or pause option. I have to press fn+f8 to pause or play. I simply want to press f8 rather than pressing fn key every time.
In the keyboard settings the box next to use f1, f2 as std function keys is unchecked. It does not matter if this box is checked or unchecked. In modifier keys I've selected the JETech 2156.

A: Unfortunately trying to fix this problem is as simple as checking a box on macOS. It is simply not something that macOS is capable of modifying—at least without third-party apps.
On a very simple level, keyboard work by sending "keystrokes" to the operating system that they are connected to. It is the job of the operating system to interpret the meaning of those keystrokes, which is generally does accurately.
The way the keyboard that you linked is designed is that it sends out the "special" keystrokes by default. For example, instead of sending out the F10 keystroke, it send out a "mute" keystroke. The OS interprets this keystoke and carries out the respective action.
If you wanted that button to send the actual F10 keystroke, the only way you can do it is by pressing Fn on the keyboard and then that button. Unless there is a specific setting that can be configured on the keyboard itself, there is no way of changing the keystroke that is sent out, and it looks like the keyboard does not support this useful feature.
So there is no way to change the actual keystrokes that are sent because the keyboard stubbornly doesn't want to send them. However, you can trick the keyboard. You can tell macOS to interpret the keystroke as something else—for example, you can tell macOS that, if it receives the "mute" command from that keyboard, it should interpret that as the F10 key. This is possible through the amazing little Karabiner Elements utility.
After installing Karabiner, open Karabiner EventViewer. Press the key that you want to change (for example the mute button). Click on the button that appears on the top right which says "Add mute to Karabiner-Elements." Then, change the action to F10. Ensure that the device at the top that is selected is your external keyboard and not "All Devices" because you don't want F10 to be triggered every time you use your Mac's keyboard to mute.
Note: one potential caveat: there are some keys that do not send a keystroke to the OS and thus can't be remapped. One example is the Fn key on external keyboards. Apart from those exceptions (to my knowledge only the Fn key), you should be able to remap just about any other key.


text:
Q: Is it common to decide not to go to graduate school after extensive undergraduate research experience? At the beginning of my undergraduate career, I was almost sure I would want to apply to graduate programs in pure mathematics. Is it common to make such drastic change at the end of one's undergraduate career?

A: I think it's very common. Oxford and Cambridge produce about 400 mathematics graduates a year, only a small fraction do PhDs.
The whole point of undergraduate research opportunities is to give you a feel for what research is. This then allows you to make a more informed choice of whether it's for you. Realizing now that it's not right for you is much better than deciding that three years down the track.
Many math PhD students are disappointed that it's not more like undergraduates maths where nice well-developed closed theories are studied. Instead a lot of it is trying to understand and make sense of strange examples in order to build a theory.
In terms of your experiences, these things happen. Sometimes only after it's written up does a student discover it's already been done. Research is very hard to plan and progression rate is generally very unclear.
Do a PhD if you love maths and can't imagine doing anything else.


text:
Q: Как не прервать аудио-стрим с сайта при переходах между страницами? Необходимо добавить на сайт прослушивание аудио-композиций, которое не будет обрываться при переходе между страницами.
Сайт работает под Yii2.
Первое, что приходит в голову - весь сайт сделать на ajax, в том числе переходы между страницами, но это переделывание работающего функционала. Прошу совета, существуют ли другой подход и решения?

A: Создайте в качестве главной страницу с таким упрощённым содержимым:

document.onclick = function(){document.querySelector("audio").play()}; // запускаем фоновую музыку кликом по произвольному месту в документе
<audio src="sound.mp3"></audio>
<iframe src="http://www.mysite.com" width=100% height=100%></iframe>

где www.mysite.com - собственно сайт. Способ хорош тем, что одинаково подходят свой или чужой сайт.


text:
Q: How to redirect https to private port? I have an webserver with snap which run in http://example.com:3001 (it doesn't have support for https) so i'm using nginx proxypass together with cerbot to generate a certificate and it works great but i have two questions:
1.- This https://example.com <--> nginx <--> http://example.com:3001 redirection is the correct way to do it?  I am not sure since it's still being posible to go directly to unsecure port 3001.
2.- It's posible to do this redirection in the host to avoid to open 3001 port to internet?
Thanks in advance.


text:
Q: pass variable from UIViewController to UIView I have created a class file for my UIView(draw2D) and ViewController(ViewControllerImage)
When the view loads, viewControllerImage receives a pushed variable. That works, I now need to assign the variable into the draw2D.
draw2D.h
@property (nonatomic, assign) double thicknessValue2;

How do I access that inside the ViewController inside the viewDidLoad to set a variable inside the draw2D?

A: I am assuming your draw2D view is a property/subview of your ViewControllerImage view?
The setter for this property can be used in one of 2 ways:
myDraw2D.thicknessValue2 = whatever;

or
[myDraw2D setThicknessValue2:whatever];

A: Instantiate draw2D (UIView) inside viewControllerImage (UIViewContoller) and acces it property.
e.g.,
UIView *someView= (UIView *)[[[NSBundle mainBundle] loadNibNamed:@"nameOfXIB" owner:nil options:nil] objectAtIndex:0];

[self.view addSubView:someView];

someView.thicknessValue2 = YourPushedValue;

Don't forget to @synthesize your thicknessValue2 in .m file.
Hope it helps!


text:
Q: Regenerating confirmation token using devise rails 4 I am trying to regenerate confirmation token for the users who have not confirmed their accounts yet. I want to resend confirmation email to the user say after few days.I am following this link to regenerate the new token for that user, and its generating it but still its not working.
https://github.com/plataformatec/devise/issues/2615.
and I am following these steps on my console locally.
@user = User.find_by_email("abc@xyz.com")
token = Devise.token_generator.generate(@user.class, :confirmation_token)

then in token i am getting array such as

token = ["gfbgk4535843tbk","8545kjbng8hguhggre8gergerkgjebg8gergkerjgg9ergejgn"]

then i am just sending an email like this
Devise::Mailer.confirmation_instructinos(@user,token.last).deliver

then its delivering an email to that user, but when user clicks on confirm account it takes user to the site but when user tries to login its not working.

A: You can resend confirmation email using Devise built in methods:
users = User.where('confirmation_token IS NOT NULL')
users.each do |user|
  user.send_confirmation_instructions
end

send_confirmation_instructions method should generate a new token if token period expired.
I've been using this approach a few times and it did what was expected.
Also you could try resend_confirmation_instructions,
  # Resend confirmation token.
  # Regenerates the token if the period is expired.
  def resend_confirmation_instructions
    pending_any_confirmation do
      send_confirmation_instructions
    end
  end

comments above the method clearly states that token will be regenerated. I haven't tried this one yet.


text:
Q: Vertex marker in Edit Vertices not appearing on half screen I'm using ArcMap on ArcGIS Desktop 10.5 and when I enter the Edit Vertices context, the vertex markers on the left side of the screen are hidden. You can click on them, but the marker does not appear. In the screenshot you can see I've selected a line for editing, the right side of the screen shows the line and vertex markers but at a certain point as you move left you see they no long appear.
Has anyone else experienced this bug or have any suggestions on fixing it?


text:
Q: Get the Spinner Value from Activity into my adapter I have a Spinner set in my Toolbar in my Activity.
In my activity I have a FragmentPagerAdapter which I populate with five Pages, from a newInstance of a Fragment.
How can I get the value of my spinner after I change it into my fragments. I'm using this spinner to set a Single/Multi Selection Mode in the RecyclerView I have in my fragment Pages.
I know how to get the value in my activity even to pass it to the FragmentPagerAdapter, but my problem is if I change it, for it to take effect in my RecyclerView I have to reload the Activity.
My Activity
        @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_pattern_selector);
        Intent intent = getIntent();
        patternImages = intent.getParcelableArrayListExtra(PATTERN_IMAGES);
        patternSelectedMode = intent.getIntExtra(PATTERN_SELECTED_MODE, 0);
        titles = getResources().getStringArray(R.array.tabs_pattern_title);
//        spinnerItems = getResources().getStringArray(R.array.spinner_pattern_selector);
        setUpPagerAdapter();
        setUpToolbar();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {

        getMenuInflater().inflate(R.menu.menu_pattern_selector, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    protected void onPostCreate(Bundle savedInstanceState) {

        super.onPostCreate(savedInstanceState);
        View mainContent = findViewById(R.id.view_pager_container);
        if (mainContent != null) {
            mainContent.setAlpha(0);
            mainContent.animate().alpha(1).setDuration(MAIN_CONTENT_FADE_IN_DURATION);
        } else {
            Log.d(TAG, "No view with ID main_content to fade in.");
        }
    }

    private void setUpPagerAdapter() {

        patternsPagerAdapter = new PatternsPagerAdapter(getSupportFragmentManager(), this);
        for (int i = 0; i < titles.length; i++) {
            switch (i) {
                case 0:
                    minIndex = 0;
                    maxIndex = 3;
                    fragmentTitle = titles[i];
                    break;
                case 1:
                    minIndex = 3;
                    maxIndex = 50;
                    fragmentTitle = titles[i];
                    break;
                case 2:
                    minIndex = 50;
                    maxIndex = 60;
                    fragmentTitle = titles[i];
                    break;
                case 3:
                    minIndex = 60;
                    maxIndex = 86;
                    fragmentTitle = titles[i];
                    break;
                case 4:
                    minIndex = 0;
                    maxIndex = 0;
                    fragmentTitle = titles[i];
                    break;
            }
            Bundle bundle = new Bundle();
            bundle.putInt(MIN_NUMBERS, minIndex);
            bundle.putInt(MAX_NUMBERS, maxIndex);
            bundle.putInt(PATTERN_SELECTED_MODE, patternSelectedMode);
            bundle.putString(TITLE, fragmentTitle);
            patternsPagerAdapter.addFragment(FragmentCommonPatterns.newInstance(minIndex, maxIndex, fragmentTitle, patternSelectedMode));
        }
        viewPager = (ViewPager) findViewById(R.id.view_pager_container);
        viewPager.setAdapter(patternsPagerAdapter);
        tabLayout = (TabLayout) findViewById(R.id.pattern_tab_layout);
        tabLayout.setupWithViewPager(viewPager);
        tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {

            //TODO Check if I need this
            @Override
            public void onTabSelected(TabLayout.Tab tab) {

                patternsPagerAdapter.getItem(tab.getPosition());
//                System.out.println("Fragment Selected " + tab.getText().toString());
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

//                System.out.println("Fragment Deselected " + tab.getText().toString());

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

//                System.out.println("Fragment Reselected " + tab.getText().toString());

            }
        });
    }

    public void setUpToolbar() {

        toolbar = (Toolbar) findViewById(R.id.toolbar_pattern_selector);
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setDisplayShowTitleEnabled(false);
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {

                onBackPressed();
            }
        });
        SpinnerAdapter spinnerAdapter = ArrayAdapter.createFromResource(this, R.array.spinner_pattern_selector, R.layout.item_spinner_pattern_selector);
        spinner = new Spinner(getSupportActionBar().getThemedContext());
        spinner.setAdapter(spinnerAdapter);
        toolbar.addView(spinner, 0);
        spinner.setSelection(patternSelectedMode);

        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

                switch (position) {
                    case 1:
                        patternSelectedMode = 1;
                        Toast.makeText(getApplicationContext(), getResources().getString(R.string.pattern_image_selected_single), Toast.LENGTH_SHORT).show();
                        for (PatternImages current : patternImages) {
                            current.setSelected(false);
                        }
                        patternsPagerAdapter.notifyDataSetChanged();
                        break;
                    case 2:
                        patternSelectedMode = 2;
                        Toast.makeText(getApplicationContext(), getResources().getString(R.string.pattern_image_selected_multiple), Toast.LENGTH_SHORT).show();
                        patternsPagerAdapter.notifyDataSetChanged();
                        break;
                    default:
                        patternSelectedMode = 0;
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
    }

    public ArrayList<PatternImages> getPatternImages() {

        return patternImages;
    }
    public int getSpinnerValue() {

        return patternSelectedMode;
    }

    public void setPattern(MenuItem item) {

        Intent returnIntent = new Intent();
        returnIntent.putParcelableArrayListExtra(PATTERN_IMAGES, patternImages);
        returnIntent.putExtra(PATTERN_SELECTED_MODE, patternSelectedMode);
        setResult(RESULT_OK, returnIntent);
        finish();
        overridePendingTransition(R.anim.in_left, R.anim.out_right);

    }
    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
//        spinner.startAnimation(AnimationUtils.loadAnimation(this, R.anim.get_attention));
//        Log.d(TAG, "onWindowFocusChanged Started");
        super.onWindowFocusChanged(hasFocus);
    }
    @Override
    public void onBackPressed() {

        if (tabLayout.getSelectedTabPosition() > 0) {
            viewPager.setCurrentItem(tabLayout.getSelectedTabPosition() - 1);
        } else {
            Intent returnIntent = new Intent();
            returnIntent.putParcelableArrayListExtra(PATTERN_IMAGES, patternImages);
            returnIntent.putExtra(PATTERN_SELECTED_MODE, patternSelectedMode);
            setResult(RESULT_CANCELED, returnIntent);
            finish();
            overridePendingTransition(R.anim.in_left, R.anim.out_right);
            super.onBackPressed();
        }
    }

Fragment
 public static FragmentCommonPatterns newInstance(int minIndex, int maxIndex, String fragmentTitle, int patternSelectedMode) {

    FragmentCommonPatterns patterns = new FragmentCommonPatterns();
    Bundle args = new Bundle();
    args.putInt(MIN_NUMBERS, minIndex);
    args.putInt(MAX_NUMBERS, maxIndex);
    args.putInt(PATTERN_SELECTED_MODE, patternSelectedMode);
    args.putString(TITLE, fragmentTitle);
    patterns.setArguments(args);
    return patterns;
}

@Override
public void onCreate(@Nullable Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    Log.d(TAG, "onCreate: ");
    minIndex = getArguments().getInt(MIN_NUMBERS);
    maxIndex = getArguments().getInt(MAX_NUMBERS);
    fragmentTitle = getArguments().getString(TITLE);
    titles = getResources().getStringArray(R.array.tabs_pattern_title);

}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

    View view = inflater.inflate(R.layout.fragment_common_patterns, container, false);
    if (fragmentTitle.equals(titles[4])) {
        floatingActionButton = (FloatingActionButton) view.findViewById(R.id.fab_custom_patterns);
        floatingActionButton.setVisibility(View.VISIBLE);
        floatingActionButton.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {

                Toast.makeText(getActivity(), "Edit your own custom patterns", Toast.LENGTH_SHORT).show();
                //TODO
            }
        });
    }
    ActivityPatternSelector activityPatternSelector = (ActivityPatternSelector) getActivity();
    patternImages = activityPatternSelector.getPatternImages();
    patternSelectedMode=activityPatternSelector.getSpinnerValue();
    setUpPatternsRecyclerView(view);
    return view;
}

private void setUpPatternsRecyclerView(View view) {

    RecyclerView recyclerPatternsView = (RecyclerView) view.findViewById(R.id.pattern_image_recycler_view);
    PatternImageAdapter adapter = new PatternImageAdapter(getActivity(), patternImages.subList(minIndex, maxIndex), patternSelectedMode);
    recyclerPatternsView.setAdapter(adapter);
    ColumnQty columnQty = new ColumnQty(getActivity(), R.layout.item_image_pattern_cardview);
    GridLayoutManager gridLayoutManager = new GridLayoutManager(getActivity(), columnQty.calculateNoOfColumns());
    recyclerPatternsView.setHasFixedSize(true);
    recyclerPatternsView.setLayoutManager(gridLayoutManager);
    recyclerPatternsView.setItemAnimator(new DefaultItemAnimator());
    recyclerPatternsView.addItemDecoration(new GridSpacing(columnQty.calculateSpacing()));
}

A: You can add an "updatePattern" method to your fragment.
Then iterate over the fragments in your adapter and update them.
Pseudo code:
for (int i = 0 ; i < fragmentsArray.size() ; i ++) {
            Fragment fragment = fragmentPagerAdapter.getItem(i);
            fragment.updateSelectedPatternMode(newPattern);
 }

PS: For cleanred code you can encapsulate the iterating over fragments inside your PagerAdapter and add a public update method to the adapter.


text:
Q: Travis CI timeout when generating code coverage for PHP I'm trying to get Travis CI to output a coverage report to be used with scrutinizer later. But I'm having trouble to get it to work.
When I add --coverage-clover=coverage.clover to my phpunit command, the generation of the coverage report fails with the following error:

Generating code coverage report in Clover XML format ...PHP Fatal error:  Maximum execution time of 30 seconds exceeded in /home/travis/.phpenv/versions/5.5.7/share/pyrus/.pear/php/PHP/Token.php on line 432

This puzzles me for several reasons:

*

*generating the report takes only about 3 seconds on my local machine which actually seems to be slower than the test server (judging from the time the test suite needs)

*command line PHP does not have a timeout usually, so this seems to be setup deliberately on Travis-CI?

*it seems noone else is having this kind of problem as I couldn't find any similar reports when googling

*my bootstrap.php file for phpunit explicitly calls set_time_limit(0);
Is there a way to fix this on my side?
Full build log at https://travis-ci.org/splitbrain/dokuwiki/jobs/16522833


text:
Q: FlowInputMappingException when mapping of object in Spring Webflow I am trying to follow the code for Spring Webflow from 'Spring in Action'. However, when I tried to run the application, I got the following error:
org.springframework.webflow.engine.FlowInputMappingException: Errors occurred during input mapping on startup of the 'pizza' flow; errors = [[RequiredError@13cb4078 mapping = order -> flowScope.order, code = 'required', error = true, errorCause = [null], originalValue = [null], mappedValue = [null]]]

I believe the line that instantiates the order object in the following flow xml is responsible for the exception:
<var name="order" class="com.mycompany.pizza.domain.Order" />
    <subflow-state id="customer" subflow="customer-flow">
        <input name="order" value="order"/>
        <transition on="customerReady" to="buildOrder" />
    </subflow-state>

My subflow xml looks like this:

<view-state id="welcome">
    <transition on="phoneEntered" to="lookupCustomer" />
</view-state>

<action-state id="lookupCustomer">
    <evaluate result="order.customer"
        expression="pizzaFlowActions.lookupCustomer(requestParameters.phoneNumber)" />
    <transition to="registrationForm"
        on-exception="com.mycompany.pizza.service.CustomerNotFoundException" />
    <transition to="customerReady" />
</action-state>

Hope there's someone who could point me at the right direction. Thanks!

A: The error is saying you are REQUIRED to pass a NOT NULL input param/obj "order" to your subflow and you are passing a null value in the order input. So if it is not provided it will throw the exception you see. At the top of your subflow should look something like this:
<input name="order" required="true" type="com.mycompany.pizza.domain.Order"/>

That being said, generally I think when passing pojos between flows/subflows it is good practice to be very explicit and fill out the 'type' attribute in both input tags on the caller of the subflow and the subflow itself and to fill out the scope prefix for the value attribute (e.g flowScope.order)
Moreover, I think your problem is that the <var> tag is NOT initializing your Order pojo that is why it is null it is the equiv of:
Order order = null;

You should explicitly set flowScope.order via a new operator or a factory-method call using the 'set' tag inside an 'on-start' tag in beginning of your parent flow. Something like this:
<on-start>
       <set name="flowScope.order" value="new com.mycompany.pizza.domain.Order()"/>
        <!-- for development purposes... assuming you are using log4j grab the logger and check that order is in fact NOT null -->
        <evaluate expression="T(org.apache.log4j.Logger).getLogger('someLogger').info(flowScope.order)"/>
</on-start>

and then (still inside your parent flow) change your subflow call to look like this:
<subflow-state id="customer" subflow="customer-flow">
    <input name="order" value="flowScope.order" type="com.mycompany.pizza.domain.Order"/>
    <transition on="customerReady" to="buildOrder" />
</subflow-state>

and... Make sure you also fill out the type attribute inside the input tag of your subflow.xml for order like so:
<input name="order" required="true" type="com.mycompany.pizza.domain.Order"/>


text:
Q: ¿Django, Flask y Express son un frame de cliente o de servidor? Disculpen mi falta de conocimiento, ya que aun soy nuevo en este tema, pero me gustaría saber lo siguiente:
¿Django, Flask y Express  son un frame de cliente o de servidor?


text:
Q: Can't access grub menu no matter what I try | Ubuntu 22.04 | EFI boot I wanna access the grub menu so I can play around with kernel parameters and have them be temporary per boot.
My system is EFI so I tried holding Esc at boot. When I do, it gets frozen at the Lenovo logo. I've also tried setting the following in /etc/default/grub...
GRUB_DEFAULT=10
GRUB_TIMEOUT_STYLE=menu
GRUB_TIMEOUT=10

...and running sudo update-grub. That makes the system get stuck at the Lenovo logo for 10 seconds before booting with the Ubuntu logo like normal.
It seems like the Lenovo logo is preventing the grub menu from showing. My laptop is a Thinkpad T440p. How do I get to my grub menu?

A: I'm interested in making graphically cool boot menu, and tried a few grub gfxmode options and theme packages, but it only shows Lenovo logo.
So I agree

It seems like the Lenovo logo is preventing the grub menu from showing.

but I don't know why, I guess gfx problem.
If such is the case, try console mode: GRUB_TERMINAL=console in /etc/default/grub.
It worked fine for my laptop Lenovo ThinkPad Edge E440.
My configutation is
$ cat /etc/default/grub | grep -v '^#' | grep -v '^$'

GRUB_DEFAULT=0
GRUB_TIMEOUT_STYLE=menu
GRUB_TIMEOUT=10
GRUB_DISTRIBUTOR=`lsb_release -i -s 2> /dev/null || echo Debian`
GRUB_CMDLINE_LINUX_DEFAULT="quiet splash"
GRUB_CMDLINE_LINUX=""
GRUB_TERMINAL=console

$ sudo update-grub

By this setup, the grub menu shown up on boot.
Typing e key successfully entered into edit mode.
My Reproduction Procedure:

*

*Erase whole disc space of /dev/sda and clean install Ubuntu 22.04_1 without network connection.

*Open the configuration file for edit:
 $ sudo vi /etc/default/grub

*Edit the following three lines like this:
 GRUB_TIMEOUT_STYLE=menu
 GRUB_TIMEOUT=10
 GRUB_TERMINAL=console

*Don't forget reconfigure update:
 $ sudo update-grub

*Reboot, worked fine.


text:
Q: Python function to display information about data I am trying to write two functions. One generates random numbers between 1 and 100 with the parameter being the frequency of numbers which saves the information to a file, and another one reads this file and displays the: total sum, average, highest and lowest value. I have managed to get the first function to work however the secound function does not. When running the program I get the TypeError: 'int' object is not iterable due to the "number=int(number)" line in the readNumbers() function, which I don't understand because I thought the number had to be changed from a string to an int in order for equations to work. Any help would be appreciated. Also is there a method of finding the maximum and minimum values without using max() and min(), I would personally like to know.
def generateNumbers(i):
    myFile=open("numbers.txt","w")

    for n in range(i):
        import random
        numbers=random.randint(1,100)
        numbers=str(numbers)
        myFile.write(numbers)
     myFile.close()

generateNumbers(400)

def readNumbers():
    myFile=open("numbers.txt","r")

    for number in myFile:
        number=int(number)
        total=(sum(number))
        average=sum/float(len(number))

    while number!=-1:
         num_list.append(number)
         high= max(num_list)
         low= min(num_list)

     print(total,average,high,low)

     myFile.close()

readNumbers()

A: Your program has several problems.
Writing the numbers:
You're not separating the numbers in anyway, so your file will contain a very long string of digits (and to nitpick, your numbers is actually random_number)
if you f.ex myFile.write("\n") after myFile.write(random_number) each number
will be separated by a newline.
Now, since separating the numbers with newline, your reading will work, except that you should read them into an array, then do total and average.
ie:
num_list = []
for number in myFile:
    if number != "\n": # there is an empty line at the end
        num_list.append(int(number))

total = sum(num_list)
average = total / len(num_list)
high = max(num_list)
low = min(num_list)

Note that you don't need the while loop
You could also do the reading with python's list comprehension, and close the file automatically with a context manager
with open("numbers.txt", "r") as f:
    num_list = [int(number) for number in f if number != "\n"]

(edited to avoid error on empty line at end)

A: Kindal is right.
You should do something like:
sum = 0;
count = 0;
for number in myFile:
    sum += number
    count += 1
average = sum /count

Moreover, I think that you can optimise a bit your code. Read the file and create a list, then you can easily calculate sum, avg, min, max.
with open("my filename.txt", 'r') as myFile:
   number_list = list()
   for number in myFile:
       number = int(number)
       if number != -1:  #Is it necessary for you?
           number_list.append(number)
sum = sum(number_list)
average = sum / len(number_list)
min_val = min(number_list)
max_val = max(number_list)


text:
Q: register bower packages in nexus oss I have configured bower and nexus using this tut:

https://books.sonatype.com/nexus-book/3.0/reference/bower.html

I have bowerrc.json like below:
{
"registry" : {
"search" : [
"http://localhost:8081/repository/bower-all/"
],
"register" : "http://localhost:8081/repository/bower-internal"
},
"resolvers" : [ "bower-nexus3-resolver" ]
}
and i use bower-nexus3-resolver as resolver integrating bower and nexus.
this config installs bower packages and packages are cached in nexus but i cant register my own bower package locally in nexus ?

A: Registering your own packages is documented here. Following the steps there should work just fine. Keep in mind that bower registries point back to a git server typically so you have to have that running as well.


text:
Q: Div Containing  and  getting formatted like link As seen below, I have  3 links inside a div with a class of "nav", and then 4 divs in a div with a class of "contact-info", each containing an image and some text.
Now for some reason, which I can't figure out, my divs inside "contact-info" are underlined and turn red when clicked, as if they would've been a link. This is even without giving it any css.
If anyone could look into my script and tell me what I'm doing wrong I'd greatly appreciate it.
<!DOCKTYPE html>

Log In

Sign Up

Contact Us

Company Name

Company Address

City, State Zip

Phone Number

Fax Number

Email Address

A: You need to close the link tags like this

Log In>

Sign Up>

Contact Us

Hope this helps :)
Also, I just had another look at the code, and there is no need to close your break tags, just

Company Name
Company Address
City, State Zip

on its own Is fine, but I don't think it makes a real difference :)


text:
Q: Ruby on Rails - Migrations, unique columns and indexing (using arrays) This question has been asked here, but an answer gave me a follow-up question.
How do I make a column unique and index it in a Ruby on Rails migration?
add_index :table_name, :column_name, :unique => true

To index multiple columns together, you pass an array of column names instead of a single column nam
add_index :table_name, [:column_name_a, :column_name_b]

I was browsing some code on the web and came across this snippet.
class AddIndexesToSyllabus < ActiveRecord::Migration
  def change
    add_index :syllabuses, :template_id, unique: true
    add_index :syllabuses, :edit_id, unique: true
    add_index :syllabuses, :view_id, unique: true
  end
end

I had no idea what unique: true did so I searched and came across the aforementioned link. However, I must ask this question. Is it possible to re-arrange that code like this.
class AddIndexesToSyllabus < ActiveRecord::Migration
  def change
    add_index :syllabuses, [:template_id, edit_id, view_id], unique: true
  end
end

In the above example, we have the table name, syllabuses along with three column-names(template_id, edit_id and view_id). The previous question led me to believe that the above is possible, but there was no confirmation. I'm trying to learn how to write efficient code and my suggestion is a lot more efficient. Would this work?
Thanks for your help.

A: You can create unique indexes either way, but the two methods are not equivalent.
Defining the multi-column index will ensure uniqueness of the combination of columns, so these combinations would all be valid:
+-------------+---------+---------+
| template_id | edit_id | view_id |
+-------------+---------+---------+
|           1 |       1 |       1 |
+-------------+---------+---------+
|           1 |       2 |       1 |
+-------------+---------+---------+
|           2 |       1 |       1 |
+-------------+---------+---------+

Whereas with the individual indexes, all but the first combination would fail.


text:
Q: How to connect raspberry pi to internet? Here i have connected my raspberry pi to my laptop using the ethernet cable.
Inside the raspberry pi boot SD card i have opened the file cmdline and added the following information at the end of the file.
ip=169.254.1.1

Now i have connected my raspberry pi to the laptop using the ethernet cable and used putty to connect to this device by using the ip address 169.254.1.1 and port 22 using SSH.
Everything is working fine , i have accesed the file system.
But now i wanted to access the intenet so i have entered the command
ping 8.8.8.8
connect:Network in unreachable

How to access to the internet?How to approach this problem?Any suggestions.
Tutorial followed : Youtube link

A: The feature you need is called "Internet Connection Sharing". From the Network and Sharing Center, select "Change Adapter Settings". Select your Internet connection and pull up its properties page. Click on the "Sharing" tab. Check "Allow other network users to connect through this computer's Internet connection". Select the network interface that connects to the Pi as the interface to share on.


text:
Q: Content does not load properly on first load, but works perfectly on refresh I hope you are doing well.
The webpage does not load correctly on the first load, but it works perfectly whenever I refresh the page. Also, on the first load, I get an error(Failed to load resource: the server responded with a status of 404 (Not Found)).
First load:

On refresh:

Main index file:
<!DOCTYPE html>
<html lang="en">
<head>

     <title>Title</title>

     <meta charset="UTF-8">
     <meta http-equiv="X-UA-Compatible" content="IE=Edge">
     <meta name="description" content="">
     <meta name="keywords" content="">
     <meta name="author" content="">
     <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">

     <link rel="stylesheet" href="css/bootstrap.min.css">
     <link rel="stylesheet" href="css/font-awesome.min.css">
     <link rel="stylesheet" href="css/aos.css">
     <link rel="stylesheet" href="css/owl.carousel.min.css">
     <link rel="stylesheet" href="css/owl.theme.default.min.css">

     <!-- MAIN CSS -->
     <link rel="stylesheet" href="css/editor.css">

</head>
<body>

    ...

    <!-- SCRIPTS -->
     <script src="js/jquery.min.js"></script>
     <script src="js/bootstrap.min.js"></script>
     <script src="js/aos.js"></script>
     <script src="js/owl.carousel.min.js"></script>
     <script src="js/smoothscroll.js"></script>
     <script src="js/custom.js"></script>
     <link rel="stylesheet" href="app.css">
</body>
</html>

Let me know if you have any questions
Sorry, if it's been already asked. I searched everywhere and I cant why that's happening.
Thanks in advance

A: First of all, you don't have to be sorry for asking out any questions. No one knows it all.
To the main question, it seems you have too many scripts loading when the site is open and it times out before it could completely finish loading.
It only finishes loading after the refresh as some of the files are already loaded.
Import only CSS and js files you need and try moving some of the scripts to the bottom end of the body tag.
Use CDN URL to load the imported scripts faster

A: The most common reason for that is a slow server, which takes more time to handle the request than the request default timeout. So, when you refresh, many of the assets are loaded from the cache, allowing the assets that failed to load on the first time to load properly.
Some solutions to this problem is:

*

*Use CDN urls rather than loading the assets from your server <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"> instead of <link rel="stylesheet" href="css/bootstrap.min.css">

*Use Lazy loading for assets that are not used immediately. More about that here.
Sometimes, the server itself is not the bottle neck, not in terms of computation I mean, but the network is! So, make sure your server's network has enough upload speed to serve your app's needs.
I can also see that you are linking a CSS file app.css at the end of the body, and I guess this is what causing the first image you posted, typically it's a good practice to load the CSS files before the body, and the JS files after it, so that the page looks it loaded faster.


text:
Q: dyld: lazy symbol binding failed: Symbol not found: _node_module_register Gatsby realated As I cannot comment because of my low reputation I have added this question so I can set my own answer. I hope this can solve issues for other developers.
I got this error: dyld: lazy symbol binding failed: Symbol not found: _node_module_register Gatsby realated
I am working with Gatsbyjs. The error appears when trying to run develop. Basically on this case it was because I have added the plugin: "gatsby-plugin-manifest" later on.
I believe the problem was because some dependencies used by this plugin-manifest are also used by this another plugin: "gatsby-plugin-sharp". They both can set the favicon to the webpage.
So my solution was:

*

*Reinstall the plugin "gatsby-plugin-sharp" just by running -> npm install --save gatsby-plugin-sharp
By doing this, now I was able to run npm run develop.
Why posting about this
Basically we know that a particular issue may be related to many things. This is why I posted this solution for this particular problem. Some other solutions tell about remove the node_modules folder and run again npm install to install all the modules quoted in package.json but in my case I wanted to try another solution because some of the plugin I am using I don't need them to get updated
Well hope this help others.

A: Just for the sake of my own programming. I will reply myself.
In deed this issue is caused for the libvips 8.9.0+ which is installed globally, at least under MacOS.
So the solution that worked for me is the same as stated in this github issue
Solution run the following command inside of the gatsby app folder:
rm -rf node_modules && SHARP_IGNORE_GLOBAL_LIBVIPS=true yarn

Note: this command will remove the folder node_modules, then, it will set the sharp global lib installed as ignored for this installation and it will run yarn.
After doing that you should be able to run:
yarn start

Good luck! May the force be with Us.


text:
Q: Shopify api variant option title set on a post According to the Shopify documentation you can post a product variant like so:
  "variant" => [
    "title" => "Guzman",
    "price" => "44.90",
    "sku" => "160011",
    "position" => 1,
    "inventory_policy" => "continue",
    "compare_at_price" => null,
    "fulfillment_service" => "manual",
    "inventory_management" => "shopify",
    "option1" => "Option1",
  ]

The above example is using Guzzle.  The above code posts to the product I'm referencing.  The problem is I can't find how to change or set the option title.  In example the default one is title:

On the shopify admin this would be set by "Edit Options" but I don't find anywhere in the API documentation on how this could be set.

A: The solution for this was that the variant title is not actually in variant.  It is in product api.
The correct way to modify the title would be like this:
$response = $shop->api()->rest('PUT', '/admin/products/{productId}.json' ,[
  "product" => [
    "option" => [
    "name" => "Size"
  ]
  ]
]);

Further documentation here:
https://help.shopify.com/en/api/reference/products/product
What threw me off was that I was in the variant api assuming variant would be where the title was.

A: As far as I know, title is based on your option.
if option1 is red and option2 is large, title would be red / large.
If you want to change Default Title, pass option value in title field as follow in variants array.
PUT /admin/products/121212121212.json

{
    "product": {
        "id": 121212121212,
        "variants": [
            {
                "title": "Guzman",
                "price": 44.90,
                "sku" :"160011",
                "position": 1,
                "inventory_policy": "continue",
                "compare_at_price": null,
                "fulfillment_service": "manual",
                "inventory_management": "shopify",
                "option1": "Guzman"
            }
        ]
    }
}

You can try it in postman and let me know if this worked for you.


text:
Q: How to store in server images upload by user with vue js and net core I'm currently working in a POS system and i'm writting the code in net core(web api) with vue as spa and mssql for my database.
I thought at first to use some storage service like aws-s3 or azure-storage ones to fetch the images from there, but I couldn't keep on going that way because there were extra costs, so I was requested to upload images to server better. So, now i'm having an issue and is that, the vue app has to be precompiled by babel when going to publish and therefore i can't changes the files in dist folder when running, so when i do it on dev stage (my machine) I see it working as good as possible, file uploads to folder ok and after compiling back, it will show the image. But, how do I accomplish this in prod stage?


text:
Q: Выдает ошибку при переборе .children Есть задание:

Функция должна перебрать все дочерние элементы элемента where
   и вернуть массив, состоящий из тех дочерних элементов
   следующим соседом которых является элемент с тегом P. Рекурсия - по желанию

@param {Element} where - где искать
@return {Array<Element>}

Пример для html

функция должна вернуть: [div, span], т.к. следующим соседом этих элементов является элемент с тегом P
Вот мой код:
    function findAllPSiblings(where) {
    var children = where.children
    var arr = [];
    for (var i = 0; i < children.length; i++) {
        if (children[i].nextElementSibling.nodeName = 'P') {
            arr.push(children[i])
        }
    }
    return arr;
}

Однако, при вызове функции findAllPSiblings(body) консоль (Firefox) выдает ошибку:

TypeError: children[i].nextElementSibling is null; can't access its "nodeName" property

В Google то же самое. Что делать? Почему не работает?

A: Вам же текст ошибки явно говорит, почему не работает.

children[i].nextElementSibling is null; can't access its "nodeName" property

children[i].nextElementSibling имеет значение null и вы не можете обратиться к свойству nodeName.
Возникает же эта ошибка не последней итерации по массиву дочерних элементов. Когда i равно children.length - 1. На данной итерации элемент является последним и он заведомо не имеет nextElementSibling, отсюда и появляется это null значение и последующая ошибка обращения к свойству.
Используйте цикл до < children.length - 1


text:
Q: php printf doesn't work with  I have php prinf and doesn't work with
.
It works only with chrome browser, what can i do to make it work with all browsers?
My php code is very long and ill provide shorter version:
sample code is like this:

$result = mysql_query("........",$db);

if(mysql_num_rows($result) > 0)
{
    $myrow = mysql_fetch_array($result);
do
{
    printf ("

%s

",$myrow["var"]);
}
while ($myrow = mysql_fetch_array($result));
}
else
{
    echo "
error...
";
}

A: from the sample code provided you have messed up the tag order. try this. Note i have moved the tag orders. Hope this is what you want to achieve. too unclear from the question.

<?php
$result = mysql_query("........",$db);

if(mysql_num_rows($result) > 0)
{
    echo '

';
    $myrow = mysql_fetch_array($result);
    do
    {
        printf ("
%s
",$myrow["var"]);
    }
    while ($myrow = mysql_fetch_array($result));
    echo '

';
}
else
{
    echo "
error...
";
}
?>

tag order should be. you cannot insert
 as a child of
.
 can have only
 as child.

...

Edit:
You may not need the
...
 tags. you can do it with simple table. Try this
<?php
$result = mysql_query("........",$db);

if(mysql_num_rows($result) > 0)
{
    echo '
';
    $rownum=1; //just a counter here, if have other real value then use it
    $myrow = mysql_fetch_array($result);
    do
    {
        printf ("
%d	%s
", $rownum, $myrow["var"]);
        $rownum++;
    }
    while ($myrow = mysql_fetch_array($result));
    echo '
';
}
else
{
    echo "
error...
";
}
?>

and if you want to do it with just ordered list you can do it like the following
<?php
$result = mysql_query("........",$db);

if(mysql_num_rows($result) > 0)
{
    echo '
';
    $myrow = mysql_fetch_array($result);
    do
    {
        printf ("
%s
", $myrow["var"]);
        $rownum++;
    }
    while ($myrow = mysql_fetch_array($result));
    echo '
';
}
else
{
    echo "
error...
";
}

Note: the type attribute of
 is deprecated in HTML 4.01. and is not supported in HTML 5.


text:
Q: number of binary strings with equal number of 0's and 1's I am trying to count the number $S$ of binary strings with equal number of 0's and 1's. Since this boils down to picking $n$ out of $2n$ places where 0's can fall into, my ansatz is
$$ S = \left(\begin{matrix} 2n \\ n \end{matrix}\right) = \frac{(2n)!}{2n!} $$
Using Stirling's approximation $ n! \approx \left(\frac n e\right)^n $
this simplifies to
$$ S \approx 2^{2n-1} \left(\frac {n} e\right)^{n} $$
However, this grows faster than the number of all possible strings of length $2n$, as
$$ 2^{2n-1} \left(\frac {n} e\right)^{n} < 2^{2n}
\Longleftrightarrow
\left(\frac {n} e\right)^{n} < 2$$
which is obviously bound.
What am I doing wrong?

A: Your mistake is that $\dbinom{2n}{n} = \dfrac{(2n)!}{n! \cdot n!}$, not $\dfrac{(2n)!}{2n!}$.
In addition, Stirling's approximation is that $n! \approx \sqrt{2\pi n} \left(\dfrac{n}{e}\right)^n$: you're missing a factor.
Think you can finish from here?


text:
Q: Buttons not displayed when using a SurfaceView My gameloop class is extended from a SurfaceView.
When I try to add a Button either programmaticly or thru XML it is not displayed - I have seen this question asked various times on the net but have found no suitable solutions. Some people have suggested sandwiching the SurfaceView in a FrameLayout but it has made no difference.
I'm surprised more people aren't using regular Buttons in their games and so this question hasn't been answered to death.
Here is my XML: (Engine = Game class that extends a surfaceview)
 <?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
 android:layout_width="fill_parent"
 android:layout_height="fill_parent">

     <com.game.test.Engine
     android:layout_width="fill_parent"
     android:layout_height="fill_parent">
     </com.game.test.Engine>

<LinearLayout android:id="@+id/linearLayout1" android:layout_width="wrap_content" android:layout_height="wrap_content">

     <Button
    android:id="@+id/btnReset"
    android:layout_width="80dp"
    android:layout_height="40dp"
    android:text="Reset"
    android:layout_alignParentRight="true"
    android:layout_alignParentBottom="true"
     android:textColor="#FFFFFF"
    android:background="@drawable/custom_button"
    ></Button>
 </LinearLayout>

A: I am also seeing this problem....playing around with it a bit, I noticed that if I 'sandwich' the button in a layout to be ABOVE the SurfaceView, the button is displayed....but if the button is below the SurfaceView, it is not displayed. So if you don't mind your button to be above the SurfaceView, you should be OK. I would prefer my buttons to be below the SV, so I'm still looking for a better soluton...


text:
Q: Why is nothing appearing on my canvas? I am such a noob and I have no idea why nothing is appearing on my canvas. Can someone help me out? I wanted to have a black box on my canvas, that was the intention anyway.
var canvas = document.createElement("canvas");
var ctx = canvas.getContext("2d");
canvas.width = 1040;
canvas.height = 400;
canvas.style.display='block';
canvas.style.marginLeft="auto";
canvas.style.marginRight="auto";

var mainFunction= function(){
ctx.fillStyle = "rgb(0, 0, 0)";
ctx.beginPath();
ctx.rect(0, 0, canvas.width, canvas.height);
ctx.closePath();
ctx.fill();
requestAnimationFrame(mainFunction);
};

mainFunction();

A: You have created a <canvas> element but have not attached it anywhere in the DOM. Perhaps you want something like
document.body.appendChild(canvas);

or another suitable container.

A: Basically, you do not have an attached canvas to the DOM.
Create a html file with <canvas id="root"></canvas>;
var canvas = document.getElementById("root");


text:
Q: Coloring polygon based on date using TileMill/CartoDB? How would you color a polygon/line/dot based on a date? The colors would be a pre-set list. I need the area to update its color based on the current (or given) date. I would be using tilemill or cartodb.
Example:
Polygon A:

*Color would be white after Jan 1,

*Color would be grey after Feb 15

*Color would be brown after March 1, etc.
Line B:

*Color would be blue after March 15,

*Color would be white after Dec 1, etc.

A: You could likely do this if you supplied the dates in for your segments in CartoDB, selected only the data you need, and you can then color it using CartoCSS.  For example, you could have data such as this in CartoDB:
            the_geom      name  type     col_date_start col_date_end       color
 Row 1:    (geometry)      a    polygon      0101            0215          white
 Row 2:    (geometry)      a    polygon      0215            0301          gray
 Row 3:    (geometry)      a    polygon      0301            ....          brown
 ....
 Row 8:    (geometry)      b    polyline     0101            0315          blue
 Row 9:    (geometry)      b    polyline     1201            0232          white

So now that your data is set up, you could probably then set up a query like this:
SELECT * FROM my_table, to_char(current_timestamp, 'MMDD') AS date_compare
WHERE date_compare::int > col_date_start AND date_compare:int < col_date_end;

This would only return the polygon data that is relevant for the current time of the page load.  You could then use CartoCSS to format your data like so:
#my_table {
  [type = 'polygon'] {
    [color='white']
      {polygon-fill:#FFFFFF;}
    [color='gray']
      {polygon-fill:#666666;}
    [color='brown']
      {polygon-fill:#B26B24;}
  }
  [type = 'polyline'] {
    [color='white']
      {line-color:#FFFFFF;}
    [color='blue']
      {line-color:#0000FF;}
  }
}

Not the most elegant of a solution, but I think it should work for your case.


text:
Q: Can't cast _InternalLinkedHashMap to anything I've been having some issues with get data from Firebase RealtimeDatabase as a Map despite me uploading it as a Map in the first place. All solutions I see are that you should just cast The snapshot.value to the data type incoming but no iteration of that works for me. I've been able to call toString() on the snapshot value and I've verified that it's a Map but the compiler doesn't even allow me to cast it to a Map let alone run it. If I try to use dynamic to prevent that compile error, I still get this  Unhandled Exception: type '_InternalLinkedHashMap<Object?, Object?>' is not a subtype of type 'Map<String, dynamic>?' in type cast.
This is what I've done,
  Future<Map<String, dynamic>> getBasicDetail(
      DatabaseReference databaseReference) async {
    DatabaseReference imageURLevent = databaseReference.child('basicDetail');

    final snapShot = await imageURLevent.get();
    return Map<String, dynamic>.from(
        snapShot.value as Map<String, dynamic>? ?? {});
  }

  Future<void> readProfileData({required String userId}) async {

    DatabaseReference ref = FirebaseDatabase.instance.ref("users/$userId");

    final basicDetail = await getBasicDetail(ref);

    // Print the data of the snapshot
    debugPrint(basicDetail.toString());
  }

I've tried every possible combination of parsing this data but nothing works. For some reason in examples and videos when you cast the right hand side to Map<String,dynamic> you get no error but my IDE doesn't even allow me to do that. I've also tried Map.from() seems to be a popular one that works but mine simple throws a runtime error.
Why does this  from https://www.youtube.com/watch?v=sXBJZD0fBa4&ab_channel=Firebase
work while mine
 doesn't?
event.snapshot.value looks valid too
[log] {bloodGroup: gh, imageURL: /data/user/0/com.piyushlimited.buzzai/app_flutter/image_picker7287835118545461685.jpg, fullName: Henry Nana Adu, weight: 523, dateOfBirth: 11/11/11, licenseNumber: 256489, age: 28}

I can access one value of data by referencing the full path to it but I have a large Map and I can't do it for each and every value in each and every category. It seems costly and time wasting. I've spent days trying a lot of things so please keep that in mind.

A: Thanks for your responses guys. Especially to @Stelios Papamichail for providing the solution 3 months ago. Firebase's response is not in a valid JSON format it seems It's a shame the official dev team hasn't taken notice of this. jsonDecode(jsonEncode(event.snapshot.value))); works perfectly. It's probably bad performance wise but I don't really care at this point I'm just happy it does. I don't know why it works either.
This now works perfectly
  Future<void> readProfileData({required String userId}) async {
    DatabaseReference ref = FirebaseDatabase.instance.ref("users/$userId");

    try {
      final DataSnapshot? snapShot = await ref.get();

      Map<String, dynamic> data = jsonDecode(jsonEncode(snapShot?.value));

      userProfile = UserProfile.fromMap(data);

      setGender(userProfile.gender);

      notifyListeners();

      log(userProfile.toString());
    } on Exception catch (e) {
      log(e.toString());
    }
  }

Hopefully more people see this and not waste their life like I have.

A: I think this is happening because event.snapshot.value is returning something that isn't expected by Map.from. Basically Map.from expects a Map<dynamic, dynamic> so you can cast your data as the same.
Try changeling your line to
final data = Map<String, dynamic>.from(event.snapshot.value as Map<dynamic, dynamic>);

A: Solution:
if you have data in the FIREBASE DATABASE,
for example: Please Click Here to Check ScreenShot
Then as of now, 12th March, 2022:
To Retrieve Data from Firebase Database, you must use following sample code.
String name = (snap.snapshot.value as Map)["name"];
print("name :: $name");

Check Complete Example with Full Sample Code:
e.g: For retrieving name and email from database.
Please click here to Check the Complete Code Sample Screenshot


text:
Q: how to move static assets of package.json libraries to cdn server from openshift build I have PHP application and am maintaining my frontend assets using npm (package.json). When I start build in openshift then the build have to import my static libraries into my project assets folder which I defined in package.json and move to CDN server (I have shared network location which I can share with build service account - PVC(Persistence Volume Claim) with ReadWrite access) and deploy my php app to my php container.
spapp

*

*applications - folder

*assets - my static assets such css, js, images

*composer.json - php libraries

*package.json - static libraries

When I request a build then the build will do the following:

*

*install my composer.json libraries (working fine now)

*install my package.json libraries into assets folder and move it to CDN server via network path or shared PVC ( Expecting )

*deploy my app to PHP container (working fine now)


text:
Q: Closing dropdown menu by clicking outside/body I've built a set of dropdown menus in CSS and jQuery, but I'm struggling to allow closing any open menus by clicking outside/on the body. I've found existing similar questions that suggest using the .closest() method, but I can't seem to get this working:
$('body').click(function(e) {
    if ($(e.target).closest('.dropdown-menu').length === 0) {
        $('.dropdown-menu').hide();
    }
});

I've also tried the following:
$('body').on('click', function() {
  if ($('.dropdown-menu').is(':visible')) {
    $('.dropdown-menu').hide();
  }
});

Thanks!


text:
Q: Integral Convergence with exponential function For the following integral,
$
 \int_{0}^{\infty} {e^{f(x)} dx},
$
Can we have a necessary and sufficient condition on $f(x)$ to affirm that this integral is convergent or divergent?

A: You want to consider the following.
$$\int_0^{\infty}e^{f(x)}dx=\int_0^ae^{f(x)}dx+\int_a^{\infty}e^{f(x)}dx$$
You want the first integral to be finite, so it shouldn't be too hard to pin down what conditions you need on $f$. Now, for the integral on $(a,\infty)$ you need to make sure that the behavior of $f$ is going to be so that $e^{f(x)}\to0$ so you want $f(x)$ to be negative, and decreasing, negative alone won't work.


text:
Q: Mock a method from another class called from a mocked method We are creating unit tests for an application and ran into a problem creating certain tests.
We are unit testing the following Handle() method of the class ActivateCommandHandler:
    public class ActivateCommand : IRequest<HttpResponseMessage>
    {
        public string Controller { get; set; }

        public ActivateCommand(string controllername)
        {
            this.Controller = controllername;
        }
    }

    public class ActivateCommandHandler : CommandHandler<ActivateCommand, HttpResponseMessage>
    {
        protected readonly ICommandsGateway _commandsGateway;
        protected readonly EndpointSettings _endpoints;
        protected readonly IUserProfile _userprofile;

        public ActivateCommandHandler(IMediator mediator, ICommandsGateway commandsGateway, IOptions<EndpointSettings> endpoints, IValidationContext validationContext, IUserProfile currentUser) : base(mediator, validationContext, currentUser)
        {
            _commandsGateway = commandsGateway;
            _endpoints = endpoints.Value;
            _userprofile = currentUser;
        }

        public override async Task<HttpResponseMessage> Handle(ActivateCommand command, CancellationToken cancellationToken)
        {
            if (_endpoints.EndpointExists(command.Controller))
            {
                // Check whether the second server controller is deactivated
                string peercontroller = _endpoints.GetPeerController(command.Controller);

                if (!string.IsNullOrEmpty(peercontroller))
                {
                    BaseRedundancySwitchStatus controllerStatus = await _commandsGateway.GetRedundancySwitchStatus(_endpoints.GetEndpointAddress(peercontroller));

                    if ((controllerStatus.CurrentState == "Activated") || (controllerStatus.CurrentState == "ActivatedWithWarning") || (controllerStatus.CurrentState == "Activating"))
                    {
                        var resp = new HttpResponseMessage(HttpStatusCode.Conflict)
                        {
                            Content = new StringContent($"{peercontroller},{controllerStatus.CurrentState}")
                        };

                        return resp;
                    }
                }

                var result = await _commandsGateway.PostActivateCommand(_endpoints.GetEndpointAddress(command.Controller));

                return result;
            }
            else
            {
                throw new InvalidControllerNameException($"ERROR: The controller {command.Controller} does not exist as an endpoint on this Control Center!");
            }
        }
    }

For this the following were mocked: _endpoints, command and _commandsGateway (interface). This works great for unit testing the parameter validation. But we now want to test the behaviour when the peercontroller status is set to a specific value.
To do this we are trying to mock out the function _commandsGateway.GetRedundancySwitchStatus(). The following is the actual test implementation. We mock the _commandsGateway.GetRedundancySwitchStatus() function to return the expected BaseRedundancySwitchStatus with CurrentState set to "Activated". After that we call the handler of the actual function to be tested and check whether we get the expected error.
[Fact]
        public async void ShouldHaveErrors_PeerControllerStateActivated()
        {
            var command = new ActivateCommand("Server Controller Slave1");

            BaseRedundancySwitchStatus result = new BaseRedundancySwitchStatus()
            {
                CurrentState = "Activated"
            };

            _commandsGateway
                .Setup(s => s.GetRedundancySwitchStatus("Server Controller Slave1"))
                .ReturnsAsync(result);

            HttpResponseMessage res = await _handler.Handle(command, CancellationToken.None);

            Assert.True(res.StatusCode == System.Net.HttpStatusCode.Conflict);
        }

Debugging the code, when I step through the code in the Handle() method where _commandsGateway.GetRedundancySwitchStatus is called, I can see that _endpoints.GetEndpointAddress(command.Controller) (which is the parameter) is called and the correct value is returned. After this the debugger steps to the next line without any indication of having executed the mock GetRedundancySwitchStatus() function. Inspecting the controllerStatus variable the value is null. I would expect the value to be the BaseRedundancySwitchStatus object which is supposed to be returned by the mocked GetRedundancySwitchStatus() function.
Where are we going wrong?


text:
Q: jQuery .val() is returning undefined on change of a select box I have a select box with some dates. I want to get the value of said dates when the input changes. I keep getting undefined for my value.
$('#date_pick').change(function(){
            var values = $('#date_pick:selected').val();
            alert(values);
});

Fiddle

A: Getting the value of a <select> element (just like every other form element), is done with the val() function.
So in your case => $('#date_pick').val().
Note that in the change callback scope you don't need to re-select the element, this inside a callback is the DOM element that triggered the callback:
$('#date_pick').change(function() {
    alert($(this).val());
});

LIVE DEMO

A: You need to put a space between the #date_pick and :selected.
var values = $('#date_pick :selected').val();

Fiddle: http://jsfiddle.net/PJT6r/9/

A: you have to remove the 'selected'!
var values = $('#date_pick').val();

It's a caffeine issue, I'm sure.

A: or just var values = $(this).val();

A: You don't need the :selected bit in your selector
 Use:
$(function(){
        $('#date_pick').change(function(){
                    var values = $('#date_pick').val();
                    alert(values);
        });
});

A: You can;
 var values = $('#date_pick option:selected').val();

A: I was getting undefined/null values when trying to get value by ID. So I tried to get the selected value by select field Name.
<select name="date_pick" id="date_pick">
</select>

Then in jQuery,
$("select[name=date_pick]").val();

And result NOT Getting undefined / null.


text:
Q: Unit test Mat-dialog and afterOpened for setup modal variables i have following aproach to setup parameters inside mat dialog component:
this.matDialog.afterOpened.pipe(first()).subscribe(({ componentInstance }) => {
      componentInstance.variableA= true;
      componentInstance.functionA("something");
    });

Now i have to write unit tests for that. I want to test that variableA are set for true and that functionA is called. I using Jest for UT.
I dont know how to write unit test to get componentInstance and check that the true value is assign and functionA was called.


text:
Q: Java: Running batch file with ProcessBuilder when app is registered as Windows Service using Procrun There is already a 7 year old question with similar title but no accepted answer, hence reposting as my question has additional details.
7 year old question:
 Running batch file from Java registered as Windows Service using Procrun
My question:
I have following java class:
public static void main(String[] args) {
    ProcessBuilder processBuilder = new ProcessBuilder(new String[] {"C:\\Work\\test.bat"});
    processBuilder.redirectErrorStream(true);
    Process process = processBuilder.start();
    int exitVal = process.waitFor();
}

when this is run directly from eclipse, test.bat is successfully executed.
However, when it is run from service, test.bat does not get executed.
I have installed the jar as a windows service using procrun. Also to validate whether service is correctly installed. I did this:
public static void main(String[] args)
    {
        try {
            DateFormat formatter = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss");
            Calendar calendar = Calendar.getInstance();
            calendar.setTimeInMillis(System.currentTimeMillis());
            File file = new File("C:\\Work\\temp.txt");
            FileUtils.writeStringToFile(file, "hello world "+formatter.format(calendar.getTime()), "UTF-8", false);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

and this block of code gets executed from service without any problem. It's just that test.bat does not get executed.
Is ProcessBuilder not allowed from procrun?
EDIT
My test.bat :
start "" cmd /c "echo Hello world!&echo(&pause"

A: Are you sure that test.bat is not being executed? Please confirm in Task Manager. Be sure to show processes from all users as your batch file will probably be running in the system account.
Note that your batch file will be launched in the isolated Session 0 and you will not be able to see the command window (and you won't be able to respond to the "pause" command"). You should consider this restriction as you graduate from your test to something real/useful...