text:
Q: nodejs result undefined (async)? I have simplified my code in nodejs below. I got udefined result  because function is async. How do I get valid result, do I have to use promises ?
function findresult() {
    var result;
    setTimeout(function () {
        var result = 2
    }, 1000);
    return result
}
console.log('findresult ' + findresult());//findresult undefined

A: You either need to use a simple callback or promise, here's a callback example:
function findresult(callback) {
    var result;
    setTimeout(function () {
        result = 2
        callback(result);
    }, 1000);
    //return result
}

And to use it:
findresult(function(result) {
    console.log("Result is: " + result);
});

A: for your example
function findresult(callback) {
    var result;
    setTimeout(function () {
        var result = 2
        callback(result);
    }, 1000);
}
findresult(function(result) {
    console.log('findresult ' + result);
});

you're essentially sending your action as a parameter (the callback) to the function, when the function is done it will give the result to your callback.
in nodejs though, you will usually also want to handle errors, the usual syntax for the callback is function(error, result) (instead of just a result) - if error is null, you can use the result (call succeeded), otherwise it has details of the error.


text:
Q: Comparison of two linear regression models with squared regressors I need to compare two linear regression models that include the regressors in levels and in squares:
$Y=a_1x^2+b_1x+c_1$ and $Y=a_2x^2+b_2x+c_2 $
Specifically, I need to test whether these regression models are significantly different (i.e., whether $a_1=a_2,b_1=b_2,c_1=c_2$).
In the forum, I read that one should build respective interactions.
Yet, I do not exactly understand what is meant by including "interactions."
What would that model look like? What should be compared with what, and what test statistic is best?
(I do not know Stata, unfortunately.)
Please advise.
Both models are based on /using the exact same population.

A: As far as I know, model comparison should only be done on the same dataset. For models with different configurations, you can try Akaike information criterion (AIC) or  Bayesian information criterion (BIC).
Your 2 models have the same regressors but different coefficients. The easiest thing to do is to check the confidence intervals for overlapping. For example, if CI of $a_1$ overlaps CI of $a_2$ or covers $a_2$ if only one model is fit, then there is no significant difference between them. You can do this for all 3 coefficients.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Format multiple geom_sf legends I am dealing with multiple sf geometries in ggplot and would like to display legend in the form of a point, a line, and a square (for the polygon). However, geom_sf legend combines my geometry features (i.e. combining line and point) displayed below:
library(ggplot2)
library(sf)

poly1 <- cbind(lon = c(5, 6, 7, 5), lat = c(52, 53, 51, 52))

poly <- st_sf(st_sfc(st_polygon(list(poly1))))
line <- st_sf(st_sfc(list(st_linestring(cbind(lon = c(5.5, 4.5), lat = c(53.5, 54.5))))))
point <- st_sf(st_sfc(st_point(cbind(lon = 5.5, lat = 52.7))))

ggplot() +
  geom_sf(data = poly, aes(fill = "A")) +
  geom_sf(data = point, aes(colour = "B"), show.legend = "point") +
  geom_sf(data = line, aes(colour = "C"), show.legend = "line") +
  scale_fill_manual(values = c("A" = "yellow")) +
  scale_colour_manual(values = c("B" = "pink", "C" = "purple")) +
  theme_minimal()

I would like three separate legends, a single yellow square, a pink point, and a purple line on the same image illustrated below. It is only the case when I plot individual geometry but not the combination of three.

I looked up similar topics, but none of them dealt with point geometries i.e. https://github.com/tidyverse/ggplot2/issues/2460
Would anyone offer any insight on this?
GitHub issue: https://github.com/tidyverse/ggplot2/issues/2763

A: I know how to seperate the legends, they only get combined now because you are mapping color twice. By mapping shape to the points and setting the color, you can get around that:
ggplot() +
  geom_sf(data = poly, aes(fill = "A")) +
  geom_sf(data = point, aes(colour = "B"), show.legend = "point") +
  geom_sf(data = line, aes(shape = "C"), show.legend = "line", color = 'purple') +
  scale_fill_manual(name = NULL, values = c("A" = "yellow")) +
  scale_colour_manual(name = NULL, values = c("B" = "pink")) +
  scale_shape_discrete(
    name = NULL,
    guide = guide_legend(override.aes = list(color = 'purple'))) +
  theme_minimal()

But: the point and line are still showing up in all three legends. I don't think they should! Perhaps you can fill a github issue.

A: Inspired by the comment from @Axeman, this issue and this post, the problem is solved using the override.aes argument in guide_legend():
library(ggplot2)
library(sf)

poly1 <- cbind(lon = c(5, 6, 7, 5), lat = c(52, 53, 51, 52))

poly <- st_sf(st_sfc(st_polygon(list(poly1))))
line <- st_sf(st_sfc(list(st_linestring(cbind(lon = c(5.5, 4.5), lat = c(53.5, 54.5))))))
point <- st_sf(st_sfc(st_point(cbind(lon = 5.5, lat = 52.7))))

ggplot() +
  geom_sf(data = poly, aes(fill = "A")) +
  geom_sf(data = point, aes(colour = "B"), show.legend = "point") +
  geom_sf(data = line, aes(colour = "C"), show.legend = "line") +
  scale_fill_manual(values = c("A" = "yellow"), name = NULL,
                    guide = guide_legend(override.aes = list(linetype = "blank", shape = NA))) +
  scale_colour_manual(values = c("B" = "pink", "C" = "purple"), name = NULL,
                      guide = guide_legend(override.aes = list(linetype = c("blank", "solid"),
                                                               shape = c(16, NA)))) +
  theme_minimal()


text:
Q: JSON - Single Quote within Double Quote I have the following code which I'm using to populate form fields. This code receives a JSON dataset which has been encoded using the PHP json_encode function.
The code works fine for single quotes and double quotes seperately, however there are occassions when I will have single quotes inside double quotes. An example would be text inside a textarea which might say: The man said "I'm going on vacation".
I've read the single quote doesn't need escaping and the double quotes are being escaped correctly. I've copied the JSON code from Firebug into a validator and it comes back correct which makes me think the code below is at fault. The error I'm getting in Firebug is a syntax error. Strangely enough if I have two single quotes (ie. to open and close) the problem no longer exists.
I've spent 3 hours looking at this and don't seem any closer to a resolution. I appeciate all advice as ever! I can provide further code snippets as needed.
$.ajax({
    type: "GET",
    url: "casedata.php",
    data: {'caseid':'<?php echo($caseid); ?>', 'callid':'<?php echo($_GET['callid']); ?>', 'stage':'thlViewCall'},
    dataType: "json",
    async: false,
    success: function(data){
        $.each((data), function(i, e) {
            if($("input[type=text]")) {
                $('#'+i).val(e);
            }
            if($("input[type=select-one]")) {
                $('#'+i+' option').prop("selectedIndex", e);
            }
            if($("input[type=select-multiple]")) {
                $('#'+i+' option').prop("selectedIndex", e);
            }
            if($("input[type=radio]")) {
                $('input[name="'+i+'"][value="'+e+'"]').attr('checked', 'checked');
            }
        });
    }
});

Edit:
Apologies, please find the JSON demonstrating this error below:
{"calldate":"06-07-2012","adviserid":"18","service":"THL","dda_sen":"eqa","finalhearing_date":"24-07-2012","reason_for_tribunal":"part_4","next_deadline_description":"before_final_evidence","understanding_paperwork":"1","ability_negotiate":"1","legal_complexity":"1","comments":"test","action":"referred_to_tss_for_telephone_support","bgInfo":"The man said \"I'm going on holiday\"","initialAdvice":"test2","logreceived":"no","monitored":"no","monitoredby":"","monitoreddate":"00-00-0000","monitorednotes":"","legalsupport":"no","legalsupportid":"0","legalsupportdate":"00-00-0000","legalsupportnotes":""}

A: I can see at least two possible issue here.

*

*You're using this selector: $('#' + i).  Does that mean you have HTML id attributes that are just numbers?  That would not be valid HTML.

*It looks like you're trying to set a selectedIndex property to some JSON element e: .prop("selectedIndex", e).  Did you mean to use i instead of e there?  That might explain the syntax error, if you're inserting text with single-quotes into an HTML attribute.

A: I have fixed this and would like to share my result considering the advice I've received in multiple questions on multiple topics.
I found selecting using input[type] very unreliable, for some reason my text fields were being detected as radio boxes causing unwanted results. The simplest way to fix this was to use class selectors applied to my form elements, an example of my code is below:
if($("[name="+i+"]").is(".textbox, .select")) {
    $("[name="+i+"]").val(e);
}

if($("[name="+i+"]").is(".radio")) {
    $("input[name="+i+"][value="+e+"]").attr('checked', 'checked');
}

This evaluates the name of the field passed in the "i" javascript variable, checks the CSS class of the field then sets the value or attribute accordingly. This is very tidy in my opinion and makes CSS styling that bit easier too.
I hope my explanation cancels out that -1 for missing the JSON to start with :-)


text:
Q: Multirow and Multicolumn Horizontally Positioned Side By Side I am trying to make a table that has multirow then multicolumn horizontally positioned side by side. I have found a lot of posts that show how to use both in the same table, but none discuss using both within the same rows or, rather, positioning them horizontally within the same space.
Here is the Latex code I am using:
\begin{table*}[ht]
\captionsetup{justification=centering}
\caption{\propose{Multirow and Multicolumn Positioned Horizontally}\label{table:2DSearchTasks}}
\centering
\begin{tabularx}{\textwidth}{|X|X|X|X|X|X|X|}
\hline
\multirow{2}{*}{This is 2-row multirow} & \multicolumn{6}{c|}{This is 6-column multicolumn} \\
\hline
  & Title 1 & Title 2 & Title 3 & 4. Title 4 & 5. Title 5 & 6. Title 6 \\
\hline
\end{tabularx}
\end{table*}

Which outputs the following table:

As you can see, there is a horizontal line that goes through the multirow on the lefthand side of the table. How can I get rid of this?
Side question: How can I wrap the text of the multirow heading?

A: Use \multirow{2}{\hsize}{...} to get the size of the X column:
\documentclass{article}

\usepackage{multirow}
\usepackage{tabularx}

\begin{document}

\begin{table*}[ht]
\begin{tabularx}{\textwidth}{|X|X|X|X|X|X|X|}
\hline
\multirow{2}{\hsize}{This is 2-row multirow} & \multicolumn{6}{c|}{This is 6-column multicolumn} \\
%\hline
\cline{2-7}
  & Title 1 & Title 2 & Title 3 & 4. Title 4 & 5. Title 5 & 6. Title 6 \\
\hline
\end{tabularx}
\end{table*}

\end{document}

As @Bernhard just told me, one can also use = instead of \hsize:
\documentclass{article}

\usepackage{multirow}
\usepackage{tabularx}

\begin{document}

\begin{table*}[ht]
\begin{tabularx}{\textwidth}{|X|X|X|X|X|X|X|}
\hline
\multirow{2}{=}{This is 2-row multirow} & \multicolumn{6}{c|}{This is 6-column multicolumn} \\
%\hline
\cline{2-7}
  & Title 1 & Title 2 & Title 3 & 4. Title 4 & 5. Title 5 & 6. Title 6 \\
\hline
\end{tabularx}
\end{table*}

\end{document}


text:
Q: Avoid undesired petitions on a REST server (client = Android) I'm working on an Android project that comunicates with a REST+JSON server. And I'd like to avoid malicious users to inject http posts in the server from outside my app.
How can I do that? I had thought in a mechanism similar to the authenticators keyrings like that (blizzard authenticator):
http://us.blizzard.com/support/article.xml?locale=en_US&tag=TOKENFAQ&rhtml=true
This way before send an request to the server the Android device generates a code and add it to the post. The server validates that code ignoring petitions with wrong codes. Don't know if that idea is valid, how to generate that codes and how to implement it for avoiding the user to sniff the network traffic, catch that code and reuse it.
Can someone guide me with that?
Thanks in advance

A: I posted more or less the same question yesterday here: Android Client, Http Server, How do I know client is sending data using my app? authentication
I decided to go ahead with SSL and right now its all setup except for the client-authorization which I will be doing today.


text:
Q: Caching bundle product pages our product detail pages (bundle products) load very slowly (10-20 seconds, most of it is scripting time). There is no caching (FPC is enabled) and every time the page is reloaded, the complete scripting including the price calculation of all 500 bundle item is carried out anew. I followed all other tips (script bundling, minifying, gzipping, production mode, ..).
Does anyone have any idea how to enable caching here (or how to speed this scripting up)? The following is used: Magento 2.1.0 CE. Has there been any progress in this regard in a newer version?
Thanks for every tip!

A: At first, you need to check if your FPC is fully working or not. You will find in the browser(Network section) X-Magento-Cache-Debug: HIT. in development mode.
Please check with Mage profiling to find out which block is taking the max time. Its another way of debugging.


text:
Q: Setting Library path for win32 console applications I am getting "dll not found:restarting the application may fix the problem" error when i try to execute a simple "HelloWorld" win32 console application.
I know the location of the .dll.
How to specify its location when executing the .exe from command prompt?
PS: copying the .dll to the .exe's current dir seems to solve the problem, but this approach is not suitable in this case.

A: DLL loading happens deep in the plumbing of windows.
If the DLL is not found in the same directory as the application, the PATH is automatically scanned in order to find the directory.
So, the simplest answer to your problem is to add the directory containing the DLL to your PATH. Depending on when the DLL needs to be loaded by your code, you may be able to (temporarily) modify the PATH from inside your "HelloWorld" application.

A: The documentation for LoadLibraryEx has some discussion on how Windows searches for your dll.  You might try using the LOAD_WITH_ALTERED_SEARCH_PATH flag if you can construct a full path to your DLL or use the SetDllDirectory function to add a directory to the search path.

A: To manually, permanently add your path to Windows PATH (permanently = until you remove it), right click My Computer>Properties>Advanced>Environment Variables>System Variables>Path>Edit>Variable Value, add a semicolon (which means "in addition to all before") and paste the full path of your dll.
Windows will search the path every time it can't find something in the current directory.

A: From: http://msdn.microsoft.com/en-us/library/7d83bc18.aspx

With both implicit and explicit linking, Windows first searches for
  "known DLLs", such as Kernel32.dll and User32.dll. Windows then
  searches for the DLLs in the following sequence:

*

*The directory where the executable module for the current process is located.

*The current directory.

*The Windows system directory. The GetSystemDirectory function retrieves the path of this directory.

*The Windows directory. The GetWindowsDirectory function retrieves the path of this directory.

*The directories listed in the PATH environment variable.


text:
Q: GWT CellList Render Done Handler? I use the GWT CellList widget to render Cell elements.
Is there a way to register a render complete or render done event to execute stuff after rendering was done?

A: I had the same question and taking a look into the code I have found a possible solution.
In the HasDataPresenter there are the code which renders the cells into the view (method resolvePendingState(JsArrayInteger modifiedRows):
if (redrawRequired) {
        // Redraw the entire content.
        SafeHtmlBuilder sb = new SafeHtmlBuilder();
        view.replaceAllChildren(newState.rowData, selectionModel, newState.keyboardStealFocus);
        view.resetFocus();
      } else if (range0 != null) {
        // Surgically replace specific rows.

        // Replace range0.
        {
          int absStart = range0.getStart();
          int relStart = absStart - pageStart;
          SafeHtmlBuilder sb = new SafeHtmlBuilder();
          List<T> replaceValues = newState.rowData.subList(relStart, relStart + range0.getLength());
          view.replaceChildren(replaceValues, relStart, selectionModel, newState.keyboardStealFocus);
        }

        // Replace range1 if it exists.
        if (range1 != null) {
          int absStart = range1.getStart();
          int relStart = absStart - pageStart;
          SafeHtmlBuilder sb = new SafeHtmlBuilder();
          List<T> replaceValues = newState.rowData.subList(relStart, relStart + range1.getLength());
          view.replaceChildren(replaceValues, relStart, selectionModel, newState.keyboardStealFocus);
        }

        view.resetFocus();

The method view.replaceAllChildren(....) calls to render cell's render method, and when it has finished a ValueChangeEvent() is fired.
@Override
public void replaceAllChildren(....) {
  SafeHtml html = renderRowValues(...);

  ....

  fireValueChangeEvent();
}

So in your cellList you should do something like:
   cellList.addHandler(new ValueChangeHandler<List<IPost>>() {

        @Override
        public void onValueChange(ValueChangeEvent<List<IPost>> event) {
          //Do something
          //Be careful because this handler could be called from other methods

        }
      }, ValueChangeEvent.getType());

A: Referring GWT CellList Widget Example
You can use your own custom Cell extending AbstractCell (As used ContactCell in the example).
There you will need to override the render method:

@Override
      public void render(Context context, ContactInfo value, SafeHtmlBuilder sb) {

  (//other codes)
  (// put your logic after render here at the last)

}


text:
Q: Angular 10 tries to parse string as typescript code When using a string as input from parent to a child component, Angular tries to parse the string as TS code and throws an error.
Example: https://stackblitz.com/edit/angular-10-communicating-between-components-8yqvse?file=src%2Fapp%2Fapp.component.html
This did not happen in Angular 8: https://stackblitz.com/edit/angular-8-getting-started-ytub1a?file=src%2Fapp%2Fapp.component.html
What caused this issue? There is no mention of parser change in Angular 10 release note.

A: This happen because string has interpolation inside {{ option }}. Check interpolation docs
So if you assign a variable to option or remove brackets will works.
Working example: https://stackblitz.com/edit/angular-10-communicating-between-components-cugx4n?file=src/app/app.component.ts
Edit: Here is the exactly commit that introduce this.


text:
Q: Debugging an llvm pass with gdb Is it possible to debug an llvm pass using gdb? I couldn't find any docs on the llvm site.

A: Yes. Build LLVM in non-release mode (the default). It takes a bit longer than a release build, but you can use gdb to debug the resulting object file.
One note of caution: I had to upgrade my Linux box to 3GB of memory to make LLVM debug mode link times reasonable.

A: First make sure LLVM is compiled  with debug options enabled, which is basically the default setting. If you didn't compile LLVM with non-default options then your current build should be fine.
All LLVM passes are run using LLVM's opt (optimizer) tool.  Passes are compiled into shared object files, i.e., LLVMHello.so file in build/lib and then loaded by the opt tool.  To debug or step through the pass we have to halt LLVM before it starts executing the .so file because there is no way to put a break point in a shared object file. Instead, we can put a break in the code before it invokes the pass.
We're going to put a breakpoint in llvm/lib/IR/Pass.cpp
Here's how to do it:

*

*Navigate to build/bin and open terminal and type gdb opt. If you compiled llvm with the debug symbols added then gdb will take some time to load debugging symbols, otherwise gdb will say loading debugging symbols ... (no debugging symbols found).

*Now we need to set a break point at the void Pass::preparePassManager(PMStack &) method in Pass.cpp. This is probably the first (or one of the first) methods involved in loading the pass.
You can do this by by typing break llvm::Pass::preparePassManager in terminal.

*Running the pass. I have a bitcode file called trial.bc and the same LLVMHello.so pass so I run it with
run -load ~/llvm/build/lib/LLVMHello.so  -hello < ~/llvmexamples/trial.bc > /dev/null

gdb will now stop at Pass::preparePassManager and from here on we can use step and next to trace the execution.

A: Following Richard Penningtons advice  + adding backticks works for me:
gdb /usr/local/bin/opt

then type
run `opt -load=/pathTo/LLVMHello.so  -hello < /pathTo/your.bc > /dev/null`

Note: I would have commented, but couldn't (missing rep.)


text:
Q: Include Unit tests in the same package as the source code in Java I'm getting back into Java after a long stint in the Ruby world and I've got a question about JUnit tests and the source I'm testing.
If I've got a package of graphics code for my company, lets call it com.example.graphics, should I include my tests in that package too or should they be included in a seperate package, like com.example.graphics.test?

A: In the same java package is fine.  It's actually necessary if you need to access package-private classes, methods, or fields.  However, the source should be logically separate:
src/main/com/example/graphics
src/test/com/example/graphics

A: If you do not need to access private classes it is actually a question of flavor.
I sometimes even tend to create an additional test-project referenced to the product-project.
Therefore, product and test are clearly seperated.

A: I personally keep all my tests in the same package, but in the test tree of Maven(which I always use for Java projects). Consider using Maven for your builds as well - it saves a lot of work on your part. It enforces a similar structure to what bkail mentions, but gives you much more than a standardized project folder layout - project lifecycle(clean, compile, package, test), plugins, etc .

A: Putting tests in a separate package does tend to avoid the problem of accidentally having some method or class at package-scope that you intended clients to use.


text:
Q: How to convert non-supported character to html entity in Java Some character not support by certain charset, so below test fail. I would like to use html entity to encode ONLY those not supported character. How, in java?
public void testWriter() throws IOException{
    String c = "\u00A9";
    String encoding = "gb2312";
    ByteArrayOutputStream outStream = new ByteArrayOutputStream();
    Writer writer  = new BufferedWriter(new OutputStreamWriter(outStream, encoding));
    writer.write(c);
    writer.close();
    String result = new String(outStream.toByteArray(), encoding);
    assertEquals(c, result);
}

A: I'm not positive I understand the question, but something like this might help:
import java.nio.charset.CharsetEncoder;

...

  StringBuilder buf = new StringBuilder(c.length());
  CharsetEncoder enc = Charset.forName("gb2312");
  for (int idx = 0; idx < c.length(); ++idx) {
    char ch = c.charAt(idx);
    if (enc.canEncode(ch))
      buf.append(ch);
    else {
      buf.append("&#");
      buf.append((int) ch);
      buf.append(';');
    }
  }
  String result = buf.toString();

This code is not robust, because it doesn't handle characters beyond the Basic Multilingual Plane. But iterating over code points in the String, and using the canEncode(CharSequence) method of the CharsetEncoder, you should be able to handle any character.

A: Try using StringEscapeUtils from apache commons.

A: Just use utf-8, and that way there is no reason to use entities.
If there is an argument that some clients need gb2312 because they don't understand Unicode, then entities are not much use either, because the numeric entities represent Unicode code points.


text:
Q: Bootstrap validation on dynamically adding multiple fields I am using bootstrap v3.1.1 and I want to validate a form with bootstrap validation but who contains a button to clone 3 fields. With cloning everything works nice, but I can't validate the cloned fields. Here is my HTML Form:
<form id="myForm" action="myAction">

            <input type="text" class="form-control input-sm" id="idFirstField_1" name="firstField[]">

            <input type="text" class="form-control input-sm" id="idSecondField_1" name="secondField[]">

            <input type="text" class="form-control input-sm" id="idThirdField_1" name="thirdField[]">

    add line
</form>

In JavaScript file I Have:
    $(document).ready(function () {
    var count = 2;
    $('#cloneButton').click(function () {
        var klon = $('#line_1');
        klon.clone().attr('id', 'line_' + (++count)).insertAfter($('#line_1'));
        $('#line_' + count).children('div').children('input').each(function () {
            $(this).val('');
            var oldId = $(this).attr('id').split('_');
            $(this).attr('id', oldId[0] + '_' + count);
        });
    });

    //For validating the fields:
    $('#myForm').bootstrapValidator({
        fields: {
            'firstField[]': {
                validators: {
                    notEmpty: {
                        message: 'Enter a value'
                    }
                }
            },
            'secondField[]': {
                validators: {
                    notEmpty: {
                        message: 'Enter a value'
                    }
                }
            },
            'thirdField[]': {
                validators: {
                    notEmpty: {
                        message: 'Enter a value'
                    }
                }
            }
        }
    });
});

I now that I must to use somethings like this
$('#myForm').bootstrapValidator('addField', klon.find('[name="firstField[]"]'));

for each field, but I don't now how correctly do it. Please help me. Thanks!!

A: if you insert the method addField in your input loop, it should work. I also suggest to save your first row as a template.
var template = $('#line_1').clone();
var options = {
    fields: {
        'firstField[]': {
            validators: {
                notEmpty: {
                    message: 'Enter a value 1'
                }
            }
        },
        'secondField[]': {
            validators: {
                notEmpty: {
                    message: 'Enter a value 2'
                }
            }
        },
        'thirdField[]': {
            validators: {
                notEmpty: {
                    message: 'Enter a value 3'
                }
            }
        }
    }
};
$('#myForm').bootstrapValidator(options);

$('#cloneButton').click(function () {
    var rowId = $('.row').length + 1;
    var validator = $('#myForm').data('bootstrapValidator');
    var klon = template.clone();
    klon.attr('id', 'line_' + rowId)
        .insertAfter($('.row').last())
        .find('input')
        .each(function () {
            $(this).attr('id', $(this).attr('id').replace(/_(\d*)$/, "_"+rowId));
            validator.addField($(this));
        })
});

FIDDLE

A: This Answer not exactly for this question but if someone want to add different field dynamically then they can use this.
$('#myForm').formValidation('addField', 'fourthField[]', {
            validators: {
                    notEmpty: {
                        message: 'Enter a value 4'
                    }
                },
});

Syntax : $("#form_name").formValidation("addField",'no of the field',{validation});


text:
Q: If statement from external config file not working I have a script that includes a config file (called accountsconfig.php) that contains a simple boolean:
<?php
$account = 'on';
?>

On my main script, I have a series of if else (if $account == true, do this, else this), but its always going to the else no matter what the value of $account is (As if it doesnt even get the value of $account). Heres an example of one of my ifelse:
 <?php
    include('accountsconfig.php');

 if ($account == 'on') { ?>
    <select name="account_number" >
         <option value="one">Account One</option>
    </select>
 <?php } else { ?>
    <h1> HIII</h1>
 <?php } ?>

This file and the accountsconfig.php are located in the same directory.
*UPDATE:*
If i add <?php echo "$account" ?> between the  in the else, it displays "off"
Any suggestions?

A: don't use the word true
if you do the use === in stead of == as its boolean
use another word or number to represent what you are doing 1/yes 2/no


text:
Q: split arrays as string in one column of pandas to multiple columns I have data frame in the below format. The description is in string format.

file
description

x
[[array(['MIT', 'MIT', 'MIT', 'MIT', 'MIT'], dtype=object), array([0.71641791, 0.71641791, 0.71641791, 0.69565217, 0.69565217])]]

y
[[array(['APSL-1.0', 'APSL-1.0', 'APSL-1.0', 'APSL-1.0', 'APSL-1.0'],       dtype=object), array([0.28552457, 0.28552457, 0.28552457, 0.28552457, 0.28552457])]]

How can i convert data Frame into below format.

file
license
score

x
['MIT', 'MIT', 'MIT', 'MIT', 'MIT']
[0.71641791, 0.71641791, 0.71641791, 0.69565217, 0.69565217]

y
['APSL-1.0', 'APSL-1.0', 'APSL-1.0', 'APSL-1.0', 'APSL-1.0']
[0.28552457, 0.28552457, 0.28552457, 0.28552457, 0.28552457]

Above is just an example. Data frame is very large.

A: Update, If elements in the column as string format, you can find array with regex formula. (Note don't use eval, Why should exec() and eval() be avoided?)
import ast
new_cols = lambda x: pd.Series({'licence':ast.literal_eval(x[0]),
                                'score':ast.literal_eval(x[1])})

df = df.join(df['m'].str.findall(r'\[[^\[\]]*\]').apply(new_cols)).drop('m', axis=1)
print(df)

Output:
    file    licence                                              score
0   x       ['MIT', 'MIT', 'MIT', 'MIT', 'MIT']                     [0.71641791, 0.71641791, 0.71641791, 0.6956521...
1   y       ['APSL-1.0', 'APSL-1.0', 'APSL-1.0', 'APSL-1.0', ...    [0.28552457, 0.28552457, 0.28552457, 0.2855245...

How regex formula find arrays: (find string start with [ and end with ] but in finding string should not have [ or ] to find all arrays.)
>>> import re
>>> re.findall(r'\[[^\[\]]*\]', "[[np.array(['MIT', 'MIT', 'MIT', 'MIT', 'MIT'], dtype=object), np.array([0.71641791, 0.71641791, 0.71641791, 0.69565217, 0.69565217])]]",)
["['MIT', 'MIT', 'MIT', 'MIT', 'MIT']",
 '[0.71641791, 0.71641791, 0.71641791, 0.69565217, 0.69565217]']

Old, You can create new column then join with old dataframe.
new_cols = lambda x: pd.Series({'licence':x[0][0], 'score':x[0][1]})
df = df.join(df['m'].apply(new_cols)).drop('m', axis=1)
print(df)

A: Input:
  file                                        description
0    x  [[array(['MIT', 'MIT', 'MIT', 'MIT', 'MIT'], d...
1    y  [[array(['APSL-1.0', 'APSL-1.0', 'APSL-1.0', '...

Doing:
import ast

df.description = (df.description.str.replace('array', '')
                    .str.replace(', dtype=object', '')
                    .apply(ast.literal_eval))
df[['license', 'score']] = [(x[0], x[1]) for x in df.description.str[0]]
df = df.drop('description', axis=1)
print(df)

Output:
  file                                            license                                              score
0    x                          [MIT, MIT, MIT, MIT, MIT]  [0.71641791, 0.71641791, 0.71641791, 0.6956521...
1    y  [APSL-1.0, APSL-1.0, APSL-1.0, APSL-1.0, APSL-...  [0.28552457, 0.28552457, 0.28552457, 0.2855245...


text:
Q: How to stop sending requests to Firebase Emulators? My Project:
Google Cloud Functions sends a SOAP request to a 3rd party API, using a Scheduled Function (Pubsub + Cloud Scheduler), parses, sanitizes and stores the response in Firestore. It's authenticated with a Service Account.
What's Wrong:
It's already deployed and working well in production. After deploy, I installed the new Firebase Emulators, which worked well. However, now it always tries to connect to the emulators when running the shell (the emulators are probably the issue):
npm run shell

In the logs I can see that it's trying to connect to the emulators, but from what I understand it should be bypassing them automatically. I can't find anything in the docs that addresses this.
My Question & Logs:
Does anyone know how to bypass this connection attempt so that I can directly write to Firestore instead of the emulators?
Here are the logs:
    [debug] [2020-06-24T20:16:37.808Z] ----------------------------------------------------------------------
[debug] [2020-06-24T20:16:37.810Z] Command:       C:\Program Files\nodejs\node.exe C:\Program Files\nodejs\node_modules\firebase-tools\lib\bin\firebase.js functions:shell
[debug] [2020-06-24T20:16:37.811Z] CLI Version:   8.4.3
[debug] [2020-06-24T20:16:37.811Z] Platform:      win32
[debug] [2020-06-24T20:16:37.811Z] Node Version:  v10.18.1
[debug] [2020-06-24T20:16:37.812Z] Time:          Wed Jun 24 2020 17:16:37 GMT-0300 (Atlantic Daylight Time)
[debug] [2020-06-24T20:16:37.812Z] ----------------------------------------------------------------------
[debug] [2020-06-24T20:16:37.812Z]
[debug] [2020-06-24T20:16:37.822Z] > command requires scopes: ["email","openid","https://www.googleapis.com/auth/cloudplatformprojects.readonly","https://www.googleapis.com/auth/firebase","https://www.googleapis.com/auth/cloud-platform"]
[debug] [2020-06-24T20:16:37.823Z] > authorizing via signed-in user
[debug] [2020-06-24T20:16:37.823Z] [iam] checking project rtiwebservices for permissions ["firebase.projects.get"]
[debug] [2020-06-24T20:16:37.827Z] >>> HTTP REQUEST POST https://cloudresourcemanager.googleapis.com/v1/projects/rtiwebservices:testIamPermissions
 {"permissions":["firebase.projects.get"]}
[debug] [2020-06-24T20:16:38.208Z] <<< HTTP RESPONSE 200 {"content-type":"application/json; charset=UTF-8","vary":"X-Origin, Referer, Origin,Accept-Encoding","date":"Wed, 24 Jun 2020 20:16:35 GMT","server":"ESF","cache-control":"private","x-xss-protection":"0","x-frame-options":"SAMEORIGIN","x-content-type-options":"nosniff","server-timing":"gfet4t7; dur=182","alt-svc":"h3-27=\":443\"; ma=2592000,h3-25=\":443\"; ma=2592000,h3-T050=\":443\"; ma=2592000,h3-Q050=\":443\"; ma=2592000,h3-Q046=\":443\"; ma=2592000,h3-Q043=\":443\"; ma=2592000,quic=\":443\"; ma=2592000; v=\"46,43\"","accept-ranges":"none","transfer-encoding":"chunked"}
[debug] [2020-06-24T20:16:38.209Z] >>> HTTP REQUEST GET http://localhost:4400/emulators

[debug] [2020-06-24T20:16:40.215Z] Error: connect ECONNREFUSED 127.0.0.1:4400
    at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1107:14)
[error]
[error] Error: Server Error. connect ECONNREFUSED 127.0.0.1:4400


text:
Q: Не запускается IntelliJ Idea Ultimate Ни с того ни с сего перестала запускаться intelliJ Idea Ultimate 2019.2.
Выдает ошибку:
Пошарил по файлам vmoptions, такой настройки не нашел.

A: Удалить файл studio64.exe.vmoptions из C:\Users\%USERNAME%\.IntelliJIdea2019.2\config


text:
Q: JavaScript either strokeRect or fillRect blurry depending on translation Earlier on I noticed that strokeRect (and any other method that involved stroke such as lineTo) created a grey 2 px wide line instead of a 1px wide black line. After some Google searching I found that context.translate(0.5, 0.5) fixed this. but now fillRect (and like before any other method that involves fill) creates a black box with a grey border around it.
Does anyone know a good way to make it so that both fillRect and strokeRect have crisp edges with no grey borders? I also don't know whether or not I should use context.translate(0.5, 0.5) for images, as it seems like SVGs have crisp edges regardless of whether or not I translate.
Here is a jsfiddle demonstrating this: http://jsfiddle.net/Tysonzero/ydm21pkt/1/
Note that the bottom strokeRect is crisp while the top one is blurry, and the top fillRect is crisp while the bottom one is blurry.

A: Strokes draw half-inside & half-outside the x,y coordinates. That's why you are seeing the blur with integer x,y and why it clears up when the x,y are offset by a half pixel. Here's more on why the blur occurs: http://www.mobtowers.com/html5-canvas-crisp-lines-every-time/
An easy way to make rects crisper is to add methods to your context instance that offset strokeRect & fillRect for best appearance:

var canvas=document.getElementById("canvas");
var context=canvas.getContext("2d");
var cw=canvas.width;
var ch=canvas.height;

// add pixel aligned versions of strokeRect & fillRect to this context instance
context.sRect=function(x,y,w,h){
  x=parseInt(x)+0.50;
  y=parseInt(y)+0.50;
  this.strokeRect(x,y,w,h);
}
context.fRect=function(x,y,w,h){
  x=parseInt(x);
  y=parseInt(y);
  context.fillRect(x,y,w,h);
}

context.strokeStyle = "#000000";
context.fillStyle = "#000000";

context.strokeRect(100, 50, 100, 100);
context.fillRect(300.5, 50.5, 100, 100);

context.sRect(100,200,100,100);
context.fRect(300.5,200,100,100);

context.fillText('Unadjusted',20,100);
context.fillText('Adjusted',20,250);
body{ background-color: ivory; padding:10px; }
#canvas{border:1px solid red;}
<canvas id="canvas" width=500 height=500></canvas>


text:
Q: Return Type Format of Python pygame.midi.Input.read() I've searched a lot to find out what does the pygame.midi.Input.read() returns.
In every documentation I found they say it's
[[status,data1,data2,data3],timestamp],...]

But what the hell is data1, data2, data3?
Someone, please explain what each list item's type and use in relation to MIDI data


text:
Q: How to add a dictionary with a number of keys less than the number of columns of the dataframe to that dataframe into a new line? I have a Dataframe like this:
df

and a dict like this:
result={'a':'cat,'b':'kiss'}
Can someone please help me to create a simple dataframe like below image? Thanks!

A: You can use concat with the DataFrame constructor :
df = pd.concat([df, pd.DataFrame(result, index=[len(df)+1])])

Alternatively, use loc :
df.loc[len(df)+1, list(result.keys())] = list(result.values())

Output :
print(df)

      a     b      c
1  food  hate   rain
2   dog  like  storm
3  same  love  flood
4   cat  kiss    NaN

A: You can use same this append() method

*

*Let's say df1 = df

*Converting dictionary to dataframe using
pd.Dataframe(result), let's say df2

*Appending df2 to the df1 using append()

A continuous index value will be maintained
df1.append(df2, ignore_index = True)


text:
Q: Are static constructors guaranteed to not be inlined? I guess so!
EDIT: The motivation for this question is: It seems to me that due to the semantics of static constructors they could never be safely inlined.

A: The jitter's inlining strategy is an implementation detail -- subject to change at any time -- so there are pretty much no guarantees about what can or can't be inlined.
Having said that, it's difficult to see how a static constructor could ever be safely inlined, bearing in mind the guarantees provided by the C# and CLI specs regarding static constructors and type initialisation.
From the Microsoft C# specification (section 10.12):

The static constructor for a closed class type executes at most once
  in a given application domain. The execution of a static constructor
  is triggered by the first of the following events to occur within an
  application domain:

*

*An instance of the class type is created.

*Any of the static members of the class type are referenced.

And from the ECMA CLI specification (section 8.9.5):

[A class can] optionally specify a method (called .cctor) to be
  called to initialize the type.
The semantics of when and what triggers execution of such type
  initialization methods, is as follows:

*

*A type can have a type-initializer method, or not.

  A type can be specified as having a relaxed semantic for its
  type-initializer method (for convenience below, we call this relaxed
  semantic BeforeFieldInit).
If marked BeforeFieldInit then the type's initializer method is
  executed at, or sometime before, first access to any static field
  defined for that type.
If not marked BeforeFieldInit then that type's initializer method
  is executed at (i.e., is triggered by):

*

*first access to any static field of that type, or

*first invocation of any static method of that type, or

*first invocation of any instance or virtual method of that type if
  it is a value type or

*first invocation of any constructor for that type.

(Note that C# classes with a static constructor will not have beforefieldinit semantics. C# classes without a static constructor will have beforefieldinit semantics.)

A: The only guarantees you have are the following :

*

*A static constructor is called automatically to initialize the class before the first instance is created or any static members are referenced.

*The user has no control on when the static constructor is executed in the program.


text:
Q: How to check a mouse pointer event is within a mask?
I need to highlight a puzzle piece on mouse hover. Each puzzle is a div, masked by an SVG. I figured out how to determine a mask bounding rectangle and check within it, but I can't figure out how to check events within complex SVG shape (Codepen — https://codepen.io/alexchekanov/pen/Yzjymgq):

A: (Text and code have been updated after comment by @herrstrietzel)
Because individual
 with a rotated SVG as background are rectangluar elements.

*

*Despite masking the outsides of the SVG, the rectangle will still overlap sibbling elements. Using a mask-image with the puzzle pieces will remove all underlaying overlaps of their sibblings, leaving you with just a few lines as final result.

*Without mask-image, only small parts of the individual pieces will react to :hover, despite changing z-index.
I tested the above to be true in Firefox.
Solution

*

*Create an in-document SVG hidden from view with style="display: none" defining the puzzle piece as a <symbol> with and id and <use> it in your
.

*Re<use> the puzzle piece four more times inside the
 and transform: rotate them to their proper location.
It took me quite some time to create the final SVG and the demo, so I did not incorporate your Javascript in the snippet. However, it should give you not much trouble attaching an eventlistener to the symbol and/or the individual path in the SVG to perform the required actions on hover/click.
As you can see in the snippet, the final hover action only takes two CSS rules to achieve the desired result:
.tt-puzzle-piece       { fill: red; transition: fill 0.2s ease }
.tt-puzzle-piece:hover { fill: lime }

BTW I used SVGedit v7.0 to create the full puzzle...
UPDATE I changed the code based on herrstrietzel comment below and moved the code around as suggested.
My previous solution did not work in Chrome/Edge, because the in-doc SVG gets put in shadow DOM and Chromium browser do not bubble hover into that DOM apparently, where Firefox does. People are not sure which User Agent developer is right as the W3C spec are not conclusive about which behaviour should be supported.
The final code now works in Chrome/Edge and Firefox. By lack of Apple devices I did not test it in Safari.
Check Stackoverflow Question 64633294 and further...
snippet (with updated code).

/* * { outline: 1px dashed } /* for debugging */

* { box-sizing: border-box }

body {
    margin: 0;
    width: 100%; min-height: 100vh;
    display: grid; place-items: center;
}

.tt-puzzle-container       { width: 50vw; height: 50vw }
.tt-puzzle-container > svg { width: 100%; height: 100% }

.tt-puzzle-piece           { fill: red; transition: fill 0.2s ease }
.tt-puzzle-piece:hover     { fill: lime }

  <svg viewbox="0 0 418 418">

    <use class="tt-puzzle-piece" href="#puzzle-piece" />
    <use class="tt-puzzle-piece" href="#puzzle-piece" transform="rotate(-72, 209, 209)" />
    <use class="tt-puzzle-piece" href="#puzzle-piece" transform="rotate(-144, 209, 209)" />
    <use class="tt-puzzle-piece" href="#puzzle-piece" transform="rotate(-216, 209, 209)" />
    <use class="tt-puzzle-piece" href="#puzzle-piece" transform="rotate(-288, 209, 209)" />
  </svg>

<svg xmlns="http://www.w3.org/2000/svg" style="display:none">
  <symbol id="puzzle-piece" viewbox="0 0 418 418">
    <path d="m90.77,377.92c-0.5,0.7 -0.3,1.6 0.4,2.1c14.8,10.1 30.8,18.3 47.5,24.3c0,0 0.1,0 0.1,0.1c1.1,0.4 2.1,0.8 3.2,1.1c0.3,0.1 0.6,0.2 0.9,0.3c0.9,0.3 1.8,0.6 2.7,0.9c0.6,0.2 1.1,0.4 1.7,0.5c0.7,0.2 1.3,0.4 2,0.6c1.3,0.4 2.6,0.8 3.8,1.1c1.4,0.4 2.8,0.8 4.2,1.1c0.5,0.1 1,0.2 1.5,0.4c0.5,0.1 1.1,0.3 1.6,0.4c0.5,0.1 1.1,0.3 1.6,0.4c1.6,0.4 3.2,0.7 4.8,1.1c0.5,0.1 1.1,0.2 1.6,0.3c1.1,0.2 2.2,0.4 3.2,0.6c0.5,0.1 1.1,0.2 1.6,0.3c1.1,0.2 2.2,0.4 3.3,0.6c0.6,0.1 1.1,0.2 1.6,0.3c1.6,0.2 3.2,0.5 4.8,0.7c0.6,0.1 1.2,0.2 1.8,0.2c0.4,0.1 0.8,0.1 1.3,0.1c0.4,0.1 0.9,0.1 1.3,0.1c0.7,0.1 1.3,0.1 1.9,0.2c0.2,0 0.4,0 0.6,0.1c30,2.8 60,-0.9 87.9,-10.5c12.1,-4.1 23.7,-9.4 34.9,-15.7c3.5,-2 6.9,-4 10.3,-6.2c1.8,-1.1 3.5,-2.3 5.3,-3.5c0.7,-0.5 0.9,-1.4 0.4,-2.1l-25.1,-34.6c-0.8,-1.1 -2.5,-1.1 -3.2,0.1c-1.2,2 -2.8,3.8 -4.8,5.2c-0.8,0.5 -1.6,1 -2.4,1.5c-7.6,3.9 -16.9,1.8 -22.1,-4.9c-3,-3.8 -4.2,-8.6 -3.6,-13.4c0.7,-4.8 3.2,-9 7.1,-11.9c2,-1.4 4.1,-2.4 6.4,-2.9c1.3,-0.3 1.9,-1.9 1.1,-3l-29.4,-40.4c-0.5,-0.6 -1.3,-0.8 -2,-0.4c0,0 0,0 0,0c-0.5,0.3 -0.9,0.6 -1.4,0.9c-0.4,0.2 -0.8,0.4 -1.1,0.7c-0.8,0.5 -1.6,0.9 -2.4,1.3c-0.3,0.1 -0.5,0.3 -0.8,0.4c-9.7,5 -20.4,7.8 -31.2,8.4c-0.3,0 -0.6,0 -0.9,0.1c-1,0 -2,0.1 -2.9,0.1c-0.4,0 -0.9,0 -1.3,0c-13.7,-0.2 -27.4,-3.9 -39.7,-11.5c0,0 -0.1,0 -0.1,0c-0.1,-0.1 -0.3,-0.2 -0.4,-0.2c-0.8,0.2 -1.2,0.2 -2,0.4l-34.5,47.5c-1.5,2.1 -4.2,2.8 -6.5,2c-0.5,-0.2 -1,-0.4 -1.4,-0.8c-1.6,-1.2 -2.5,-3.4 -2.3,-5.9c0,-0.2 0,-0.4 -0.1,-0.7c-3.4,-9.2 -14.2,-9.1 -18,-2.1c-1.9,3.4 -1.4,7.7 1.1,10.7c2.5,2.9 6.2,4.1 9.8,3.2c1.9,-0.5 3.9,-0.2 5.2,0.8c0.5,0.3 0.8,0.7 1.2,1.1c1.5,1.9 1.6,4.7 0.1,6.8l-30.2,41.6z" />
  </symbol>
</svg>


text:
Q: Serialise Nested Class to Table Rows in Spring I'm using Spring Boot with the expected dependencies (Jackson, Hibernate etc.).
I'm have a table called Buildings where Unit, Number, Street etc. are all columns. But I prefer to parse this and return this as a class I created called "StreetAddress".
When I send this JSON, I get an error.
"address": {
    "unit":"0101",
    "number":"19",
    "suffix":"STREET",
    "suburb":"Example",
    "state":"EXP",
    "streetName":"Example",
    "postCode":"400"
}

This is the error:
Cannot construct instance of `com.App.Entity.Helpers.StreetAddress` (no Creators, like default construct, exist): cannot deserialize from Object value (no delegate- or property-based Creator)

I have this as setAddress in my Building model. Is there any annotation I can use to tell Jackson how to parse this properly?
private String subunit;
private Integer number;
private String streetname;
private String suffix;
private String suburb;
private String state;
private Integer postcode;

public void setAddress(StreetAddress address) {
        this.subunit = address.getUnit();
        this.number = address.getNumber();
        this.streetname = address.getStreetName();
        this.suffix = address.getSuffix().toString();
        this.suburb = address.getSuburb();
        this.state = address.getState().toString();
        this.postcode = address.getPostCode();
    }

Clarification:
public class StreetAddress {
private String unit;
private Integer number;
private String streetname;
private StreetSuffix suffix;
private String suburb;
private AUState state;
private Integer postcode;

public StreetAddress(String unit, int number, String street, StreetSuffix suffix, String suburb, AUState state, int postcode) {
    this.unit = unit;
    this.number = number;
    this.streetname = street;
    this.suffix = suffix;
    this.suburb = suburb;
    this.state = state;
    this.postcode = postcode;
}

public String getUnit() {
    return unit;
}

public Integer getNumber() {
    return number;
}

public String getStreetName() {
    return streetname;
}

public String getSuffix() {
    return suffix.toString();
}

public String getSuburb() {
    return suburb;
}

public AUState getState() {
    return state;
}

public Integer getPostCode() {
    return postcode;
}

}

A: The error message says that Jackson doesn't know how to create an object of type StreetAddress, because it could not find a suitable constructor. Jackson either expects a parameterless constructor (in which case it will pass the JSON data by assigning fields or calling setters), or a constructor with annotations that tell Jackson which JSON attribute should be passed to which parameter.
The easiest way to resolve this is to simply not declare a constructor, and make the fields public instead:
public class StreetAddress {
    public String unit;
    // ... more fields here
}

Alternatively, you can keep the fields private, but declare a setter for each field:
public class StreetAddress {
    private String unit;
    // ... more fields here

    public void setUnit(String unit) {
        this.unit = unit;
    }
    // ... more setters here
}


text:
Q: Try to deploy app via PAServer 21 but in vain This bothered me for over half a year already.
When I used Rad Studio 10.4.1, it is ok to deploy app to the iOS device.
While I installed Rad Studio 10.4.2 on another PC, and installed PAserver 21 (12.2.10.3) on another macbook, it failed to deploy app to the iOS device.
Connection seems to be ok...

Provisioning seems to be good...

But the compiler will stop at...

PAServer shows message like this

The process will hang there until I quit in PAServer

I have consulted with Embarcaderom but with no answer.
Can someone help to solve this problem?
Thanks with all my heart...


text:
Q: Find and Copy varying text to an adjacent cell Here goes: my first post, and I'm NOT a programmer, but I'm hoping you guys can help!
I have a list of 300 cells which all reference specific chapters of a book contained in the text of the cell.  The content of each cell varies, but the content I need to extract is consistently in this format:
"...can be found in Chapter A01: The History of The Blues."
"...can be found in Chapter D27: The Many Faces of The Blues."
I want to extract just the chapter number text "A01" or "D27", etc. and copy it into the cell adjacent to where the text was found.
In the cell, the chapter number I want to copy is always preceded by the word "Chapter" and a space, and is always followed by a colon.
I've been searching the forum for a couple of hours, and you all have already helped me figure out how to use VB to find, copy and paste the exact text match to another cell, and I did find this answer, which looked promising, but I can't figure out how to modify the details to make it work for me!
Copy part of cells that varies in both length and content using VBA
Thanks for any help you can give me!!

A: If your text is in cell A1, then paste this formula into B1:
=MID(A1,SEARCH("Chapter ",A1)+8,3)

You can then copy B1 to B2:B100 to extract there aswell.

A: Here is the VBA code. I'm assuming your data are in the Range("A1:A300").
Sub ExtractChapter()
Dim Data As Range, RowData As Long, Text As String, Chapter As String

Set Data = Range("A1:A300")       'Change this depends on your data located
RowData = Data.Rows.Count
For i = 1 To RowData
    Text = Data(i)
    Chapter = Mid$(Text, InStr(Text, ":") - 3, 3)
    Data(i).Offset(0, 1) = Chapter
Next
End Sub

A: While what others are saying is true (you don't really need a VBA Macro for this), here is something that works.This will work even if your chapters are more than three characters long (variable chapter number text length).
Sub SEFindStrings()

Dim searchRange As range

'wherever your search range is, modify. Mine started at B4 so I used that as the start
'cell and in my Cells method I used "B". Change so it fits your data
Set searchRange = range("B4", Cells(Rows.count, "B").End(xlUp))

Dim myCell As range
Dim locationStart As Integer
Dim locationEnd As Integer
Dim keyWords As String

keyWords = "can be found in Chapter "

'Goes through, and if the cell isn't empty it finds the phrase 'can be found in Chapter '
'and then gets the next three characters.
For Each myCell In searchRange
    If myCell.Value <> "" Then
    locationStart = InStr(myCell.Value, keyWords)
        If locationStart <> 0 Then
        locationEnd = InStr(locationStart, myCell.Value, ":") - 1
            myCell.Offset(0, 1).Value = (Mid(myCell.Value, _
            (locationStart + Len(keyWords)), locationEnd - Len(keyWords)))
        End If
    End If
Next myCell

End Sub


text:
Q: What is the term to describe the use of "City Hall" in "you can't fight City Hall"? I know there's a word to describe the use of the words "City Hall" in the common phrase "you can't fight City Hall", where "City Hall" = "the office of the mayor of the city", but I can't remember what it is. I don't think it's anthropomorphism but the proper term has been on the tip of my tongue all day and I just can't bring it to mind.

A: Yours is a textbook case of metonymy, which Silva Rhetorica by BYU's Gideon Burton defines as

Reference to something or someone by naming one of its attributes.

City hall is a building associated with local government, and used metaphorically to represent local government as a whole. See also What is the difference between metonymy and synecdoche?
It is not anthropomorphism because we are not talking about the physical building itself. An anthropomorphism might be represented by something like

Erie's City Hall squats lazily, reaching toward State Street but never quite making it.

A: The word you are looking for is metonymy.


text:
Q: How to a recover a text from a wrong encoding? I have got some files created from some asian OS (chinese and japanese XPs)
the file name is garbled, for example:

иè+¾«Ñ¡Õä²ØºÏ¼

how i can recover the original text?
I tried with this in c#
Encoding unicode = Encoding.Unicode;
Encoding cinese = Encoding.GetEncoding(936);
byte[] chineseBytes = chinese.GetBytes(garbledString);
byte[] unicodeBytes = Encoding.Convert(unicode, chinese, chineseBytes);
//(Then convert byte in string)

and tried to change unicode to windows-1252 but no luck

A: It's a double-encoded text. The original is in Windows-936, then some application assumed the text is in ISO-8869-1 and encoded the result to UTF-8. Here is an example how to decode it in Python:
>>> print 'иè+¾«Ñ¡Õä²ØºÏ¼'.decode('utf8').encode('latin1').decode('cp936')
新歌+精选珍藏合辑

I'm sure you can do something similar in C#.

A: Encoding unicode = Encoding.Unicode;

That's not what you want. "Unicode" is Microsoft's totally misleading name for what is really the UTF-16LE encoding. UTF-16LE plays no part here, what you have is a simple case where a 936 string has been misdecoded as 1252.
Windows codepage 1252 is similar but not the same as ISO-8859-1. There is no way to tell which is in the example string as it does not contain any of the bytes 0x80-0x9F which are different in the two encodings, but I'm assuming 1252 because that's the standard codepage on a western Windows install.
Encoding latin= Encoding.getEncoding(1252);
Encoding chinese= Encoding.getEncoding(936);

chinese.getChars(latin.getBytes(s));

A: The first argument to Encoding.Convert is the source encoding, Shouldn't that be chinese in your case? So
Encoding.Convert(chinese, unicode, chineseBytes);

might actually work. Because, after all, you want to convert CP-936 to Unicode and not vice-versa. And I'd suggest you don't even try bothering with CP-1252 since your text there is very likely not Latin.

A: This is an old question, but I just ran into the same situation while trying to migrate WordPress upload files off of an old Windows Server 2008 R2 server. bobince's answer set me on the right track, but I had to search for the right encoding/decoding pair.
With the following C#, I found the relevant encoding/deciding pair:
using System;
using System.Text;

public class Program
{
    public static void Main()
    {
        // garbled
        string s = "2020竹慶本樂ä»æ³¢åˆ‡äºžæ´²æ³•çµ-Intro-2-1024x643.jpg";
        // expected
        string t = "2020竹慶本樂仁波切亞洲法筵-Intro-2-1024x643.jpg";

        foreach( EncodingInfo ei in Encoding.GetEncodings() )  {
            Encoding e = ei.GetEncoding();
            foreach( EncodingInfo ei2 in Encoding.GetEncodings() )  {
                Encoding e2 = ei2.GetEncoding();
                var s2 = e2.GetString(e.GetBytes(s));
                if (s2 == t) {
                    var x = ei.CodePage;
                    Console.WriteLine($"e1={ei.DisplayName} (CP {ei.CodePage}), e2={ei2.DisplayName} (CP {ei2.CodePage})");
                    Console.WriteLine(t);
                    Console.WriteLine(s2);
                }
            }
        }

        Console.WriteLine("-----------");
        Console.WriteLine(t);
        Console.WriteLine(Encoding.GetEncoding(65001).GetString(Encoding.GetEncoding(1252).GetBytes(s)));
    }
}

It turned out that the correct encoding/deciding in my case was:
e1=Western European (Windows) (CP 1252), e2=Unicode (UTF-8) (CP 65001)

So the last line of code is a one-liner for the correct conversion Console.WriteLine(Encoding.GetEncoding(65001).GetString(Encoding.GetEncoding(1252).GetBytes(s)));.


text:
Q: Insert a div class inside wordpress menu

About Assetline

Products & Services

Commercial Credit

Portfolio Management

News & Events

This is the menu structure what I want to integrate into WordPress . But there's an issue to add a div id ( ) inside of a menu . Any idea to achieve this ?

A: You forgot to close some of your first li tags. If that does work, remove the div, and assign the id in the child ul.

    level 1

          level 2 A

          level 2 B

                level 3


text:
Q: Output taxonomy term names for translations I'm currently outputting the term id's for several languages on a page. How can I output the term names for each instead?
I've tried to use the get_term function to specifically get the French name for the taxonomy term and it still comes out in English even though the ID is the French id.
Where am I going wrong?
  <?php
  $taxonomy = "categories";
  $terms = get_terms( array(
    'suppress_filters' => false,
    'taxonomy' => $taxonomy,
    'hide_empty' => false,
  ) );

  if  ($terms) {
    foreach ($terms  as $term ) { ?>

        EN: <?php echo $english = icl_object_id($term->term_id,'categories',false,'en'); ?>

        FR: <?php echo $french = icl_object_id($term->term_id,'categories',false,'fr'); ?>

        DE: <?php echo $german = icl_object_id($term->term_id,'categories',false,'de'); ?>

        IT: <?php echo $italian = icl_object_id($term->term_id,'categories',false,'it'); ?>

        RU: <?php echo $russian = icl_object_id($term->term_id,'categories',false,'ru'); ?>

        ES: <?php echo $spanish = icl_object_id($term->term_id,'categories',false,'es'); ?>

        <?php echo get_term(icl_object_id($french, 'categories', false, 'fr'))->name; ?>

    <?php }
  }
  ?>

I'm using WPML.

A: Hopefully this will help others. I ended up switching the language at each point:
  <?php
  global $sitepress;
  $current_lang = $sitepress->get_current_language(); //save current language
  $taxonomy = "categories";
  $terms = get_terms( array(
    'suppress_filters' => false,
    'taxonomy' => $taxonomy,
    'hide_empty' => false,
  ) );

  if  ($terms) {
    foreach ($terms  as $term ) { ?>

        EN: <?php echo $english = apply_filters( 'wpml_object_id', $term->term_id,'categories',false,'en'); ?>

        FR: <?php echo $french = apply_filters( 'wpml_object_id', $term->term_id,'categories',false,'fr'); ?>

        DE: <?php echo $german = apply_filters( 'wpml_object_id', $term->term_id,'categories',false,'de'); ?>

        IT: <?php echo $italian = apply_filters( 'wpml_object_id', $term->term_id,'categories',false,'it'); ?>

        RU: <?php echo $russian = apply_filters( 'wpml_object_id', $term->term_id,'categories',false,'ru'); ?>

        ES: <?php echo $spanish = apply_filters( 'wpml_object_id', $term->term_id,'categories',false,'es'); ?>

        <?php $sitepress->switch_lang('en'); ?>
        EN: <?php echo get_term(icl_object_id($french, 'categories', false, 'en'))->name; ?>

        <?php $sitepress->switch_lang('fr'); ?>
        FR: <?php echo get_term(icl_object_id($french, 'categories', false, 'fr'))->name; ?>

        <?php $sitepress->switch_lang('de'); ?>
        DE: <?php echo get_term(icl_object_id($french, 'categories', false, 'de'))->name; ?>

        <?php $sitepress->switch_lang('it'); ?>
        IT: <?php echo get_term(icl_object_id($french, 'categories', false, 'it'))->name; ?>

        <?php $sitepress->switch_lang('ru'); ?>
        RU: <?php echo get_term(icl_object_id($french, 'categories', false, 'ru'))->name; ?>

        <?php $sitepress->switch_lang('es'); ?>
        ES: <?php echo get_term(icl_object_id($french, 'categories', false, 'es'))->name; ?>

        <?php $sitepress->switch_lang($current_lang); //restore previous language ?>

    <?php }
  }
  ?>


text:
Q: How do I return the value of a HashSet item instead of the index? I am creating a HashSet in C# of type int.  The HashSet is filled with randomly generated numbers.  I'd like to select one of these numbers from the it at random and return it to the user.  The problem is, I only see solutions that return the index of the item in the HashSet not the actual value.  I'd like to know how I can access the value of my HashSet items.
Here's what I have at the moment, first I create a list from 10 to 20 which forms part of my list control, the reason for this is to set a limit on how many items a list can hold.
List<int> list_length = Enumerable.Range(10, 20).ToList();

I then iterate over list_length and add a random number to my primary list which is called hash_values
private readonly HashSet<int> hash_values = new HashSet<int>();

foreach (var i in list_length)
{

    hash_values.Add(rnd.Next(10, 20));
}

I then access the hash_values list and return a random value from it.
int get_random_number = rnd.Next(hash_values.Count());

return Json(get_random_pin);

You'll notice that the random return is actually selecting a value from the lists total count.  This is no use.  What I'd like to do is pick an item at random and turn it's value not the index.
Let's say I have a list with 5 values, the hash_values table will store it like this:
[0] 100
[1] 200
[2] 300
[3] 400
[4] 500

Returning something like a random number from the lists total count will only select the index, so I would receive [1] instead of 100.  So, how do I return the value instead of the index?

A: I would suggest to use the returned index to access the value in the hashset:
int get_random_value = hash_values.ElementAt(rnd.Next(hash_values.Count()));

EDIT:

the reason for this is to set a limit on how many items a list can hold.

you could also simply fix this number in an int and use a normal for loop
int maxNumberOfItems = 10;

for (int i = 0; i < maxNumberOfItems; i++)
{
    hash_values.Add(rnd.Next(10, 20));
}

EDIT 2 Disclaimer:
The approach of using an index on a HashSet is actually counter productive since if you want to access the value the HashSet would do it in O(1) but using the index it will do it in O(n) like it is described in this answer

A: HashSet is a Set collection. It only implements the ICollection interface. It has great restrictions on individual element access: Compared with List, you cannot use subscripts to access elements, such as list[1]. Because HashSet only saves one item for each piece of data, and does not use the Key-Value method, in other words, the Key in the HashSet is the Value. If the Key is already known, there is no need to query to obtain the Value. All you need to do is check Whether the value already exists.

A: If you get the index, then you can always to that index and fetch that value and return it. I don't see any harm by doing this.

A: HashSet is not ordered by nature, but you can always just convert you HashSet to a List or an Array by calling ToList or ToArray respectively.
The other solution with ElementAt will probably work the same, but depending on the implementation details it might not be as efficient as e.g. array (if it loops through IEnumerable).


text:
Q: CAS Single LogOut(SLO) not working - CAS 4.2.3 I am having issues with Single LogOut in CAS. I am using CAS server 4.2.3 and Spring 3.2. My client casified applications are configured on spring security. Followed the following documentation, http://docs.spring.io/spring-security/site/docs/3.2.9.RELEASE/reference/htmlsingle/#cas-singlelogout
I have 2 cas client web application. When I logout from one of the cas client web application, and refresh the page in the 2nd cas client application which I already logged in (in the same browser in a different tab), I would think that the login page would show up as I already did a single LogOut from the 1st cas client application. But it doesn't work.
I am not sure what I am missing. I have posted the code snippet of web.xml, spring-security.xml, logout.jsp and cas.log
Any help or pointers is greatly appreciated.
web.xml
<filter>
    <filter-name>characterEncodingFilter</filter-name>
    <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
    <init-param>
        <param-name>encoding</param-name>
        <param-value>UTF-8</param-value>
    </init-param>
</filter>

<filter>
    <filter-name>springSecurityFilterChain</filter-name>
    <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>

<filter-mapping>
    <filter-name>characterEncodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

<filter-mapping>
    <filter-name>springSecurityFilterChain</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

<listener>
    <listener-class>org.jasig.cas.client.session.SingleSignOutHttpSessionListener</listener-class>
</listener>

<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

spring-security.xml
<bean id="serviceProperties" class="org.springframework.security.cas.ServiceProperties">
    <property name="service" value="https://<hostname>:8444/WebApp3/j_spring_cas_security_check" />
    <property name="sendRenew" value="false" />
</bean>

<sec:http use-expressions="true" entry-point-ref="casEntryPoint">
    <sec:intercept-url pattern="/login/*" access="permitAll()" />
    <sec:intercept-url pattern="/lib/**" access="permitAll()" />
    <sec:intercept-url pattern="/**" access="isAuthenticated()" />
    <sec:form-login login-page="/ingress.do" default-target-url="/ingress.do" always-use-default-target="false"
        authentication-failure-url="/login.jsp" />

    <sec:logout logout-success-url="/logout.jsp" />
    <sec:custom-filter ref="requestSingleLogoutFilter" before="LOGOUT_FILTER" />
    <sec:custom-filter ref="singleLogoutFilter" before="CAS_FILTER" />
    <sec:custom-filter position="CAS_FILTER" ref="casFilter" />

</sec:http>

<bean id="singleLogoutFilter" class="org.jasig.cas.client.session.SingleSignOutFilter" />

<bean id="requestSingleLogoutFilter" class="org.springframework.security.web.authentication.logout.LogoutFilter">
    <constructor-arg value="https://<hostname>/cas/logout" />
    <constructor-arg>
        <bean class="org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler" />
    </constructor-arg>
    <property name="filterProcessesUrl" value="/logout/cas" />
</bean>

<bean id="casFilter" class="org.springframework.security.cas.web.CasAuthenticationFilter">
    <property name="authenticationManager" ref="authenticationManager" />
</bean>

<bean id="casEntryPoint" class="org.springframework.security.cas.web.CasAuthenticationEntryPoint">
    <property name="loginUrl" value="https://<hostname>/cas/login" />
    <property name="serviceProperties" ref="serviceProperties" />
</bean>

<sec:authentication-manager alias="authenticationManager">
    <sec:authentication-provider ref="casAuthenticationProvider" />
</sec:authentication-manager>

<bean id="casAuthenticationProvider" class="org.springframework.security.cas.authentication.CasAuthenticationProvider">
    <property name="authenticationUserDetailsService">
        <bean class="org.springframework.security.core.userdetails.UserDetailsByNameServiceWrapper">
            <constructor-arg ref="userService" />
        </bean>
    </property>
    <property name="serviceProperties" ref="serviceProperties" />
    <property name="ticketValidator">
        <bean class="org.jasig.cas.client.validation.Cas20ServiceTicketValidator">
            <constructor-arg index="0" value="https://<hostname>/cas" />
        </bean>
    </property>
    <property name="key" value="an_id_for_this_auth_provider_only" />
</bean>

<bean id="userService" class="org.hpi.iris.services.CustomUserDetailsService" />

<bean id="logoutFilter" class="org.springframework.security.web.authentication.logout.LogoutFilter">
    <constructor-arg value="/" />
    <constructor-arg>
        <list>
            <bean class="org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler" />
        </list>
    </constructor-arg>
</bean>

<bean id="servletContext" class="org.springframework.web.context.support.ServletContextFactoryBean" />

<bean id="etf" class="org.springframework.security.web.access.ExceptionTranslationFilter">
    <property name="authenticationEntryPoint" ref="casEntryPoint" />
</bean>

<bean id="wrappingFilter" class="org.jasig.cas.client.util.HttpServletRequestWrapperFilter" />

logout.jsp
Logout of in all applications

cas.log
2016-09-19 15:47:09,995 DEBUG [org.jasig.cas.logout.SamlCompliantLogoutMessageCreator] - Generated logout message: [<samlp:LogoutRequest xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol" ID="LR-1-qFurZ54zaXVbviIalCkZ93lDbYuBAT6m5qE" Version="2.0" IssueInstant="2016-09-19T15:47:09Z"><saml:NameID xmlns:saml="urn:oasis:names:tc:SAML:2.0:assertion">@NOT_USED@</saml:NameID><samlp:SessionIndex>ST-2-Ag6SgNIyvMUGT9mKNkEo-<hostname></samlp:SessionIndex></samlp:LogoutRequest>]
2016-09-19 15:47:09,995 DEBUG [org.jasig.cas.logout.LogoutManagerImpl] - Sending logout request for: [https://<hostname>:8444/WebApp3/j_spring_cas_security_check]
2016-09-19 15:47:10,000 DEBUG [org.jasig.cas.logout.LogoutManagerImpl] - Prepared logout message to send is [org.jasig.cas.logout.LogoutManagerImpl$LogoutHttpMessage@1771cadc[url=https://<hostname>:8444/WebApp3/j_spring_cas_security_check,message=<samlp:LogoutRequest xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol" ID="LR-1-qFurZ54zaXVbviIalCkZ93lDbYuBAT6m5qE" Version="2.0" IssueInstant="2016-09-19T15:47:09Z"><saml:NameID xmlns:saml="urn:oasis:names:tc:SAML:2.0:assertion">@NOT_USED@</saml:NameID><samlp:SessionIndex>ST-2-Ag6SgNIyvMUGT9mKNkEo-<hostname></samlp:SessionIndex></samlp:LogoutRequest>,asynchronous=true,contentType=application/x-www-form-urlencoded]]
2016-09-19 15:47:10,068 DEBUG [org.jasig.cas.logout.LogoutManagerImpl] - Captured logout request [org.jasig.cas.logout.DefaultLogoutRequest@655231e3[ticketId=ST-2-Ag6SgNIyvMUGT9mKNkEo-<hostname>,service=https://<hostname>:8444/WebApp3/j_spring_cas_security_check,status=SUCCESS]]
2016-09-19 15:47:10,069 DEBUG [org.jasig.cas.ticket.registry.DefaultTicketRegistry] - Attempting to retrieve ticket [TGT-**********************************************lfaFE4hhow-<hostname>]
2016-09-19 15:47:10,071 DEBUG [org.jasig.cas.ticket.registry.DefaultTicketRegistry] - Ticket [TGT-**********************************************lfaFE4hhow-<hostname>] found in registry.
2016-09-19 15:47:10,072 DEBUG [org.jasig.cas.ticket.registry.DefaultTicketRegistry] - Removing children of ticket [TGT-**********************************************lfaFE4hhow-<hostname>] from the registry.
2016-09-19 15:47:10,084 DEBUG [org.jasig.cas.ticket.registry.DefaultTicketRegistry] - Removing ticket [TGT-**********************************************lfaFE4hhow-<hostname>] from the registry.
2016-09-19 15:47:10,099 DEBUG [org.jasig.cas.CentralAuthenticationServiceImpl] - Publishing org.jasig.cas.support.events.CasTicketGrantingTicketDestroyedEvent@b348523[ticketGrantingTicket=TGT-**********************************************lfaFE4hhow-<hostname>]
2016-09-19 15:47:10,100 DEBUG [org.jasig.cas.audit.spi.AssertionAsReturnValuePrincipalResolver] - Trying to see if target's return value is instance of [Assertion]...
2016-09-19 15:47:10,100 DEBUG [org.jasig.cas.audit.spi.AssertionAsReturnValuePrincipalResolver] - Resolving principal from the delegate principal resolver: [org.jasig.cas.audit.spi.TicketOrCredentialPrincipalResolver@3d5cf9c4]...
2016-09-19 15:47:10,100 DEBUG [org.jasig.cas.audit.spi.TicketOrCredentialPrincipalResolver] - Resolving argument [String] for audit
2016-09-19 15:47:10,100 DEBUG [org.jasig.cas.ticket.registry.DefaultTicketRegistry] - Attempting to retrieve ticket [TGT-**********************************************lfaFE4hhow-<hostname>]
2016-09-19 15:47:10,101 DEBUG [org.jasig.cas.CentralAuthenticationServiceImpl] - Ticket [TGT-**********************************************lfaFE4hhow-<hostname>] by type [Ticket] cannot be found in the ticket registry.
2016-09-19 15:47:10,109 DEBUG [org.jasig.cas.audit.spi.TicketOrCredentialPrincipalResolver] - Could not locate ticket [TGT-**********************************************lfaFE4hhow-<hostname>] in the registry
2016-09-19 15:47:10,110 DEBUG [org.jasig.cas.audit.spi.AssertionAsReturnValuePrincipalResolver] - Meaningful principal id could not be resolved by [org.jasig.cas.audit.spi.AssertionAsReturnValuePrincipalResolver@4dafaeaa]. Returning [audit:unknown]...
2016-09-19 15:47:10,110 DEBUG [org.jasig.cas.web.support.TGCCookieRetrievingCookieGenerator] - Removed cookie with name [TGC]
2016-09-19 15:47:10,110 DEBUG [org.jasig.cas.web.WarningCookieRetrievingCookieGenerator] - Removed cookie with name [CASPRIVACY]
2016-09-19 15:47:10,118 DEBUG [org.jasig.cas.services.web.RegisteredServiceThemeBasedViewResolver] - View resolved: /WEB-INF/view/jsp/default/ui/casLogoutView.jsp
2016-09-19 15:47:10,179 DEBUG [org.jasig.cas.authentication.FileTrustStoreSslSocketFactory] - Connecting socket to <hostname>/<hostip>:8444 with timeout 5000
2016-09-19 15:47:10,181 DEBUG [org.jasig.cas.authentication.FileTrustStoreSslSocketFactory] - Enabled protocols: [TLSv1, TLSv1.1, TLSv1.2]
2016-09-19 15:47:10,181 DEBUG [org.jasig.cas.authentication.FileTrustStoreSslSocketFactory] - Enabled cipher suites:[TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256, TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256, TLS_RSA_WITH_AES_128_CBC_SHA256, TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256, TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256, TLS_DHE_RSA_WITH_AES_128_CBC_SHA256, TLS_DHE_DSS_WITH_AES_128_CBC_SHA256, TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA, TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA, TLS_RSA_WITH_AES_128_CBC_SHA, TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA, TLS_ECDH_RSA_WITH_AES_128_CBC_SHA, TLS_DHE_RSA_WITH_AES_128_CBC_SHA, TLS_DHE_DSS_WITH_AES_128_CBC_SHA, TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, TLS_RSA_WITH_AES_128_GCM_SHA256, TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256, TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256, TLS_DHE_RSA_WITH_AES_128_GCM_SHA256, TLS_DHE_DSS_WITH_AES_128_GCM_SHA256, TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA, TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA, SSL_RSA_WITH_3DES_EDE_CBC_SHA, TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA, TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA, SSL_DHE_RSA_WITH_3DES_EDE_CBC_SHA, SSL_DHE_DSS_WITH_3DES_EDE_CBC_SHA, TLS_EMPTY_RENEGOTIATION_INFO_SCSV]
2016-09-19 15:47:10,181 DEBUG [org.jasig.cas.authentication.FileTrustStoreSslSocketFactory] - Starting handshake
2016-09-19 15:47:10,205 DEBUG [org.jasig.cas.authentication.FileTrustStoreSslSocketFactory] - Secure session established
2016-09-19 15:47:10,206 DEBUG [org.jasig.cas.authentication.FileTrustStoreSslSocketFactory] -  negotiated protocol: TLSv1.2
2016-09-19 15:47:10,206 DEBUG [org.jasig.cas.authentication.FileTrustStoreSslSocketFactory] -  negotiated cipher suite: TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256
2016-09-19 15:47:10,206 DEBUG [org.jasig.cas.authentication.FileTrustStoreSslSocketFactory] -  peer principal: CN=<hostname>, OU=HPI, O=HP, L=Bloomington, ST=MN, C=US
2016-09-19 15:47:10,206 DEBUG [org.jasig.cas.authentication.FileTrustStoreSslSocketFactory] -  issuer principal: CN=<hostname>, OU=HPI, O=HP, L=Bloomington, ST=MN, C=US
2016-09-19 15:47:31,024 DEBUG [org.jasig.cas.util.CasSpringBeanJobFactory] - Created job org.jasig.cas.services.DefaultServicesManagerImpl$ServiceRegistryReloaderJob@4340fcf7 for bundle org.quartz.spi.TriggerFiredBundle@8f5988b

A: Apparently I figured out an answer for the question where I logout out of one CAS client, the other CAS client doesn't get logged out. For this to happen, CAS server needs to understand all the registered services.
I thought that CAS service management tool was responsible for doing this. However, that did not work for me. It looks like CAS management service doesn't do it. In spite of installing a service management tool and linking it to my CAS server did not work.
I had to go a step further and add few configuration files related to RegexRegisteredService. Thought this configuration is present in service management tool, CAS server doesn't seem to recognize that, like I mentioned before. Hence, I had to copy those files from service management tool to CAS server. In CAS server, i placed it in the following location, ../WEB-INF/classes/services. The file name is usually like AppName-UniqueID.json
The json file would look something like this,
{
"@class" : "org.jasig.cas.services.RegexRegisteredService",
"serviceId" : "https://<hostname>/AppName/j_spring_cas_security_check",
"name" : "App Name",
"id" : 7042148554761,
"logoutType" : "BACK_CHANNEL",
"logoutUrl" : "https://<hostname>/AppName/<Logout URL>"
}

Remember, you need to have separate file for each cas client application.
Once I did this step, I was able to see the response from CAS server, when i logout from 1 CAS client, in other CAS client console. Now, the rest of the work needs to be done in the CAS client side to recognize this logout action from CAS and logout the local session, which is what I am working on now.
I am new to CAS. In my experience, I found the CAS documentation little vague. It probably needs little more clarity.


text:
Q: Extract string column in multiple columns I have the next df:
Match                       Count
Asren_Blue_Coached           879
Asren_Blue_NotCoached        721
Asren_RED_Coached            6567
Asren_RED_NotCoached         764
Asren_White_Coached          762
Asren_White_NotCoached       431
Asren_Yellow_Coached         375
Asren_Yellow_NotCoached      412
Hrew_Blue_Coached            689
Hrew_Blue_NotCoached         634
...

I want to add three new columns,
One column for each word before the underscore in column 'Match'
So, the expected output looks like this:
Match                       NewCol1   NewCol2    NewCol3      Count
Asren_Blue_Coached           Asren      Blue     Coached       879
Asren_Blue_NotCoached        Asren      Blue     NotCoached    721
Asren_RED_Coached            Asren      RED      Coached       6567
Asren_RED_NotCoached         Asren      RED      NotCoached    764
Asren_White_Coached          Asren      White    Coached       762
Asren_White_NotCoached       Asren      White    NotCoached    431
Asren_Yellow_Coached         Asren      Yellow   Coached       375
Asren_Yellow_NotCoached      Asren      Yellow   NotCoached    412
Hrew_Blue_Coached            Hrew       Blue     Coached       689
Hrew_Blue_NotCoached         Hrew       Blue     NotCoached    634
...

Do you know how can I do it?
I'm working with pandas in Jupyter

A: You can use str.split, and assign the return to 3 columns named are you wish, and specify the delimiter to be "_"
See below:
df[['NewCol1', 'NewCol2','NewCol3']] = df['Match'].str.split('_', expand=True)

which prints your desired output:
print(df)
                     Match  Count NewCol1 NewCol2     NewCol3
0       Asren_Blue_Coached    879   Asren    Blue     Coached
1    Asren_Blue_NotCoached    721   Asren    Blue  NotCoached
2        Asren_RED_Coached   6567   Asren     RED     Coached
3     Asren_RED_NotCoached    764   Asren     RED  NotCoached
4      Asren_White_Coached    762   Asren   White     Coached
5   Asren_White_NotCoached    431   Asren   White  NotCoached
6     Asren_Yellow_Coached    375   Asren  Yellow     Coached
7  Asren_Yellow_NotCoached    412   Asren  Yellow  NotCoached
8        Hrew_Blue_Coached    689    Hrew    Blue     Coached
9     Hrew_Blue_NotCoached    634    Hrew    Blue  NotCoached

A: You can use the Series.str.split() to split a column on a delimiter. Then just mark expand=True to get new columns instead of a list.
df["Match"].str.split("_", expand=True)


text:
Q: DDD : nested aggregates and many to many relationships I'm currently working on a Publishing Bounded Context. The main players in this context are Product and Listing.
Product : can be listed in multiple marketplaces. One Product Many Listing.
Listing : can have many products because some marketplace support variation listing. One Listing Many Product.
Based on the above I have a Many-To-Many relationship between Listing and Product.
I created an aggregate for both. The Product aggregate which contains listings and the Listing Aggregate which contains products.
Is it acceptable to have Listing defined in both aggregates or should I define Listing once to be used in both aggregates?
First Listing would be within the product aggregate because the product AR has a factory method that enforces rules when creating Listing(such as avoid duplicate listing in same marketplace and ensure we have stock qty for listing)
Second Listing would be an aggregate root which can contains info from many Product needed at the moment of publishing. This way I can create method on Listing to map it to a schema definition provided by different marketplaces (such as Ebay and Amazon). Also I want to be able to persist Listing independently from Listings within the same Product.
Do the two aggregates have too much overlap with duplicate definitions ? Is this to be expected within one  bounded context?
Also how can I keep the duplicate representation of Listing synchronize with each other?

A:
First Listing would be within the product aggregate because the product AR has a factory method that enforces rules when creating Listing(such as avoid duplicate listing in same marketplace and ensure we have stock qty for listing)

Should a product know its own stock, its own marketplaces, its own listings and create listings too? This is too much responsibility for an entity! I would suggest to let a ListingFactory check the stock and the marketplces with other services or repositories that hold this information.

Is it acceptable to have Listing defined in both aggregates or should I define Listing once to be used in both aggregates? Also how can I keep the duplicate representation of Listing synchronize with each other?

Avoid cyclic dependency between Product and Listing and a mess by maintaining a single list (have a look at this question for a similar tangle: How to design many-to-many relationships on deletion?). Seems to me you should have an aggregate of marketplaces, which contains your listings. You could setup a marketplace service or repository that gets all Listings if you need to access all listings based on a product (like in the ListingFactory I proposed).

Do the two aggregates have too much overlap with duplicate definitions ?

Your definition of product "can be listed in multiple marketplaces" is not a very satisfying definition, because after reading this definition the question still remains: What is it then that can be listed? At its core a product can be defined without knowledge of listings, but within this context it probably would still be better to explicitly name the relationship. Since a (product) listing can not be defined without a product, but a product can be defined without a listing. They need not be duplicates. I would expect your product to be completely listing-unaware, but related to listings within the context.

Is this to be expected within one bounded context?

All definitions build on each other, so within any context you can expect overlap, duplication, synonyms, extensions, near similarity, cross-referencing, different types of relationships, etc. It requires quite a bit of investigatory consciousness to separate the primary from the secondary, the predicates from the subjects and objects, the nucleus from the membrane. However, this is also what makes it so much fun :)
definition of word: "A single distinct meaningful element of speech or writing, used with others (or sometimes alone) to form a sentence.."
definition of sentence: "A set of words that is complete in itself, typically containing a subject and predicate, conveying a statement, question, exclamation.."


text:
Q: Element on every page when printing in WebKit For example, I'm trying to have a
 or  appear on all pages when printing in WebKit.
This works in IE/FF:

@media print {
  .logo {
    position: fixed;
    right: 0;
    top: 0;
  }
}

Seems like this is an outstanding bug in WebKit, are there any workarounds? Thank you.

A: This is how it should work for the watermark...
div.watermark{
    display:none;
}

and then for @media print
div.watermark{
    display:block;
    position:fixed;
    z-index:-1;
    width:100%;
    height:100%;
}
    div.content > *:first-child,x:-moz-any-link{margin-top:0;}/* ff only */
    div.watermark,x:-moz-any-link{z-index:auto;}/* ff only */
    div.watermark,x:-moz-any-link,x:default{z-index:-1;}/* ff3 only */

    @media all and (min-width: 0px){div.watermark{width:8.5in;}} /* opera only */

    div.watermark div{
        position:absolute;
        left:0;
        width:99%;
    }

I think this article explains what you want to do effectively http://www.andypemberton.com/css/print-watermarks-with-css/ (archived link)
Unfortunately this is still an issue with webkit.
Solution: You have to clone your image class with javascript after every say a standard page size in pixels and keep it hidden for screen and add...
page-break-before: always;
page-break-inside: avoid;
display:block

Look at this answer for details https://stackoverflow.com/a/19170212/1278540
And look at this demo http://fiddle.jshell.net/jaap/7ZGVv/2/show/
Not bad IMO.


text:
Q: Xcode 10.1: Pods not compiling when running UITest I am trying to implement UITests in an application I'm working on.
When I am in my UITests.swift file and I try to run the app from a test, Xcode gives the following error for some of the pods I'm using:
Command CompileSwift failed with a nonzero exit code

It gives this error for a bunch of pods that are compiling just fine when running the regular project:

My PodFile looks as follows:
# Uncomment the next line to define a global platform for your project
platform :ios, '9.0'

source 'https://github.com/cocoapods/specs.git'

project 'Project.xcodeproj'

use_frameworks!

# Define all thirdparty pods we need
def thirdparty
    pod 'Moya', '~> 11.0'
    pod 'Alamofire'
    pod 'SwiftyJSON'
    pod 'Differ'
    .. a bunch of other pods
end

# Pods for Project project
target 'Project' do
    thirdparty
end

# Pods for ProjectTests
target 'ProjectUITests' do
    thirdparty

    pod 'Nimble'
end

I'm having a hard time reasoning why this is happening, as my project normally compiles just fine. Other posts on S.O. regarding this problem report that the problem also occurs when building the project rather than just running for a test
Question How can I make sure that all pods I use in my project, also compile correctly when building from a UITest?

A:
How can I make sure that all pods I use in my project, also compile correctly when building from a UITest?

The only way to know whether something will build or not is to try to build it. So when you change your CocoaPods configuration, even if that's just to update to a newer version of one or more pods, you need to try building each target.
target 'ProjectUITests' do
    thirdparty
    pod 'Nimble'
end`

According to your Podfile, you've got the pod Nimble being used only in the ProjectUITests target. If that's the only target that fills to build, then it seems likely that that pod is the culprit.
Except for one case (at least as far as you've shown) your Podfile doesn't specify versions for the various pods that it specifies. If you leave out the version for a given pod, your project will use the latest available version. That means that anytime you update your pods you'll pull down the latest version, even if that new version contains breaking changes. It would be safer to specify the version that you know works, or at least to limit the version to minor version and patch updates, like:
pod 'Nimble', '~>7.0'

That will let CocoaPods automatically use the latest version up to but not including 8.0. If the pod developer properly follows the semantic versioning scheme, that should ensure that you don't inadvertently pull in any breaking changes.

A: The problem is that target :AppModuleTests do do not have an app host and you are using inherit! :search_paths. This means that this target would find the dependencies to load them from the host but in this case there is none.
target TestApp do
    pods
    target :AppModuleTests
end
This worked for me.


text:
Q: powershell escape from >> i'm just getting into PowerShell and i've encountered this problem:
if i place the escape character (') or single quotation mark (") at the end of a command PowerShell enters into a suspend/whatever mode where there are ">>" on the left on the screen, instead of "PS C:>", i know that PS just expects more information/commands/whatever from me and that is why it is providing me with new lines and what-not, but how do i escape/stop that? Even after pressing "Enter" a few times, PS just provides me with more >>s, i want to end my input and finish the command, and so far i was unable to find any information on that, mostly because i don't even know what's it called.

A: It's waiting for a closing quote or brace }, so you can either enter one of those and press enter twice more, or use Crtl+C to cancel the current command.
FYI:
' = literal quote (expects another single quote)
" = quotes to use when interpolating strings (expects another double quote)
` = escape character (continuation of the current line)
, = list separator (expects another list element)
{ = begin of script block (expects closing curly bracket)

As long as whatever you're doing is balanced, pressing enter twice will exit the block. You'd get another >> on the first press in case you wanted to start anything else, if not it will return you to the prompt.


text:
Q: build.gradle how to apply a closure from another file I have a closure of defined in a another build.gradle file called other.gradle. Here is the contents:
Closure callback =  {

    productFlavors {
        ...
        devel {
            ...
        }

        prod {
            ...
        }
    }
}

Now in my build.gradle file I want to call this closure like this:
apply from: 'other.gradle'
productFlavors(callback());

but I keep getting an error that callback() cant be found.  Both files are in the same directory.  My issue is how do i get the build.gradle file to see the callback closure in the 'other.gradle' file.

A: It should be done in the following way:
other.gradle
project.ext.callback = { c ->
    println(c)
}

build.gradle
apply from: 'other.gradle'

callback('a')

Or in same cases callback should be referred via project.instance, e.g. project.callback('a').


text:
Q: How to use toLowerCase() function before filter?
I want to lowercase product.productName before filter, but I couldn't do that. I tried some thing but didn't work. Is there any way that I can lowercase product.productName before filter?

A: .map() could be used as a step before filter()
products
  .map(product => product.productName.toLowerCase())
  .filter(...)

A: Simply convert to lowercase inside filter before comparing.
e.g.
product.productName.toLowerCase().includes .....
If it complains about being an object, convert to string first.
product.productName.toString().toLowerCase().includes ....


text:
Q: Questions getting closed too fast (within hours). Give it some time to live
Possible Duplicate:
Let questions stay open for a minimum amount of time before being closed?

This is has happened to me a few times, and it's getting annoying. I post a question, sometimes for discussion, and within hours it gets closed before I have the chance to read the answers or comments or make things clearer if some people think it's a duplicate. I want to go "No.. No. it's close to some other question but it's not a real duplicate.. let me clarify". It seems there are some people are just too click happy to downvote or close questions.
Some of us do not 'live' in SO  and we don't check in every 10 minutes the whole day. So give me a chance to answer questions or make things clearer before executing the victim.
Proposal: Force a question to stay open for some period of time before it gets closed.
(I had issues with the re-open option). The other issue is that once a question is closed, those people who left comments or answers are gone.

A: The question was closed quite quickly because this topic, maybe not word for word, has been discussed on meta over and over again.
If you have an issue with getting a down vote or your question being closed as a duplicate, not a real question etc etc then the only thing I can suggest is take time to ask your question.

*

*Check and check again that someone else hasn't already asked that question (or a similar question that answers your question)

*If you find a similar question but it doesn't answer your question then link to it.  This shows that you have actually looked and may prevent it from being closed as a duplicate.

*Make sure your question makes sense, gets to the point and is formatted properly. sounds silly but it it more likely to get an answer.

Lets put this in to perspective, you get a down vote and you lose 2 rep. Get one up vote on an answer and you get 10 rep.  Ask a good question and you'll 5 rep.
It's not going to be difficult to get the 2 rep back.  I really don't see why people get the hump about down votes and/or closed questions.  It seems people bitch and moan about it but you don't get rewarded at work if you do a bad job.
UPDATED:
@Tony - StackOverflow is designed to be run by the community so the community can decide whether a question is valid or not.  In the same vein, they can decide whether it should be re-opened.
You can still comment on closed questions so it's not as if you can't ask or comment as to why it was closed.
I can't see how placing a time limit on a question before it can be closed is going to change anything - it will still get closed.  As I said before, if you ask the "right" question then it won't get closed. Ask a duplicate question, it's going to get closed.
The idea is to keep the relevant questions open and get rid of the rest.  If I search for something I don't want to look through 10-20 (maybe more) duplicate questions - I just want the answer but more importantly I want the correct answer as decided by the community.
That's why StackOverFlow works so well - you get good questions with good answers and you get them quickly.

A: No.
Really.
Questions that should be closed should be closed as quickly as possible, lest people waste effort answering them.

The other issue is that once a question is closed, those people who left comments or answers are gone.

*

*You can @-address those people in the comments.

*You can edit to bring the question back to the front page (be aware that doing so repeatedly is considered abuse and will bring unwanted attention from the moderators).

*You can cast the first vote to re-open

*10k users can see your closed question in the 10k tools, and if you have cast a re-open vote they may see it in the list of pending re-opens. At least some of the 10k users do check those lists and look for questions that need attention.

How do you think questions go through multiple rounds of opening and closing and accumulate comment threads dozens of comment long?