text: Q: Specify separate icon and name for each instance of an app? For example, if I have a command line program (say nano) I want to launch directly with a shortcut, but I want the new instance of Terminal.app to have a dock icon depicting nano running in a terminal window, and for it to be named "Nano" in the dock. I also need this to be done without creating a second copy of the Terminal.app file, and preferably for it to be compatible with the command open -n -a Terminal.app /path/to/binary


text:
Q: Completely two different tabs with different routes in Angular Ionic app I was trying to get two different completely tabs menus on Angular Ionic app. I have already tabs on the bottom of my app.
1st menu tabs
Dashboard - Search - Inbox - Profile
I need to create 2nd menu tabs:
Dashboard - Games - Chat - Contact
I want to have the same Dashboard in both cases.
In my Tabs Routing module :
    const routes: Routes = [
  {
    path: 'tabs',
    component: TabsPage,
    children: [
      {
        path: 'tabs',
        loadChildren: () => import('../tabs/tabs.module').then( m => m.TabsPageModule)
      },
      {
        path: 'dashboard',
        loadChildren: () => import('../dashboard/dashboard.module').then(m => m.DashboardPageModule)
      },
      {
        path: 'search',
        loadChildren: () => import('../search/search.module').then(m => m.SearchPageModule)
      },
      {
        path: 'inbox',
        loadChildren: () => import('../inbox/inbox.module').then(m => m.InboxPageModule)
      },
      {
        path: 'profile',
        loadChildren: () => import('../profile/profile.module').then(m => m.ContactPageModule)
      },
      {
        path: '',
        redirectTo: '/tabs/about',
        pathMatch: 'full'
      }
    ]
  },
  {
    path: '',
    redirectTo: '/tabs/about',
    pathMatch: 'full'
  }
];

Tabs html page
<ion-tabs>

  <ion-tab-bar slot="bottom">
    <ion-tab-button tab="about">
      <ion-icon name="person-circle-outline"></ion-icon>
      <ion-label>Dashboard</ion-label>
    </ion-tab-button>

    <ion-tab-button tab="tabs">
      <ion-icon name="play-outline"></ion-icon>
      <ion-label>Search</ion-label>
    </ion-tab-button>

    <ion-tab-button tab="tabs">
      <ion-icon name="albums"></ion-icon>
      <ion-label>Index</ion-label>
    </ion-tab-button>

    <ion-tab-button tab="blog">
      <ion-icon name="albums-outline"></ion-icon>
      <ion-label>Profile</ion-label>
    </ion-tab-button>
  </ion-tab-bar>

</ion-tabs>

I have difficulties to define the routing for the second type of tabs.
Is it possible to have two completely different tabs in Angular? If yes, I would really appreciate if you could help me with Routing or any tips very appreciated.

redpajama_set_name: RedPajamaStackExchange


text:
Q: UTF-8 encoding in JSP pages of AppEngine project since upgrading to Java 8 I've recently upgraded a large Java AppEngine project from Java 7 to Java 8. After doing that, org.eclipse.jetty.servlet.ServletHandler.updateMappings started throwing this exception:

java.lang.IllegalStateException: No such servlet: jsp

After some investigation, it appears that removing this block of code from web.xml resolves that problem:
 <jsp-config>
    <jsp-property-group>
        <url-pattern>*.jsp</url-pattern>
        <page-encoding>UTF-8</page-encoding>
    </jsp-property-group>
 </jsp-config>

Once I remove that, though, the pages aren't UTF-8 encoded, so non-ascii characters aren't showing up correctly.
I've tried adding variations of the following to the JSP:
<%@ page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>

I've also gone into the controller and tried to set a character encoding there. The endpoint for serving up the JSP file looks like this:
@GET
@Path("{subResources: .+}")
public Viewable foo(@Context HttpServletRequest request, @Context HttpServletResponse response) {
    ...
    return new Viewable("/index.jsp", map);
}

I also tried creating a filter and setting the encoding through that, but that didn't have any effect, either. When I use the network inspector in my browser, the Content-Type header does come back as text/html;charset=utf-8... just the text is wrong, like it was assumed to be ascii somewhere along the chain.
The project uses Guice and Jersey. Unfortunately it is a very large and complex project and I'm unable to provide the full source, or a smaller project that reproduces the issue. Another part of the web.xml file sets up Guice like this:
<filter>
    <filter-name>guiceFilter</filter-name>
    <filter-class>com.google.inject.servlet.GuiceFilter</filter-class>
</filter>

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

<listener>
    <listener-class>com.myproject.GuiceConfig</listener-class>
</listener>

There is then a Guice JerseyServletModule that sets things up further, including a block like this:
    jerseyParams.put("com.sun.jersey.config.property.packages", StringUtils.join(packages, ";"));
    jerseyParams.put("com.sun.jersey.api.json.POJOMappingFeature", "true");
    jerseyParams.put(ServletContainer.PROPERTY_WEB_PAGE_CONTENT_REGEX, "(/(tportal|images|styles|jsp)/.*|.*html|.*jsp|" +
            ".*ico|.*png|.*jpg|.*css|.*js|.*txt|.*xml)");

    filterRegex("^((?!^\\/(admin|_ah)((\\/\\w+)|\\/?$)).)*$").through(GuiceContainer.class, jerseyParams);

The last thing to add is that some of the libraries the project uses are quite out of date. I'd ideally not update any which introduce breaking changes in later versions, if any do that. For example, version 1.11 of Jersey guice and jersey server are used. I haven't tried upgrading to 1.19.4 to know if there are breaking changes or if it would help at all.
Here are some related posts I've referenced in my attempts to resolve this:

*

*Getting IllegalStateException: No such servlet: jsp when accessing deployed Spring application to Google App Engine

*UTF-8 encoding in JSP page


text:
Q: How align in horizontal the menu? I'm trying to align my text (horizontal) but my efforts are not working
.menu{
    background: hsla(290,60%,70%,0.3);
    list-style: none;
}
.menu li{
        width: 200px;
}
.menu li a{
    padding: 8px 16px;
    float:center;
    display: inline;
    text-align: right;
    text-decoration: none;
}
.menu li a:hover{

    background-color: hsla(200,100%,40%,0.2);
}

A: Try this:

ul {
  list-style: none;
}

a {
  text-decoration: none;
}

.menu {
  display: flex;
  justify-content: center;
  background: hsla(290,60%,70%,0.3);
  padding: 8px 16px;
}
.menu li{
  flex: 1;
  text-align: center;
}
.menu li a:hover{
  background-color: hsla(200,100%,40%,0.2);
}

thing

stuff

things

stuffs

thingsstuff

A: Check this Demo. You have used  float:center; use float:left against it. It's should work.
Demo


text:
Q: How to find the Tolls in Google Map API? I am using Google Map API 3.0 to calculate the distance of two places. I can calculate it easily.
But now I need to find out every bridge or ferry service tolls (if any).
For example if I try to get the route direction of [DFW Airport, Grapevine, TX, USA] to [McKinney, TX, USA] in Google Map I get "This route has tolls".
But using Google Map API I can't find it. How can I figure out this?

A: I think Google Maps gives advice about tolls and ferries.
But Google Maps API totally ignore these.


text:
Q: How can I save user information using uid in real-time database using flutter? I am working on saving car details of the user on real-time firebase but having difficulties. Any assistance is highly appreciated. Below is the sample of the code that I am working on. It has two dropdown buttons that are depended on each other and store vital information on the car model and make of the user.
 return Scaffold(
      appBar: AppBar(
        title: const Text('Car Type'),
        centerTitle: true,
      ),
      body: SingleChildScrollView(
        key: _formKeyValue,
        // autovalidateMode: AutovalidateMode.always,
        child: Column(
          children: <Widget>[
            const SizedBox(
              height: 10,
            ),
            DropdownButton<String?>(
              value: selectedCarModel,
              items: dataset.keys.map((e) {
                return DropdownMenuItem<String?>(
                  value: e,
                  child: Text(e),
                );
              }).toList(),
              onChanged: onCarModelChanged,
              hint: const Text('car model'),
            ),

            const SizedBox(
              height: 10,
            ),
            DropdownButton<String?>(
                value: selectedCarMake,
                hint: const Text('car make'),
                items: (dataset[selectedCarModel] ?? []).map((e) {
                  return DropdownMenuItem<String?>(
                    value: e,
                    child: Text(e),
                  );
                }).toList(),
                onChanged: (val) {
                  setState(() {
                    selectedCarMake = val!;
                  });
                }),

            const SizedBox(
              height: 10,
            ),
            // year textfield
            Padding(
              padding: const EdgeInsets.all(8.0),
              child: TextFormField(
                controller: _yearController,
                enableSuggestions: false,
                keyboardType: TextInputType.number,
                decoration: InputDecoration(
                  hintText: 'Year',
                  border: OutlineInputBorder(
                    borderRadius: BorderRadius.circular(10),
                    borderSide: const BorderSide(color: Colors.orange),
                  ),
                ),
              ),
            ),
            //space in between the two fields
            const SizedBox(
              height: 10,
            ),
            //applied model textfield
            Padding(
              padding: const EdgeInsets.all(8.0),
              child: TextFormField(
                controller: _appModelController,
                enableSuggestions: false,
                keyboardType: TextInputType.name,
                decoration: InputDecoration(
                  hintText: 'Applied Model',
                  border: OutlineInputBorder(
                    borderRadius: BorderRadius.circular(10),
                    borderSide: const BorderSide(color: Colors.deepOrange),
                  ),
                ),
              ),
            ),
            const SizedBox(
              height: 10,
            ),
            //numberplate textfield
            Padding(
              padding: const EdgeInsets.all(8.0),
              child: TextFormField(
                controller: _numberPlateController,
                enableSuggestions: false,
                decoration: InputDecoration(
                  hintText: 'Number Plate',
                  border: OutlineInputBorder(
                    borderRadius: BorderRadius.circular(10),
                    borderSide: const BorderSide(color: Colors.deepOrange),
                  ),
                ),
              ),
            ),
            const SizedBox(
              height: 10,
            ),
            //add car textbutton
            ElevatedButton(
              onPressed: () {
                if (_yearController.text.isNotEmpty &&
                    _appModelController.text.isNotEmpty &&
                    _numberPlateController.text.isNotEmpty) {
                  insertData(
                    _yearController.text,
                    _appModelController.text,
                    _numberPlateController.text,
                  );
                }
              },
              child: const Text('ADD CAR'),
            ),


text:
Q: Joining columns in pandas with specific condition My DataFrame looks like below:
Main_column column_1 column_2 column_3 column_4
qw          qw       NaN      rt       NaN
we          qe       NaN      qe       NaN
er          NaN      NaN      NaN      NaN
NaN         NaN      cg       NaN      NaN
NaN         NaN      NaN      vb       bn

DF should looks like below:
Main_column column_1 column_2 column_3 column_4 new_column
qw          qw       NaN      rt       NaN      qw
we          qe       NaN      qe       NaN      we
er          NaN      NaN      NaN      NaN      er
NaN         NaN      cg       NaN      NaN      cg
NaN         NaN      NaN      vb       bn       vb

So basically I need to create a new column based on values from privies one. There are 2 things that needs to be take into account.

*

*If there is a value in "Main_column", the same values should be in "new_column".

*If there is no values in "Main_column", we should take value from the next column (if there is any).

Do you have any idea how to do that?
Regards

A: Use -
df['new_column'] = df['Main_column'].copy()
for col in df.columns:
    df['new_column'] = df['new_column'].fillna(df[col])

Output
0    qw
1    we
2    er
3    cg
4    vb
Name: Main_column, dtype: object


text:
Q: Kotlin Generics custom Type using Wildcard So in Java I can do the following, to define a Type which has an Superclass and Interface constraint.
public class Main<ControllerType extends Node & Controller> {
    private ControllerType controller;
    private ControllerType controller2;

    private Main(ControllerType controller, ControllerType controller2) {
        this.controller = controller;
        this.controller2 = controller2;
    }

    public static void main(String[] args) {
        Main<?> main = new Main<>(new Home(), new Parent());
    }
}

But in Kotlin this is not possible.
class Main<ControllerType>(val controller: ControllerType, val controller2: ControllerType)
        where ControllerType : Node, ControllerType : Controller

fun main(args: Array<String>) {
    val main = Main<*>(Home(), Parent())
}

I get the following error on the star projection:

Projections are not allowed on type arguments of functions and properties

So how could one, solve this problem. I looked into type aliases but they don't have my desired functionality.

A: No, there is no way to do it as Java like wildcard. This is not possible because wildcard is NOT safe.
private Main(ControllerType controller, ControllerType controller2)

controller and controller2 are suppose to be the same or inherited type but Java allow you to duck type it with wildcard.
Star projection is not a wildcard replacement. Star projection is you use when you do not know the exact type and allow you to perform safe operation.
If controller and controller2 are two different type, then you should have two generic parameters.
class Main<T, U>(val controller: T, val controller2: U)
        where T : Node, T : Controller, U : Node, U : Controller

fun main(args: Array<String>) {
    val main = Main(Home(), Parent())
}

A: The error is caused solely by an attempt to use wildcard(projection) in an instance creation expression. It has nothing to do with intersection types or Kotlin.
In the statement
Main<?> main = new Main<>(new Home(), new Parent());

<> is NOT <?>, it is <Node>
in Kotlin the same statement would be
val main : Main<*> = Main<Node>(Home(), Parent())

or (without the explicit type argument)
val main : Main<*> = Main(Home(), Parent())


text:
Q: CRM 2011 Ribbon bar Missing after applying update Rollup 14 in IE not the chrome or Firefox? When reviewing issue further, I have found out  below solution:
Log in to CRM as an administrator.

*

*Go to Settings > Administration.

*Click System Settings.

*On the "Customizations" tab, uncheck Load pages in the most recent version of Internet Explorer.

Even this one is not working for me.
I am getting below error in page load event in IE not the chrome or Firefox
SCRIPT5: Access is denied.
PageLoader.js, line 1 character 1226
I am stuck with as my production release on Monday. Any help is highly appreciated.

A: After Long two days investigation I have found out the reason for the issue. We had previous rollup activity feed solution. After importing the new version of Activity feeds this hectic issue was sorted out.
Activity feed new solution is available with rollup up package.it can be found by exacting the rollup package. Previously this was available in Microsoft Dynamic market place.

A: Do you use any script that have fixed url?
Seems similar issue with:
Grey ribbon on Account form in IE "SCRIPT5: Access is denied." in PageLoader.js
And try IIS Reset might help clearing cached content.


text:
Q: Integration by substitution involving complex numbers Say I would like to integrate e$^($$^i$$^a$$^-$$^b$$^)$$^x$, from 0 to infinity, where $a$ and $b$ are positive, real numbers. Am I allowed to substitute $x'=(ia-b)x$?

A: You seem to want to use $x$ to mean two different things. What you can say is that, for any fixed $z\in\mathbb{C}$, $\frac{dy}{dx}=zy\iff y(x)=y(0)e^{zx}$. You can also say that $\int_0^\infty e^{-zx}dx=\frac{1}{z}$ provided $\Re z > 0$.


text:
Q: Send pdf in base 64 to print I need to send base 64 for printing, I need to open the chrome print window, but my code just opens the pdf file in a new window. there is no problem with a regular html page, and when there is a pdf element on the page, it is not displayed
var objbuilder = '';
    objbuilder += ('<object width="100%" height="100%"      data="data:application/pdf;base64,');
    objbuilder += (base64PDF);
    objbuilder += ('" type="application/pdf" class="internal">');
    objbuilder += ('<embed src="data:application/pdf;base64,');
    objbuilder += (base64PDF);
    objbuilder += ('" type="application/pdf" />');
    objbuilder += ('</object>');
var win = window.open("","_blank","titlebar=yes");
        win.document.title = "My Title";
        win.document.write('');
        win.document.write(objbuilder);
        win.document.write('');
        win.print()

A:                 const binary = atob(pdfSrc.replace(/\s/g, ''));
                const len = binary.length;
                const buffer = new ArrayBuffer(len);
                const view = new Uint8Array(buffer);
                for (let i = 0; i < len; i++) {
                    view[i] = binary.charCodeAt(i);
                }
                const blob = new Blob([view], {type: "application/pdf"});
                const url = URL.createObjectURL(blob);
                const iframe = document.createElement('iframe');
                iframe.style.display = 'none';
                iframe.src = url;
                document.body.appendChild(iframe);
                iframe.contentWindow.print();

A: We define the function that base64 string convert to ArrayBuffer
const base64ToArrayBuffer = (data) => {
    const bString = window.atob(data);
    const bLength = bString.length;
    let bytes = new Uint8Array(bLength);
    for (let i = 0; i < bLength; i++) {
        const ascii = bString.charCodeAt(i);
        bytes[i] = ascii;
    }
    return bytes;
}

 const content = base64ToArrayBuffer(base64PDF);
 const blob = new Blob([content], { type: "application/pdf" });
 const url = window.URL.createObjectURL(blob);

 const iframe = document.createElement('iframe');
 iframe.style.display = 'none';
 iframe.src = url;
 document.body.appendChild(iframe);
 iframe.contentWindow.print();


text:
Q: Word 2007 VBA pause macro for user to manually select cursor position or range with the mouse I have many macros which act on a selected range (eg a row in a table, or a random selection area (not in a table)), only part of the active document, in Word 2007.  (They perform multiple tasks on the same selection - eg format specified strings, replace multiple spaces with tabs, resize images etc)
I have tried to write an inputbox procedure which allows the user to select the range or check and modify the pre-selected range (if they forgot to do so before executing the macro, or need to select a specific area during a macro.
It is looking like the inputbox doesn't have that capability in word?
Can anyone help with how this can be achieved?
I've done it in excel with InputBox but the code doesn't work in Word, and couldn't find anything helpful on google...
This is the code in Excel which does what I want to do in word:
     'input box prompt+pause to select range
    Set User_RangeSelection = Application.InputBox("select cells to move, with the mouse", Default:=Selection.Address, Type:=8)
        If User_RangeSelection Is Nothing Then 'if cancel is clicked - otherwise selects existing cell selection
            MsgBox "No Selection made, exiting."
'            Exit Sub 'cancels the whole macro after this routine!
        End If
'---------------------------------------------------
    User_SelectedRange = User_RangeSelection.Address(False, False) 'name the selection as a range
    Range(User_SelectedRange).Select 'selects range IN SHEET; OR enter single commands here
'------------------------- Code to execute on/with selection

The code/syntax for word is clearly completely different - tried many changes but none have got past popup error codes.
"TYPE:=8" "NAMED ARGUMENT NOT FOUND"
After above line removed, The Inputbox shows a 1-line bit of the actual string selected, DOESNT show the area highlighted in the doc, and does not permit clicking in the doc
"as Range" added at the end "Expected: End of statement"
"address"-"Method or data member not found"
"range" "sub or function not defined"

A: Indeed, the way Word implements the VBA InputBox is different from Excel. Excel is "one, big table"; Word is really "just text", formatted on-screen to look like a table, where required. That's the "why" behind the behavior, FWIW.
You should be able to do something similar, but it will take a bit more work. I can't give you an exact solution since the exact requirements aren't clear and it would be a bit "too broad". But to get you started on the basic "specify the range" part...
(Note: I'm typing this from memory on a mobile device, so there may be syntax errors)
Dim CellRef as String, RowIndex as Variant, ColIndex as Variant
Dim CommaPos as Long
Dim Tbl as Word.Table, Cel as Word.Cell, Dim rng as Word.Range

If Selection.Information(wdWithinTable) Then
  CommaPos = Instr(CellRef, ",")
  CellRef = InputBox("Type in the cell row and column (1,3)")
  If CommaPos <> 0 Then
    RowIndex = Left(CellRef, CommaPos-1)
    ColIndex = Mid(CellRef, CommaPos + 1)
    Set tbl = Selection.Tables(1)
    Set Cel = tbl.Cell(rowIndex, colIndex)
    Set rng = cel.Range
  Else
    MsgBox "Please enter a correct cell reference")
  End If
Else
  MsgBox "Please click in the table, first"
End If


text:
Q: Collapse / Fold methods in Aptana? I'm not sure if I'm missing something as I'm new to Aptana but. I'm having trouble collapsing my class methods. I like to collapse everything except the function I'm currently working in within my class but everytime collapse and then go to edit, everything expands again.
I'm guessing it's therefore some sort of feature that everything within a class is expanded when editing any method within the class. Is there any way around this at all. I'm loving Aptana so far, but this is extremely annoying.

A: For Mac, it's Shift-Command-/ using the / on the numpad
It doesn't work with the / next to the shift key.
I suspect this will work on PC, too.

A: Like you this one has bugged me on and off for quite a while and it's even more annoying when I found out how stupidly simple the answer is. It's not written in any of the documentation that I can find.
But all you have to do is fold up all the methods, functions, classes etc that you want folded, then hit "ctrl s" to save. That's it. This step is not required in some other editors so it didn't occur to me immediately.
Thereafter if you hover over the + icon you get a preview of the folded up code.
Obviously if you click on + the code expands.
By the way: if you want to add to the items that can be folded:
select window -> preferences
either type "folding" in the type filter text box
or
select general -> PyDev -> Code Folding
check the appropriate items -> apply -> ok


text:
Q: Is there a way to use compareTo with double? Java I was wondering is it possible to compare 2 double elements from arraylist with compareTo? I've tried something like, but everyone knows that I will receive and error, but still I want to use this compareTo if it's possible.
prekiuArray.stream().sorted((p1, p2) -> p1.getPrice().compareTo(p2.getPrice())).forEach(p -> System.out.printf("%s%n", p));

A: double is a primitive and has no methods. Double (the boxed version) implements Comparable, so you can use compareTo on that, or you can use Double.compare(double d1, double d2) to compare primitives
The best way to solve this does not involve a lambda at all. You can use Comparator.comparingDouble and pass it a method reference:
... .stream().sorted(Comparator.comparingDouble(MyClass::getPrice)) ...

Comparator.comparing would be used instead of comparingDouble if getPrice returned a boxed Double to avoid unboxing it unnecessarily.

A: You may do it like so,
prekiuArray.stream().sorted(Comparator.comparingDouble(Prekiu::.getPrice()))
                .forEach(p -> System.out.printf("%s%n", p));


text:
Q: method match1.regex seems not working in ruby I'm following a tutorial on regular expressions in ruby, but a method called regex that seems not working
Tutorial

re = /(\w*)\s(\w*),\s?([\w\s]*)/
match1 = str1.match re
match2 = str2.match re
match1.regex # => wsw,s[ws]     (this is IRB's unique way of showing regular expressions; it will still work normally)

My console

The regex method the method throws an error

1.9.3-p547 :033 > re = /(\w*)\s(\w*),\s?([\w\s]*)/
 => /(\w*)\s(\w*),\s?([\w\s]*)/
1.9.3-p547 :034 >     match1 = str1.match re
 => #<MatchData "Joe Schmo, Plumber" 1:"Joe" 2:"Schmo" 3:"Plumber">
1.9.3-p547 :035 >     match2 = str2.match re
 => #<MatchData "Stephen Harper, Prime Minister" 1:"Stephen" 2:"Harper" 3:"Prime Minister">
1.9.3-p547 :036 > match1.regex
NoMethodError: undefined method `regex' for #<MatchData "Joe Schmo, Plumber" 1:"Joe" 2:"Schmo" 3:"Plumber">
    from (irb):36
    from /home/fernando/.rvm/rubies/ruby-1.9.3-p547/bin/irb:12:in `<main>'
1.9.3-p547 :037 >

A: I think it should be
match1.regexp

with a final 'p'


text:
Q: Pairwise spacings of an ordered sequence of uniform random numbers Given an ordered list of $m$ uniform random numbers in the range $1$ to $n$
$$a_{1} \le a_{2} \le \ldots \le a_{m}, \forall a_{i}: a_{i}\in [1;n] \cap \mathbb{N}$$
compute the pairwise spacings of these numbers:
$$d_{1} = a_{2}-a_{1}
  d_{2} = a_{3}-a_{2}
  \ldots
  d_{m-1} = a_{m}-a_{m-1}$$
Then, define $Y$ as the number of distinct $d_{i}$ that appear more than once:
$$
Y = | \bigcup \limits_{i=1}^{m} \{d_{i}: \exists j \ne i : d_{i} = d_{j} \}|
$$
(Note that for each distinct value that appears more than once, Y is increased by only one, no matter how often this value actually appears).
George Marsaglia [1] has stated that Y is Poisson-distributed with $\lambda = \frac{m^{3}}{4m}$, but I couldn't find a proof for that anywhere and I've just spent an entire day trying to figure it out myself. I seem to be unable to even get the probability of 2 $d_{i}$s having the same value. Does anyone have an idea how to start? Or is there even a "simple" explanation for the Poisson-distribution?
I would be happy already if I could only prove that Y is Poisson-distributed at all, but I can't even do that by myself.
Thanks a million times for any help!
[1] http://www.stat.fsu.edu/pub/diehard/cdrom/pscript/keynote.ps

A: This is clearly wrong, since $Y\lt m$ whereas the Poisson distribution has support on all of $\mathbb N$. Perhaps it was meant as an approximation? It's hard to tell, since the link you provided has gone stale. Note also that one of the $m$s in your expression for $\lambda$ should probably be an $n$, both because the result must depend on $n$ and because otherwise the fraction could be reduced.


text:
Q: Server Operator on csgo why i get this error when use cheats in offical matchmaking in csgo says example: sv_cheats 1      Can't change replicated sv_cheats 1 from console of client, only server operator can change its value and godmode not working in matchmaking only in paractice bots

A: You can't use sv_cheats 1 on official servers, because, as the response said:

You are not an operator.

... Admin, basically.

If you want to run cheats, you'll want to get your own server or play single-player.
You can't just waltz onto a random server you don't own and change settings you aren't allowed to change, just like you can't just waltz into a random person's house and completely repaint their walls.


text:
Q: What is the difference between AngularJS $window.alert() and Javascript alert()? It seems that the AngularJS $window.alert() and Javascript alert() are the same. Under what conditions should we use which one of them? Or are there no difference at all?

A: It is exactly the same thing - global methods in JavaScript (running in browser) are methods of the window. AngularJS' $window is alias for window object.

$window: A reference to the browser's window object.

Note that you may override $window for your tests, but in regular code both are the same.

A: The difference is that in tests you can mock out the $window object so that instead of using the real alert it stubs to console.log or something else. If your code called alert directly then there is no way to override the real alert so in your tests you would see alerts popping up whenever your method used an alert.
Beyond just testing, in theory you could even use an alternative provider for $window which had an extra fancy alert implementation. Imagine if you wanted to use an alert built on bootstrap dialogs. Using the $window provider would permit you to change this in one place by injecting a new implementation and none of your other code would change.
You will not see a difference in your running code (both perform identically) but loosely coupling your code like this pays off later.

A: They are identical, because $window === window, unless you have overridden it.


text:
Q: Function $f(x)=\int_0^\infty\left|\sin(t)\cdot\sin(x\,t)\cdot e^{-t}\right|\,dt$ Let
$$f(x)=\int_0^\infty\Big|\sin(t)\cdot\sin(x\,t)\cdot e^{-t}\Big|\,dt,$$
where $|\dots|$ denotes the absolute value. We are concerned only with positive values of $x$ (i.e. let the domain of the function be $\mathbb{R}^+$).
The graph of this function looks roughly as follows (modulo possible errors in numeric algorithms used to plot it):

The function values at rational points can be evaluated in a closed form, e.g.
$$f\left(\frac32\right)=\frac2{145}\left(24+\frac{27\,\sqrt3\,\left(e^{\frac\pi3}+e^{-\frac\pi3}\right)-24\,\left(e^{\frac\pi3}-e^{-\frac\pi3}\right)-4}{e^\pi-e^{-\pi}}\right).$$

Questions:

*

*Is the function $f(x)$ continuous? Is it smooth? Is it analytic?

*How many local extrema does it have?

*What is the $\lim\limits_{x\,\to\,\infty}f(x)$, if it exists?

*Can we find a closed-form value of $f(x)$ at an explicit irrational point (given by a closed-form expression)?

*Is there a general formula for values of $f(x)$ at rational points?

A: The general formula for rational $x$ can be derived as
follows. Consider, first, a convergent sum of the form $\sum_k
\frac{p(k)}{q(k)}$, where $p$ and $q$ are polynomials, $\deg q\geq
\deg p+2$, and $q$ only has simple roots. If $\rho$ is a variable that
runs over the roots of $q$, then
$$ \frac1{q(x)} = \sum_{q(\rho)=0}\frac{1}{q'(\rho)}\frac1{x-\rho}, $$
so the sum can be written as
$$ \sum_k \frac{p(k)}{q(k)} =
\sum_{q(\rho)=0} \frac1{q'(\rho)} \sum_k \frac{p(k)\bmod k-\rho}{k-\rho} + \lfloor p(k)/(k-\rho)\rfloor. $$
Now, $p(k)\bmod k-\rho = p(\rho)$ is a constant,
$$ \sum_{k\geq0} \frac{z^k}{k-\rho} = \Phi(z,1,-\rho), $$
by definition of Lerch's transcendent function, and the fact that the original sum is convergent assures us we can ignore the terms $\sum_\rho\frac{\lfloor p(k)/(k-\rho)\rfloor}{q'(\rho)}$, as they must necessarily sum to zero.
Therefore, since $\Phi$ has an asymptotic expansion
$$ \Phi(z,1,-\rho) = -\log(1-z) - \gamma - \psi(-\rho), $$
($\gamma$ is Euler's gamma, and $\psi$ is the digamma function), and
since the fact that the original sum converges assures us that we can
ignore all terms of $\Phi(z,1,-\rho)$ independent of $\rho$ as we take
the limit $z\to1-$ to recover the sum, we therefore have
$$ \sum_{k\geq0} \frac{p(k)}{q(k)} = -\sum_{q(\rho)=0} \frac{p(\rho)}{q'(\rho)}\psi(-\rho). $$
The function $f$ has the form
$$ f(x) = -\frac{\coth\frac\pi2}{\pi} + \frac2\pi\sum_{n\geq0} S(n, \sin(2\pi nx), \cos(2\pi nx)), $$
where $S(n,\gamma,\delta) = \frac{p(n,\gamma)/q(n,\delta)}{\cosh\pi-\delta}$ is given as in sos440's answer by
$$ p(n,\gamma) = (2n^2x^2-1)\sinh\pi+2nx\gamma, \qquad q(n)=(4n^2-1)(4n^4x^4+1). $$
When $x=r/s$ is rational, this can be simplified. Rewrite the sum as
$$ \sum_{n\geq0}S(n,\sin2\pi nx, \cos2\pi nx) = \sum_{0\leq\alpha<s} \frac{1}{\cosh\pi-\cos2\pi\alpha x} \sum_{m\geq0}
\frac{p(ms+\alpha, \sin2\pi\alpha x)}{q(ms+\alpha)}, $$
and now the inner sum over $m$ is a convergent sum of terms rational in $m$, so can be written as
$$ \sum_{q(\rho)=0}\frac{-1}{q'(\rho)} \frac1{s} \sum_{0\leq\alpha<s} \frac{p(\rho, \sin2\pi\alpha
   x)}{\cosh\pi-\cos2\pi\alpha x} \psi\left(\frac{\alpha-\rho}{s}\right),
$$
where $\rho$ runs over the roots of $q(n)$: $\{\pm\frac12,
\frac{e^{\pi i j/4}}{x\sqrt{2}}\}$, $j$ odd.
This is pretty much a closed form, it is a finite sum of digamma terms, but
you might not be able to simplify it much, especially by hand. For
example, Mathematica now gives:
$$
f({\textstyle\frac52}) =
\left(
68-68 \sqrt{5}-500 \sqrt{10-2 \sqrt{5}} \cosh\frac{\pi }{5}+272 \cosh\frac{2 \pi }{5}-\left(125 \sqrt{10-2 \sqrt{5}}+125 \sqrt{5 \left(10-2 \sqrt{5}\right)}\right) \cosh\pi-\left(160+160 \sqrt{5}\right) \sinh\frac{\pi }{5}+160 \sinh\frac{3 \pi }{5}-160 \sinh\frac{7 \pi }{5}
\right)/\left(
689(-1+\sqrt{5}-4 \cosh\frac{2 \pi }{5})\sinh\pi\right)
$$

A: My calculation shows that
$$f(x) = \frac{1}{\pi}\coth\left(\frac{\pi}{2}\right)
+ \frac{2}{\pi} \sum_{n=1}^{\infty} \frac{(2n^{2}x^{2} - 1) \sinh\pi + 2nx\sin (2\pi n x)}{(4n^{2} - 1)(4n^{4}x^{4} + 1) (\cosh \pi -\cos (2\pi n x))}. \tag{1} $$
This allows (at least theoretically) calculate the value of $f$. This shows that

*

*The series $\text{(1)}$ defines a holomorphic function, say $\tilde{f}$, on $\Bbb{C} \setminus \Bbb{R}$ with poles
$$ \frac{\pm 1 \pm i}{2n} : n = 1, 2, \cdots
\quad\text{and}\quad
\frac{k}{n} \pm \frac{i}{2n} : k \in \Bbb{Z}, n = 1, 2, \cdots. $$
Because these poles accumulate to $\Bbb{R}$ as $n\to\infty$, I'm not sure if $\tilde{f}$ and $f$ can be amalgamated to yield a nice function.

*This sum converges uniformly on $\Bbb{R}$: putting $y = nx$,
$$ \left| \frac{(2n^{2}x^{2} - 1) \sinh\pi + 2nx\sin (2\pi n x)}{(4n^{4}x^{4} + 1) (\cosh \pi -\cos (2\pi n x))} \right| \leq \frac{(2y^{2} + 1)\sinh \pi + 2|y|}{(4y^{4}+1)(\cosh \pi - 1)}, $$
which is uniformly bounded by some constant $C > 0$. Thus we can take limit $x \to \infty$ pointwise to $\text{(1)}$, proving that
$$ \lim_{x\to\infty} f(x) = \frac{1}{\pi}\coth\left(\frac{\pi}{2}\right). $$

*The graph of its derivative is shown below: I'm unable to find any clear pattern that the zeros of $f'(x)$ must satisfy. One exception is that some zeros seem to be very close to integers.

To derive $\text{(1)}$, I just exploited the following formula:
$$ \left| \sin x \right| = \frac{2}{\pi} \sum_{n \in \Bbb{Z}} \frac{1 - \cos(2nx)}{4n^{2} - 1}, \quad x \in \Bbb{R} $$
Since each summand is non-negative, Tonelli says that we can plug this to the integral and interchange the order of limiting operators to obtain
$$ f(x) = \frac{4}{\pi^{2}} \sum_{m \in \Bbb{Z}} \sum_{n \in \Bbb{Z}} \frac{1}{(4m^{2}-1)(4n^{2} - 1)} \int_{0}^{\infty} (1 - \cos 2mt)(1 - \cos 2nxt) e^{-t} \, dt. $$
Calculating the integral and utilizing the fact $\sum_{n\in\Bbb{Z}} (4n^{2}-1)^{-1} = 0$, this reduces to
$$ f(x) = \frac{4}{\pi^{2}} \sum_{m \in \Bbb{Z}} \sum_{n \in \Bbb{Z}} \frac{1}{(4m^{2}-1)(4n^{2} - 1)(4(nx+m)^{2} + 1)}. $$
Further simplification then gives $\text{(1)}$.

EDIT.

*

*Numerical observation suggest that $f$ is $C^{2}(\Bbb{R}^{+})$, and heuristic investigation suggests that $f^{(3)}$ has jump discontinuity at every point in $\frac{1}{2}\Bbb{Z} \cup \frac{1}{3}\Bbb{Z}$.


text:
Q: Angular move directive from div to div I have problem in my project I have something like this:

    <left></left>
    <right></right>

http://plnkr.co/edit/deBMT5DAaoU47t4RxDhK?p=preview
in right pane I have few nesting directive and last directive have option to maximalize I need maximalize this directive in central pane, probably I would like fill the empty div parent div hide. I need something like this because I have in directive I have data what I need display and jquery plugin and so on. but I no have idea how do it could someone help me?

A: As i understood, you can get access to any element inside your directive via elm params. Here it is.
`http://plnkr.co/edit/IhwysGj8gq2If01CoxP7?p=preview`


text:
Q: Create Azure Blob Service container and make it publicly readable I create an Azure Blob Storage container just fine:
connect_str = 'REDACTED'
blob_service_client = BlobServiceClient.from_connection_string(connect_str)
container_name = req.params.get('UserId').replace('.', '')
container_client = blob_service_client.create_container(container_name)

Then the rest of the code creates and adds a file to the container. Problem is, the container's public access level is private by default.
How can I make it create the container with a public access level set to public and readable? Right now I have to go change it manually.
https://learn.microsoft.com/en-us/python/api/azure-storage-blob/azure.storage.blob.publicaccess?view=azure-python This only seems to return what type of public access it is, it doesn't change it.
EDIT: I think I need to use https://learn.microsoft.com/en-us/python/api/azure-storage-blob/azure.storage.blob.containerclient?view=azure-python#set-container-access-policy-signed-identifiers--public-access-none----kwargs- but I am not sure how to use it

A: According to the docs, you should be able to set it in the create_container call:
create_container(name, metadata=None, public_access=None, **kwargs)


text:
Q: CUDA, NPP Filters The CUDA NPP library supports filtering of image using the nppiFilter_8u_C1R command but keep getting errors. I have no problem getting the boxFilterNPP sample code up and running.
eStatusNPP = nppiFilterBox_8u_C1R(oDeviceSrc.data(), oDeviceSrc.pitch(),
                                  oDeviceDst.data(), oDeviceDst.pitch(),
                                  oSizeROI, oMaskSize, oAnchor);

But if I change it to use nppiFilter_8u_C1R instead, eStatusNPP return the error -24 (NPP_TEXTURE_BIND_ERROR). The code below is the alterations I made to the original boxFilterNPP sample.
NppiSize oMaskSize = {5,5};
npp::ImageCPU_32s_C1 hostKernel(5,5);

for(int x = 0 ; x < 5; x++){
    for(int y = 0 ; y < 5; y++){
        hostKernel.pixels(x,y)[0].x = 1;
    }
}

npp::ImageNPP_32s_C1 pKernel(hostKernel);

Npp32s nDivisor = 1;

eStatusNPP = nppiFilter_8u_C1R(oDeviceSrc.data(), oDeviceSrc.pitch(),
                               oDeviceDst.data(), oDeviceDst.pitch(),
                               oSizeROI,
                               pKernel.data(),
                               oMaskSize, oAnchor,
                               nDivisor);

This have been tried on CUDA 4.2 and 5.0, with same result.
The code runs with the expected result when oMaskSize = {1,1}

A: Filter applies the mask extending upward and to the left, following the mathematical convention that the convolution between two functions reverses the direction of the second function.
The box filter mask extends downwards and to the right, which is probably more intuitive.
In any case, the problem is caused by the fact that the input image in the changed code would have to be sampled at what would effectively be SOURCE[-4, -4) in order to compute DESTINATION[0, 0]. Since the input image is being accessed via a texture sampler, binding the source image pointer offset by (-4, -4) causes the texture-bind error you're seeing.
Workaround: The simplest workaround for this issue would be to set the anchor point to (4, 4), which would effectively move the mask down and to the right. You still need to be aware that you'd want to invert the weights in the kernel array (i.e. K[-4, -4] -> K[0, 0], K[0, 0] -> K[-4, -4], etc.).

A: I had the same problem when I stored my kernel as an ImageCPU/ImageNPP.
A good solution is to store the kernel as a traditional 1D array on the device. I tried this, and it gave me good results (and none of those unpredictable or garbage images).
Thanks to Frank Jargstorff in this StackOverflow post for the 1D idea.
NppiSize oMaskSize = {5,5};
Npp32s hostKernel[5*5];

for(int x = 0 ; x < 5; x++){
    for(int y = 0 ; y < 5; y++){
        hostKernel[x*5+y] = 1;
    }
}

Npp32s* pKernel; //just a regular 1D array on the GPU
cudaMalloc((void**)&pKernel, 5 * 5 * sizeof(Npp32s));
cudaMemcpy(pKernel, hostKernel, 5 * 5 * sizeof(Npp32s), cudaMemcpyHostToDevice);

Using this original image, here's the blurred result that I get from your code with the 1D kernel array:

Other parameters that I used:
Npp32s nDivisor = 25;
NppiPoint oAnchor = {4, 4};

A: Thank you for the help.
Got over the error, but I'm seeing some odd behavior. The image changes depending on what program I run just before and the image do not show what i am going fore.
The example that I am trying to mimic is the nppiFilterBox_8u_C1R with the use of nppiFilter_8u_C1R where i set the kernel to ones and the nDivisor to the sum of the kernel.
This code is still a alteration on the boxFilterNPP sample code.
NppiSize oMaskSize = {5,5};
npp::ImageCPU_32s_C1 hostKernel(5,5);
for(int x = 0 ; x < 5; x++){
    for(int y = 0 ; y < 5; y++){
        hostKernel.pixels(x,y)[0].x = 1;
    }
}

npp::ImageNPP_32s_C1 pKernel(hostKernel);
Npp32s nDivisor = 25;
NppiPoint oAnchor = {4, 4};
eStatusNPP = nppiFilter_8u_C1R(oDeviceSrc.data(),oDeviceSrc.pitch(),
                               oDeviceDst.data(), oDeviceDst.pitch(),
                               oSizeROI,
                               pKernel.data(),
                               oMaskSize, oAnchor,
                               nDivisor);

Since the kernel is only ones the need to invert the weights should not be a issue.
The 5 different kinds of image this code return are show below. Mostly the last one is returned.
http://1ordrup.dk/kasper/image/Lena_boxFilter1.jpg
http://1ordrup.dk/kasper/image/Lena_boxFilter2.jpg
http://1ordrup.dk/kasper/image/Lena_boxFilter3.jpg
http://1ordrup.dk/kasper/image/Lena_boxFilter4.jpg
http://1ordrup.dk/kasper/image/Lena_boxFilter5.jpg

I think the reason this happens is that the kernel is not initilised correctly or no used, thus data with pseudo-random content is used for the kernel.


text:
Q: Unable to receive integer return value when calling Python function from C++ I am calling a Python function from my C++ code. The Python function takes two numbers as input and returns the sum. I am unable to retrieve the sum value in C++ code. Below are code for both C++ and Python files.
C++ code:
#include<iostream>
#include "Python.h"

int main()
{
    Py_Initialize();

    PyRun_SimpleString("import sys; sys.path.insert(0, '/home/aakash/Desktop/code/testpc')");

    //Run a python function
    PyObject *pName, *pModule, *pFunc, *pArgs, *pValue;
    pName = PyUnicode_FromString((char*)"sample");
    pModule = PyImport_Import(pName);
    pFunc = PyObject_GetAttrString(pModule, (char*)"main2");

    // pArgs = PyTuple_Pack(1, PyUnicode_FromString((char*)"Greg"));
    pArgs = PyTuple_New(2);
    PyTuple_SetItem(pArgs, 0, PyLong_FromLong(5));
    PyTuple_SetItem(pArgs, 1, PyLong_FromLong(6));
    pValue = PyObject_CallObject(pFunc, pArgs);
    auto result = _PyUnicode_AsString(pValue);
    std::cout << result << std::endl;
    Py_Finalize();
    return 0;
}

Python code in sample.py file:
def main2(a, b):
    print("getting sum ")
    c = a + b
    return c

Getting error:- TypeError: bad argument type for built-in operation.
Request to help for other datatypes too.

A: I got the solution by replacing auto result = _PyUnicode_AsString(pValue); with int result = PyFloat_AsDouble(pValue);. But I am not fully convinced as I needed an integer, but I had to use a function which looks to be meant for dealing with Float/Double. So, waiting for an accurate answer. Thanks!


text:
Q: Good .NET library for fast streaming / batching trigonometry (Atan)? I need to call Atan on millions of values per second.  Is there a good library to perform this operation in batch very fast.  For example, a library that streams the low level logic using something like SSE?
I have profiled the application, and I know that this call to Atan is a bottleneck.
I know that there is support for this in OpenCL, but I would prefer to do this operation on the CPU.  The target machine might not support OpenCL.
I also looked into using OpenCV, but it's accuracy for Atan angles is only ~0.3 degrees.  I need accurate results.

A: Why don't you try Brahma? To my understanding, it's a free and open source GPGPU library that doesn't depend on OpenCL, instead converting code to HLSL/GLSL shaders via LINQ.
EDIT: Sample code:
ComputationProvider provider = new ComputationProvider();
CompiledQuery query = provider.Compile<DataParallelArray<float>>(
    data => from value in data
            select (float)Math.Atan(value)); // Do your calculations here...

DataParallelArray<float> input = new DataParallelArray<float>(provider, new float[] { 0, 1, 2, 3, 4, 5, 6, 7, }); // etc...
IQueryable result = provider.Run(query, input);

foreach (float value in result)
    Console.WriteLine(value);


text:
Q: Blenderbot FineTuning I have been trying to fine-tune a conversational model of HuggingFace: Blendebot. I have tried the conventional method given on the official hugging face website which asks us to do it using the trainer.train() method. I tried it using the .compile() method. I have tried fine-tuning using PyTorch as well as TensorFlow on my dataset. Both methods seem to fail and give us an error saying that there is no method called compile or train for the Blenderbot model. I have even looked everywhere online to check how Blenderbot could be fine-tuned on my custom data and nowhere does it mention properly that runs without throwing an error. I have gone through Youtube tutorials, blogs, and StackOverflow posts but none answer this question. Hoping someone would respond here and help me out. I am open to using other HuggingFace Conversational Models as well for fine-tuning.
Here is a link I am using to fine-tune the blenderbot model.
Fine-tuning methods: https://huggingface.co/docs/transformers/training
Blenderbot: https://huggingface.co/docs/transformers/model_doc/blenderbot
from transformers import BlenderbotTokenizer, BlenderbotForConditionalGeneration
mname = "facebook/blenderbot-400M-distill"
model = BlenderbotForConditionalGeneration.from_pretrained(mname)
tokenizer = BlenderbotTokenizer.from_pretrained(mname)

#FOR TRAINING:

trainer = Trainer(
    model=model,
    args=training_args,
    train_dataset=small_train_dataset,
    eval_dataset=small_eval_dataset,
    compute_metrics=compute_metrics,
)
trainer.train()

#OR

model.compile(
    optimizer=tf.keras.optimizers.Adam(learning_rate=5e-5),
    loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
    metrics=tf.metrics.SparseCategoricalAccuracy(),
)

model.fit(tf_train_dataset, validation_data=tf_validation_dataset, epochs=3)

None of these work.

A: Maybe try using the TFBlenderbotForConditionalGeneration class for Tensorflow. It has what you need:
import tensorflow as tf
from transformers import BlenderbotTokenizer, TFBlenderbotForConditionalGeneration

mname = "facebook/blenderbot-400M-distill"
model = TFBlenderbotForConditionalGeneration.from_pretrained(mname)
tokenizer = BlenderbotTokenizer.from_pretrained(mname)

model.compile(
    optimizer=tf.keras.optimizers.Adam(learning_rate=5e-5),
    loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
    metrics=tf.metrics.SparseCategoricalAccuracy(),
)
....

See the docs for more information.


text:
Q: Java NullPointerException with truncated stacktrace I am getting following failure for my RabbitMQ listner.
I use Spring Boot 1.4.1  with Spring integration 4.3.3 (with spring-boot-starter-amqp and spring-integration-amqp). I also use RabbitMQ 3.5.7.
Issue occurs for small number of messages, randomly under significant traffic (non luck reproducing it sofar locally).
What puzzles me is the fact that stack trace does not point to my application, just to frameworks. Below I attach full stacktrace. Is it bug in spring, rabbitMQ driver or server?
2017-05-02 10:38:42.337 [501de2ff-cd24-4c28-8434-48bc942457d9]  WARN 1 --- [messageListenerContainer-2] s.a.r.l.ConditionalRejectingErrorHandler : Execution of Rabbit message listener failed.

org.springframework.amqp.rabbit.listener.exception.ListenerExecutionFailedException: Listener threw exception
        at org.springframework.amqp.rabbit.listener.AbstractMessageListenerContainer.wrapToListenerExecutionFailedExceptionIfNeeded(AbstractMessageListenerContainer.java:870)
        at org.springframework.amqp.rabbit.listener.AbstractMessageListenerContainer.doInvokeListener(AbstractMessageListenerContainer.java:780)
        at org.springframework.amqp.rabbit.listener.AbstractMessageListenerContainer.invokeListener(AbstractMessageListenerContainer.java:700)
        at org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer.access$001(SimpleMessageListenerContainer.java:95)
        at org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer$1.invokeListener(SimpleMessageListenerContainer.java:187)
        at org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer.invokeListener(SimpleMessageListenerContainer.java:1187)
        at org.springframework.amqp.rabbit.listener.AbstractMessageListenerContainer.executeListener(AbstractMessageListenerContainer.java:681)
        at org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer.doReceiveAndExecute(SimpleMessageListenerContainer.java:1165)
        at org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer.receiveAndExecute(SimpleMessageListenerContainer.java:1149)
        at org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer.access$1100(SimpleMessageListenerContainer.java:95)
        at org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer$AsyncMessageProcessingConsumer.run(SimpleMessageListenerContainer.java:1312)
        at java.lang.Thread.run(Thread.java:745)
Caused by: org.springframework.messaging.MessageHandlingException: nested exception is java.lang.NullPointerException
        at org.springframework.integration.handler.MethodInvokingMessageProcessor.processMessage(MethodInvokingMessageProcessor.java:96)
        at org.springframework.integration.handler.ServiceActivatingHandler.handleRequestMessage(ServiceActivatingHandler.java:89)
        at org.springframework.integration.handler.AbstractReplyProducingMessageHandler.handleMessageInternal(AbstractReplyProducingMessageHandler.java:109)
        at org.springframework.integration.handler.AbstractMessageHandler.handleMessage(AbstractMessageHandler.java:127)
        at org.springframework.integration.dispatcher.AbstractDispatcher.tryOptimizedDispatch(AbstractDispatcher.java:116)
        at org.springframework.integration.dispatcher.UnicastingDispatcher.doDispatch(UnicastingDispatcher.java:148)
        at org.springframework.integration.dispatcher.UnicastingDispatcher.dispatch(UnicastingDispatcher.java:121)
        at org.springframework.integration.channel.AbstractSubscribableChannel.doSend(AbstractSubscribableChannel.java:77)
        at org.springframework.integration.channel.AbstractMessageChannel.send(AbstractMessageChannel.java:423)
        at org.springframework.integration.channel.AbstractMessageChannel.send(AbstractMessageChannel.java:373)
        at org.springframework.messaging.core.GenericMessagingTemplate.doSend(GenericMessagingTemplate.java:115)
        at org.springframework.messaging.core.GenericMessagingTemplate.doSend(GenericMessagingTemplate.java:45)
        at org.springframework.messaging.core.AbstractMessageSendingTemplate.send(AbstractMessageSendingTemplate.java:105)
        at org.springframework.integration.handler.AbstractMessageProducingHandler.sendOutput(AbstractMessageProducingHandler.java:292)
        at org.springframework.integration.handler.AbstractMessageProducingHandler.produceOutput(AbstractMessageProducingHandler.java:212)
        at org.springframework.integration.handler.AbstractMessageProducingHandler.sendOutputs(AbstractMessageProducingHandler.java:129)
        at org.springframework.integration.handler.AbstractReplyProducingMessageHandler.handleMessageInternal(AbstractReplyProducingMessageHandler.java:115)
        at org.springframework.integration.handler.AbstractMessageHandler.handleMessage(AbstractMessageHandler.java:127)
        at org.springframework.integration.dispatcher.AbstractDispatcher.tryOptimizedDispatch(AbstractDispatcher.java:116)
        at org.springframework.integration.dispatcher.UnicastingDispatcher.doDispatch(UnicastingDispatcher.java:148)
        at org.springframework.integration.dispatcher.UnicastingDispatcher.dispatch(UnicastingDispatcher.java:121)
        at org.springframework.integration.channel.AbstractSubscribableChannel.doSend(AbstractSubscribableChannel.java:77)
        at org.springframework.integration.channel.AbstractMessageChannel.send(AbstractMessageChannel.java:423)
        at org.springframework.integration.channel.AbstractMessageChannel.send(AbstractMessageChannel.java:373)
        at org.springframework.messaging.core.GenericMessagingTemplate.doSend(GenericMessagingTemplate.java:115)
        at org.springframework.messaging.core.GenericMessagingTemplate.doSend(GenericMessagingTemplate.java:45)
        at org.springframework.messaging.core.AbstractMessageSendingTemplate.send(AbstractMessageSendingTemplate.java:105)
        at org.springframework.integration.endpoint.MessageProducerSupport.sendMessage(MessageProducerSupport.java:171)
        at org.springframework.integration.amqp.inbound.AmqpInboundChannelAdapter.access$400(AmqpInboundChannelAdapter.java:45)
        at org.springframework.integration.amqp.inbound.AmqpInboundChannelAdapter$1.onMessage(AmqpInboundChannelAdapter.java:95)
        at org.springframework.amqp.rabbit.listener.AbstractMessageListenerContainer.doInvokeListener(AbstractMessageListenerContainer.java:777)
        ... 10 common frames omitted
Caused by: java.lang.NullPointerException: null

A: After long investigation it turned out there is nothing wrong with Spring or rabbitMQ.  Root cause was in my own code.
Log attached to question has complete stacktrace, but java truncates stacktraces!
Java 1.5.0 introduced flag OmitStackTraceInFastThrow, enabled by default. This is performance optimization. It removes common part of stacktraces from exceptions.
In my case, I had full stacktrace for first 130 occurences of this exception. Further occurences had stacktrace truncated. Easiest way to get full stacktrace was to restart  the application.
See http://jawspeak.com/2010/05/26/hotspot-caused-exceptions-to-lose-their-stack-traces-in-production-and-the-fix/ for details.


text:
Q: Show that $T : [0,\sqrt{3} + \sqrt{5} + \sqrt{7}] \to [0,\sqrt{3} + \sqrt{5} + \sqrt{7}] $ is mixing. Is this shuffling map on the unit interval mixing ?
$$ f(x)  = \left\{
\begin{array}{ccl}
x + (\sqrt{5} + \sqrt{7}) & \text{ if } & 0 < x < \sqrt{3} \\
x + (\sqrt{7} - \sqrt{3}) & \text{ if } & \sqrt{3} < x < \sqrt{3} + \sqrt{5} \\
x - (\sqrt{3}+\sqrt{5}) & \text{ if } & \sqrt{3} + \sqrt{5} < x < \sqrt{3} + \sqrt{5} + \sqrt{7}\\
\end{array} \right. $$
Here $f : [0, \sqrt{3}+\sqrt{5}+ \sqrt{7}] \to [0, \sqrt{3}+\sqrt{5}+ \sqrt{7}] $ yet we could rescale so to be map $f: [0,1] \to [0,1]$.

*

*this is a 1-1 map

*this exchanges the permutations in the interval $\pi = (3,2,1)$.

*it's called an interval exchange map.

Such a map is very likely to be ergodic and weak-mixing. Let's review those definitions.

*

*for every measurable set $A \in \mathcal{B}$ we have $T^{-1}(A) \subset A$ implies either $\mu(A) = 0$ or $\mu(A) = 1$.

*strong mixing $\displaystyle \lim_{n \to \infty} \mu(A \cap T^{-n}B) = \mu(A) \cdot \mu(B)  $ so the two sets $A$ and $B$ are eventually "independent".

*weak-mixing $\displaystyle \lim_{n \to \infty} \frac{1}{n} \left| \sum_{k=0}^{n-1} \mu(A \cap T^{-k}B) - \mu(A)\mu(B) \right|= 0 $ so the "average" over all the over lap with the pre-images should be independent.
Maybe one could show that the invariant measure of the interval exchange map, is just Lebesgue measure (which served as a replacement for the Riemann integration).  We are guessing as much.
Then one could ask what the strong mixing and weak-mixing statements should represent here.  What number theory problem could be represented there?

Here is the image after $n = 10^5$ iterations.  So we have $\big\{ (x, T^n (x)) :  x = \frac{m}{10^5} \text{ and }0 < m < 10^5 \big\}$.

This looks like it might be mixing.  Here is after a million ($n = 10^6$) iteratios.

There's no formula for the quantative mixing of exchange maps.


text:
Q: How to include all the contents of a file in the  using XSLT? I want to have a separate file that holds some javascript functions. When XSLT processes my application, i want it to output all the contents of this file to the HTML. I do not want to reference a library, but instead have all the functions inside inside my html.
I know of <xsl:include> but i cannot include anything inside  or <body> tags.
Is this possible?

A: Well assuming your file (e.g. scripts.xml) to be included is XML e.g. has a contents like
<script type="text/javascript">
function foo() { ... }
function bar() { ... }
...
</script>

then in XSLT you can simply use
<xsl:template match="/">
  <html>
    <body>
      <xsl:copy-of select="document('scripts.xml')/script"/>
    </body>
  </html>
</xsl:template>

If that does not help then you need to explain in more details what kind of file you have, which XSLT version you use (XSLT 2.0 can also read in non-XML  plain text files like Javascript code).
[edit]
Here is an XSLT 2.0 sample using unparsed-text (requires an XSLT 2.0 processor like Saxon or AltovaXML):
<xsl:template match="/">
  <html>
    <body>
      <script type="text/javascript">
         <xsl:value-of select="unparsed-text('file.js')"/>
      </script>

    </body>
  </html>
</xsl:template>

A: Use the unparsed-text() function to read the content of a text file.
<xsl:stylesheet version="2.0"
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output omit-xml-declaration="yes" indent="yes"/>

 <xsl:template match="/">
     <html>
      <body>
        <xsl:sequence select="unparsed-text('YourFile.js')"/>
      </body>
     </html>
 </xsl:template>
</xsl:stylesheet>


text:
Q: How to use reflection to invoke a private field without using "setAccesible()" I've encountered this problem multiple times.
The problem:
I have some class with private Fields (For example User information which is a Dto):
public class RegisterRequest {
    private String firstName;
    private String lastName;
    private String username;
    private String email;
    private String fieldOfStudy;
    private String password;
}

After searching the community on how to read the values of these fields (when for example doing a post request), I saw a lot of answers that said the solution is Reflection.
Lets say I want to check if any field is null (in another class), then my reflection-method would be the following:
for (Field f : registerRequest.getClass().getDeclaredFields()) {
    try {
        Field field = registerRequest.getClass().getDeclaredField(f.getName());
        field.setAccessible(true);
        Object value = field.get(registerRequest);
        if (value == null) {
            throw new AccountException("Vul alle velden in.");
        }
    }
    catch (NoSuchFieldException | IllegalAccessException e) {
        e.printStackTrace();
    }
}

Now I'm wondering if there is a way to do this without using field.setAccesible(true), Since bypassing the accessibility of fields could lead to run-time errors. I.e. We shouldn't use reflection to change the visibility of a field.
Thank you for your time!

A: Do the validity check in the class that contains the private Data:
public boolean isValidForm() {
    for (Field field : this.getClass().getDeclaredFields()) {
        try {
            if (field.get(this) == null) {
                return false;
            }
        } catch (IllegalAccessException e) {
            throw new AccountException("Something went wrong");
        }
    }
    return true;
}

Use this function in your other class by doing:
if(!registerRequest.isValidForm) {
   throw new AccountException("...")
}

Credits to Geocodezip

A: Maybe there's something I didn't undertsand in your post but I don't think you should use reflection to do validation on your DTO. Here's a solution on how you could handle validation using javax:
@Data
@Value
class RegisterRequest {
    @NotNull(message = "First name should not be null")
    String firstName;
    @NotNull(message = "Last name should not be null")
    String lastName;
    @NotNull(message = "Username should not be null")
    String username;
    @NotNull(message = "Email should not be null")
    String email;
    @NotNull(message = "Field of study should not be null")
    String fieldOfStudy;
    @NotNull(message = "Password should not be null")
    String password;
}

If you use java17+ you can use a record like this (and get rid of lombok):
public record RegisterRequest(
        @NotNull(message = "First name should not be null")
        String firstName,
        @NotNull(message = "Last name should not be null")
        String lastName,
        @NotNull(message = "Username should not be null")
        String username,
        @NotNull(message = "Email should not be null")
        String email,
        @NotNull(message = "Field of study should not be null")
        String fieldOfStudy,
        @NotNull(message = "Password should not be null")
        String password
) {
}

Then you can make a unit test on your validation like this:
class RegisterRequestTest {

    private Validator validator;

    @BeforeEach
    public void setUp() {
        try (ValidatorFactory factory = Validation.buildDefaultValidatorFactory()) {
            validator = factory.getValidator();
        }
    }

    @ParameterizedTest
    @MethodSource("invalidRegisterRequest")
    void validation_should_be_invalid(RegisterRequest registerRequest) {
        assertThat(validator.validate(registerRequest)).isNotEmpty();
    }

    private static List<RegisterRequest> invalidRegisterRequest() {
        return List.of(
                new RegisterRequest(null, "lasstname", "username", "email", "fieldOfStudy", "password"),
                new RegisterRequest("firstName", null, "username", "email", "fieldOfStudy", "password"),
                new RegisterRequest("firstName", "lasstname", null, "email", "fieldOfStudy", "password"),
                new RegisterRequest("firstName", "lasstname", "username", null, "fieldOfStudy", "password"),
                new RegisterRequest("firstName", "lasstname", "username", "email", null, "password"),
                new RegisterRequest("firstName", "lasstname", "username", "email", "fieldOfStudy", null)
        );
    }

}

In my examples I used @NotNull like in your post but I would recommand to use @NotBlank because in addition to checking for nullity, it checks if the property contains at least one non-blank character.


text:
Q: Collapsing rows with consecutive ranges in two separate columns I would very much appreciate your help on this one. I'm trying to condense a data frame of 200,000+ rows, where the integer of one row in column "start" is the exact to the next consecutive row in column "end". For reference, these are chromosomal base pair positions, and an example code below:
genomic_ranges <- data.frame(sample_ID = c("A", "B", "B", "B", "C"),
                         start = c(1, 20, 30, 40, 250),
                         end =  c(5, 30, 40, 70, 400),
                         feature = c("normal", "DUP", "DUP", "DUP", "DUP"))

sample_ID start end feature
1         A     1   5  "normal"
2         B    20  30     "DUP"
3         B    30  40     "DUP"
4         B    40  70     "DUP"
5         C   250 400     "DUP"

I have tried logical vectors, boolean operators, ifelse statements, forloops etc, I can't find a way to 1)delete the rows showing middle ranges, and 2)paste together the 1st and last rows which contain the true start and end position of the range.
Some of what I've tried:
ifelse(cnv_catalogue_final$end == cnv_catalogue_final$start, "to_delete", "other"))
cnv_catalogue_final$end %in% cnv_catalogue_final$start
dplyr::filter(slice_min(start, x) | slice_max(end, x))

Even if I use something like this (StartA <= EndB)  and  (EndA >= StartB) I'll still be loosing either the start or end position.
*Edit: thank you all for your feedback! I've updated the question with code. These rows do have ID's identified by sample_ID. Ideally, I would like 1 row with the complete range of 20-70, instead of it being cut into segments of 20-30, 30-40, and 40-70, in 3 rows with the same sample_ID identifier.

A: There are several ways to achieve this, here is one:
library(tidyverse)
genomic_ranges %>%
  group_by(sample_ID) %>%
  summarize(start = min(start),
            end = max(end),
            feature = feature[1])

which gives:
# A tibble: 3 x 4
  sample_ID start   end feature
  <chr>     <dbl> <dbl> <chr>
1 A             1     5 normal
2 B            20    70 DUP
3 C           250   400 DUP

A: After much searching, trial/error, and chatting with colleagues, I've found another way to collapse ranges, and per usual its a much simple solution that I expected. I simply used valr package's bed_merge() function.
This is specific for genomic ranges (bed_merge() needs chromosome numbers - built in specificity yay!), and is particularly helpful when the only unique identifier between samples is the range. Grouping by sample_ID is still necessary because ranges can overlap between samples. Only down side is that this function doesn't preserve any additional data in your df, so a key would be useful to make to merge your metadata and ranges.
Here is an example:
library(tidyverse)
library(valr)
df <- data.frame(sample_ID = c("A", "B", "B", "B", "B", "B", "B", "B", "C", "C"),
                 chrom = c(1, 1, 1, 1, 1, 1, 1, 1, 1, 1),
                 start = c(1, 20, 30, 40, 70, 90, 100, 110, 130, 250),
                 end =  c(5, 30, 40, 70, 80, 100, 110, 130, 150, 400),
                 feature = c("normal", "DUP", "DUP", "DUP", "DUP", "DUP", "DUP", "DUP", "DUP", "DUP"))

> df
   sample_ID chrom start end feature
1          A     1     1   5  normal
2          B     1    20  30     DUP
3          B     1    30  40     DUP
4          B     1    40  70     DUP
5          B     1    70  80     DUP
6          B     1    90 100     DUP
7          B     1   100 110     DUP
8          B     1   110 130     DUP
9          C     1   130 150     DUP
10         C     1   250 400     DUP

collapsed_df <- df %>%
  group_by(sample_ID) %>%
  bed_merge()

> collapsed_df
# A tibble: 5 × 4
# Groups:   sample_ID [3]
  sample_ID chrom start   end
  <chr>     <dbl> <int> <int>
1 A             1     1     5
2 B             1    20    80
3 B             1    90   130
4 C             1   130   150
5 C             1   250   400


text:
Q: Using "Show detail" segue to replace detail view controller in spilt view controller I am using a Universal storyboard with adaptive segues to build my interface. I have a UISplitViewController with a UITableViewController set as the master view controller. I am using this table to present two different types of information, so when the user taps on a cell I need to figure out what cell they tapped in order to display one of two different view controllers as appropriate for the selected cell. I have the relationship set up in Storyboard to have the detail view controller be the first of the two view controllers, which is fine since I render UI overtop anyways until they tap a cell. I discovered I can create a segue from the table view controller to my other view controller that should be displayed when an appropriate cell is tapped - this is a "Show detail (e.g. Replace)" segue. I gave it an identifier and I simply call [self performSegueWithIdentifier:ReplaceDetailSegueIdentifier sender:self]; when an appropriate row is selected to go ahead and replace the existing view controller in the detail with the correct view controller. This works great when I select a cell that should show the second view controller. It properly replaces the first detail view controller with the second view controller. So then I set up another segue that will be performed when the user then taps a row that should show the original first view controller. But when that occurs, the app crashes at the line where the segue is performed (but no info is logged to Console - just states EXC_BAD_ACCESS).
So it seems once you have performed a Show detail segue once, subsequent calls to replace the detail view controller crash the app. This is also true if I select a row that replaces the original detail controller with the second view controller and then I select another row that should show that same second view controller - the app crashes.
How would I set it up so that it will properly show the appropriate detail view controller based on the cell they have selected, ensuring the app does not crash?

A: I discovered the crash is caused by deallocating the detail view controller which is the UISplitViewControllerDelegate, so the master is referencing an object that doesn't exist. The solution is to set the delegate to the new view controller that will be presented (or nil if it doesn't conform to UISplitViewControllerDelegate). Now it works without issue.

A: You should hook the segue up to the cell selection as normal, then you can determine which cell was selected in the prepareForSegue as follows:
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    if ([[segue identifier] isEqualToString:@"showDetail"]) {
        NSIndexPath *indexPath = [self.tableView indexPathForSelectedRow];
        ...


text:
Q: Usage of dispatch group inside another group Needed some advice/review on possible downsides of using a dispatch group inside another group, if it could lead to a race condition/deadlock or just wrong practice.
1) Can a dispatch_group_enter exist inside the scope of another group? I could not find an example from Apple following such practice. Remember, secondCall needs to happen after firstCall. There is a dependency. Thoughts?
2) What would be a good design to execute a thirdCall - which again depends on result of firstCall result. But agnostic of the completionHandler timing i.e. can happen later and doesn't need to wait for completionHandler to finish.
Here's a simplified example of the completion handler incorporating 3 calls -
-(void)someMethod:(void (^)(NSError *error))completionHandler {

    dispatch_group_t serviceGroup = dispatch_group_create();

    dispatch_group_enter(serviceGroup);
    __typeof__(self) __weak weakSelf = self;
    [self.obj firstCall completion:^(NSError *firstError) {
        __typeof__(self) strongSelf = weakSelf;

        // Second Call
        if (!firstError.code) {
            dispatch_group_enter(serviceGroup);
            [strongSelf.obj secondCall completion:^(void) {
                dispatch_group_leave(serviceGroup);
            }];
        }

        // Third call
        if (!firstError.code) {
            [strongSelf executeThirdCall];
        }

        dispatch_group_leave(serviceGroup);
    }]; // Closing block for first call.

    dispatch_group_notify(serviceGroup, dispatch_get_main_queue(), ^{
        if (completionHandler) {
            completionHandler(error);
        }
    });
}

Some classic examples of dispatch groups can be found in this answer.

A: I can't think of any issues with this code.
However I am not sure you need dispatch groups at all for this example.
You are executing three requests. Request 2 and Request 3 both depend on the result of the Request 1. You need to call the function's completionHandler when Request 2 is finished. Can't you do it into the completion handler of Request 2?


text: Q: Is there a way to view IP addresses that have been assigned, historically, to a single Windows XP workstation? For example, if a laptop had an IP address of a.b.c.d during period x and then an IP address of a.b.c.e during period y, would it be possible to see both of these addresses in a list somewhere (perhaps in the registry)?


text:
Q: NodeJS Lambda function returns null while still waiting for callback Problem: I have a Lambda function written in NodeJS, simplified version below, which is meant to make a post to a specific URL to get a value in the body of the response. Then I'd like it to do something with that value in functionB, however, the function returns null while waiting for the callback from functionA.
Also, I'm new to NodeJS but I have tried to research this as much as I could before turning to you guys for help, if you find a question that this is a duplicate of, please direct me towards it with a little guidance as I may have come across it before without knowing why it's the same as my problem. Any help is greatly appreciated!
var XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;

exports.handler = (event, context, callback) => {
  functionA(event.payload, function(err, data) {
    if(data) {
      console.log(data);
      valueB = data;

      functionB(valueB, function(err, data) {
        if(err) {
          console.error('Unknown Error');
        } else {
          console.log(data);
          callback(null, successMessage);
        }
      });
    } else {
      console.error('Unknown Error');
    }
  });
}

function functionA(payload, callback) {
  var xmlhttp = new XMLHttpRequest();
  var result;

  // new HttpRequest instance, in the real code storedURL has been set
  xmlhttp.open("POST", storedURL, true);
  console.info("Linking to: ", storedURL);

  xmlhttp.onload = function () {
    console.log('Entering onload function');
    if (xmlhttp.readyState === xmlhttp.DONE) {
      console.log('readyState done');
      if (xmlhttp.status === 200) {
        console.log('status 200');
       // console.log(xmlhttp.responseText);
        var data = xmlhttp.responseText;
        //console.log(data);
        callback(null, data);
      } else {
        console.log('error');
        console.log(xmlhttp.response);
        callback("error in callback");
      }
    } else {
      console.log('error');
    }
  };

  xmlhttp.send(payload);
}

function functionB(valueB, callback) {
  //Do something with valueB
  callback(null, successMessage);
}


text:
Q: Not autorized to execute any command using Service Connector on MongoDB I am using the MongoDB on my app and when I try to access the database directly using the service connector, I am able to connect but then I am getting :
Error: error: {
    "ok" : 0,
    "errmsg" : "not authorized on admin to execute command { *any command*}",
    "code" : 13
}

and this on any query or command.
Is there a way to change authorization or accessing the data of my MongoDB
P.S: My MongoDB was bind as in the tutorial: https://docs.developer.swisscom.com/tutorial-python/bind-service.html

A: It looks like you're trying to execute commands on the admin database on which your user is not authorized. You can find the correct database which your user is authorized on in the credentials (key mongodb.credentials.database) but ideally you connect using the provided URI (mongodb.credentials.uri) which will connect you to the correct database automatically.
You can have a look at the Python example in the tutorial you linked to find out how to access and use those credentials correctly.

A: The answer from Sandro Mathys is correct and helpful, I wish to clarify/simplyfy a little bit.
The service broker grants you the Role dbOwner and creates a database with random name for you. This is done during cf create-service process.

The database owner can perform any administrative action on the
  database. This role combines the privileges granted by the readWrite,
  dbAdmin and userAdmin roles.

You have no privileges on admin database. The admin database is only for Swisscom operators. Please use for login with mongo shell the parameter --authenticationDatabase with the random database name from cf env.

Specifies the database in which the user is created. See Authentication Database.
If you do not specify a value for --authenticationDatabase, mongo uses the database specified in the connection string.


text:
Q: How to integrate grails 2 with angular 4 or 5? I have a Grails 2.3.9 project using completely the GSP nechanims defined by the Grails Framework.
Now, I need to convert this to a Grails (REST) + Angular (4 or 5) project. Also I need all the resources to be in the same project, not in two separated projects running independently, the main problem here is that I don't find anywhere a way to integrate Angular 5 with Grails 2, all I see on the web and forums is Grails 2 + AngularJS or the new Grails 3 Angular profile, but i can't use those options.
To resume, how can i integrate Angular (4 or 5) with Grails 2, not two separated projects running independently?
Thanks in advance.


text:
Q: NoClassDefFound : Scala/xml/metadata I'm running a simple spark program in Java (IDE : Eclipse Luna, Maven).
My Sample program is
import org.apache.spark.SparkConf;
import org.apache.spark.api.java.JavaSparkContext;

public class testSpark {
    public static void main(String[] args) {
        SparkConf conf = new SparkConf().setAppName("Testing").setMaster("local");
        JavaSparkContext sc = new JavaSparkContext(conf);

        System.out.println(sc.appName());
    }
}

But I'm getting error while running my sample program
Exception in thread "main" java.lang.NoClassDefFoundError:
scala/xml/MetaData  at
  org.apache.spark.ui.jobs.JobsTab.<init>(JobsTab.scala:30)     at
  org.apache.spark.ui.SparkUI.initialize(SparkUI.scala:50)  at
  org.apache.spark.ui.SparkUI.<init>(SparkUI.scala:61)  at
  iScope.testSpark.main(testSpark.java:9)

Caused by:
  java.lang.ClassNotFoundException: scala.xml.MetaData  at
  java.net.URLClassLoader.findClass(Unknown Source)     at
  java.lang.ClassLoader.loadClass(Unknown Source)

My pom.xml file is
<dependency>
    <groupId>org.apache.spark</groupId>
    <artifactId>spark-core_2.11</artifactId>
    <version>1.2.1</version>
</dependency>
<dependency>
    <groupId>com.google.guava</groupId>
    <artifactId>guava</artifactId>
    <version>18.0</version>
    </dependency>
<dependency>
    <groupId>org.apache.spark</groupId>
    <artifactId>spark-mllib_2.11</artifactId>
    <version>1.2.1</version>
</dependency>

A: Adding the following dependency fixed the issue for me.
<dependency>
    <groupId>org.scala-lang.modules</groupId>
    <artifactId>scala-xml_2.11</artifactId>
    <version>1.0.6</version>
</dependency>

A: As your exception's stack trace clearly states, the problem happens when SparkUI tries to build up the Jobs Tab. For that to happen, the JobsTab class (org.apache.spark.ui.jobs.JobsTab) tries to create a page (org.apache.spark.ui.jobs.JobPage) and attach it to itself. If you look into the JobPage source code you will note that it makes heavy use of scala.xml (The Standard Scala XML Library), which you are probably missing.
As already pointed out by other contributors, adding the scala.xml library to the list of your dependencies should fix the problem. At the time of writing, the latest version is 1.2.0 for Scala 2.13 (you can check the Maven repository for updates), hence:
Maven:
<dependency>
    <groupId>org.scala-lang.modules</groupId>
    <artifactId>scala-xml_2.13</artifactId>
    <version>1.2.0</version>
</dependency>

Gradle:
compile group: 'org.scala-lang.modules', name: 'scala-xml_2.13', version: '1.2.0'

SBT:
libraryDependencies += "org.scala-lang.modules" %% "scala-xml" % "1.2.0"

A: SparkUI seems to use a scala package, try adding this dsependency to your pom file to put the scala.xml package on your classpath.
<dependency>
    <groupId>org.scala-lang</groupId>
    <artifactId>scala-xml</artifactId>
    <version>2.11.0-M4</version>
</dependency>

A: you need to add the class or .jar file which contains this class into the java classpath.


text:
Q: Segues won't work after adding new navigation controller and root controller I just inherited a project that uses a Storyboard + nibs.
The Storyboard had a navigation controller set as the initial view controller, and then had the first view controller set as its root. Very simple.
I decided to create a new view controller and make that the new root controller. I still have the old root view controller, its just not the root anymore. So for speed, I deleted the navigation controller, selected my new root view controller, and embedded it inside of a navigation controller.
Worked perfectly. Here's what I don't understand...
My setup looks identical to what was there before, but I had to add the following to the app delegate:
  LaunchController *launch = [[LaunchController alloc] initWithNibName:@"LaunchController" bundle:nil];
  UINavigationController *navigation = [[UINavigationController alloc] initWithRootViewController:launch];

  self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
  [self.window setRootViewController:navigation];
  self.window.backgroundColor = [UIColor whiteColor];
  [self.window makeKeyAndVisible];

Why did I have to add this, but the previous version didn't need it, even though I feel like the changes I made still kept the setup identical to what I had before?
Throughout the app, performSegueWithIdentifier is being called and now those always fail and say "Receiver has no segue with identifier."
If I remove the above code from the app delegate, then my root controller that's both a nib and on the Storyboard doesn't show on screen. It loads, but you can't see anything. However, now all of my segues work.
So what's going on here? I realize I probably screwed something up when creating a new navigation controller and root view controller, but I can't figure this out.
I have been spending some more time working with nibs, and I've been adding the above app delegate code, so I really don't even understand how the previous developer was making this work in the first place without that code in the app delegate.
Any help is greatly appreciated.

A: If you're using storyboard then you don't have to write any code in App Delegate class. Instead you mention your storyboard like Project file -> Targets -> General -> Deployment Info -> Main Interface.
 Here you see Main_iPhone is my storyboard for the project. Now any View Controller inside that storyboard which is set as "Is Initial View controller" will be loaded by the app automatically for you.


text:
Q: How to dynamically add an input field I want to add dynamically input fields. Like

Is there a good component in PF on how to add such a component?
Pls give me a hint on how you would develop it, cause I have no clue at the moment.
I really appreciate your answer.
My technology stack:

*

*Hibernate: 4.0.1.Final

*Spring: 3.1.1.RELEASE

*Primefaces: 3.5

*jsf-version: 2.2.0-m08

*PrimefacesMobile-version: 0.9.3

*Apache Tomcat/7.0.12

A: Maybe the following piece of code can help you out, I'm afraid there's not a component for this (at least to my knowledge):
HTML
<h:form>
    <ui:repeat value=#{bean.values}
               var="value">
        <h:inputText value="#{value}" />
        <br />
    </ui:repeat>

    <h:commandButton value="Extend">
        <f:ajax listener="#{bean.extend}"
                process="@form"
                render="@form" />
    </h:commandButton>
    <h:commandButton action="#{bean.submit}"
                     value="Save" />
</h:form>

BEAN
@ManagedBean
@ViewScoped
public class Bean {
    private List<String> values;

    @PostConstruct
    public void init() {
        values = new ArrayList();
        values.add("");
    }

    public void submit() {
        // save values in database
    }

    public void extend() {
        values.add("");
    }

    public void setValues(List<String> values) {
        this.values = values;
    }

    public List<String> getValues() {
        return values;
    }
}


text:
Q: Camel ftp get file from ftp location on demand Hi I have a scenario where I get notified through a soap service call to pick file from an remote ftp location.The ftp server details would be same but the folder name and file will be sent dynamically,
How can i implement it using apache camel.?
Any suggestions or thoughts might be helpful.

A: I think you should use headers for that. So, you will load your dynamic information into headers and use them in the ftp component with toD.
So you can have something like the following
<toD uri="sftp:username:password@ftp.server.com/${header.CamelFolder}?fileName=${header.CamelDownloadFile}"/>

But since you want to get from an FTP in the middle of the route you can try Content Enricher EIP
<route>
  <from uri="..."/>
  <!-- set your dynamic values as headers -->
  <setHeader headerName="CamelFolder">
     <simple>...</simple>
  </setHeader>
  <setHeader headerName="CamelDownloadFile">
     <simple>...</simple>
  </setHeader>

  <pollEnrich>
    <simple>sftp:username:password@ftp.server.com/${header.CamelFolder}?fileName=${header.CamelDownloadFile}</simple>
  </pollEnrich>
  ...
</route>


text:
Q: Trying to find an $\arctan(x/y)$ identity. I have this equation :
$$\theta = \arctan\left(\tfrac xd\right) + \arctan\left(\tfrac yd\right).$$
$\theta$ is an angle and I am trying to express $d$ as a function of $\theta$.
So is there a way to extract $d$ from the equation in the two $\arctan$s above ?
This is a pure math question this is why I don't post an image of the geometry.
Thank you.

A: Note that
$$
\theta = \arctan(x/d) + \arctan(y/d) \\
\tan(\theta) = \tan(\arctan(x/d) + \arctan(y/d)) \\
\tan \theta = \frac{x/d + y/d}{1 - (\frac{xy}{d^2})}\\
\tan \theta = d\frac{x+y}{d^2-xy}\\
\tan \theta(d^2 - xy) = d(x+y)\\
(\tan \theta)d^2 - (x+y)d -xy\tan \theta = 0
$$
From there, apply the quadratic formula:
$$
d = \frac{x+y\pm \sqrt{(x+y)^2 + 4xy\tan^2 \theta}}{2\tan \theta}
$$


text:
Q: Dynamic values in a Lex custom slot I'm trying to create an intent for my app with a custom slot for a 'category' in Amazon Lex. Is there a way to hook-up the slot values to a GET request that fetches the categories from my database?

A: I think you should give few samples for the slot values in the Lex console, then after the user enter some category you can validate in the backend using GET requests by matching.


text:
Q: Error while running .Net 1.1 Application in visual studio I get the following message when I try to run a .net 1.1 web application in Visual Studio 2003:

Error while trying to run project.Unable to start debugging on the web server. There is no managed code running in the process. In order to attach a process with the .Net debugger, managed code must be running in the process before attaching.

Can any body tell what I am missing here.
FYI : The application is working fine on the live server.

A: Have you tried the following?

*

*Right click the ASP.Net project > Properties

*select Configuration Properties > Debugging

*Enable the below mentioned entries in 'Debuggers' frame.

*

*ASP.Net Debugging

*Unmanaged code debugging.

Check this link, as well.


text:
Q: why pushState() does not work for clean URLs? I have two kind of URL:

*

*arguments URL like www.example.com/page.php?test=argument

*parameters URL (clean URLs) like www.example.com/classname/methodname/arg1/arg2
Now I need to use of pushState(); for replacing a new URL. For arguments URL it works as well, But the problem is for parameters URL.
Here is my code:
var db    =  'database';
var word  =  'hello';
window.history.pushState("object", "title", "page.php?s="+db+"&q="+word);

output for arguments URL: (this is fine)
www.example.com/page.php?test=argument                                  // Current URL
www.example.com/page.php?s=database&q=hello                             // New URL

output for parameters URL:
www.example.com/classname/methodname/arg1/arg2                          //Current URL
www.example.com/classname/methodname/arg1/page.php?s=database&q=hello   // New URL

While I want this: (for both arguments and parameters URL)
www.example.com/page.php?s=database&q=hello

How can I fix it for parameters URL ? In other word, Is it possible to I remove all parameters before pushing ? (removing current parameters before appending)

A: I assume that pushState is honoring the cwd (current working directory).  try prepending a leading slash /, so:
window.history.pushState("object", "title", "/page.php?s="+db+"&q="+word);


text:
Q: What's the best way to checkout selected files and folders from a bare git repository on linux? I'm setting up a git repository for a website on a GoDaddy shared hosting account. Normally one would set up a git bare repo on the server that contained the live web data only, then on a push to the remote use a git post-receive hook to checkout to the live directory (thanks to @VonC for the links).
That's fine, but I've set up the repository to include work files as well. On the server I have,

/home/username/repo.git/work_folders, and /home/username/repo/web_files_and_folders

for the repository, and,

/home/username/public_html/web_files_and_folders

for the live files and folders.
The work_folders usually contain svg, png and jpg files used to generate the png and jpg files for the website. These are master files which are part of the development of the website.
The thing is I can't find an easy way to get git to checkout the web_files_and_folders only to live from any given branch. I could use the shell to wildcard select the web_files_and_folders but that doesn't solve knowing the branch name (which could change of course with each branch).
Do I need to merge to master (for instance) and then do the shell wildcard in the post-receive hook? If so, that may be a problem for other less tech savy people I'm trying to get to use the repo.
EDIT -------------------
So, to update. From a terminal shell I entered,
GIT_WORK_TREE=/home/user/public_html/dev git checkout -f dev devpath/web/*

which extracted the right files from the web folder but rather than getting,
/home/user/public_html/dev/*

I got,
/home/user/public_html/dev/devpath/web/*

Evidently I'm missing something about how to change the extract path.
EDIT 2 -------------------
Ok, more detail...
I currently have a bare repo setup on a shared server at,
/home/user/repo.git

The local repository has 2 branches, dev and master, with a file format like,
/devpath/logos/
/devpath/photos/
...
/devpath/web/  (website root files and folders)

The idea is to develop in the dev branch, push to the server and test on the dev.url of the website, and when things are good merge the dev branch into the master, push to the server and go live. Currently 2 of us are developing the website.
The post-receive hook isn't completed yet but is similar to this one. My use is pretty much the same as this link except I want the remote repository to store the other development files. These files are part of the website development and need to be shared.
What you saw in my first edit was an attempt to checkout the dev branch to the dev test site. On the server this test site is a subdomain and is accessed as a folder under the public html root in the filesystem.
It looks to me like checking out with a wildcard selector,
GIT_WORK_TREE=/home/user/public_html/dev git checkout -f dev devpath/web/*

also puts the files under that same path prior to the wildcard. I need to be able to define a new default path.
I have Git 1.7.1 on the server.

A:
that doesn't solve knowing the branch name

Regarding that, a post-update hook can detect the branch being pushed.
See:

*

*"Separate Git Deployments on a Single Server"

*"how to process files on a branch in post-receive hook in git"

Something like:
#!/bin/bash

while read oldrev newrev ref
do
  branch=`echo $ref | cut -d/ -f3`

  if [ "master" == "$branch" ]; then
    ....

A: Solve this with plumbing:
GIT_WORK_TREE=deploy/path GIT_INDEX_FILE=manifest/path \
        git read-tree -um commit:web_files_and_folders


text:
Q: not able to get forecasting plot in tabset panel in flexdashboard using actionButton and eventReactive methods of shiny I have a dataframe (in R) containing the data which looks like this:
[https://github.com/imlemarque/Data/raw/main/Data.csv][1]

I am creating a flexdashboard in R and the code is as follows:
---
title: "Forecast"
output:
  flexdashboard::flex_dashboard:
    orientation: rows
    vertical_layout: fill
    theme:
      bg: '#FFFFFF'
      fg: '#2c3e50'
      primary: '#18bc9c'
runtime: shiny

---

```{r global, include=FALSE, warning=FALSE, message=FALSE}
# libraries
library(flexdashboard)
library(readr)
library(tidyverse)
library(ggridges)
library(shinydashboardPlus)
library(shiny)
library(dplyr)
library(lubridate)
library(tidyr)
library(padr)
library(shinythemes)
library(rio)
library(shinyjs)
library(forecast)

# pre-set the bw theme.
theme_set(theme_bw())

# convert to proper date
df$Date1 <- df$Date
df$Date <- as.Date(df$Date, format="%m/%d/%Y")

Var <- setdiff(names(select_if(df, is.numeric)), c("Date", "CovidPeriod"))

```

Forecasting {data-icon="fa-signal"}
=======================================================================

## Row {.sidebar data-width=280 data-padding=10}

```{r}
br()
selectInput("Series2", label = "Select Series:", choices = Var, multiple = FALSE, width = "98%")
checkboxInput("covid1", "Exclude covid period?", FALSE)
output$value1 <- renderText({ input$covid1 })
hr()

# Select option for confidence interval
selectInput(inputId = "conf_int", label = "Confidence Interval:",
            choice = c("99%" = "99", "95%" = "95", "80%" = "80"), multiple = FALSE, width = "98%")
hr()

sliderInput("Horiz", "Forecast Horizon:", min = 1, max = 52, value = 13)
sliderInput("HoldOut", "Holdout Period:", value = 52, min = 24, max = 104, step = 4 )
hr()

actionButton(inputId="goButton", "Start forecasting!", class = "btn-primary btn-lg")

df2 <- reactive({
        newdf <- df
        if(input$covid){
            newdf <- filter(df, CovidPeriod != 0)
        }
        newdf
})

```

Row {data-height=160}
-----------------------------------------------------------------------

### KPI1 {.value-box}

```{r}

renderValueBox({
valueBox(round(0.7457475, digits = 3), icon = "fa-check-square", caption = "Model Accuracy", color = "#95d7ae")
})

```

### KPI2  {.value-box}

```{r}

renderValueBox({
valueBox(round(0.34535435, digits = 3), icon = "fa-check-square", caption = "Misclassification rate", color = "primary")
})

```

### KPI3 {.value-box}

```{r}

renderValueBox({
valueBox(round(0.858656, digits = 3), icon = "fa-check-square", caption = "Recall", color = "primary")
})
```

Row {data-height=850}
-----------------------------------------------------------------------------

###

```{r}

# Create reactive Date Column in format YYYY-MM-DD
sliderValues2 <- reactive({

  df0 <- df2() %>% mutate(Year = as.integer(year(Date)),
                          Month = as.integer(month(Date)),
                          Day = as.integer(day(Date))
                          )
  df0$Date2 <- strftime(paste(df0$Year, df0$Month, df0$Day, sep="-"), "%Y-%m-%d")
  df0 %>% select(Date = "Date2", input$Series2)

  })

# Render data reactively as Table
ARIMA <- eventReactive(input$goButton, {

  if (nrow(sliderValues2())==0)
    return()

  sliderValues2()

})

tabsetPanel(type = "tabs",
            tabPanel("ARIMA", icon = icon("area-chart"), renderTable({ARIMA()}), value=1),
            tabPanel("ARIMA2", icon = icon("area-chart"), plotOutput("ARIMA2", width="100%", height="100%"), value=1),
            id = "timeSeriesTabs")

```

My problem is that I am not able to generate forecast using Arima model to show in the ARIMA2, nor I am able to generate final table that should be shown in ARIMA tab panel.
I am getting Error:
argument is of length zero

Could someone please help in:

*

*Run the fresh Arima model, on the data reactively gathered and when clicked on Go Button

*Getting ARIMA model plots in ARIMA tab?

*Model performance metrics in another tab (please create it)

A: Seems to work fine if you comment out the themes part:
---
title: "Forecast"
output:
  flexdashboard::flex_dashboard:
    #theme:
    #  bg: '#FFFFFF'
    #  fg: '#2C3E50'
    #  primary: '#18BC9C'
    orientation: rows
    vertical_layout: fill
runtime: shiny
---

```{r global, include=FALSE, warning=FALSE, message=FALSE}

# ...
# assign df to your structure to start with, i.e.,
# df <- structure(list(Date = c("1/1/2010", "1/8/2010", "1/15/2010",
#    "1/22/2010", "1/29/2010", "2/5/2010", "2/12/2010", "2/19/2010", ...
#     ...   ...   ...
#     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
#     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0))) #, class = "col_spec")

# sapply(df, length)
#   Date        Var1        Var2        Var3        Var4 CovidPeriod
#    592         554         543         482         592         448

df <- as.data.frame(lapply(df, function(x) x[1:448])) # make sure all the columns have same number of rows
# ...

```

with the following output:

You may try to investigate more on why themes part is not working by reinstalling bslib etc.,
remotes::install_github("rstudio/bslib")

For forecasting with ARIMA:
library(lubridate)
library(forecast)
start <- 1
end <- 105
n <- nrow(df)
npred <- 20
var <- 'Var1'
tsdata <- ts(df[,var], start=decimal_date(ymd(df$Date[start])), end=decimal_date(ymd(df$Date[end])), frequency=365/7)
fit <- auto.arima(tsdata) # automatically find best arima parameters
pred <- as.data.frame(forecast(fit, h=npred))
out1 <- df[c('Date',var)][start:end,]
out1$type <- 'train'
out2 <- df[c('Date',var)][(end+1):(end+npred),]
out2$type <- 'holdout'
out <- rbind(out1, out2)
for (col in c('Point Forecast', 'Lo 95', 'Hi 95')) {
  out3 <- out2
  out3[,var] <- pred[col]
  out3$type <- col
  out <- rbind(out, out3)
}
ggplot(out, aes(Date, Var1, col=type)) + geom_line(lwd=2)