text:
Q: RUN LARAVEL WEBSOCKET ON HEROKU is it still not possible to run laravel-websockets on Heroku?
Cause have searched everywhere and all i could see is Heroku did not support laravel web-socket and that is 2019..
i don't know if by now Heroku would have supported it...

redpajama_set_name: RedPajamaStackExchange


text:
Q: laravel api using passport to fetch data from product? Need help to fetch data from product table using sql query in laravel
via laravel passport api authentication.

A: handle access token using laravel passport api authentication.

A: Create a route in your api.php
Route::middleware(['auth:api', 'throttle:60'])->group(function () {
    Route::get('products', 'Api\ProductController@getProducts');
}

Write the getProducts function in your ProductController
public function getProducts(){
    return Product::all();
}

Send a get request into /api/products with Authorization header. Its value will be your access token. Do not forget to add 'Bearer ' before it. (there is space between your access token and Bearer word).
I recommend you to use Postman for this job.


text:
Q: display gallery of a facebook page in a html website I am a newbie at html, facebook graph api, jquery.
I have the following code to obtain all the albums in a facebook fan page ( not a general profile) to display it in a simple format, I do not see any errors in the developer console of chrome, but the photos are not being displayed. Any ideas on how I view all the pics from the facebook fan page ?
<!DOCTYPE html>

http://docs.jquery.com/Tutorials:Introducing_$(document).ready()
working demo


text:
Q: How to efficiently multiply for every sub-array alone first dimension of a 3d np.array, Python 3 I have a 3d np.array x, with x.shape == (r, n, m).
This means alone the dimension r, each element is a 2d-array n-by-m.
For each of those 2d-array, I want to multiply it by an vector.
This is an example.
import bumpy as np
x = np.array([[[1, 2, 3, 4],
               [4, 5, 6, 7],
               [7, 8, 9, 10]],
              [[4, 5, 6, 7],
               [7, 8, 9, 10],
               [10, 11, 12, 13]],
              [[7, 8, 9, 10],
               [10, 11, 12, 13],
               [13, 14, 15, 16]]])

So x.shape is (r=3, n=3, m=4). Alone the first dimension there are three 2d-arrays
r1 = [[1, 2, 3, 4],
      [4, 5, 6, 7],
      [7, 8, 9, 10]]

r2 = [[4, 5, 6, 7],
      [7, 8, 9, 10],
      [10, 11, 12, 13]]

r3 = [[7, 8, 9, 10],
      [10, 11, 12, 13],
      [13, 14, 15, 16]]]

For each 2d-array, I want to do the same operation: the first row is multiplied by k**(n-1), the second row is multiplied by k**(n-2), and so on. The last row is multiplied by k**(n-n).
Take r1 for example:
k = 0.9
n = 3
r1_operated = np.empty_like(r1)
r1_operated[0] = r1[0] * k**(n-1)  # n = 3, so (n-1) = 2
r1_operated[1] = r1[1] * k**(n-2)  # n = 3, so (n-2) = 1
r1_operated[1] = r1[2] * k**(n-n)  # n = 3, so (n-n) = 0

What I have written above is ugly, and can be very chunky if r and n are very large.
Do you know any elegant and efficient way to code this algorithm?
I am using Python3. Thanks!

A: Make use of numpy.broadcasting:
x * (k ** np.arange(x.shape[1]-1, -1, -1))[:,None]

x * (k ** np.arange(x.shape[1]-1, -1, -1))[:,None]

#array([[[  0.81,   1.62,   2.43,   3.24],
#        [  3.6 ,   4.5 ,   5.4 ,   6.3 ],
#        [  7.  ,   8.  ,   9.  ,  10.  ]],

#       [[  3.24,   4.05,   4.86,   5.67],
#        [  6.3 ,   7.2 ,   8.1 ,   9.  ],
#        [ 10.  ,  11.  ,  12.  ,  13.  ]],

#       [[  5.67,   6.48,   7.29,   8.1 ],
#        [  9.  ,   9.9 ,  10.8 ,  11.7 ],
#        [ 13.  ,  14.  ,  15.  ,  16.  ]]])

For comparison:
def by_element(r):
    k = 0.9
    n = 3
    r1_operated = np.empty_like(r1, dtype=np.float)
    r1_operated[0] = r[0] * k**(n-1)  # n = 3, so (n-1) = 2
    r1_operated[1] = r[1] * k**(n-2)  # n = 3, so (n-2) = 1
    r1_operated[2] = r[2] * k**(n-n)
    return r1_operated

by_element(x[0])
#array([[  0.81,   1.62,   2.43,   3.24],
#       [  3.6 ,   4.5 ,   5.4 ,   6.3 ],
#       [  7.  ,   8.  ,   9.  ,  10.  ]])

by_element(x[1])
#array([[  3.24,   4.05,   4.86,   5.67],
#       [  6.3 ,   7.2 ,   8.1 ,   9.  ],
#       [ 10.  ,  11.  ,  12.  ,  13.  ]])

by_element(x[2])
#array([[  5.67,   6.48,   7.29,   8.1 ],
#       [  9.  ,   9.9 ,  10.8 ,  11.7 ],
#       [ 13.  ,  14.  ,  15.  ,  16.  ]])


text:
Q: Java infering wrong type of a typed HashSet
Possible Duplicate:
ClassCastException when calling TreeSet<Long>.contains( Long.valueOf( someLongValue ) )

Please see the screenshot for the problem:

It seems an entry in the Typed Set cylinderIds is suddenly of type String - but how did that happen?
The bean is used from within a JSF page, but I always thought that the type system in Java should prevent this ... Any idea what is going wrong here?
Using 1.7.0_06 64 Bit on Windows 7, the application is run within a JBoss 7.1.0 on the same Java version.

A: This is not exactly Java's fault. Generic type information is just lost during runtime. Java/JSF/EL does not run during compiletime, but during runtime. All it sees during runtime is a Set, not a Set<Long>.
When JSF sets submitted input values as bean properties, it retrieves them in first place as String as that's the default return type of request.getParameter(), which JSF is using under the covers to obtain request parameters. As long as no converter is specified, JSF will set those submitted String values unconverted in the Set via reflection. This is basically what is happening "under the covers":
package com.stackoverflow.q14521882;

import java.lang.reflect.Field;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;

public class Test {

    private Set<Long> set = new HashSet<Long>();

    public static void main(String[] args) throws Exception {
        Test test = new Test();
        Field field = test.getClass().getDeclaredField("set");
        Object object = field.get(test);
        if (object instanceof Collection) {
            ((Collection) object).add("string");
        }
        System.out.println(test.set.iterator().next().getClass()); // CCE!
    }

}

It would work when you was using Long[] instead of Set<Long>, but given that it's a Set in first place, you'd like to hold unique values only and the Long[] is therefore likely not an option. In order to solve it, you need to explicitly specify a Converter in the input component. You can use JSF builtin LongConverter for this, which has a converter ID of javax.faces.Long:
<h:selectManyListbox ... converter="javax.faces.Long">

A: The first problem is that you ask for a new Iterator each time you step into the while. The second problem is that Iterator is generic so you better do something like this:
Iterator<Long> cylinderIter = cylinderIds.iterator();

while(cylinderIter.hasNext()) {
    cylinderIter.next() // ...
    // do something
}

The third problem is that I can't see where you happen to populate that Set. I can help you more if you show us the code.

A: Without to see your code I could answering that something is changing the type of your set:

Generics are implemented by type erasure: generic type information is
  present only at compile time, after which it is erased by the
  compiler. The main advantage of this approach is that it provides
  total interoperability between generic code and legacy code that uses
  non-parameterized types (which are technically known as raw types).
  The main disadvantages are that parameter type information is not available at run time, and that automatically generated casts may fail
  when interoperating with ill-behaved legacy code. There is, however,
  a way to achieve guaranteed run-time type safety for generic
  collections even when interoperating with ill-behaved legacy code.

The generics article of oracle documentation explain you better.
Try this code for see when the problem is happening:
Set<Long> s = Collections.checkedSet(new HashSet<Long>(), Long.class);


text:
Q: JavaScript background images Guessing this will be a real easy fix for someone with the know-how. I am still learning JavaScript and I'm always trying to learn more.
I currently have the following code:
<script type="text/javascript">
$(window).load(function() {
$("#background").fullBg();
});
</script>

This works fine. at the moment #background is:
<img src="images/background.jpg" alt="" id="background" />

However I want to be able to put the background in as a div background and not just an image.
How do I change the script above so that the function applies to the background-image of a div which will be set in CSS instead of pointing to the img tag as it currently does?
I have tried to search the internet for a solution; however I am not good enough at JS yet to word my search correctly to find what I am looking for.
Thanks in advance and sorry if my description is poor.

A: If I understood correctly, you're trying to assign a css property to the DIV.
Then you should use .css('propertyName', 'value').
You can find the documentation at jQuery .css()

A: .css() is what you're looking for (this example uses jQuery)
<script type="text/javascript">
$(window).load(function() {
    $("#background").css({
        "background-image" : "url(images/background.jpg);",
    });
});
</script>

A: The plugin you are using (fullBg) was designed to work with img elements, not background images. Why do you even need a div? If you style the img with CSS as the plugin docs suggests, the outcome will be the same.


text:
Q: ng2-charts Doughnut Chart How to make labels visible every time along with the corresponding count than just showing in tooltip Is there any option available in ng2-chart(http://www.chartjs.org/docs/latest/) - Doughnut chart, to make the labels visible every time in the graph than just showing them in the tooltip?
Component:
public mobileChartOptions: any = {
        responsive: true,
        legend: {
            display: true,
            position: 'bottom',
            labels: {
                padding: 10
            }
        }
    };

public mobileOptions = Object.assign({
                                elements: {
                                    arc: {
                                        borderWidth: 0
                                    }
                                }
                            }, this.mobileChartOptions);
public mobileUsersData: {
                        colors: [{
                                    backgroundColor: ["#3FB7D0", "#6C71CC", "#ffeb3b", "#4caf50", "#2196f"]
                                }],
                        options: this.mobileOptions,
                        chartType: 'doughnut',
                        labels: [],
                        data: [],
                        loaded: false,
                        dataAvailable: false
                    };

Html:
<canvas height=" " baseChart class="chart"
                        [data]="mobileUsersData.data"
                        [labels]="mobileUsersData.labels"
                        [options]="mobileOptions"
                        [colors]="mobileUsersData.colors"
                        [chartType]="mobileUsersData.chartType"
                        (chartHover)="chartHovered($event)">
                </canvas>


text:
Q: Custom user page for rails using devise - Using Rails 4 and Ruby - 2.2 I am currently using devise for authentication which generates user.rb and controller for user, Welcome page(root page after authentication) which is main page of application where I need to show the total number of user created account in application, number of subject opted by current user and other details of current user. I am unable to route to user page when I am using the same user.rb and user_controller.rb.
routes.rb
  root "welcome_pages#home"
  devise_for :users
  resources :subjects
  resources :books

application.html.erb
    <%= link_to "Home",  root_path %>

<%= link_to "Books",   books_path %>

<%= link_to "Subjects", subjects_path %>

<%= link_to "Users", users_path %>

What am I missing ? I am getting the following errors
No route matches [GET] "/users_path"

Let me know if I need to provide more informations.
Thanks in advance.

A: You gotta add user resource separately, something like:
devise_for :users
resources :users, only: [:index, :show] do
  .....
end

users controller
def index
  @users = User.all
end

*

*preferred version since _user.html.erb will be reusable

views/users/index.html.erb
<%= render @users %> #this iterates thru all users and invokes _user partial

views/users/_user.html.erb
<%= user.name %> #in this case you don't need @ since you used this rails shortcut @user.each do |user|.

*version

views views/users/index.html.erb
<% @users.each |user| do %>
  <%= user.name %>
  ....
<% end %>


text:
Q: How does irradiance behave over time? I am trying to clarify data on weather from the Royal Netherlands Meteorological Institute (KNMI); I have incorporated the Solar Position Algorithm (SPA), such that I can calculate sunset and sunrise (by means of the zenith angle, i.e. setting the zenith to 90 degrees). What I am trying to do is get a model of the behaviour of the irradiance (joules per square centimeters J/cm2). That is, by means of the irradiance measurements per hour provided by the KNMI. The thing that struck me is that the overall irradiance is quite variable.
In the underlying figure the sinusoid is a model which should resemble the measurements on a clear sky day. The spiky curve reflects the actual measurements, and the somewhat horizontal line is cloudcover, i.e. 8 is totally cover and 0 is clear sky.

So, what strikes me is for example that the irradiance measurements of two days later (day 59) has a maximum irradiance of 46 J/cm2 with full cloud cover (measure 8).
In other words; full cloud cover on day 57 at 12:00 results in $\approx$ 65 J/cm2, whereas on day 59 with the same cloud cover and same timestamp results in $\approx$ 27 J/cm2.
It seems as if there is another relevant factor which has a significat impact on irradiance. What could it be?
METADATA (Source: KNMI):

*

*Cloud cover (in octants), at the time of observation (9=sky
invisible)

*Global radiation (in J/cm2) during the hourly division

A: The reason for this is that cloud cover doesn't tell you much about the optical properties of the clouds. There are lots of different types of clouds and they differ greatly in terms of droplet sizes, density and thickness. All of this affect their scattering and absorption properties. Cloud cover is just a measure of what fraction of the sky is covered by clouds and doesn't take into account what type of clouds it is.
Even if you have full cloud cover that doesn't transmit any light directly, some light will be transmitted through volume scattering in the clouds. The amount of light transmitted this way will depend mostly on the thickness of the cloud layer. Sometimes you even have total overcast, but the clouds are so thin that you still see shadows on the ground and the countours of the sun through the clouds. From what I understand this is still classified as full cloud cover, even though direct sun light is clearly transmitted.


text:
Q: Capturing Popups, Alerts, and Exceptions from Excel with VB 2010 This is my first time posting in stackoverflow.  I started learning VB 2010 yesterday (though I do know some Ruby) and have googled this problem a lot but haven't found much.
I've written a program that takes a CSV list of filepaths (all .XLS files) and attempts to open them.  These excel workbooks were flagged as unreadable by another program; my program tries to capture the warning, popup, or exception that caused the error.  It works for most exceptions (password protected, Unreadable Content, Dangerous File, etc.), but some popups that require you to click the 'OK' button to continue aren't caught.  Maybe they aren't categorized as Exceptions or something, I'd love to know. It would be great to at least get the text form of them.  Here is my script:
Private Sub runReportButton_Click(ByVal sender As System.Object, ByVal e As        System.EventArgs) Handles runReportButton.Click
    Dim Exl As New Excel.Application()
    Exl.Visible = False
    Exl.DisplayAlerts = False

    For Each row As DataGridViewRow In dgvReport.Rows
        If Not IsNothing(row.Cells(0).Value) Then
            If row.Cells(0).Value.ToString.Contains(".xls") Then

                Try
                    'Open the workbook and attempt to catch the error!'
                    'Use bogus passwords to cause Password Protected Error, Readonly disabled so the Password popup shows.  Update links disabled because it wasn't being caught anyways'
                    Dim wb As Excel.Workbook = Exl.Workbooks.Open(row.Cells(0).Value.ToString, [ReadOnly]:=False, [WriteResPassword]:="WWWWWWWWWWW", [Password]:="WWWXWXWWWXW", [UpdateLinks]:=False)
                    row.Cells(4).Value = "Could not catch an error :("
                    wb.Close(0)
                    dgvReport.Refresh()
                Catch ex As Exception
                    'Writes the Exception Message to the data grid view'
                    row.Cells(4).Value = ex.Message
                End Try
                ProgressBar1.Value += 1
            End If
        End If
        Exl.Quit()
    Next row
    dgvReport.Refresh()
End Sub

The reason I'm having a problem is that certain popups only occur when I open the file manually.  Even with Excel set to visible and display alerts on, programmatically the file opens and closes without any popups.  One particular warning is the following:

"One or more worksheets in this workbook have names that contain square brackets:[]. To avoid unexpected results when referencing these worksheets, remove any square brackets from their names."

It doesn't seem like a fatal error, but it causes the other program to flag it as unreadable because we cannot be certain of the integrity of the contents (i.e. the unexpected results).  So my need isn't to ignore these popups or improve the other program, it's to capture this pesky popup message.  If anyone can shed any light on the duality of this popup's behavior or provide a different approach to capturing alerts it would be much appreciated!


text:
Q: D3 transitions - pause and resume I am trying to understand 'pause' and 'resume' for D3 transitions from this guide. While I understand how 'pause' is working, I am little lost when it comes to 'resume'. I couldn't make sense of the author's explanation, specifically the 'linear' or first resume explanation. My question is what is e.attr("T",0); and .attr("T",1); doing exactly?
I am applying the resume functionality to a playhead for video or waveform example here: jsfiddle

A: The code e.attr("T",0) and .attr("T",1) sets attributes for the node that is selected. That is, a new attribute "T" is created and set. The purpose of this is purely to facilitate stopping and resuming -- 0 represents a transition before start and 1 at the end.
If this attribute is included in the transition, the value will gradually change from 0 to 1. As the author of the tutorial points out, this can be used to get the state of the transition at any point in time -- you simply need to query the value of "T". If you save the particular transition as well, you can use the value to pause and resume at any point.
Note that there is nothing special about "T". You can use any (unused) attribute name. The purpose is only to have some way of telling how far the transition has progressed.

A: I've been struggling with this exact problem too and I think there's a typo on the example that has been throwing me off. Where the author writes:
var e = d3.select("#time");
e.attr("T",0);

c.transition()
    .duration( time )
    .ease( "linear" )
    .attr("T",1);

It seems as though e will update its T attribute as c transitions, which doesn't make sense. Instead I think it should be as follows:
var e = d3.select("#time");
e.attr("T",0);

e.transition()
    .duration( time )
    .ease( "linear" )
    .attr("T",1);

Now we select the #time element, set the initial value of its T attribute to 0 then add a transition to the same element e (instead of c) that changes T to 1 over the course of the specified duration.


text:
Q: How do you avoid labels overlapping in a Pie chart? I would like to avoid this situation of overlapping text labels in a Pie chart that I'm drawing:

Is there a 'recognised' way to do it? ie a particular text placement algorithm? And if not, then how to do it efficiently?
EDIT: So that it looks similar to this type of label placement: Overlapping Labels in Pie-Chart

A: UPDATED:
I've got a better system to organise the labels which just lists the labels on the relevant side and then adds lines from each label to the appropriate segment.
You can see an example here:
https://www.rgraph.net/demos/pie-basic.html
And the code to create that chart is:

<canvas id="cvs" width="350" height="250">
    [No canvas support]
</canvas>


text:
Q: How to get all test cases from test suite in VSTS without run data I'm trying to get all the test cases from a test suite in VSTS, even test cases that have no run data, marked as "Active." I know how to get the case ID, but not the name/title. Right now it goes through the run data and results and gets all the information from the result, but it won't work if there is no run data.
I'm working in C# using RestSharp for RestRequests. This is one of my RestRequests: /_apis/test/runs?planId=" + planID.ToString() + "&includeRunDetails=true&api-version=5.0-preview.2 This works to get all the information I need for test cases with run data. I have been using Microsoft docs on VSTS API for help: https://learn.microsoft.com/en-us/rest/api/vsts/?view=vsts-rest-5.0
Getting the test cases from the suite would be ideal, but I'll accept anything that works.

A: You can combine Get all test cases in a suite api and Returns a list of work items api. First, get the test case ids from the api below:
GET https://{accountName}.visualstudio.com/{project}/_apis/test/Plans/{planId}/suites/{suiteId}/testcases?api-version=5.0-preview.3

Then, get more information of the test cases from the following api:
GET https://{accountName}.visualstudio.com/{project}/_apis/wit/workitems?ids={ids}&api-version=5.0-preview.3


text:
Q: Jade locals undefined with Express.js app.use(function(req, res, next){
    res.locals.xxx = 'aaaa';
    next();
});

app.set('views', path.join(__dirname, '../views'));
app.set('view engine', 'jade');

In Jade:
meta(name='csrf-token', content='#{xxx}')

content is undefined.
And there is a long list of app.use('/xxx/xxx', ...). Do I have to pass locals in these routers? Or where is it not working here?

A: Try without the quotes and parantheses:
meta(name='csrf-token', content=xxx)

This works for me


text:
Q: Palatino font size I'm using Palatino for my dissertation, but 10pt is too small and 11pt is too large (looks childish). I would like to select something in between. Any suggestions on how to do this?
Edit: following the other threads, there seem to be three answers:

*

*(pdflatex, 11pt memoir, fix-cm, renew \normalsize): this only changes \normalsize (so not \small, \huge, etc.)
\documentclass[11pt,a4paper,twoside,openright]{memoir}
\renewcommand*{\rmdefault}{ppl}
\usepackage{fix-cm}
\renewcommand{\normalsize}{\fontsize{10.5pt}{12.5pt}\selectfont}
\begin{document}
{\tiny This is tiny}\\
{\scriptsize This is script size}\\
{\footnotesize This is footnote size}\\
{\small This is small}\\
{\normalsize This is normal size}\\
{\large This is large}\\
{\Large This is larger}\\
{\LARGE This is very large}\\
{\huge This is huge}\\
{\Huge This is very huge}
\end{document}

*(pdflatex, 11pt memoir, fix-cm, relscale): this doesn't work at all (since you would need to use \relscale{0.96} whenever changing from \normalsize to \small or something)
\documentclass[11pt,a4paper,twoside,openright]{memoir}
\renewcommand*{\rmdefault}{ppl}
\usepackage{fix-cm,relsize}
\begin{document}
\relscale{0.96}
{\tiny This is tiny}\\
{\scriptsize This is script size}\\
{\footnotesize This is footnote size}\\
{\small This is small}\\
{\normalsize This is normal size}\\
{\large This is large}\\
{\Large This is larger}\\
{\LARGE This is very large}\\
{\huge This is huge}\\
{\Huge This is very huge}
\end{document}

*(lualatex, 11pt memoir): this changes all type sizes (\normalsize, \small, \huge, etc.)
\documentclass[11pt,a4paper,twoside,openright]{memoir}
\usepackage{fontspec}
\setmainfont[Scale=0.96]{Palatino Linotype}
\begin{document}
{\tiny This is tiny}\\
{\scriptsize This is script size}\\
{\footnotesize This is footnote size}\\
{\small This is small}\\
{\normalsize This is normal size}\\
{\large This is large}\\
{\Large This is larger}\\
{\LARGE This is very large}\\
{\huge This is huge}\\
{\Huge This is very huge}
\end{document}

For example in my case, \normalsize was 10.91pt and afterwards 10.46pt. Perfect! Note also that in the third option, the system's Palatino font is used, while in the first two, URW Palladio is used. To conclude I would say that lualatex (or perhaps also xelatex etc.) is the way to go. The \usepackage[scale=0.95]{tgpagella} option mentioned in the comments also works, but this is specific to the font package.
However, there is still an issue remaining: how to change the math type size? I'm using \usepackage{lmodern}.

A: use also TeX Gyre Pagella Math:
\documentclass[11pt,a4paper,twoside,openright]{memoir}
\usepackage{unicode-math}
\setmainfont[Scale=0.96]{TeXGyre Pagella}
\setmathfont[Scale=0.96]{TeXGyrePagellaMath-Regular}
\begin{document}
{\tiny This is tiny}\\
{\scriptsize This is script size}\\
{\footnotesize This is footnote size}\\
{\small This is small}\\
{\normalsize This is normal size}\\
{\large This is large}\\
{\Large This is larger}\\
{\LARGE This is very large}\\
{\huge This is huge}\\
{\Huge This is very huge}

\[ \int\limits_1^\infty \frac1{x^2}\mathrm{d}x=1 \]

\end{document}


text:
Q: What's the exactly azure server location when you choose West Europe I have choose the west Europe as my cloud server location, but the ip address shows the server is in United States, does somebody know about this?
someone told me there's already a question been answered,Why does Windows Azure Western Europe have U.S IP Address?
but my question is a little different, all other cloud service in my subscription is West Europe IP, except some are United States, and how can i ensure that the server is locate in West Europe?


text:
Q: how my makefile aotumatically change .o prerequisite to .c targets? here is my Make file.
look at target olmenu-proto1,  it depends on olmenu-proto1_yacc.o
But I haven't define any target called olmenu-proto1_yacc.o.
Interestingly, when I invoke make olmenu-proto1,it works!
Strangely enough!
I want to know why it would do this, thank you!

A: Please include the relevant bits of your makefile in your question, rather than asking people to follow a link to another site.  Especially one where it's impossible to view unless you enable a lot of javascript, which many people leave mostly disabled.
In any event, most likely the reason is because make can envision how to create targets by chaining together rules, even if you don't list the prerequisites explicitly.  For more information see Chains of Implicit Rules in the GNU make manual.


text:
Q: My h:inputText value is not validated when it is bound to a field of some instance of a parametrized class gathered from a HashMap? I am trying to do some "custom lightweight" JSF component binding. In my bean (controlling some JSF page) i'm declaring a HahsMap where keys ranging over my h:inputText ids (appearing in the page) map these ids to custom HInputText<T> objects (T in the example given below is Long). Then i am using HInputText<T> objects to hold a subset of corresponding h:inputText attributes : value supposed to be of type T, rendered, required, etc. In this direction fields from the HInputText<T> objects give values to the h:inputText attributes.
My problem is that when using such an h:inputText inside a h:form, JSF validation does not take place : i can type alphanumeric chars in the h:inputText (supposed to hold a Long value) and my form submits without showing any errors. Note that required and rendered attributes are managed correctly (since required is set to true, i have an error when i leave the h:inputText field empty) and that when i try to display back the value of the h:inputText in the page using some h:outputText the alphanumeric chars are displayed.
Is there some trick to make JSF validation work without having to explicitly define a custom Validator for each h:inputText?
HInputText.class:
public class HInputText<T>
{
    private String id;
    private boolean rendered;
    private boolean required;
    private T value;
    private Class<T> myClass;

    // getters and setters for all fields

    public HInputText(Class<T> myClass, String id)
    {
        this.myClass = myClass;
        this.id = id;
        this.rendered = true;
        this.required = true;
    }
}

Code snippet from my Managed Bean :
@ManagedBean(name="saisieController")
@SessionScoped
public class SaisieController
{
    ...
    private HashMap<String,HInputText<Long>> htagLongInputTexts;

    public HashMap<String, HInputText<Long>> getHtagLongInputTexts()
    {
        return htagLongInputTexts;
    }

    public void setHtagLongInputTexts(HashMap<String, HInputText<Long>> hLongInputTexts)
    {
        this.htagLongInputTexts = hLongInputTexts;
    }

    public void addHtagLongInputText(HInputText<Long> hLongInputText)
    {
        getHtagLongInputTexts().put(hLongInputText.getId(), hLongInputText);
    }

    public HInputText<Long> getHtagLongInputText(String hLongInputTextId)
    {
        return(getHtagLongInputTexts().get(hLongInputTextId));
    }

    @PostConstruct
    public void init()
    {
        setHtagLongInputTexts(new HashMap<String, HInputText<Long>>());
        addHtagLongInputText(new HInputText<Long>(Long.class, "HIT_LongTestHIT"));
    }

    public String doNothing()
    {
        return null;
    }
}

and finally a snippet from my jsf page:
<h:form>
    <h:inputText
        id = "HIT_LongTestHIT"
        value = "#{saisieController.htagLongInputTexts['HIT_LongTestHIT'].value}"
        rendered = "#{saisieController.htagLongInputTexts['HIT_LongTestHIT'].rendered}"
        required = "#{saisieController.htagLongInputTexts['HIT_LongTestHIT'].required}"
    />
    <h:message for = "HIT_LongTestHIT" styleClass = "error-text" />
    <h:commandButton value = "submit" action = "#{saisieController.doNothing()}" />
    <h:outputText value = "#{saisieController.htagLongInputTexts['HIT_LongTestHIT'].value}" />
</h:form>

A:
Is there some trick to make JSF validation work without having to explicitly define a custom Validator for each h:inputText?

No, that's not possible. Due to type erasure the generic type information is not available during runtime. JSF/EL has no idea that T is actually a Long, let alone that there's actually some T. You really need to explicitly specify a converter which is in this particular example the LongConverter with a converter ID of javax.faces.Long.
<h:inputText ... converter="javax.faces.Long">

or, dynamically so you want
<h:inputText ...>
    <f:converter converterId="#{saisieController.htagLongInputTexts['HIT_LongTestHIT'].converterId}" />
</h:inputText>

You can find an overview of all available standard JSF converters in the javax.faces.convert package summary. You can find out their converter IDs by navigating to the Constant field values link on the public constant CONVERTER_ID.


text:
Q: Configuring OpenLDAP init script on CentOS 6.4 If I just run slapd with no arguments (as root) it starts and works fine. When I try to start it using /etc/init.d/slapd start however, it dies immediately.
I see from looking at the init script that there's a configuration file at /etc/sysconfig/ldap, but I haven't been able to find a working combination of settings. Does anybody know what I need to do?

I went back to the default init script and tried running with debugging, but I didn't see anything helpful. Main details were:
daemon --pidfile=/var/run/slapd.pid --check=slapd /usr/sbin/slapd -h '" ldap:///"' -u ldap
/bin/bash -c 'ulimit -S -c 0 >/dev/null 2>&1 ; /usr/sbin/slapd -h " ldap:///" -u ldap'`.

A: After trying to start manually using /usr/sbin/slapd -u ldap and discovering it didn't work, I eventually thought to try turning off selinux (setenforce 0; I have another question about making it work with selinux enabled) which allowed it to run as the ldap user (and therefore allowed the standard init script to work).
The man page says that the default URL when -h is not given is ldap:/// (TCP on all interfaces on default port). So to get the equivalent behavior to running slapd with no arguments you need to set
SLAPD_LDAP=yes
SLAPD_LDAPI=no
SLAPD_LDAPS=no

in /etc/sysconfig/ldap.


text:
Q: How I can use svn from eclipse I have just installed Eclipse 3.7 Indigo. What should I use for svn?

A: Try installing Subclipse.

A: You can either use Subversive or Subclipse. Just install it through Help -> Eclipse Marketplace.

A: Subclipse is the svn plugin for eclipse that you need to install.
Download & install instruction can be found here.

A: http://aaronbonner.tumblr.com/post/6793073974/two-essential-update-sites-for-eclipse-indigo
try with tigris.


text:
Q: Why does the application stops in address sanitizer build? I have a code similar to below code
A.mm
- (void)Foo {
    const unsigned long long dataLen = 0; // In a particular case dataLen is 0
    NSMutableData* data = [NSMutableData dataWithLength:dataLen];
    b->TestGetData(data.mutableBytes, data.length);
}

B.cpp
void B::TestGetData(void* data,
                    unsigned long long dataLength) {
    memset(data, 0, (size_t)dataLength);

    std::string reqBody = ""; // in a particular case reqBody is empty
    memcpy(data, reqBody.c_str(), dataLength);
    printf("[data = %s]", (char*)data);
}

When I build the application using AddressSanitizer the program stops with
SUMMARY: AddressSanitizer: heap-buffer-overflow (libclang_rt.asan_osx_dynamic.dylib:x86_64h+0x267dd) in printf_common(void*, char const*, __va_list_tag*)

{
  "access_size" : 2,
  "access_type" : 0,
  "address" : 105690556485681,
  "description" : "heap-buffer-overflow",
  "instrumentation_class" : "AddressSanitizer",
  "pc" : 4539582430,
  "stop_type" : "fatal_error"
}

but there is no issue when the application is build without AddressSanitizer
Also in case of AddressSanitizer I noticed that the bytes at memory address of data were BE 00 00 00 ... but without AddressSanitizer the bytes were 00 00 00 ...
I am not able to understand:

*

*where does byte \XBE come from?

*why there is an issue in AddressSanitizer build?

*why does it report heap-buffer-overflow?


text:
Q: datepicker change date format on form submit I am using jQuery datepicker, and I am displaying my date in

dd-mm-yyyy

format but I need to send date in

yyyy-mm-dd

format to store in database.
$(document).ready(function(){
    $('.datepicker').datepicker({
        format : 'dd-mm-yyyy',
        maxDate : new Date(),
        selectMonths : true,
        selectYears: d,
        yearRange: 100 ,
    });
});

the above code will show date format

dd-mm-yy

and when I submit the form using ajax, it sends using this same format. I need to change the submit format to

yyyy-mm-dd

Check this fiddle.

A: Please try this to get the value
 $("#mydate").datepicker("option", "dateFormat", "yyyy-mm-dd" ).val();


text:
Q: How to run Ag asynchronously with vimproc and quickrun - VIM? I'm using Ag, vimproc, quickrun
I'm able to run .php asynchronously with this settings in my .vimrc
nnoremap <leader>r :QuickRun<CR>
let g:quickrun_config = get(g:, 'quickrun_config', {})
let g:quickrun_config = {
\   "_" : {
\       'runner':                    'vimproc',
\       'runner/vimproc/updatetime': 60,
\       'outputter/quickfix':        ':quickrun-module-outputter/quickfix',
\       'outputter/buffer/split':    ':rightbelow 8sp',
\   },
\}

Does anyone know how can I run ag asynchronously?
Ag settings in .vimrc
if executable("ag")
  let g:ctrlp_user_command = 'ag %s -i --nocolor --nogroup --hidden
    \ --ignore .git
    \ --ignore .svn
    \ --ignore .hg
    \ --ignore .DS_Store
    \ --ignore "**/*.pyc"
    \ -g ""'
endif
nnoremap <leader>a :Ag!<Space>
nnoremap <leader>aa :Ag! <C-r>=expand('<cword>')<CR>
nnoremap <leader>aaa :Ag! <C-r>=expand('<cword>')<CR><CR>

A: A generic solution to use asynchronous command with Vim is using a plugin called vim-dispatch, you can launch command in the background with :Start!
Alternatively, this is also a fork of vim called neovim, which is trying to address that issue. At the time of this post, it is not necessarily mature enough, but this is something to consider as well for the future.


text:
Q: How do you translate from checkstyle.xml to eclipse code style format/profile and back again? I have eclipse code formatter and profile xml docs and I'd like to build a checkstyle.xml which I can use in my maven builds to run reports and generate the eclipse files.   maven-eclipse-plugin appears to be able to generate the eclipse files from the checkstyle.xml (I think), but I'm not sure how to go the other way and I'm not looking forward to doing it by hand.
If data flows via maven from checkstyle -> eclipse it should flow in the reverse direction.
Does anyone know how to generate a checkstyle.xml from the 2 eclipse files?

A: Not all data transformations are bidirectional, so it does not necessarily follow that because you can transform from Checkstyle to Eclipse that the inverse transformation can be applied.
In this case I think it is more a case of requirements and having a single canonical configuration source. The Maven Checkstyle configuration is required for all Maven builds. As a convenience it makes sense to have a tool that maps the configuration into the IDE so the validations can be applied during the Eclipse build (this is what the checkstyle-m2eclipse integration does).
Generally it's a good idea to have one canonical source for your configuration, and it makes most sense from a build portability perspective for that to be the Maven configuration. So while you could probably technically transform in the other direction you aren't gaining much by doing so. Out of interest, what benefit do you think this transformation would be to you?


text:
Q: Dompdf not working in Symfony and displays characters I already installed the dompdf in composer but I cannot render a pdf file and it shows some characters on the browser. Is there something i missed out on the code?

%PDF-1.3 1 0 obj << /Type /Catalog /Outlines 2 0 R /Pages 3 0 R >> endobj 2 0 obj << /Type /Outlines /Count 0 >> endobj 3 0 obj << /Type /Pages /Kids [6 0 R ] /Count 1 /Resources << /ProcSet 4 0 R /Font << /F1 8 0 R >> >> /MediaBox [0.000 0.000 595.280 841.890] >> endobj 4 0 obj [/PDF /Text ] endobj 5 0 obj << /Producer (��dompdf  + CPDF) /CreationDate (D:20191015175221+02'00') /ModDate (D:20191015175221+02'00') >> endobj 6 0 obj << /Type /Page /MediaBox [0.000 0.000 595.280 841.890] /Parent 3 0 R /Contents 7 0 R >> endobj 7 0 obj << /Filter /FlateDecode /Length 67 >> stream x��2�300P@&�ҹ�B�M���-L�L�,BR����B��5R�5cB�\C�'3 endstream endobj 8 0 obj << /Type /Font /Subtype /Type1 /Name /F1 /BaseFont /Times-Roman /Encoding /WinAnsiEncoding >> endobj xref 0 9 0000000000 65535 f 0000000009 00000 n 0000000074 00000 n 0000000120 00000 n 0000000274 00000 n 0000000303 00000 n 0000000462 00000 n 0000000565 00000 n 0000000703 00000 n trailer << /Size 9 /Root 1 0 R /Info 5 0 R /ID[<728657938b76cb1e658d7f5ccfa3c466><728657938b76cb1e658d7f5ccfa3c466>] >> startxref 812 %%EOF

use Dompdf\Dompdf; use Dompdf\Options;

/**
* @Route("/add")
*/

 public function pdf()
{
    $pdfOptions = new Options();
    $pdfOptions->set('defaultFont', 'Arial');

    $dompdf = new Dompdf($pdfOptions);
    $dompdf->loadHtml('Hello world');
    $dompdf->setPaper('A4', 'portrait');
    $dompdf->render();
    $dompdf->stream("mypdf.pdf", [
        "Attachment" => false
    ]);
}

A: I had the same problem. I fixed this by adding exit(0); after $dompdf->stream();

A: Same problem here !
Find my way around by adding ob_get_clean(); just before $dompdf->stream('name.pdf');
$html = 'Test';
$dompdf = new Dompdf();
$dompdf->loadHtml($html);
$dompdf->setPaper('A4');
$dompdf->render();
ob_get_clean();
$dompdf->stream('name.pdf');


text:
Q: EF DbContext and StructureMap scoping Ok, I give up...
What I want is to share the EF4's DbContext instance per request. I configured StructureMap like this:
For<MyContext>().Use(new MyContext("LocalhostConnString"));

But when I refresh my site, or even open it in another browser, I get the same exact instance of MyContext. Why is this shared across requests?
Am I missing something?

A: Yes... about 4 characters. Try:
For<MyContext>().Use(() => new MyContext("LocalhostConnString"));

If you give StructureMap an object instance, it will treat that instance as a singleton and return the same one every time. If instead you give it a lambda that creates an instance, it will run that lambda each time the type is requested.


text:
Q: Finding the determinant of a $5\times 5$ matrix Let
$$A = \left[\begin{array}{rrrrr}6 & 2 & 2 & 2 & 2 \\ 2 & 6 & 2 & 2 & 2 \\ 2 & 2 & 6 & 2 & 2 \\2 & 2 & 2 & 6 & 2 \\ 2 & 2 & 2 & 2 & 6\end{array}\right] \in {M}_{5}(\mathbb{R})$$
Which of following options is $\det(A)$ ?

*

*$4^4 \times 14$

*$4^3 \times 14$

*$4^2 \times 14$

*$4   \times 14$

I think we have
$$\det \left[\begin{array}{ll}6 & 2 \\ 2 & 6\end{array}\right] = 4 \times 8$$
$$\det \left[\begin{array}{lll}6 & 2 & 2 \\ 2 & 6 & 2 \\ 2 & 2 & 6\end{array}\right] = 4^{2} \times10$$
and for any $n$ we have $\det(A_n)= 4^{n-1} \times (6+2×(n-1))$ so "1" is true.

A: As, dimension of nullspace of $(A-4I)$ is $4$. So, Geometric multiplicity of eigenvalue $4$ is $4$, as matrix $A$ is symmetric, so, $A$ must be diagonalizable, and hence, Algebraic multiplicity and Geometric multiplicity of eigenvalue $4$ is same, so, Algebraic multiplicity of eigenvalue $4$ is $4$.
And, as each row sum is $14$, so, $14$ is another eigenvalue of algebraic multiplicity $1$.
Det($A$)=multiplication of eigenvalues= $4^4×14$

A: $$\begin{vmatrix}6 & 2 & 2 & 2 & 2 \\ 2 & 6 & 2 & 2 & 2 \\ 2 & 2 & 6 & 2 & 2 \\2 & 2 & 2 & 6 & 2 \\ 2 & 2 & 2 & 2 & 6\end{vmatrix}=\begin{vmatrix}4 & 0 & 0 & 0 & -4 \\ 0 & 4 & 0 & 0 & -4 \\ 0 & 0 & 4 & 0 & -4 \\0 & 0 & 0 & 4 & -4 \\ 2 & 2 & 2 & 2 &\ \ 6\end{vmatrix}=\begin{vmatrix}4 & 0 & 0 & 0 & -4 \\ 0 & 4 & 0 & 0 & -4 \\ 0 & 0 & 4 & 0 & -4 \\0 & 0 & 0 & 4 & -4 \\ 0 & 0 & 0 & 0 & 14\end{vmatrix}$$

A: According to the Matrix Determinant Lemma, $\det(A+uv^T)= \det(A)(1+v^T A^{-1}u)$, hence
$$\det(A) = \det(4I + 2\cdot\mathbf 1 \mathbf 1^T) = \det(4I)(1+2\cdot \mathbf 1^T(\tfrac{1}{4}I)\mathbf 1) = 4^n (1 +\tfrac{1}{2}n) $$
For $n=5$, that's $4^5\cdot \frac{7}{2} = 4^4 \cdot 14$

A: Your generalization, with an obvious but unstated definition of $A_n$, can be proved as follows. Define $E_n$ as the $n\times n$ matrix whose entry are all $1$s. You can show its only nonzero eigenvalue is $2n$, and the associated eigenspace is $1$-dimensional. By the rank-nullity theorem, the eigenvalue $0$ has multiplicity $n-1$. So $A_n=4I_n+2E_n$ has eigenvalues $4,\,2n+4$ with respective multiplicities $n-1,\,1$.


text:
Q: facebook extending the access token Hi I've seen the answer here
http://facebook.stackoverflow.com/questions/8982025/how-to-extend-access-token-validity-since-offline-access-deprecation
and gave it a go but I'm having trouble getting it to work.
I have an expired token - but obviosuly just need a way to auto update it.
is this possible can someone slip me some code
At present I'm trying this
try {
$result = $facebook->api(
                '/me/permissions/',
                'get',
                array('access_token' => $token)
        );
}
catch(FacebookApiException $e) {

    echo "token invalid";
    $facebook->setAccessToken($token);
    echo $facebook->getExtendedAccessToken();
}

But I still get
token invalid{"error":{"message":"Error validating access token: Session has expired at unix time 1338858000. The current unix time is 1338985046.","type":"OAuthException","code":190,"error_subcode":463}}

Any help. Thanks
Richard

Hi thanks for your help I've got the extended stuff to work and I'm understanding a little more
- I have a followup question say my token becomes invalid - what to do then?
I'm still logged into facebook and I've given permission to my app so it's all there I just need a new key.
I've tried this
$facebook = new Facebook(array(
                'appId'  => FACEBOOKAPPID,
                'secret' => FACEBOOKSECRET,
                'cookie' => true,
            ));

$url = $facebook->getLoginUrl(array('canvas'=>1,'fbconnent'=>1,'scope'=>'offline_access,publish_stream,email,user_about_me,user_birthday,user_website'));
file_get_contents($url);
$fb_session = $facebook->getUser();
echo $fb_session.'
';

$token = $facebook->getExtendedAccessToken();
echo $token.'
';

As it seems that you need to 'login' to facebook to get the details again but it seems that you can't use file_get_contents as facebook requires the cookie that is on your machine. I'm trying to do this on the fly so not to bother the user with any popups and also they have already given the app permission.
Any ideas?
Richard
Oh and just doing this doesn't seem to work either.
$facebook = new Facebook(array(
    'appId'  => $this->fbApiKey,
    'secret' => $this->fbSecretKey,
    'cookie' => true,
));
$token = $facebook->getAccessToken();

A: try this code
$facebook = new Facebook(array(
    'appId'  => $this->fbApiKey,
    'secret' => $this->fbSecretKey,
    'cookie' => true,
));
$token = $facebook->getAccessToken();

A: According to the Removal of offline_access permission:

Scenario 4: Client-side OAuth and Extending Access_Token Expiration Time through New Endpoint
Using the new endpoint below, you will be able to extend the
  expiration time of an existing, non-expired, short-lived user
  access_token. Please note, the endpoint can only be used to extend the
  short-lived user access_tokens. If you pass an access_token that had a
  long-lived expiration time, the endpoint will simply pass that same
  access_token back to you without altering or extending the expiration
  time

Once the long lived access token expires you'll need to get a new short lived token and then extend it.
As for "how to extend it", it's on the same post:
https://graph.facebook.com/oauth/access_token?
    client_id=APP_ID&
    client_secret=APP_SECRET&
    grant_type=fb_exchange_token&
    fb_exchange_token=EXISTING_ACCESS_TOKEN


text:
Q: didSelectRowAtIndexPath not being called, i have tried every method on overflow, any other reason can cause this bug? I have checked out every similar question and every answer,I have implemented with code. I have set
self.tableView.allowsMultipleSelection = NO;
self.tableView.allowsSelection = YES;
self.tableView.userInteractionEnabled = YES;

Check out  the method name of what i expect of is didSelectRowAtIndexPath . There is
no UITapGestureRecognizer.UI Hierarchy shows nothing on the cell.
I have not implemented the  method: willSelectRowAtIndexPath, shouldHighlightRowAtIndexPath, tableView:didDeselectRowAtIndexPath.
My custom cell is clean without xib.
Tapping the cell doesn't work ,but dragging the cell works and calls  didSelectRowAtIndexPath.
Is there anyone know any other reason that can cause this bug?
wired! I have try take this UITableViewController into a demo and show, but in this demo it worked. Maybe some method in my project block didSelectRowAtIndexPath. How can find which method has blocked? How can I catch the tap event ,and find out which method has happened

A: If you are using UITableViewController inside a UIViewController, please check if you set the delegate & datasource of the UITableViewController or not.

A: - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath

check return height is correct. You can set cell backgroundColor to check cell frame.


text:
Q: xsl:for-each - How to format list? I am new at this so please forgive me if I am being ignorant.  This is a sample of my XML data.
<record ID="ART5843">
  <title>This is a sample record</title>
  <edition></edition>
  <persauthorfull>Lykins, Amy D.</persauthorfull>
  <persauthorfull>Cantor, James M.</persauthorfull>
  <persauthorfull>Blanchard, Ray</persauthorfull>
  <keywords>Generic</keywords>
  <keywords>Criminal offences</keywords>
  <keywords>Civil offences</keywords>
  <keywords>Men</keywords>
  <keywords>Psychology</keywords>
  <keywords>Research</keywords>
  <subjects></subjects>
</record>

I need the <persauthorfull> to rename to <PA> and then to output on a single line separated by semi-colon, such...
<PA>Lykins, Amy D.; Cantor, James M.; Blanchard, Ray</PA>

I am using XSL for-each to extract the names, but I have no idea of how to format them.
<xsl:for-each select="a:persauthorfull">
  <PA>
    <xsl:attribute name="type">
    <xsl:value-of select="."/>
    </xsl:attribute>
  </PA>
</xsl:for-each>

From what I am surmising this is a single iteration over the author - is there another way?

A: If you're trying to get:
<PA>Lykins, Amy D.; Cantor, James M.; Blanchard, Ray</PA>

then you should be doing (in XSLT 1.0):
<PA>
    <xsl:for-each select="persauthorfull">
        <xsl:value-of select="."/>
        <xsl:if test="position()!=last()">
            <xsl:text>; </xsl:text>
        </xsl:if>
    </xsl:for-each>
</PA>

A: If you are using XSLT 2.0, string-join() is what you are looking for:
<PA>
   <xsl:value-of select="string-join(a:persauthorfull,'; ')"/>
</PA>

EDIT: As suggested by Michael Kay, there is an even simpler approach:
<xsl:value-of select="persauthorfull" separator="; "/>

Using either line of code, the text content of all persauthorfull elements is joined, delimited by "; ".

Let me also clear up what your current code does. You write:

From what I am surmising this is a single iteration over the author

That's true - if by "single iteration" you mean one iteration for each a:persauthorfull element. This will create several PA elements in the output, if there is more than one author. Also, the name of the author ends up in an attribute type:
<PA type="Blanchard, Ray"/>

Stylesheet
<?xml version="1.0" encoding="UTF-8" ?>
<xsl:transform xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="2.0">
    <xsl:output method="xml" omit-xml-declaration="yes" encoding="UTF-8" indent="yes" />

    <xsl:strip-space elements="*"/>

    <xsl:template match="@*|node()">
        <xsl:copy>
            <xsl:apply-templates select="@*|node()"/>
        </xsl:copy>
    </xsl:template>

    <xsl:template match="record">
        <xsl:copy>
            <xsl:apply-templates select="@*|persauthorfull[1]/preceding-sibling::*"/>
            <PA>
                <xsl:value-of select="string-join(persauthorfull,'; ')"/>
            </PA>
            <xsl:apply-templates select="persauthorfull[last()]/following-sibling::*"/>
        </xsl:copy>
    </xsl:template>

</xsl:transform>

XML Input
<record ID="ART5843">
  <title>This is a sample record</title>
  <edition></edition>
  <persauthorfull>Lykins, Amy D.</persauthorfull>
  <persauthorfull>Cantor, James M.</persauthorfull>
  <persauthorfull>Blanchard, Ray</persauthorfull>
  <keywords>Generic</keywords>
  <keywords>Criminal offences</keywords>
  <keywords>Civil offences</keywords>
  <keywords>Men</keywords>
  <keywords>Psychology</keywords>
  <keywords>Research</keywords>
  <subjects></subjects>
</record>

XML Output
<record ID="ART5843">
   <title>This is a sample record</title>
   <edition/>
   <PA>Lykins, Amy D.; Cantor, James M.; Blanchard, Ray</PA>
   <keywords>Generic</keywords>
   <keywords>Criminal offences</keywords>
   <keywords>Civil offences</keywords>
   <keywords>Men</keywords>
   <keywords>Psychology</keywords>
   <keywords>Research</keywords>
   <subjects/>
</record>

A: Following XSLT generates the output and can be adjusted to meet further unknown requirements:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:template match="/*">
<PA>
   <xsl:apply-templates select="persauthorfull"/>
</PA>
</xsl:template>
<xsl:template match="persauthorfull">
  <xsl:value-of select="."/>
  <xsl:if test="position()!=last()"><xsl:text>;</xsl:text></xsl:if>
</xsl:template>
</xsl:stylesheet>

Output:
<?xml version="1.0" encoding="UTF-8"?>
<PA>Lykins, Amy D.;Cantor, James M.;Blanchard, Ray</PA>

With "can be adjusted" I just meant - it's e.g. possible to omit the XML namespace-declaration, but maybe you want to keep it. As I suppose that you may want to add further information from your input later, this can be easily done extending the template.
In case you're new to XSLT, just as short info how this works - <xsl:template match="/*"> matches the whole input XML from root. Then <xsl:apply-templates select="persauthorfull"/> only applies templates to nodes named persauthorfull. As there is one template matching these nodes - <xsl:template match="persauthorfull">, the nodes are processed there. All other nodes will be omitted. And <xsl:if test="position()!=last()"><xsl:text>;</xsl:text></xsl:if> takes care about adding a ; after each node value when its position() is not the last().


text:
Q: Is this method in solving trigonometric equation viable? So I have an equation $2\sin2\theta=1-\cos\theta$ and my task was to find the solutions between the range of $0\leq\theta\leq360^\circ$ I can infer that $\cos\theta=-\frac{1}{2}$, and I realized something by substituting $\cos$ with $\sqrt{1-\sin^2\theta}$, I can infer that $\sin\theta=\frac{\sqrt{3}}{2}$.
Is this a viable method? Is my analysis correct?

A: A better way to test if your hypothesis is correct is to expand $2 \sin 2 \theta$, rearrange, and then substitute your values.
In your case, $4 \sin \theta \cos \theta + \cos \theta = 1 \rightarrow \cos \theta (4 \sin \theta + 1) = 1.$  Using the values you've supplied, $-\frac  {1}{2} * 4 (\frac {\sqrt {3}}{2}) = -\sqrt {3},$ which is clearly not equal to $1.$
On the other hand, $2 \sin 2 \theta + \cos \theta = 1 \rightarrow \cos \theta (4 \sin \theta + 1) = 1$, so either $\cos \theta = 1$ or $\sin \theta = 0$.  In either case, $\theta = 0°$ would be the only solution.

A: $$2\sin^2\dfrac\theta2=1-\cos\theta=2\sin2\theta$$
$$2\sin^2\dfrac\theta2=4\sin\dfrac\theta2\cos\dfrac\theta2\cos\theta$$
Either $\sin(\theta/2)=0,\theta=?$
Or $\sin(\theta/2)=2\cos\theta\cos(\theta/2)$
Or $\tan(\theta/2)=2\cos\theta$
Use https://www.cut-the-knot.org/arithmetic/algebra/WeierstrassSubstitution.shtml to form a cubic equation in $\tan(\theta/2)$


text:
Q: Make vimdiff ignore unicode equivalence classes I try to compare two directories synced by synching. I do this using the following:
vimdiff <(cd "~/Pictures/shared" && find . | sort) <(ssh argon "cd ~/pictures/shared && find . " | sort)

One machine is a recent archlinux box and the local machine is a MacBook Pro. Skimming through the diff I have problems finding real differences because most of the differences are Umlauts that get somehow interpreted wrong:

Hexdump shows the character differ. Here its a german ö (U+00F6) while there it is a o with combining diaeresis ◌̈ (U+0308). Is vimdiff capable of recognizing these equivalences as identical?

A: You can edit each of the buffers to replace the problematic character with the same character in both (eg. here I'd replace them with o). Vimdiff should automatically update after modifying one of the buffers.
For the replacement you can use :%s/<ctrl+v>u00f6/o/g (and equiv for the other) the u00f6 should automatically be replaced with the unicode sign in the command line after typing it.

A: I found a way to translate the encoding before comparing them by piping the output through iconv -f utf-8 -t utf-8-mac:
vimdiff <(cd ~/Pictures/shared && find . | sort) <(ssh argon "cd ~/pictures/shared && find . " | iconv -f utf-8 -t utf-8-mac | sort)

Also see this question on iconv.


text:
Q: C++/cli: Cannot convert parameter 1 I am trying to convert a C# code which works with a DLL into C++, so my c++ application can work with the DLL. So here I am developing a C++/cli application
I am working on this C# code:
private void SendUSBData(byte[] Data)
{
    if (this.USB.SpecifiedDevice != null)
    {
        this.USB.SpecifiedDevice.SendData(Data);
    }
}

SendData() is a method available in the dll. Following is it's definition in dll
public void SendData(byte[] data);

OK, now in my C++ code, I tried to convert C# code like this
void MissileLauncher::sendUSBData(unsigned char *data)
{
    if(usb.SpecifiedDevice!=nullptr)
    {
        //System::Byte
        usb.SpecifiedDevice->SendData(&data);
    }
}

I get the following error when I run this code
1>------ Build started: Project: CallToCSharp, Configuration: Debug Win32 ------
1>  MissileLauncher.cpp
1>MissileLauncher.cpp(200): error C2664: 'UsbLibrary::SpecifiedDevice::SendData' : cannot convert parameter 1 from 'unsigned char **' to 'cli::array<Type,dimension> ^'
1>          with
1>          [
1>              Type=unsigned char,
1>              dimension=1
1>          ]
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========

I tried the following as well
void MissileLauncher::sendUSBData(array<System::Byte>^data)
{
    if(usb.SpecifiedDevice!=nullptr)
    {
        //System::Byte
        usb.SpecifiedDevice->SendData(&data);
    }
}

it gave me the following error
1>------ Build started: Project: CallToCSharp, Configuration: Debug Win32 ------
1>  MissileLauncher.cpp
1>MissileLauncher.cpp(125): error C2664: 'MissileLauncher::sendUSBData' : cannot convert parameter 1 from 'unsigned char *' to 'cli::array<Type> ^'
1>          with
1>          [
1>              Type=unsigned char
1>          ]
1>MissileLauncher.cpp(159): error C2664: 'MissileLauncher::sendUSBData' : cannot convert parameter 1 from 'unsigned char *' to 'cli::array<Type> ^'
1>          with
1>          [
1>              Type=unsigned char
1>          ]
1>MissileLauncher.cpp(164): error C2664: 'MissileLauncher::sendUSBData' : cannot convert parameter 1 from 'unsigned char *' to 'cli::array<Type> ^'
1>          with
1>          [
1>              Type=unsigned char
1>          ]
1>MissileLauncher.cpp(166): error C2664: 'MissileLauncher::sendUSBData' : cannot convert parameter 1 from 'unsigned char *' to 'cli::array<Type> ^'
1>          with
1>          [
1>              Type=unsigned char
1>          ]
1>MissileLauncher.cpp(186): error C2664: 'MissileLauncher::sendUSBData' : cannot convert parameter 1 from 'unsigned char *' to 'cli::array<Type> ^'
1>          with
1>          [
1>              Type=unsigned char
1>          ]
1>MissileLauncher.cpp(188): error C2664: 'MissileLauncher::sendUSBData' : cannot convert parameter 1 from 'unsigned char *' to 'cli::array<Type> ^'
1>          with
1>          [
1>              Type=unsigned char
1>          ]
1>MissileLauncher.cpp(200): error C2664: 'UsbLibrary::SpecifiedDevice::SendData' : cannot convert parameter 1 from 'cli::array<Type> ^*' to 'cli::array<Type> ^'
1>          with
1>          [
1>              Type=unsigned char
1>          ]
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========

How can I get rid of this?
Update
As proposed in an answer, I tried the following code
void MissileLauncher::sendUSBData(unsigned char *data)
{
    if(usb.SpecifiedDevice!=nullptr)
    {
        int N = 10;
            cli::array<char>^ newData = gcnew cli::array<char>(N);

        for (int i = 0; i < N; ++i)
            newData[i] = data[i];

        //System::Byte
        usb.SpecifiedDevice->SendData(newData);
    }
}

Now, it is giving me the below error
1>------ Build started: Project: CallToCSharp, Configuration: Debug Win32 ------
1>  MissileLauncher.cpp
1>MissileLauncher.cpp(206): error C2664: 'UsbLibrary::SpecifiedDevice::SendData' : cannot convert parameter 1 from 'cli::array<Type> ^' to 'cli::array<Type,dimension> ^'
1>          with
1>          [
1>              Type=char
1>          ]
1>          and
1>          [
1>              Type=unsigned char,
1>              dimension=1
1>          ]
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========

To be honest, I really don't know whether I coded this code correctly, as suggested.

A: You need to convert your data from char* to cli::array<char>^. The cli::array template is what implements System::Array in C++/CLI. To do so you need to know the length of the data:
int N = /* length of data */
cli::array<System::Byte>^ newData = gcnew cli::array<System::Byte>(N);
for (int i = 0; i < N; ++i)
    newData[i] = data[i];

A: Your second version was almost correct.  Here it is from the question:
void MissileLauncher::sendUSBData(array<System::Byte>^data)
{
    if(usb.SpecifiedDevice!=nullptr)
    {
        //System::Byte
        usb.SpecifiedDevice->SendData(&data);
    }
}

And here's the fix:
        usb.SpecifiedDevice->SendData(/* & <- take that out */ data);

A: by using the following code, convert c-style byte array to CLR byte array:
using namespace System::Runtime::InteropServices;

const char* from = xxxx; //(or unsigned char/signed char)
size_t length = strlen(from);
array<System::Byte>^ target = gcnew array<unsigned char>(length);
Marshal::Copy((System::IntPtr)from, target, 0, length);


text:
Q: LabelSelector for Secrets List in k8s I want to get Secret object from k8s cluster using go-client API
I have function that looks like that
func GetSecret( version string) (retVal interface{}, err error){
    clientset := GetClientOutOfCluster()
    labelSelector := metav1.LabelSelector{MatchLabels: map[string]string{"version":version}}

    listOptions := metav1.ListOptions{
        LabelSelector: labelSelector.String(),
        Limit:         100,
    }
    secretList, err := clientset.CoreV1().Secrets("namespace").List( listOptions )
    retVal = secretList.Items[0]
    return retVal, err
}

GetClientOutOfCluster is basically retrieves configuration from cluster or from local ~/.kube/config
I used metav1.LabelSelector just like i do when i generate new Deployment object.So i thought i was cool. But ListOptions.LabelSelector is a string.
When i run my function it fails.
unable to parse requirement: invalid label key "&LabelSelector{MatchLabels:map[string]string{version:": name part must consist of alphanumeric characters, '-', '_' or '.', and must start and end with an alphanumeric character (e.g. 'MyName',  or 'my.name',  or '123-abc', regex used for validation is '([A-Za-z0-9][-A-Za-z0-9_.]*)?[A-Za-z0-9]')

I cannot find example of usage of this function anywhere. Documentation assumes that you know what is LabelSelector.
What is format of LabelSelector for ListOptions?
Thanks

A: You can use the k8s provided function to do the toString operation
import "k8s.io/apimachinery/pkg/labels"
...

func GetSecret(version string) (retVal interface{}, err error){
  clientset := GetClientOutOfCluster()
  labelSelector := metav1.LabelSelector{MatchLabels: map[string]string{"version":version}}

  listOptions := metav1.ListOptions{
    LabelSelector: labels.Set(labelSelector.MatchLabels).String(),
    Limit:         100,
  }
  secretList, err := clientset.CoreV1().Secrets("namespace").List(listOptions)
  retVal = secretList.Items[0]
  return retVal, err
}

A: func GetSecret( version string, param2 string) (retVal interface{}, err error){
    clientset := GetClientOutOfCluster()
    labelSelector := fmt.Sprintf("version=%s, param2=%s", version, param2)

    listOptions := metav1.ListOptions{
        LabelSelector: labelSelector,
        Limit:         100,
    }
    secretList, err := clientset.CoreV1().Secrets("namespace").List( listOptions )
    retVal = secretList.Items[0]
    return retVal, err
}


text:
Q: Spacing between bootstrap elements 4 Our website use bootstrap 4.x
Currently is:

How to add spacing between this elements?
Below is full code Bootstrap:

<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">

menu

slider

LIMITED EDITION

Baby Hipseat
Carrier
Waist Stool

Discount

40% Off

Shop now

image1

image2

image3

image4

image5

image6

I would like an effect similar to:

Could someone please help how can i do this? I will be grateful for any hint. I searched the forum but unfortunately I don't see any similar solution here. Thanks again to everyone for the help.

A: So you should add a padding to the main container:
.banner-slider-cat .bn-inner{
  padding:0 10px 10px 0;
}

The padding is just on right and bottom because you'll have a margin on items on left and top:
.item-bn-inner, .slider-2 {
  margin-left: 10px;
  margin-top: 10px;
}

The you have to resize the "Combo 5x newborn..." container to 182px:
.item-bn-inner .item-bn{
  height: 182px;
}

A: You should add margin to the elements, you could do margin-right, margin-top etc. Margin will create extra space between an element ( class ) you put it on.
margin-top: 10px;
margin-left: 10px;
margin-right: 10px;
margin-bottom: 10px;
margin: 10px;

In your case:
.item-bn-inner{margin:10px}


text:
Q: How to remove slashes while adding scripts on umbraco cms I'm facing an issue on umbraco cms, while i'm adding scripts to the pages its adding a slash for each insertion of scripts on the frontend pages.
Please suggest how to remove those slashes.

@inherits Umbraco.Web.Macros.PartialViewMacroPage
  <script>
   $(document).ready(function() {
       if ($("html").attr("lang") == "ar-AE") {
          $(".globe").attr('href', '/about-us/');
       } else {
           $(".globe").attr('href', '/من-نحن/');
       }
   });
 </script>


text:
Q: firewalld: logging of blocked outgoing connections I have configured firewalld so that the firewall will blockes also outgoing connections. The outgoing traffic I need I have white listed by adding specific rules. This works fine.
But now I want to know, if there are outgoing connections which are currently still  blocked by firewalld. To check this I have set LogDenied to all and restart/reload firewalld. Now I can see many firewalld message in /var/log/messages for REJECTed incomming messages like
Mar  5 19:45:29 kvm011 kernel: FINAL_REJECT: IN=br0-enp3s0 OUT= MAC=80:ee:73:9d:59:09:98:9b:cb:bf:c3:7e:08:00 SRC=192.168.1.254 DST=192.168.1.3 LEN=60 TOS=0x00 PREC=0x00 TTL=64 ID=55873 DF PROTO=TCP SPT=41047 DPT=80 WINDOW=29200 RES=0x00 SYN URGP=0

But it seems, that blocked outgoing traffic will be not logged. I have test it: The SMTP port 25 is not white listed for outgoing traffic. So if I try to send an email, the email is marked as ''deferred'' and I see in maillog that the email cannot send:
Mar  5 19:46:21 kvm011 postfix/smtp[3240]: connect to xxx.xxx.org[193.111.xxx.xxx]:25: Connection timed out

But there is no firewalld message in the /var/log/messages file (for the blocked connection on port 25). Must I activate these kind of messages in firewalld? If so, how can I do that?

A: Found it! I must add explicit a rule to enable logging for outgoing blocked connections:
firewall-cmd --direct --permanent --add-rule ipv4 filter OUTPUT 1 -j LOG --log-prefix \"FINAL_REJECT: \" --log-level 4

After reload or restart firewalld I get my expected logs like:
 Mar  6 11:56:01 kvm011 kernel: FINAL_REJECT: IN= OUT=br0-enp3s0 SRC=192.168.1.3 DST=193.111.xxx.xxx LEN=60 TOS=0x00 PREC=0x00 TTL=64 ID=59572 DF PROTO=TCP SPT=57134 DPT=25 WINDOW=29200 RES=0x00 SYN URGP=0


text:
Q: How to add .md files automatically to the output html file(s) with mkdocs? My goal is to be able to create content that get's automatically added to the html page(s) created with mkdocs. One example usage for this could be a blog.
The solution may require placing .md files into

*

*Same folder

*Subfolders by year, month and day

*Subfolder by year and month

and it should add every .md file inside the folder (and possibly subfolders) automatically to the generated html. For me, the best solution would add following contents automatically to the navigation menu (option 3. above):
mkdocs.yml
docs/
  blog/
    2020/
      01/
        05.md
        22.md
        30.md
      03/
        01.md
        08.md

Desired output would be a tree-like presentation of titles (2020/01/05, 2020/01/22, ..etc) in a html page with links to the pages, or a navigation menu entry which follow similar tree-like structure. Other suggestions are also welcome. The main point is to have this automated; without having a need to create entry to some other page or mkdocs.yml each time a .md file is added.
I checked mkdocs-blog, but it lacks documentation, and mkdocs-blog-plugin, but after configuration nothing showed up in the nav panel and it uses suboptimal file structure (option 2).
I am looking for clear instructions that would offer the easiest/best way to accomplish the goal defined above.

A: I decided to have another look on mkdocs-blog, and found a way to accomplish what I needed. Writing it here in case it can help someone in the future.
1. Installing mkdocs-blog
At the time of writing, mkdocs-blog is not on pip, so one needs to install it from git. For example, using:
pip install git+https://github.com/andyoakley/mkdocs-blog

or by downloading the folder and running pip install <folder_with_setu.py>.
2. Needed folder structure
The needed folder structure, at least with v.0.1.0. is YYYY/mm, and the year folders should be directly below docs. Any other folders and files are neglected. Files inside the monthly folders can be named in any way. Example:
.
├── docs
│   ├── 2020
│   │   ├── 06
│   │   │   └── 05.md
│   │   └── 07
│   │       ├── 22.md
│   │       └── 23.md
│   ├── other_folder
│   ├── third_folder
│   ├── some.md
│   ├── another.md
│   └── index.md
└── mkdocs.yml

3. Listing most 3 most recent on a page
The code is taken from mkdocs-blog/tree/master/tests/test_data/docs/recent.md with a small change1. It uses the Jinja2 templating language. The files are ordered by modification date.
# Most recent

{% for p in config['ordered'][-3:] | reverse %}
  {% set page = p[0] %}
  {% set mtime = p[3] %}

  {{ page.file.url[:-5] }}

{% endfor %}

4. Listing Archives
The code is taken from mkdocs-blog/tree/master/tests/test_data/docs/archive.md with a small change1. It uses the Jinja2 templating language. The files are ordered by modification date.
# Archives
(**Note:** sorted by file edit date)

{% set chronological = config['chronological'] %}

{% for year in chronological|sort(reverse=True) %}

{{ year | strftime("%Y") }}

  {% for month in chronological[year] %}

{{ month | strftime("%B")  }}

    {% for mtime in chronological[year][month]|sort(reverse=True) %}
      {% set page = chronological[year][month][mtime] %}
      {{ page.file.url[:-5]}}

    {% endfor %}
  {% endfor %}

{% endfor %}

1 The small change needed: For some reason the page did no have title (or even meta). I posted an issue here. Therefore, instead of
{{ page.title }}

I needed to use
{{ page.file.url[:-5] }}

or
{{ page.file.url[:-5].split('/')[-1] }}

which makes the links to be the filenames.


text:
Q: AndroidStudio error: null value in entry: workingDir=null I had the build/make error
error: null value in entry: workingDir=null
when building my project in AdroidStudio

A: Just remove the .gradle directory in the root project directory


text:
Q: How to set height of list items in HTML? Here is my code:
HTML

HOME

COMPANY

SOLUTIONS

SERVICES

NEWS & EVENTS

BLOGS

CONTACTS

CSS
.header .menu ul { margin:33px 10px 0 0; padding:0; float:right; width:auto; height:12px; list-style:none;}
.header .menu ul li { margin:0 4px; float:left;}

It does not recognize the height feature. Why? How can I set the height of menu item?

A: You're missing a semicolon :-)
You can also try setting the line-height property of the li tags to change the position of the text in the element:
.line-height-li {
    line-height: 30px;
}

A: Just increase the padding-top and padding-bottom as you want. Line height effect other. I found out it by testing it. It work for me.

A: .header .menu ul { margin:33px 10px 0 0; padding:0; float:right; width:auto;list-style:none;}
.header .menu ul li { margin:0 4px; float:left;}
.active{height:50px;}

A: ul is set to a height of 12 pixels, at least in Firefox.

A: Is the height set on the correct element? You're asking how to set the height of a menu item (presumably, an li) but your CSS says you're setting the height of the ul. Perhaps, moving height: 12px; from where it is to .header .menu ul li could help.

A: The height of the list does not necessarily change the height of the visible list items. I created a small example to show how those heights look like, if you hover on the items, you'll see the height's changing. That because of the overflow attribute of the list.

.menu ul {
  margin: 10px 10px 10px 5px;
  padding: 10px;
  float: right;
  width: auto;
  height: 12px;
  list-style: none;
  background: cyan;
  overflow: hidden;
}

.menu ul:hover {
  overflow: visible;
}

.menu ul li {
  margin: 4px;
  padding: 4px;
  float: left;
  background: yellow;
}

HOME

COMPANY

SOLUTIONS

SERVICES

NEWS & EVENTS

BLOGS

CONTACTS

Anyway, in your example, there's no div with a class "header" in your HTML, that's confusing for beginners. Your CSS rules begin with ".header".