Can anyone identify the instrument that James Morrison is playing in this picture?

Question: From the bell flare it looks like it might be some sort of flugel horn. Can anyone say for definite what it is?
Comment: The source of the photo might be helpful.
Comment: Voting to close, as an identification question.
Comment: I don't know much about brass, but seems like it could be a rotary-valve flugelhorn.
Comment: Australian trumpet..?
Comment: @Theodore The flare is kinda borderline between flugelhorn and cornet, to my eyes. On the flugelhorn side, looks like the mouth pipe goes right into valve one. Cornet mouth pipes usually go through a tuning slide first and then into valve three.
Answer: Based on the proportions of the instrument it can only be a flugelhorn. Morrison has his instruments custom made by Schlagerl. They built a bass trumpet for him in a very similar form (source):
Comment: Good find! Started exploring Schlagerl website also but gave up...


Bootstrap Feature Selection in Linear Modeling

Question: I'm working on a linear model with the "abalone" data set in R. I tried to build a more traditional linear model but found that the normality assumption was badly violated, even with a natural log transformation of the outcome.  I instead decided to try bootstrapping.  I ran 2,000 models, each time selecting features using stepAIC() and stepVIF().  I then analyzed which features "survived" within the 2,000 resulting models.  Most of my predictors were present either ~100% of the time or ~0% of the time.  One predictor however, was present ~28% of the time.

If a traditional linear model does not appear to work, is pivoting to a bootstrap technique a logical next step?  Or at least not a ridiculous one?

Is this a feature selection process that makes sense?  The other methodology I was thinking of was to run all of the models for all of the predictors, then only retain the ones that have confidence intervals entirely above or below 0. (as determined by quantiles of coefficients)

Assuming this is a valid feature selection process, what should I do about the predictor that shows up ~28% of the time.  My instinct is to leave it out on the basis of a naive ~50% threshold, but somehow that feels off.

I also notice that this method gives one predictor labeled "Diameter" a negative coefficient related to the outcome ("Rings") even though they are positively correlated in the full data set.  That seems like a red flag, right?

I know this is a long one and I appreciate the support.
Answer: First off, if you plan to use your model to predict "rings" (rather than infer causal effects of covariates) you would want to consider out-of-sample MSE to make decisions about which model to use. If you're trying to understand relationships/effects of covariates, you should consider which types of confounding are likely to exist in the situation and use that to inform your decisions. I took a look at the dataset description, and I'll assume that you just care about prediction.

From what I understand, using stepwise regression to do model selection is a fairly common practice. Considering multiple iterations of the algorithm is definitely better than running it once and using those results. However, you might also try using ridge regression (one package for this is glmnet) because the variables in this dataset will be fairly collinear.

Stepwise selection is probably a better method than merely choosing coefficients significantly different from zero. (However, ridge regression is probably better than both of those in the presence of multicollinearity)

If you go ahead with stepwise variable selection (and assuming that you're only interested in prediction) you could compare the out-of-sample MSE for the model with and without the variable that occurs 28% of the time, and choose the model with smaller MSE.

The discrepancy between sign of the correlation between a variable and the outcome and sign of the regression coefficient is due to multicollinearity.

I haven't fit any models, but here's a possible example. Imagine a case where abalone get more shell weight as they get older, but their non-shell weight gets big when they're fairly young and then decreases as they get older. In this situation, the total abalone weight might be positively associated with rings/age only because total weight includes shell weight. If you were to fit a model that contained both shell weight and total abalone weight, the coefficient for shell weight would be positive because it strictly increases as abalone get older. However, the coefficient for total abalone weight would represent the effect of total weight after conditioning on shell weight. So, the remaining effect would be negative because non-shell-weight decreases as an abalone gets older.


How do I set a property on a Storyboard UIViewController between segues on iOS 5?

Question: I am trying to set a simple image on an UIImageView as such when a button is touched on the first view:
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    ImageViewController *imageViewController = [segue destinationViewController];
    imageViewController.title = @"test";
    imageViewController.imvBig.image = [UIImage imageNamed:@"test.png"];
    imageViewController.lblTest.text = @"test2";
}

The .title gets set and appears just fine, but for some reason I can't get the imvBig.image to show up, nor can I get the label text to appear. Yes, I have the property created with an Outlet, etc (as I just dragged it over from IB right into the code and it was autocreated).
Can someone tell me how to properly set a property from one regular view to the next in a Storyboard setup?
Answer: Probably the ImageViewController has not loaded its views from the storyboard yet when the system sends prepareForSegue:sender:, so those outlets (imvBig and lblTest) are nil.  Messages sent to nil are silently ignored.
It's usually not appropriate for the source view controller to muck around with the destination view controller's views.  The destination view controller should set those view's settings, usually in either viewDidLoad, viewWillAppear:, or viewDidAppear:.
Comment: Usually you declare properties on the destination view controller for data you want to pass to it in prepareForSegue.  Then, in that view controller's viewDidLoad (or later if appropriate), update its views to reflect the data.
Comment: I need to set a URL from a previous view on the navigation stack. I need to know how to pass data to the ImageViewController properly.
Answer: Looks like I was able to get this to work by creating an NSString property and then setting the label to the string on viewDidLoad of the ImageViewController:
- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.

    self.lbltest.text = _myString;
}

I guess I can't set the property directly, until after the view is loaded.
Comment: It's both a "can't" and a "shouldn't" - you wouldn't want the calling view controller directly manipulating subviews in the new controller, since you might change how you want to display things some time later. Much better to just pass the data and sort out the correct way to display it in viewDidLoad().
Answer: You don't need to set the viewController just use the segue destinationViewController property. I always set a identifier in the storyboard first so I can use multiple segues:
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if ([[segue identifier] isEqualToString:@"Show ImageViewController"]) {

[segue.destinationViewController setTitle:@Test"];
[segue.destinationViewController setFoo:@"Bar"];
//More stuff to set
}

}
also create an image in the ImageViewController as a property and synthesize it,then set that to the image view in the viewDidAppear:
self. imvBig.image = myNewImge;//this in the viewDidLoad

And Set that image in the segue:
[segue.destinationViewController setMyImage:[UIImage imageNamed@"test.png"]];


help - sed - insert space between any string of form XxxXxx, without replacing the pattern

Question: If the string is of the pattern XxxXyzAbc...
The expected out put from sed has to be Xxx Xyz Abc ...
eg: if the string is QcfEfQfs, then the expected output is Qcf Ef Efs.
If i try to substitute the pattern [a-z][A-Z] with space then the sed will replace the character or pattern with space, like Qc f fs.
Is there any way to insert space in between without replacing the pattern ?.
Kindly help. Thanks.
Answer: Use match groups.
$ sed 's/\([a-z]\)\([A-Z]\)/\1 \2/g' <<< 'XxxXyzAbc'
Xxx Xyz Abc

Answer: A more accurate pattern match - one with fewer spurious matches on strings that are not in the XxxYyyZzz format - is:
sed 's/\([A-Z][a-z][a-z]*\)\([A-Z][a-z][a-z]*\)\([A-Z][a-z][a-z]*\)/\1 \2 \3/'

Consider the inputs:
XxxYyyZzz
xxxYyyZzz
X xY yZ z

One other answer I see will insert spaces in all the strings - when it should only modify the first string.
Updated to allow for the QcfEfEfs example - it isn't clear from the question how many lower case letters in a row are allowed.  It could be 1 or 2; or it could be 1 or more - using a * allows for 1 or more; otherwise, use \{1,2\} for 1 or 2.
Comment: You're missing a closing square bracket. Your command fails on the OP's "QcfEfQfs".
Comment: @Dennis: drat - yup.  I fixed it in the version I tested; and forgot to change the code before adding answer.  Bother  And yes, I missed the QcfEfEfs example...I wonder how many lower-case letters in a row...
Answer: This might work for you (GNU sed):
sed 's/\B[[:upper:]]/ &/g' file

Looks for a non-word boundary followed by an uppercase character and inserts a space throughout the line.


Jruby Rake Task - Thread.current changes when trapping INT signal

Question: In a rake task running on jruby-1.7.6, I spawn many Threads on demand and store each of the spawned threads:
puts Thread.current # => #<Thread:0x1e95aeb7>
Thread.current[:spawned_threads] = {}

# New thread spawned for every new request and stored and
# Thread.current obviously remains the same:

puts Thread.current # => #<Thread:0x1e95aeb7>

thread_object = Thread.new {
  # code in infinite loop
}
Thread.current[:spawned_threads]["thread_#{counter}"] = thread_object

When I exit the rake task, I terminate all the spawned threads. I use signal handlers :
trap('INT')  {
  terminate_threads
  exit!
}

def terminate_threads
  puts Thread.current                   # => #<Thread:0x7604790c> A different thread!
  puts Thread.current[:spawned_threads] # => nil

  Thread.current[:spawned_threads].each do |key, thread| # Error!!!
    thread.terminate
  end
end

Work-around: Thread.list.last[:spawned_threads] has all my spawned threads.
But wait,
THE SAME CODE IN RUBY 1.9.3 WORKS FINE. Thread.current REMAINS THE SAME.
QUESTIONS:

In JRuby, why does Thread.current differ during signal trapping?
Is a separate being thread spawned just to handle signals?

PLUS, in the signal handler(again), when I try to access an already created Redis connection, it stalls indefinitely, returning nothing! [Happens only in JRuby, not sure if related to signal handling.]
Answer: I don't think there is any guarantee of what thread your signal handler will happen in. Even in other languages like C with pthreads this kind of thing is complicated.
I also doubt that Ruby mandates a specific thread will receive your signal, it just so happens that the "main" thread is the one that does. That could possibly change in the future.
You should restructure your code so that there is a well-known place that you can send messages to from any thread. This might take the form of a global variable. You will then need to provide appropriate multithreaded protection to that object's methods, as you never know what thread(s) will be calling a method and when.


Creating Answer File For Windows 7 Deployment

Question: We use Dell Computers here and we are wanting to create a standard Desktop Image for Deployment. We only have the OEM copy of Windows 7 Professional that ships with each system.
I understand about using the AIK to create the answer file but my question is about what "Product Key" to use in the answer file, if any ??
We don't want to run into any activation issues after the fact.
Any insight would be very helpful.
Answer: OEM copies of Windows each need a seperate Product ID.
If I recall correctly, you can enter system deatils and the Product IDs in WAIK and it will automatically map Product IDs to hardware.
Another option is to have the Windows 7 installer prompt the user at install time and teach the user how to find the Product ID when needed. Maybe Dell has attached the Product ID on a sticker somewhere on the systems.
Answer: Ok so there is a way to do this in fact we use this method where I work.
Dell activates windows using a certificate and a bat file on it's OEM installation disk.
first you will need to copy the OEM cert and SLP.bat files from your Dell OEM CD.The OEM Cert is located on the CD under sources\$OEM$\$$\system32\OEM and is called OEM (XrML Digital License). slp.bat is located under sources\$OEM$\$$\setup\scripts.
Then save them to your deployment share.
 Currently it should look something like this:
cscript %windir%\system32\slmgr.vbs -ilc %windir%\system32\oem\OEM.xrm-ms
cscript %windir%\system32\slmgr.vbs -ipk 32KD2-K9CTF-M3DJT-4J3WC-733WD

but seeing as our OEM folder will be elsewhere we will need to change it to this:
cscript %windir%\system32\slmgr.vbs -ilc OEMLOCATION\OEM.xrm-ms
cscript %windir%\system32\slmgr.vbs -ipk 32KD2-K9CTF-M3DJT-4J3WC-733WD

In your answer file under the OOBE pass in your answer file add:
 Microsoft-Windows-Shell-Setup_neutral
  FirstLogonCommands
   SynchronousCommand(Order="1")
     Action- AddListItem
     CommandLine- \\server\share\dellcert\makeOEM.bat
     Description- Make OEM Folder
     Order- 1
     RequiresUserInput- True
   SynchronousCommand(Order="2")
     Action- AddListItem
     CommandLine- \\server\share\DellCert\copyslp.bat
     Description- Copy slp.bat to share folder
     Order- 2
     RequiresUserInput- True
   SynchronousCommand(Order="3")
     Action- AddListItem
     CommandLine- \\server\share\DellCert\copycert.bat
     Description- Copy Dell Cert
     Order- 3
     RequiresUserInput- True
   SynchronousCommand(Order="4")
     Action- AddListItem
     CommandLine- \\server\share\DellCert\Runslp.bat
     Description- Run slp.bat
     Order- 4
     RequiresUserInput- True

The only way I was able to get it to work correctly was by braking it up into 4 parts as shown and set RequiresUserInput to true (don't ask me why it just would work otherewise
I actually posted more details about this else where: http://starvinggeek87.blogspot.com/2013/05/useing-windows-deployment-service-to.html


Prove the local expression of Riemannian curvature tensor

Question: I try to prove the following expression of Riemannian curvature tensor:
For local coordinate $\{x^i\}$, let $g_{ij}=g(\frac{\partial}{\partial x^i},\frac{\partial}{\partial x^j})$ and $R_{ijkl}=R(\frac{\partial}{\partial x^i},\frac{\partial}{\partial x^j},\frac{\partial}{\partial x^k},\frac{\partial}{\partial x^l})$, then $$R_{ijkl}=\frac{1}{2}\left(\frac{\partial^2g_{il}}{\partial x^j\partial x^k}+\frac{\partial^2g_{jk}}{\partial x^i\partial x^l}-\frac{\partial^2g_{ik}}{\partial x^j\partial x^l}-\frac{\partial^2g_{jl}}{\partial x^i\partial x^k}\right)+g_{rs}\Gamma^r_{jk}\Gamma^s_{il}+g_{rs}\Gamma^r_{jl}\Gamma^s_{ik}$$

My try:
By definition, $R_{ijkl}=g(R_{(\frac{\partial}{\partial x^i}\frac{\partial}{\partial x^j})}\frac{\partial}{\partial x^k},\frac{\partial}{\partial x^l})$
Since $[\frac{\partial}{\partial x^i}\frac{\partial}{\partial x^j}-\frac{\partial}{\partial x^j}\frac{\partial}{\partial x^i}]=0$, $R_{(\frac{\partial}{\partial x^i}\frac{\partial}{\partial x^j})}\frac{\partial}{\partial x^k}=-(D_{\frac{\partial}{\partial x^i}}D_{\frac{\partial}{\partial x^j}}-D_{\frac{\partial}{\partial x^j}}D_{\frac{\partial}{\partial x^i}})\frac{\partial}{\partial x^k}$
Then by definition of Christofle symbol, $D_{\frac{\partial}{\partial x^i}}\frac{\partial}{\partial x^k}=\Gamma^s_{jk}\frac{\partial}{\partial x^s}$, then I have $$R_{ijkl}=\left(\frac{\partial}{\partial x^j}\Gamma^r_{ik}\right)g_{rl}-\left(\frac{\partial}{\partial x^i}\Gamma^r_{jk}\right)g_{rl}+\Gamma^r_{ik}\Gamma^s_{jr}g_{sl}-\Gamma^r_{jk}\Gamma^s_{ir}g_{sl}$$
Then I am not sure how to proceed. I know $\Gamma^r_{ik}=\frac{1}{2}g^{rs}(g_{is,k}+g_{ks,i}-g_{ik,s})$, then if I expand $\frac{\partial}{\partial x^j}\Gamma^r_{ik}$ by chain rule, I get something like $\frac{\partial}{\partial x^j}g^{rs}$, which I don't know how to cancel. Also when I compare my result to the desired one, even the expressions of the last two terms are not the same. Do you have any advice? Thanks!
Answer: If $E_i$ is a coordinate vector field, then $$ E_i g^{jk} = - g^{jm}
g^{kn} E_i g_{mn} $$
$$
E_i \Gamma_{jk}^l = \underbrace{ (- g^{la} g^{sb} E_i g_{ab})
\underbrace{\frac{1}{2}(E_jg_{ks}+ E_k g_{js}- E_s g_{jk}
)}_{=\Gamma_{jk}^t g_{ts} } }_{=:A}+ \frac{1}{2} g^{ls} E_i( E_j g_{ks} +
E_k g_{js} - E_s g_{jk} ) $$
And $$ A=(- g^{la} g^{sb} E_i g_{ab}) \Gamma_{jk}^t g_{ts} g_{lm} =
-\Gamma_{jk}^b E_i g_{mb} = - \Gamma_{jk}^b \{ \Gamma_{im}^s g_{sb}
+ \Gamma_{ib}^s g_{sm} \} $$
$$ R_{ijkm} = R_{ijk}^l g_{lm} =\bigg\{ (- g^{la} g^{sb} E_i g_{ab})
\Gamma_{jk}^t g_{ts} + \frac{1}{2} g^{ls} E_i( E_j g_{ks} + E_k
g_{js} - E_s g_{jk} )\bigg\} g_{lm} $$
$$ - \bigg\{  (- g^{la} g^{sb} E_j g_{ab}) \Gamma_{ik}^t g_{ts} + \frac{1}{2} g^{ls} E_j( E_i g_{ks} + E_k g_{is} - E_s
g_{ik} ) \bigg\} g_{lm} + (\Gamma_{jk}^s\Gamma_{is}^l  -
\Gamma_{ik}^s\Gamma_{js}^l ) g_{lm}
 $$
$$  = \frac{1}{2} \{ E_iE_k g_{jm} - E_iE_m g_{jk} - E_jE_k g_{im} +
E_mE_j g_{ik} \} - \Gamma_{jk}^b \Gamma_{im}^s g_{sb} +
\Gamma_{ik}^b\Gamma_{jm}^s g_{sb} $$


Flutter: Error when trying to add data into a Map List

Question: I am very much new to Flutter. I am developing a testing app and blow is my code.
main.dart
import 'package:flutter/material.dart';

import './pages/homepage.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return MaterialApp(
      theme: ThemeData(primaryColor: Colors.green),
      home: Homepage(),
    );
  }
}

homepage.dart
import 'package:flutter/material.dart';

class Homepage extends StatelessWidget {
  List<Map<String, String>> productMap;

  Homepage() {
    productMap.add({"title": "Chocolate", "imageUrl": ""});
  }

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Scaffold(
      appBar: AppBar(
        title: Text("Choco Factory"),
      ),
      body: HomepageUI(),
    );
  }
}

class HomepageUI extends StatefulWidget {
  HomepageUI() {}

  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return _HomepageUIBuilder();
  }
}

class _HomepageUIBuilder extends State<HomepageUI> {
  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Expanded(
      child: Column(
        children: <Widget>[
          ListView.builder(
            itemBuilder: _listBuilder,
          )
        ],
      ),
    );
  }

  Widget _listBuilder(BuildContext context, int index) {
    return Card(
      child: Column(
        children: <Widget>[
          Image.asset("name"),
          Text("data"),
          RaisedButton(
            onPressed: () {},
            child: Text("Details"),
            color: ThemeData().primaryColor,
          )
        ],
      ),
    );
  }
}

I get the following error and I can't figure out why. I am from Java background and the code seems OK to me. Also I have another question, in Java Map we can add many key-value pairs to the Map but in Flutter it seems only one key-value pair is possible?
Launching lib\main.dart on A37f in debug mode...
Built build\app\outputs\apk\debug\app-debug.apk.
I/Choreographer(11935): Skipped 87 frames!  The application may be doing too much work on its main thread.
I/flutter (11935): ══╡ EXCEPTION CAUGHT BY WIDGETS LIBRARY ╞═══════════════════════════════════════════════════════════
I/flutter (11935): The following NoSuchMethodError was thrown building MyApp(dirty):
I/flutter (11935): The method 'add' was called on null.
I/flutter (11935): Receiver: null
I/flutter (11935): Tried calling: add(_LinkedHashMap len:2)
I/flutter (11935): When the exception was thrown, this was the stack:
I/flutter (11935): #0      Object.noSuchMethod (dart:core/runtime/libobject_patch.dart:50:5)
I/flutter (11935): #1      new Homepage
I/flutter (11935): #2      MyApp.build
I/flutter (11935): #3      StatelessElement.build
I/flutter (11935): #4      ComponentElement.performRebuild
I/flutter (11935): #5      Element.rebuild
I/flutter (11935): #6      ComponentElement._firstBuild
I/flutter (11935): #7      ComponentElement.mount
I/flutter (11935): #8      Element.inflateWidget
I/flutter (11935): #9      Element.updateChild
I/flutter (11935): #10     RenderObjectToWidgetElement._rebuild
I/flutter (11935): #11     RenderObjectToWidgetElement.mount
I/flutter (11935): #12     RenderObjectToWidgetAdapter.attachToRenderTree.<anonymous closure>
I/flutter (11935): #13     BuildOwner.buildScope
I/flutter (11935): #14     RenderObjectToWidgetAdapter.attachToRenderTree
I/flutter (11935): #15     _WidgetsFlutterBinding&BindingBase&GestureBinding&ServicesBinding&SchedulerBinding&PaintingBinding&SemanticsBinding&RendererBinding&WidgetsBinding.attachRootWidget
I/flutter (11935): #16     runApp
I/flutter (11935): #17     main
I/flutter (11935): #18     _runMainZoned.<anonymous closure>.<anonymous closure> (dart:ui/hooks.dart:189:25)
I/flutter (11935): #23     _runMainZoned.<anonymous closure> (dart:ui/hooks.dart:180:5)
I/flutter (11935): #24     _startIsolate.<anonymous closure> (dart:isolate/runtime/libisolate_patch.dart:300:19)
I/flutter (11935): #25     _RawReceivePortImpl._handleMessage (dart:isolate/runtime/libisolate_patch.dart:171:12)
I/flutter (11935): (elided 4 frames from package dart:async)
I/flutter (11935): ════════════════════════════════════════════════════════════════════════════════════════════════════

Answer: List<Map<String, String>> productMap;

should be
List<Map<String, String>> productMap = [];

otherwise productMap is only declared, but not initialized (null)
Comment: this solution did not work for me. List> savedList = []; Map sData = {
                'filetype': 'image',
                'filepath': 'demo.jpg',
              }; savedList.add(sData); Please suggest. Thanks.
Answer: You have not initialised the List.
Please change
List<Map<String, String>> productMap;

to
List<Map<String, String>> productMap = <Map<String, String>>[];

Hope this helped!
Comment: `>` on the right side is redundant. It's inferred from the left side.


How do you add an Event Listener that fires when tinymce get function gets called?

Question: This tinymce get function returns an Editor instance when passed an id. I would like to have an event fire (or a callback) every time this function is called:
tinymce.get('mytextbox')

I have tried:
tinymce.on('Get', function(e){console.log('Get called!',e);});

But that didn't work. Is there anything built into tinymce for this?
Comment: I don't think such a functionality exists
Answer: Unfortunatly, there is no such functionality built in Tinymce.


How to build a cross compiler of GHC in Alpinelinux?

Question: I have done following steps in Alpinelinux v3.9 x86_64 and got error.

Run bootstrap.sh in aport to get aarch64-alpine-linux-musl-* tools.
Build and install llvm6 in x86_64.
Link all aarch64-alpine-linux-musl-* to aarch64-unknown-linux-*.
Configure ghc 8.6.3 only with "--target=aarch64-unknown-linux".
<code>Configure completed successfully.

   Building GHC version  : 8.6.3
          Git commit id  : 31cd867e4d37072c3ce1d51efadc94e66ddc1c28

   Build platform        : x86_64-alpine-linux
   Host platform         : x86_64-alpine-linux
   Target platform       : aarch64-unknown-linux

   Bootstrapping using   : /usr/bin/ghc
      which is version   : 8.4.3

   Using (for bootstrapping) : gcc
   Using gcc                 : aarch64-unknown-linux-gcc
      which is version       : 8.2.0
   Building a cross compiler : YES
   Unregisterised            : NO
   hs-cpp       : aarch64-unknown-linux-gcc
   hs-cpp-flags : -E -undef -traditional
   ar           : aarch64-unknown-linux-ar
   ld           : aarch64-unknown-linux-ld.gold
   nm           : aarch64-unknown-linux-nm
   libtool      :
   objdump      : aarch64-unknown-linux-objdump
   ranlib       : aarch64-unknown-linux-ranlib
   windres      :
   dllwrap      :
   genlib       :
   Happy        :  ()
   Alex         :  ()
   Perl         : /usr/bin/perl
   sphinx-build :
   xelatex      :

   Using LLVM tools
      clang :
      llc   : llc
      opt   : opt

   HsColour was not found; documentation will not contain source links

   Tools to build Sphinx HTML documentation available: NO
   Tools to build Sphinx PDF documentation available: NO
----------------------------------------------------------------------

For a standard build of GHC (fully optimised with profiling), type (g)make.

To make changes to the default build configuration, copy the file
mk/build.mk.sample to mk/build.mk, and edit the settings in there.

For more information on how to configure your GHC build, see
   http://ghc.haskell.org/trac/ghc/wiki/Building
</code>
Make.
<code>===--- building final phase
make --no-print-directory -f ghc.mk phase=final all
"ld" -z noexecstack -r  -o libraries/ghc-prim/dist-install/build/HSghc-prim-0.5.3.o  libraries/ghc-prim/dist-install/build/GHC/CString.o libraries/ghc-prim/dist-install/build/GHC/Classes.o libraries/ghc-prim/dist-install/build/GHC/Debug.o libraries/ghc-prim/dist-install/build/GHC/IntWord64.o libraries/ghc-prim/dist-install/build/GHC/Magic.o libraries/ghc-prim/dist-install/build/GHC/PrimopWrappers.o libraries/ghc-prim/dist-install/build/GHC/Tuple.o libraries/ghc-prim/dist-install/build/GHC/Types.o   libraries/ghc-prim/dist-install/build/cbits/atomic.o libraries/ghc-prim/dist-install/build/cbits/bswap.o libraries/ghc-prim/dist-install/build/cbits/clz.o libraries/ghc-prim/dist-install/build/cbits/ctz.o libraries/ghc-prim/dist-install/build/cbits/debug.o libraries/ghc-prim/dist-install/build/cbits/longlong.o libraries/ghc-prim/dist-install/build/cbits/pdep.o libraries/ghc-prim/dist-install/build/cbits/pext.o libraries/ghc-prim/dist-install/build/cbits/popcnt.o libraries/ghc-prim/dist-install/build/cbits/word2float.o
ld: libraries/ghc-prim/dist-install/build/GHC/CString.o: Relocations in generic ELF (EM: 183)
ld: libraries/ghc-prim/dist-install/build/GHC/CString.o: Relocations in generic ELF (EM: 183)
ld: libraries/ghc-prim/dist-install/build/GHC/CString.o: error adding symbols: file in wrong format
make[1]: *** [libraries/ghc-prim/ghc.mk:4: libraries/ghc-prim/dist-install/build/HSghc-prim-0.5.3.o] Error 1
make: *** [Makefile:127: all] Error 2

$ file ./libraries/ghc-prim/dist-install/build/GHC/CString.o
./libraries/ghc-prim/dist-install/build/GHC/CString.o: ELF 64-bit LSB relocatable, ARM aarch64, version 1 (SYSV), not stripped
</code>
Answer: Got it. After remove ld.gold and copy ld as ld.gold, building process passed. Simple test passed.


Creating a stable, auto-scaling app server cluster

Question: I have two servers, each running anywhere from 50-100 different legacy webapps, written in languages ranging from PHP to Python to Ruby-on-rails to NodeJS.
We're wanting to kill off these machines as they're old, insecure and badly organised, have no consistent configuration logic, and are also running two instances of mysqld each (don't ask).
To that end, I want to do the following:

Delete any now-depreciated legacy projects
Sandbox each app somehow, possibly into its own Docker or Passenger container
Create the new servers as an auto-scaling stateless cluster, moving each MySQL database to its own RDS instance
Possibly even be able to auto-scale inactive apps in a manner similar to how Heroku does

Ultimately, I'm wanting to do something similar to what Deis or Flynn do, though neither of those is production-ready at the moment.
I'm honestly a bit overwhelmed by it all and am really not sure where to start. Any suggestions? Is Passenger something I should even be considering? Docker?
Thank you!
Comment: there is no easy easy way to autoscale where it just works. It requires a lot of backend development to get there. Like for example where I work we utilize docker a lot and we use metrics in graphite to tell if we need to spin up more docker containers. There is no silver bullet here
Comment: @Mike: Valid point; but having the ability to set thresholds (similar to how AWS' Elastic Beanstalk platform does things) would be helpful.
Comment: that's where we use graphite and hook into it.. i'm not sure of anything out there that is out of the box like beanstalk is
Answer: I'm not quite sure what your actual questions are. Your overall question is fairly vague. You have three main questions here from what I can gather:

Where should I start to get my own scalable PaaS infrastructure?
Is Passenger something I should even be considering?
Is Docker something I should be considering?

I'll answer number 3 first since that is easiest. The answer is Yes. If your going to be building something new, Docker will help get you into a more portable world, which will in turn help get you to a more scalable point. Your legacy webapps would run as their own containers, with their own sets of dependencies, and thus, become more portable.
The answer to number 2 sounds more dependent on Ruby and the Ruby applications in general. Can you run Passenger? Maybe... This seems more dependent on how the application was written and what servers it might be compatible with. However, it does appear that Phusion is making strides to be very Docker friendly. The have Docker images specifically around running Ruby, Python, and Node.js applications at least - https://github.com/phusion/passenger-docker.
My answer to number 1 would be to start by containerizing legacy applications. Make the applications more twelve factor compliant (http://12factor.net/) if they are not already. Make them more service oriented. Instead of running stuff like MySQL, Redis, Apache, PHP-FPM, etc in one container, separate them out into different services that connect to each other over TCP and HTTP (Docker links would be a great place to start with this - https://docs.docker.com/userguide/dockerlinks/).
By getting your applications to a point where they run in their own container, use external services that could run anywhere, and can be versioned with a default working configuration (a release), then you are getting closer to a world where you can then start writing scheduling, service discovery, and deployment scripting.
If you haven't already, check out stuff that comes a little earlier than a full-blown Docker PaaS such as https://coreos.com/ or http://www.projectatomic.io/. Something like these give you scheduling around your own containers / units rather than actually building your application containers for you. For learning in development, you might use something like http://www.fig.sh/ or http://decking.io/. Great for testing out your new service oriented containers locally.
For more tooling around Docker, keep an eye on https://stackoverflow.com/questions/18285212/how-to-scale-docker-containers-in-production. The top answer has a pretty good overview of what is currently out their and the author keeps it updated fairly well.
Comment: Apologies for the breadth of the question, in retrospect I could've separated it into multiples. That said, you answered it really well! Will leave open for a few more days but will accept if nobody else has anything else!


Unresolved Segmentation fault while trying to simplify directory path using stacks

Question: I was trying to resolve my segmentation fault when i was using stacks to simplify my directory path. But I can't seem to find anything that would cause the issue. Am I missing something?
string Solution::simplifyPath(string A) {
    string a="";
    stack<char> one;
    stack<char> res;
    for(int i=0; i<A.length();i++){
        one.push(A[i]);
    }
    one.pop();
    while(one.top()!='/'){
        res.push(one.top());
        one.pop();
        }
    res.push('/');
    while(res.top()!=NULL){
        a+=res.top();
        res.pop();
    }
    return a;
}

Error message:

Runtime Error. Your submission stopped because of a runtime error. ex: division by zero, array index out of bounds, uncaught exception You can try testing your code with custom input and try putting debug statements in your code.

Segmentation fault.

Comment: Did you run it in the debugger?
Comment: What happens to `while(one.top()!='/')` if `one` doesn't have a `'/'` in it?
Comment: See https://ericlippert.com/2014/03/05/how-to-debug-small-programs/
Comment: @Riataro In my opinion the function does not make sense.:)
Answer: while(res.top()!=NULL)

std::stack::top() does not return NULL when the stack is empty. It causes undefined behaviour instead.
Comment: @Riataro the point is that you should have found it using the debugger.
Comment: Thank you. I completely overlooked that.
Answer: You must check if the stack is not empty before using stack::top() or stack::pop().
while(!one.empty() && one.top()!='/')


How does one compose fills and solos for the drumkit?

Question: I keep hearing that rudiments are the building blocks of drumming. How do you create drum fills and solos out of rudiments?
They say that solos and fills are made from rudiments. Are they ALL made from nothing but rudiments? Are rudiments the only way to compose them?
How do you know what drums to play the rudiments on and in which order? Is it really just random? It can't be. There has to be some music theory or compositional rules that dictate what can or can't be done and how but I can't find them anywhere.
Answer: Rudiments are just the different basic sequences. You can play them in any order, but you will find some work well and some sound less good.
As with many aspects of music, it comes down to what you think sounds good. It is not random, but depends on what you are trying to do.
Your best plan is to listen to drummers you really like and learn their fills and solos - this will give you a natural feel for what you can do with the various rudiments.
Answer: In the same way you'd compose any other passage of music, but ignore the elements of harmony and melody. Although, as with a lot of sound art or noise composition, you can write something with the 'idea' of melody but without precise pitches. Do you want your fill to ascend in pitch, or descend?
Think like this:

rhythm: Are there any distinctive rhythms in your piece you could re-use here? Make it seem more like a part of the overall piece?

Dynamics: Is your music loud at this point? Is it getting louder, or quieter. Do you want the fill to be winding down to a quiet point, or get louder and 'drop off'
Syncopation: Don't forget, this is a chance to feature your drummer's technical ability, try out some distinct rhythms, pick out some beats, try throwing in triplets or look up some latin rhythms.
Ending: Will your fill end, say, on a cymbal, letting it's sound over-hang into the next part, or end suddenly.
Feel: Is this a short drum solo? Or a part of the overall rhythmic feel, are you expecting, say, vocals or a solo instrument to be heard at the same time? If so, don't take the focus away from these.

These are all general rules which also apply to other parts of composition, always ask yourself questions about what you want to compose.
It's also worth remembering that most drummers do a lot of work without precise scores and would be perfectly happy to see an empty bar with 'drum fill' written over the top, it really depends how much you want to specify (also, if you have to, if this is a school or college composing project, specify every drum hit).
Comment: Also worth noting with drum fills is that you don't have to hit every semiquaver, you can get more effect by leaving gaps than by making a constant attack on the kit.


What Permissions does a user need to upload content into AEM Mobile Cloud service from AEM

Question: I have setup a package that I built on an AEM author instance running on my local machine. I have it connecting to the AEM Mobile on demand cloud service.
When I have my package uploaded to a hosted AEM author instance, where I am not able to log in as admin. When I load the mobile project I see an error that the cloud config path does not exist. And I also don't see the 'Upload Shared Resources' button and can't upload articles.
What paths and permissions on those paths does my user need to fix this?
Answer: I was able to track down the paths and the permissions needed on those paths.
For the cloud config does not exist error the user needs
read access to the cloud config path: /etc/cloudservices/dps2015
In order to upload the user needs
read access to /etc/contentsync
and
read, write, create, delete access to /var/contentsync
and
read access to /var


ExtJS combo box data from json

Question: i have json :
<code>{"total":100, "category": [Village, City, School, HighSchool]}
</code>
for extjs combobox :
<code>reader: new Ext.data.JsonReader({
root: 'category'},
[{name: 'category'}])
</code>
it not loods my data in it when i look in firebug it shows
thks for your help...
Answer: I don't see the error that firebug shows, but your JSON is invalid. Try:
<code>{"total":100, "category": ["Village", "City", "School", "HighSchool"]}
//values in array should be in double quotes
</code>
Comment: ok i have changed the json style and populateing with not jsonstore only store

ExtJS combo box data from json


Emacs; custom functions defined repetitively, how to use dolist, or other approach

Question: Emacs' Bookmarks are great, as is navigating the list of buffers. But I find it nice to have shorter chords to get directly to where I want to go. So I have been accruing a repetitive set of functions and keybindings for all my favorite files and folders.
I wondered if I could use a dolist to handle this repetitiveness, but am no good programmer.
Here is one of the (seven and rising) repetitively defined functions, and a feeble attempt at writing the dolist following:
(defun jump-to-main ()
  (interactive)
  (find-file main))
(global-set-key (kbd "C-c m") 'jump-to-main)

This might barely qualify as pseudocode:
(dolist (x '(("m" main)
             ("t" tech))
           (defun (concat 'jump-to- (cdr x)) ()
             (interactive)
             (find-file (cdr x)))
           (global-set-key (kbd (concat "C-c " (car x)))
                           '(concat 'jump-to- (cdr x)))
           ))

The payoff in an elegant init file, versus how fast I am at solving at Lisp problems... hoping the Stackoverflow can save me.
Other strategies and approaches are appreciated.
EDIT:
With lawlist's suggestion, my question may reduce and be more clear presented the following way. I would like to reduce the repetition in the following series of keybindings.
(global-set-key (kbd "C-c A")
                (lambda ()
                  (interactive)
                  (find-file fileA)))

(global-set-key (kbd "C-c B")
                (lambda ()
                  (interactive)
                  (find-file fileB)))

...

(global-set-key (kbd "C-c Z")
                (lambda ()
                  (interactive)
                  (find-file fileZ)))

fileK for example expands to something like "~/fileK.txt".
EDIT:
So here is another try:
(dolist (x '(("m" main)
             ("t" tech))
           (global-set-key (kbd (concat "C-c " (car x)))
                           (lambda ()
                             (interactive)
                             (find-file (cdr x))
                             ))))

The keybinding part seems okay, but (find-file (cdr x)) isn't doing what I need, and I couldn't fix it in a small amount of googling lisp.
Here are the expressions I'm using to focus on the broken parts:
(setq somefile "~/somefile.txt")
(setq x '("s" . somefile))
(concat "C-c " (car x))
(find-file (cdr x))

The last line is the one that doesn't work, as (cdr x) apparently evaluates to (main). I tried slipping in an eval to expand the main variable, but it doesn't seem...
Reading Phil's answer now, this may take me a while.
Comment: How about a fancy function with choices?  One keyboard shortcut and then several choices -- 1 2 3 4 or a b c d e?  Like these -- there are four (4) ideas in that link?:  http://stackoverflow.com/a/19284395/2112489  I've also recently updated my context menu example, if that type of option interests you . . . here is the context menu update that differs from the one in the previous link:  http://stackoverflow.com/a/24346990/2112489
Comment: Where is `main` located?  Where is `tech` located?  I'm confused . . .  Are they files or directories?  Are you trying to open a dired-mode buffer or a file visiting buffer?  Something like this?  `(global-set-key (kbd "C-c m") (lambda () (interactive) (dired "/Volumes")))`
Comment: @lawlist, `main` and `tech` are variables for filenames. I'm using variables so that I can move files around on a whim, and it won't break my Emacs' workflow. By the way, I can use `find-file` uniformly as it will open `dired` for directories.
Comment: How about?  `(global-set-key (kbd "C-c m") (lambda () (interactive) (find-file main)))`  and  `(global-set-key (kbd "C-c t") (lambda () (interactive) (find-file tech)))`
Comment: @lawlist, That only combines each pair of functions, and to the detriment, if I want to view keybindings, would get `?` instead of a name of a function. But, what I'm more worried about, is that I have seven functions that look exactly the same, and it gets larger. I will edit the question to make it more clear where my unwanted repetition is... Ah, but if using the lambda makes it easier to construct the dolist, then that would take precedence.
Comment: I think you are already doing it correctly (**without** the `dolist` / `car` / `cdr` / `concat` / etc.), and if you want a pretty describe key readout in your buffer, then your first example is also good -- i.e., `defun jump-to-main . . .`
Comment: Your last `dolist` form should work at one condition: you put your Elisp file in `lexical-binding` mode (i.e. add `-*- lexical-binding:t -*-` somewhere on its first line).
Answer: FWIW, a fairly direct translation of your pseudo-code is:
(defvar my-file-main (expand-file-name "~/main") "My main file")
(defvar my-file-tech (expand-file-name "~/tech") "My tech file")

(dolist (x '(("m" . my-file-main)
             ("t" . my-file-tech)))
  (let* ((sym (cdr x))
         (func (intern (concat "jump-to-" (symbol-name sym)))))
    (defalias func `(lambda ()
                      ,(format "Jump to file `%s'." (symbol-name sym))
                      (interactive)
                      (find-file ,sym)))
    (global-set-key (kbd (concat "C-c " (car x))) func)))


Measures of interdependence of events of different types

Question: A mouse does four things: eats (E), drinks (D), defecates (S), and urinates (U). A time chart records the occurrence of each event along with the time in minutes (after the commencement of measurement) at which the event occurred. The time-chart actually has around 12,000 events of which the following is a sample.
<code>S, 5
D, 9
S, 14
S, 17
D, 17
D, 21
E, 23
U, 28
D, 31
E, 33
E, 36
U, 37
E, 39
D, 39
D, 39
S, 42
E, 46
U, 49
D, 51
S, 52
</code>
As you can see, there might be no obvious ordering to the events and one event type might be followed by another event of the same type. I'm interested to discover something about the possible interdependence of events. For example, defecation (S) might be presumed to be stimulated by eating (E), but there is also the possibility that the reverse is true and that S leads to sensations of emptiness that then promote an increased likelihood of E. In case it is not clear, I'm not just interested in the frequency of the immediately following events. For example, S might stimulate E, irrespective of any intervening D or U events.
At this stage, I don't know how to phrase my question better than that. I would appreciate advice on: (a) whether there is a standard expression or phrase to describe the problem I am faced with … so that I can do a sensible search, (b) improving the question (!), and (c) measures and calculation. I can always re-edit and improve my question in the light of new information!
Comment: 1. Please correct the count in your first sentence. Presumably you mean four things. 2. You should make explicit whether the time variable is the time at which it occurs or how long it occurs for. For convenience it would help to give units (seconds after the start of the observation period?). 3. "Interested to discover something" is pretty broad, perhaps too broad for a suitable question. Can you be any more precise? Note that if you're "just trying to find anything" you can't really talk about significance very meaningfully (or get unbiased effect estimates) unless you sample split ... ctd
Comment: ctd ... using part of the data to formulate models or hypotheses and the remainder to estimate or assess them.
Comment: Many thanks @Glen_b for the helpful comments. I have corrected the errors and, I hope, made the description clearer. By "discover something about the interdependence of events", I (probably) mean something like "does the occurrence of event type X decrease the time it would otherwise take for event type Y to occur?". There must, simply because of the most basic causation model, be a relationship between E and S, as well as D and U. Absent E altogether, and S will never occur; absent D, U will not occur ... and the mouse will die. But what more can I say?
Answer: You could start with a multi-state Markov process in continuous time, with four states (and maybe a fifth for something else?)  Here is an introduction, and there is an R package msm.


Nested .pth Files or Loading Extra site-dirs from a Network

Question: The goal is to have a universal directory where I can add packages on the network that are automatically added to sys.path without needing to run site.addsitedir or sys.path.append each time I import said packages. Is there a way to do this?
Background: I have a small network of users who all need access to the same scripts. Every time I want to add a new package for them to use, I add the path to their PYTHONPATH environment variable. The user base has started to grow, and so have the number of packages.
If I could set up a master.pth on the network that is loaded when they start any of the scripts (without requiring extra code in all of them), I'd be very grateful. It appears, though, that you can't nest .pth files, so simply adding a pointer .pth to the master.pth directory doesn't seem to work.
Edit: Regarding Comments from @S.Lott (was a little big for a comment): Take, for example, wxPython. Three objects are placed into the site-packages directory: wxversion.py, a directory called wx-2.8-msw-unicode, and a .pth file. The .pth file points to that directory, which contains all of the importable packages (wx, wxPython, etc.). I currently have three other packages that are structured in a similar way, one of which has several base modules. I would need to move all of the importable modules into the same directory to get the desired result.
If, however, .pth files could be "nested", I could add all of these directories to master.pth, keeping a relatively clean folder. I hope that makes sense, and thanks for your help!
Comment: Simply adding separate `.pth` files to Python's ordinary site-packages directory works perfectly.  What's wrong with doing that?  Why add another file and this "indirection"?
Comment: @S.Lott: Mostly because I don't want to update/add the `.pth` files every time I add a new package to everyone on the network. I want to do a one time setup and just update the network directory after that.
Comment: There is no "royal road" to system administration.  You should probably reconcile yourself to writing, debugging and support installers for your users to add packages to their various Python installations.  Or.  Use a single shared directory for all of your users.
Comment: Using a single shared directory is the closest thing to what I'm looking for. I guess I'll just have to live with a messy shared directory (all importable packages must be in the same directory).
Comment: "messy shared directory"?  But that's what a lot of people do to keep things simple and neat.  I don't get what you're complaining about.  Please elaborate.
Comment: I've added a reply to your comment in the original question.
Comment: "I would need to move all of the importable modules into the same directory to get the desired result."?  And?  What's wrong with that?  I don't get the problem.
Comment: I go from having 4, well named, versioned directories and a pth file, to 14 unversioned base modules that require investigation to figure out which one it belongs to. The idea is to get things to work and be easily manageable, rather than just work.
Comment: Where did the directories go?  Why did they disappear?  My site-packages has a few .PTH files and a few subdirectories.  Why did your subdirectories vanish?
Comment: I'm discussing of the theoretical "networked site-packages" directory, not the actual one that is found in the python directory. This "networked site-packages" directory does not read .pth files, even though it is in the PYTHONPATHS environment variable, because it is not the _actual_ site-packages directory. Does that make sense?
Comment: If the network share is on PYTHONPATH, then the packages are directly available and the .PTH files don't matter, do they?
Comment: This, unfortunately, does not work. For example: create a directory outside of the python directory, say `C:\foo`. Download wxPython, and place it in that directory (`C:\foo\wx-2.8-msw-unicode`). Add more if you like. Add the directory `C:\foo` to your `PYTHONPATHS`. Open a new python interactive shell and run `import sys; for i in sys.paths: print i` to verify that the path is there, then `import wx`. You will get an Import Error (assuming you don't have wxPython in your site-packages).
Comment: That's your **real** problem.  Please post that as your real problem.  It should work.  It does for me.  I'm hoping that the `PYTHONPATHS` in your comment is just a typing error, since it should be `PYTHONPATH`.  Please post a question describing this problem, since solving that problem makes this question unnecessary.
Comment: Yes, sorry, `PYTHONPATHS` was a typo. I will update the original question.
Comment: You might want to open a **new** question with the `PYTHONPATH` issue, completely separate from this.
Comment: Does my answer work for you?  If so, please accept it; if not, what problems are you having?
Comment: This is especially important in `virtualenv` installations. It took me a very long time to realize that this was the cause of not loading modules from a site-packages folder added to virtualenv by way of the wrapper function `add2virtualenv` (which effectively does what @TorelTwiddler wants to do manually). The behavior is non-intuitive and (in my opinion) is a python bug. At the very least, the error message needs to be changed; Python should know that there's a nested pth file that it refused to import.
Comment: Note that this is [issue #4033](http://bugs.python.org/issue4033) in the Python bug tracker. It's open, but assigned as a documentation issue.
Answer: You have a couple options:

modify your site.py file -- look for the PREFIXES list and add your network path to it:
Have one custom .pth file in each machine's site-packages folder with the following line:
import sys; sys.path.append('/network/path/to/modules_and_packages')

The downside to using site.py is that when you upgrade to a different python you'll have to find and adjust all the site.pys on all the machines.  Using the custom .pth file it's a simple matter of copying into the new 'site-packages' folders.
Both solutions allow you to have the network location set up just like the normal site-packages folder.  For example:
m:\python_site_packages\   # network drive and folder
   |
   |- dbf.py  # for accessing dBase III and VFP .dbf files
   |
   |- web\
       |- __init__.py
       |- application.py
       |- (etc)

Just a reminder -- if the server becomes unavailable, so will all the network packages.
Comment: I don't believe that sys.path.append will load `.pth` files in the appended location.  At least, it doesn't from within virtualenv on Python 2.7.


Access dom element with vuejs and vuetify dialog

Question: I have a div tag with an 'id="meet"' into v-dialog.
I need to access the node of this tag after I open the dialog.
I am using
let node=document.querySelector("#meet").

My problem is that it always returns "null".
Here is the codepen: https://codepen.io/luizalves/pen/NWxKbXQ
What is wrong here?
Answer: According to your CodePen, it returns null only on first open.
The content of the component is loaded dynamically by default, only after the first opening of the v-dialog.
You could add eager prop to v-dialog element to force it.
<v-dialog
    v-model="dialog"
    max-width="290"
    eager
>
...


How do I convert malformed HTML to PDF with iText and XMLWorker?

Question: I am trying to convert HTML(with external CSS) into PDF using Itext XMLWorkerHelper,  am facing the run-time exception whenever XMLWorkerHelper parses a malformed HTML. For example:
The html below has input tag not closed : and XMLWorkerHelper cannot parse and throws run-time exception.

if i try with proper HTML input tag enclosed,it works fine.
How can i convert malformed or complex HTML (along with css) to PDF using Itext.
below is my code:
var test_html = File.ReadAllText("C:/Desking _ Lender Program - Dealertrack.html");
var test_css = File.ReadAllText("C:/login.css");
using (var msCss = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(test_css)))
                    {
                        using (var msHtml = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(test_html)))
                        {

                            //Parse the HTML
                            try
                            {
                                iTextSharp.tool.xml.XMLWorkerHelper.GetInstance().ParseXHtml(writer, doc, msHtml, msCss);
                            }
                            catch { }
                        }
                    }

Comment: Upgrade to iText 7 and use the pdfHTML add-on. That upgrade of XML Worker fixes the problem you mention.
Comment: Make your HTML well-formed with JSoup before you feed it to XMLWorker. pdfHtml, mentioned by Bruno, already does that for you but in iText 5 it is still a manual step.
Comment: If you are a licensed user then you don't need to use Stack Overflow, which is community support without guarantees. You can use our support system, JIRA, with the web interface or the email address that was provided to your company when you purchased. If you don't have this information then you will have to ask the person inside your company who was responsible for purchasing an iText license.
Comment: @AmedeeVanGasse - Regarding the use of iTextSharp and XMLWorker 5.XX, the .NET de facto standard HTML parser is [HtmlAgilityPack](https://www.nuget.org/packages/HtmlAgilityPack/), maybe in large part due to the fact that the .NET port of JSoup is not maintained.
Comment: i upgraded to Itext 7 licensed version. Can any of to point me to correct resources i can refer to and i am using c# as programming language. Please let me know if i can get some support form Itext since am using a licensed version . Thanks alot @BrunoLowagie
Comment: i have a itextsharp licensed key and i tried to use the same key for itext7 - it didnt work,  also i just downloaded a trail version key and tried to use itext7 pdfHTML - it didnt work saying license file is corrupted. @AmedeeVanGasse need help
Comment: A license key for iText 5 (iTextSharp) will not work for iText 7. A license key for iText 7 will not work for IText 5.
Comment: Thanks alot. i downloaded the Itext7 trail key and got it working. Is there a sample or way to apply external css while converting html to pdf using pdfHTML. @AmedeeVanGasse
Answer: It's a bit unclear whether you've decided to use iText7 or iTextSharp (5.x.x), but here's a simple example of the latter using HtmlAgilityPack to clean up malformed HTML:
var malformedHtml = @"

Malformed HTML

A paragraph with improperly nested tags

Cell 1, row 1	Cell 1, row 2";
HtmlDocument h = new HtmlDocument()
{
    OptionFixNestedTags = true, OptionWriteEmptyNodes = true
};
h.LoadHtml(malformedHtml);

string css = @"
h1 { font-size:1.4em; }
hr { margin-top: 4em; margin-bottom: 2em; color: #ddd; }
table { border-collapse: collapse; }
table, td { border: 1px solid black; }
td { padding: 4px; }
span { color: red; }";

using (var stream = new MemoryStream())
{
    using (var document = new Document())
    {
        PdfWriter writer = PdfWriter.GetInstance(document, stream);
        document.Open();
        using (var htmlStream = new MemoryStream(Encoding.UTF8.GetBytes(h.DocumentNode.WriteTo())))
        {
            using (var cssStream = new MemoryStream(Encoding.UTF8.GetBytes(css)))
            {
                XMLWorkerHelper.GetInstance().ParseXHtml(writer, document, htmlStream, cssStream);
            }
        }
    }
    File.WriteAllBytes(OUTPUT, stream.ToArray());
}

PDF output:
Answer: And if you are free to choose your particular iText flavour, please go with iText7 and pdfHTML. It supercedes XMLWorker, supports a wider range of tags and CSS3.0.


MongoDB couldnt connect to server 127.0.0.1:27017

Question: This is a picture of the response it is giving me. I cannot copy cmd stuff for some reason = (

Please let me know if you need more info. I figure it is something sort of trivial. This is so foreign to me.
MORE DETAILS:
So the command I ran now was
mongod --dbpath c:\users\hassan\docs\tutorial

ALSO TRIED
mongod --dbpath c:\users\hassan\docs\tutorial\data

mongod --dbpath c:\users\hassan\docs\tutorial\data\db

tutorial is the folder with the app.js file that I run
Comment: Can you show us the error response you get when you run the commands above?
Answer: The problem is that you do not have your \data\db folder. Create it and everything will be ok.
P.S. you can copy the text by doing right click, then mark, then select text then CTRL+C.
Comment: @user2783087 are you sure that the folder exists, because mongo clearly tells you that it is not there.
Comment: so can you show the output as a normal text after you created a folder?
Comment: Node problem is completely another question, and I have little experience with node.js
Comment: I tried creating a \data\db folder and a \data folder and in neither did it work ;(
Comment: after I add it, it still doesnt
Comment: http://i.imgur.com/uy9Yn9s.png
k so actually now I think it works....it just...uh..it might be a problem with my node = (
Comment: ( = ! ty
yea I think it's node. I am not totally sure though =  (


Script not running on startup for GPO

Question: I have seen many posts on this website about something similar but none of them have had the resources to fix my issue so I will go into as much detail as I can. If I leave any information out let me know.
We have a server with an exe file on it to start an update for a software called Bluebeam. I wrote a script file to start that exe on startup and placed it in the same directory as the exe. Nothing happened when I did that, I would start up a computer that I know has delegation and run gpupdate /force to get it going and restart the computer, nothing happens. I then made it so when there was a user logon it would do the same. Same result. I made sure "enforced" was enabled, I enabled "always wait for the network at computer startup and logon," and finally I also enabled "configure scripts policy processing"
None of those helped. I looked into the script files again and I noticed that when I clicked "show files" under my GPO, the script I wanted wasn't there. So I added it manually and forced the update again, nothing.
I am only running this under a test environment right now so I am not pushing this to my domain controllers, servers, or really any users. I am pushing this to 2 different computers right now and they are not working.
I will show you photos of everything I have and if you all have any questions let me know.
Image showing GPs on the test environment
delegation to a computer called dantest, the one I am trying this with
the script at startup
the script at logon
Comment: Does the host have the Apply Group Policy permission?
Comment: @GregAskew where do I check that?
Comment: @GregAskew, never mind I found it and yes it does
Comment: Startup Scripts only run at computer startup. Have you rebooted the test computers since fixing the GPO? Are the computer accounts in the Scope of Management of the GPO?
Comment: @joeqwerty yes to both. I have restarted the computer many times as well as forcing the group policy update through a command line. And the GPO is linked to my test environment and the DANTEST computer I am updating/restarting is delegated as a computer within the scope of my GPO
Comment: Have you verified that the script and the executable run as expected outside of the context of the GPO?
Comment: @joeqwerty yep the script runs exactly as expected locally on the machine. only having problems when I try to push it our through GP
Comment: Does the script / installer run silently, or does it actually launch a windowed installer application? Also, does it require any input from a user?
Answer: Forget about the Startup Script in "Computer Configuration" because the script you set there is executed by the System even before anyone is logged in.
This is typically not interactive (you can add scripts to cleanup certain directories, or configure something on the computer, but you can't start an end-user application here, the app will not show but may be running in the background).
Well, you configured the Logon Script in "User Configuration" too, that's better because the scripts here are executed in the user's context, however, since Windows 8.1 the Logon Scripts don't run for five minutes after a user logs on. This is by design to speed up the loading of the user's desktop. However you can change that:

If you want the logon scripts to run at user logon without any delay,
you should configure the Configure Logon Script Delay setting to
Disabled in the Computer Configuration\Administrative
Templates\System\Group Policy location.

But, still, this is not the preferred way of achieving what you want, as Microsoft says:

This mechanism allows administrators to perform various maintenance
and management tasks on client computers, including (but not limited
to) collecting diagnostic information, invoking security scans,
cleaning or resetting system state, and installing tools.

you are out of scope because you don't want to "perform various maintenance and mangement tasks" with your use case.
I recommend you to deploy a Run Registry Key instead. You can still deploy that with Group Policy:
If you want to deploy this on a Computer (so that it applies to everyone logging in on the computer), then, in your GPO, go to Computer Configuration -> Preferences (not "Policies") -> Windows Settings -> Registry -> New Registry Item, and create a new REG_SZ value under the path shown in the documentation (HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Run), give it a meaningful Value name, and set the Value data to be the path of the executable on the computer.
If you want to deploy this setting on a per-user basis, then use the same method but on User Configuration instead of Computer Configuration (and HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Run instead of HKLM).
Don't forget to link the Group Policy on an O.U containing your Users if you are using User Configuration, or on a Computer O.U if you are using Computer Configuration (same for the Delegation rights, add users if you are working with User Configuration or Computers if you are working with Computer Configuration)
Comment: I did what you said and made a registry, forced an update, and waited for some time and still nothing happened. With the registry is there something I need to click in order for it to activate on the computer. I clicked "apply" when I made it and then clicked ok and closed out of GP editor. Also, should I delete the other configurations I have? Thanks!
Comment: @Nick Run this command as admin on a client computer and see if you can see your GPO `gpresult /h c:\temp\report.html` it will export a report and you'll be able to see if your policy applies to the computer or not. Additionally, can you see the registry key on the client computer
Comment: there is nothing underneath the preferences -> windows setting tab except for drive maps. No registry or anything of the like
Comment: @Nick If you created the registry configuration under "User Configuration", ensure the GPO is linked to an O.U containing your users. If you create the registry configuration under "Computer Configuration", ensure the GPO is linked to an O.U containing your computers.
Comment: It is linked and there is nothing. https://docs.google.com/document/d/1HcCG7Rem-pO8FksjGFgpbDin9a0LohGgBfQ-kU5xGNY/edit?usp=sharing
Answer: You're close, but missing one important thing: based on your screen shot, no objects have the "Apply" permission for this GPO. The default GPO would grant the 'Read' and 'Apply' permissions to the "Authenticated Users" group. I'm guessing that you removed this from the security filtering setting so you could apply it only to your test machine.
To fix the startup script policy and still keep it only applicable to your "DANTEST" computer, edit the GPO, open its properties, and go to the security settings. Add the computer account for DANTEST and grant it the 'Apply' permission (in addition to the 'Read' permission).
If you want to use the logon script, follow the same process to add the 'Apply' permission for the user who is testing the script. Then move the logon script out of the Computer Settings section of the GPO and into the User Settings of the GPO.
Finally, when you're done testing, you can simply add "Authenticated Users" with the "Read and Apply" permissions, which is the default security filtering.
Comment: Tried this. The "Read (from security filtering)" automatically applies it, each of them has the apply permission checked in the security tab already.
Comment: As for the ones that say "read," only the "CREATOR OWNER" user did not have apply set, I made sure it did and it did not change anything
Comment: What information does your group policy processing event log contain?
Comment: No errors and nothing about the update even happening. Its like there is no gpo actually getting pushed out
Comment: Do you have the GPO linked to the OU where the test computer lives or to the domain root?

Script not running on startup for GPO


What can we conclude when the confidence interval for a regression line slope contains 0?

Question: If my confidence interval, say $(-.4, .7)$, for a regression line slope contains $0$, I am looking for the strongest conclusion that I can make from that. Can I conclude that "there is no statistical significance that there is a non-constant linear relationship between the two variables involved"?
My flawed reasoning and possible source of confusion: Even though $0$ is in this confidence interval, the set $\lbrace0\rbrace$ has measure $0$, so the probability of having slope $0$ should always be $0$ (regardless of whether or not $0$ is in the confidence interval).
Answer: I would phrase it as follows.

We can't even pin down if the relationship is positive or negative.

This gets out of the issues surrounding the fact that we kind of know the parameter is not exactly zero, but it shows how we lack much information. (Think of someone telling you that your stock portfolio is either going to increase or decrease in value. I would not find that helpful!)
Comment: That's more like an interpretation of a (Bayesian) credible interval than a (frequentist) confidence interval.
Comment: For example, if the confidence interval for my stock was $(-0.001, 100^100)$, although there's a chance it can be negative, isn't there an overwhelmingly large chance that it is positive?


Simple AJAX Function Issue: How does server receive message from client automatically?

Question: I read some tutorials from w3school about ajax. I assume that how does server receive message from client automatically. I have two pages, one is for client and one is for server. When someone type something and click submit, then the server page will automatically append on the screen. This is what I use:
client:

<input type="number" name="f1" id="f1" placeholder="first number..." />
<input type="number" name="f2" id="f2" placeholder="second number..." />
<input type="submit" id="submit" value="submit" />

server:
$(function(){
$("#pmsg").hide();
$("#msg").load("client.html", function(){
$("#pmsg").show().delay(1000).hide();
});

});

new message

I can't achieve the result that I want, could someone tell me how to fix it? thx!
I solved the problem. I use php to write the message into a txt file and then use $.get to get the message from that file.
Comment: You didn't understand AJAX at all? Where is you server side content?
Answer: You are basically using the jQuery liberary and its load function to do the ajax work.
It actually work like this:
It create the http object as per browser (for IE - activexobject, FF - xmlhttprequest) and send the request to url that we are called as server site.
There are four states:
0: request not initialized
1: server connection established
2: request received
3: processing request
4: request finished and response is ready

Below is the code:
var xmlhttp;
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
    }
  }
xmlhttp.open("GET","ajax_info.txt",true);
xmlhttp.send();


Let $A$ be a semigroup and $X\subseteq A$. Define $X_0=X$ and $X_{n+1}=X_n\cup \{ab\, |\, a\in X,\, b\in X_n\}$. Then $\cup_{n=0}^{\infty}X_n=Sg^A(X)$

Question: Let $A$ be a semigroup and $X\subseteq A$. Define $X_0=X$ and $X_{n+1}=X_n\cup \{ab\, |\, a\in X,\, b\in X_n\}$.
Then $\bigcup\limits_{n=0}^{\infty}X_n=Sg^A(X)$, which is the subsemigroup of $A$ generated by $X$.
This is my proof:
( $\subseteq$ ) It suffices to check, by induction on $n$, that $X_n\subseteq Sg^A(X)$ for all $n$.
$X_0=X\subseteq Sg^A(X)$ since $Sg^A(X)$ is the smallest subsemigroup of $A$ containing $X$.
Assume that $X_n\subseteq Sg^A(X)$. If $x\in X_{n+1}\backslash X_n$, then $x=ab$ for some $a\in X$ and $b\in X_n$.
So $a,\, b\in Sg^A(X)$ and $x=ab\in Sg^A(X)$ as well. Hence $X_{n+1}\subseteq Sg^A(X)$.
( $\supseteq$ ) It suffices to check that $\bigcup\limits_{n=0}^{\infty}X_n$ is a subsemigroup of $A$ containing $X$.
My question is how to finish the remaining part. If $a,\, b\in \bigcup\limits_{n=0}^{\infty}X_n$, how to prove $ab\in \bigcup\limits_{n=0}^{\infty}X_n$?
Answer: Hint:
$x\in X_n$ iff we can write $x=\prod_{i=0}^ma_i$ for $a_i\in X$ and some $m\leq n$.
This can be proved by means of induction on $n$.


How to skip cucmber steps if certain condition matched

Question: In cucumber with java i am writing a test case, where in one step i am looking for one web element.
If this web element is not found then i want to skip all the steps below this and also wants to mark this scenario as pass.
How to do that ?
When User logs into application
Then check if element is present (if this web element is not present then skip below steps)
Then navigate to Queue page
Then click on Fetch button
Answer: Maybe you can rewrite the Gherkin Steps in a way that is not conditional. And within the step that is where you can write the condition as an if-else statement.
<code>Scenario: --
  Given --
  When User logs into application
  Then navigate to fetch button

--

@Then('navigate to fetch button')
  // check the element
  // add an if-else statement
</code>


java - scanning txt into 2D arrays with own class

Question: to start with i want to say this is no homework or somthing, i just want deeper knowledge about these kind of arrays with I/O so feel free to just tell me how you tackle the problem WITH SCANNER, if its solvable :P
if i have a txt file that is like:
    car 1 2 3 4 5
    boat 1 2 3 4 5
    plane 1 2 3 4 5

and i have made a new class in new .java-file which is an abstract 2d array:
    class Type
    {
           String type;
           int number;
    }
    public toString()
    {
            return String.format("%02d:%02d", type, number);
    }

is it possible to get an outprint like:
    car:1 car:2 car:3
    boat:1 boat:2 boat:3

etc? thanks.
edit: also an ArrayList of course..
edit2:
    while (scanner.hasNext())
    {
        list.add(scanner.hasNext(), 0); //the array should be <car, 0>
    }                                  //later i will loop through numbers

Comment: You state: `i have tried, but unfortunately i have so much other to study like maths so i dont have too much time to experiment` -- So in effect you're saying that your time is more valuable than ours? Come on now!
Comment: It's solvable. Why not give it a try first before posting here? You won't break your computer by doing this, and even if your code doesn't work, you'll learn much more in the process of trying to push your abilities than you would if someone spoon-feeds you a solution.
Comment: i have tried, but unfortunately i have so much other to study like maths so i dont have too much time to experiment >.<
Comment: i get stuck on this part also:
ArrayList list = new ArrayList();
....
list.add(scanner.nextInt(), null); //adding the type

and i just dont seem to know how to iterate and put the number, can you use indices with scanner like scanner.nextInt(1) (which would be first number)
Comment: im only meaning what im saying, that lack of time prevents me from experimenting. but alright, ill check into it in some weeks when im done with my exams then... close this :)
edit: you are mean, hovercraft :(
Comment: To solve this with a Scanner, consider using two Scanners, one to read each line, and the other that you create inside of your `while (firstScanner.hasNextLine())` loop to read each token contained in the line. Again, experiment with it and you'll probably get it to work. If you go this route though, don't forget to dispose of each Scanner object when you're done with it.
Comment: Alternatively, you could use 1 Scanner to read each line, and then split the String that you get via `myString.split(" ");` and then iterate through the array returned in a for loop.
Comment: yea im about to do that now. the thing i dont get with abstract arrays (or any of dimension > 1) how you add just one.
i mean if i scan the first token in the line, which is the type i want to "list.add(scanner.next(), )" and then loop and add the numbers with the type.

i think the javadocs/tuts lacs the info about these kind of things, or i just havent learned how to search properly
Comment: Please clarify your question including showing the code of just what you mean in the statement above as an edit to your original question.
Answer: First thing that comes to mind is this (assuming your file will always have that structure):

Read your line and use string.split("\\s+"); to break your line into word tokens (\\s+ denotes one or more space in regular expression language).
If you can be certain that the word will always be the first element in the line, then, you can iterate from your 2nd token (your first number) till your last token (your last number) and with each iteration you create a new Type object where the type is the first token and the number is the nth token.

The above should allow you to construct objects which when printed, will yield your desired output.
If on the other hand, the order of the tokens is not known, but you are sure that in every line you will have one word and n numbers, you can use further regular expressions such as ^\\w+$ and ^\\d+$ to see which token is either a word or a digit respectively. Once you know which token is what, you can refer to the above points to get your code to work.
For more information on regular expressions, you can take a look at this tutorial.
Comment: yeah i know its solvable that way but i prefer using scanner, since it could be real useful in general when handeling files since it splits them to tokens implicity.
Answer: The pseudo-code of what I'm suggesting is this:
create line Scanner
while scanner has next *line*
   get the next line
   use String#split(" ") to create a String array from this line
   Create your object from the items in this array
   Add your new object into your list
end while loop

Comment: yeah i guess this is the answer, i did a similar pseudo-sketch when i thought about this problem:

        (while scanner has next line)
        (save the next line first in the array list)
        (while scanner.hasNextInt(), print  and increment num)

and i still dont understand how to get my 2d arrays to work properly as my edit, so thanks for the post and ill get back at this problem in a couple of weeks when i have more time to learn about 2d-arrays in action with scanners, im not gettin anywhere at this point :P

darnit, codebrackets doesnt work for replies >.<


Prove that every vertex of a 2-regular graph G lies on an exactly one circle

Question: My only idea so far is that if a vertex $v$ would lie on more than one circle, i. e. on 2 circles, then those 2 circles must separate in some vertex in order to be different and that cannot be because each vertex has  a degree of 2.
I'm not even sure whether my assumption could somehow help me in proving the statement. I would be thankful for some hints.
Comment: A $2$-regular graph is the union of disjoint cycles.
Answer: It suffices to prove that every 2-regular graph the disjoint union of cycles. Let $G$ be a 2-regular graph. Pick any vertex $v_1$ of $G$.  The vertex $v_1$ has at least two neighbors.  Say $v_2$ is a neighbor.  Now $v_2$ has two neighbors, and so has another neighbor besides $v_1$. Call this neighbor $v_3$.  By repeating this process, we get a sequence of vertices $v_1, v_2, \ldots$.  Since the graph is finite, at some point we repeat a vertex, $v_k$ say.  So $v_k, v_{k+1}, \ldots,  v_k$ is a cycle $C$ in the graph $G$.  Observe that $C$ is a 2-regular subgraph of $G$. Because $G$ is 2-regular, the edges of $G$ incident to each vertex of $C$ are also the edges of $C$. We remove from $G$ the edges and vertices of $C$. The induced subgraph $G-C$ is again a 2-regular graph.  We now repeat the above procedure to get another cycle, and so on.
Comment: Thank you, that was exactly what I was looking for.
Answer: Here is another answer:
Since $G$ is $2$-regular, sum of vertices degrees of $G$ is $2n$ hence $m = n$. Now consider $G$ and suppose it has $r$ different connected components. Call them $G_1$ through $G_r$ and suppose $G_i$ has $k_i$ vertices. We have $k_1+k_2+...+k_r = n$. Suppose $T_i$ is a spanning tree of $G_i$ and hence has $k_i-1$ edges so $T_1$ through $T_r$ omit $r$ edges of $G$. As $G$ is $2$-regular, each $T_i$ is a path so is $P_{k_i}$. (Root each tree from a leaf and assertion becomes evident) Any edge between non-endpoint vertices of $P_{k_i}$ results in a vertex of degree $3$ so the only possible edge that can be added is the one between the endpoints of the path and as each component $G_i$ must have $k_i$ edges each such edge should be present hence we conclude each $G_i$ is isomorphic to $C_{k_i}$ and we conclude a stronger result other than each vertex being present on exactly one cycle. $\blacksquare$


Concurrency value in JMS topic listener in Spring

Question: I know Spring but I am a newbie in JMS and started reading the Spring JMS. From the Spring JMS doc Spring doc, I read the following
The number of concurrent sessions/consumers to start for each listener.
Can either be a simple number indicating the maximum number (e.g. "5")
or a range indicating the lower as well as the upper limit (e.g. "3-5").
Note that a specified minimum is just a hint and might be ignored at
runtime. Default is 1; keep concurrency limited to 1 in case of a topic
listener or if queue ordering is important; consider raising it for
general queues.

Just want to understand why should the concurrency limited to 1 in case of a topic listener? If I increase it, say to 10 instead of 1, what would happen?
Answer: Each subscriber receives a copy of each message published to a Topic. It makes no sense at all to put up multiple consumer, since all your application would do is to receive the same message 10 times, in different threads.
In the case of a Queue, messages on the queue would be distributed among 10 threads and hence, handled concurrently. That is indeed a very common scenario - load balancing.


Android WebView Disable Iframe Loading

Question: In my app I have an WebView which displays some webpages.
Some webpages contain iframes. and some iframes load alertboxes, confirmboxes, prompts and popups.
I want to block loading that iframe but not loading it? or atleast disable these popups (without disabling javascript)
I tried to block these pages by filtering them by following method
in the on page started method
use the if condition to match the url with the url which gives popups
if matched restart the webview

however i found that the url is always of the main site and not the site the iframe loads so if statement is never true
how do I block the iframe or popups?
any help would be appreciated
thankyou
Answer: You need to implement WebViewClient and override shouldOverrideUrlLoading.
Check if it's an iframe with if (!request.isForMainFrame()).
Then you can manually load the content of the url and sanitize it.
@TargetApi(24)
@Override
public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
    if (!request.isForMainFrame()) {
        if (shouldBlock(request.getUrl()))
            return true;
    }
    return super.shouldOverrideUrlLoading(view, request);
}

Comment: i found shouldOverrideUrlLoading not called if url contain target = newblank

Android WebView Disable Iframe Loading


Center absolute positioned overflowing div

Question: This is what I tried and it gets me 99% there.

.polaroids-container {
  overflow-x: auto;
  position: relative;
  height: 245px;
  padding-top: 10px;
  display: -webkit-flex;
  -webkit-justify-content: center;
  display: flex;
  justify-content: center;
  padding-left: 0;
  padding-right: 0;
}

.polaroids {
  position: absolute;
  min-width: max-content;
}

Images here

Images here

Images here

Images here

Images here

Images here

This will center my content but the first element in the div is getting cut off on the left. As you can see in the image the scroll bar is all the way to the left so you cannot scroll left to see that content.
The objective here is to center all the divs within class polaroids and not have the first one not get chopped off.
Answer: Okay, I did a quick fiddle and I see what you're doing now.  Add "left:0" to polaroids.  Once your alignment is set, then set your scroll to be centered using JavaScript.
.polaroids {
  position: absolute;
  left:0;
  min-width: max-content;
}

Comment: All that did was make the overflowing div no longer overflow the parent. I need this div to be scroll-able horizontally.
Comment: Did a quick test.  Looks like this is an alignment issue and not a margin issue like I first thought.  See revised answer.
Comment: left:0; completely removes the centering. I need the variable width absolute div to be centered. Even when its overflowing.
Comment: Try this.  The Left:0 fixes the cropping issue, but you then need to center your scrollbar using the above JavaScript.  What you were doing before was centering your content along the margin of your container which was cropping it.


How to make a random draw from a mgcv GAM model

Question: Hi there statistical wizards!
I have a (maybe) minor problem, where I would like to use the predicted fit (fit) and standard error (se.fit) from a GAM model to take a random draw. Ideally I would like to know how to convert this standard error to a standard deviation so as to use rnorm(mean, sd) on each fitted value.
To compute the standard deviation from the standard error we need an N value, but I'm not sure how to compute this.
So far my code looks like this:
library(mgcv)
library(ggplot2)

eReefs.chl = c(0.24596960, 0.15762042, 0.10942775, 0.12170488, 0.08990742, 0.07395359, 0.08712383, 0.08182129, 0.08367566)
SON = c(-1.7, -1.1,  0.2, -0.2,  0.4,  2.4, -0.7, -0.7,  0.7)
years = 2010:2018

dat = data.frame(cbind(eReefs.chl, SON, years))

gamfit = mgcv::gam(eReefs.chl~s(SON, bs = "cs", k=4), data = dat)
mgcv::gam.check(gamfit)
plot(gamfit, residuals = T, pch=19, cex=1, xlab = "SON Nino3.4", ylab = "Median Chlorophyll Concentration",
     all.terms = T, shade=T, shift = coef(gamfit)[1])

newdat = data.frame(SON = c(0.3,  0.8, -0.2,  0.1,  0.7, -1.0, -0.4,  2.3, -1.4, -1.3, -0.6, -0.3,  1.2,  0.3,  0.7, -0.3,
                            0.7, -1.4, -0.4,  1.0, -1.7, -1.1,  0.2, -0.2,  0.4,  2.4, -0.7, -0.7, 0.7), years = 1990:2018)

pred = predict(gamfit, newdata = newdat, se.fit = T)

# Now I want to draw from a particular year to run stochastic simulations,
# so I want to create  a standard deviation from the SE, but I don't know N

#stddev = pred$se.fit*n
#rnorm(1, pred$fit[1], stdvev[1])

I would really appreciate some help on this, or an alternative approach. For context I am fitting about 1500 of these gam's so thats why I want to use the fit and standard error to draw from later after the model has been fit.
Comment: You understand that the standard errors only correspond to the expected value, not the prediction, right?
Answer: That standard error is the uncertainty in the estimate for the expected/fitted value. For the variance of the posterior distribution, you want the estimated value of the variance (or scale parameter) for the model you fitted. You fitted something like
$$y_i = \beta_0 + f(x_{1i}) + \varepsilon_i$$
where $\varepsilon_i \sim N(0, \sigma^2)$, where the variance of the residuals (data) is estimated $\hat{\sigma}^2$. Another way of writing this is
$$Y \sim N(\hat{\mu}_i, \hat{\sigma}^2)$$
$$\hat{\mu}_i = \beta_0 + f(x_{1i})$$
Notice that $\hat{\sigma}^2$ is separate from the predicted value $\hat{\mu}_i$, and is an estimate of the variance of the data not the uncertainty in the predicted value. It is this $\hat{\sigma}^2$ that you want to get.
One way to do this for the Gaussian models you fitted requires three things:

the expected value, which will be the value you pass to mu
the estimated variance/scale parameter,
observation weights, which we presume to be 1 here.

You already have mu as this is the fitted value for the new observation(s). The estimated variance/scale parameter can be extracted from the model as component sig2 of the fitted model. (This may not exist in all GAMs fitted by mgcv, so we can try to extract it as
summary(model)[["dispersion"]]

but for these Gaussian GAMs, model$sig2 will suffice, where model is your fitted GAM model.) Let's call this variance/scale parameter sig2.
In the case of weights, the standard deviation for use in rnorm() is
sqrt(sig2/wt)

where wt is the weight for that observation. As I presume you will want a weight of 1, then you can just use
sqrt(sig2)

This process extends to all of the models the gam() is capable of fitting — although the detail will be different.
You can get a function that given mu, sig2 and wt will generate draws from the correct distribution for a GAM using the fix.family.rd() function in mgcv. You pass it the family function for the fitted model & extract the newly added rd component.
rdfun <- fix.family.rd(family(model))$rd

For Gaussian models this is:
> fix.family.rd(gaussian())$rd

function (mu, wt, scale)
{
    rnorm(mu, mean = mu, sd = sqrt(scale/wt))
}
<bytecode: 0xd0e81b8>
<environment: 0x950aa40>

Which is where we see how this is implemented/computed.
As for the detail for other models, if you are unsure, consult the rd functions mgcv adds. For example, for the Poisson:
> fix.family.rd(poisson())$rd
function (mu, wt, scale)
{
    rpois(length(mu), mu)
}
<bytecode: 0xd0e95a0>
<environment: 0xcd55138>

we see that we only need mu, the expected value to make draws from the posterior distribution, but for the negative binomial we need something extra, the $\theta$ parameter of the (particular parameterisation of the) negative binomial distribution
> fix.family.rd(nb())$rd
function (mu, wt, scale)
{
    Theta <- exp(get(".Theta"))
    rnbinom(mu, size = Theta, mu = mu)
}
<environment: 0xe4f9c80>

Comment: Thanks so much, that was a really detailed and clearly written response :) I think I'm all set. You're a legend Gavin, my afternoon just got a lot easier
Comment: @SamMatthews Happy to help. My [*gratia* pkg](https://gavinsimpson.github.io/gratia/) has a `simulate()` method for GAMs, which encapsulates all of this, however it wouldn't be useful in this case if you don't want to save the models.
Comment: I'll definitely keep it in mind for future work. I've just already written my workflow so didn't want to mess around to much. Thanks again


Enviar um objeto usando Gson

Question: Estou com o seguinte problema: preciso enviar um objeto para o meu web-service, porém, não é viável usar JSONStringer, pois a minha classe possui muitos campos. Qual seria a melhor forma de resolver este problema? Usei o seguinte método, porém não funcionou (retorna que meu objeto é nulo), segue o código:
 public String postPedido( Pedido pedido)
 {
        int statusCode = 400;
        try
        {

            HttpPost request = new HttpPost(SVC_URL );
            request.setHeader("Accept", "application/json");
            request.setHeader("Content-type", "application/json");

           Gson gson = new Gson();

           String json = gson.toJson(pedido, Pedido.class);
           StringEntity entity = new StringEntity(json);

           request.setEntity(entity);

            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpResponse response = httpClient.execute(request);

            statusCode = response.getStatusLine().getStatusCode();

        }

        catch (Exception e)
        {
            e.printStackTrace();

        }

        return String.valueOf(statusCode);
    }

Segue a assinatura do método do Web Service:
[OperationContract]
    [WebInvoke(
        Method = "POST",
        UriTemplate = "PostPedido",
        BodyStyle = WebMessageBodyStyle.WrappedRequest,
        ResponseFormat = WebMessageFormat.Json,
        RequestFormat = WebMessageFormat.Json)]
    bool PostPedido(Pedido pedido);

E o método é este:
public bool PostPedido(Pedido pedido)
    {
        var teste = new StringBuilder();
        bool result = false;
        if (pedido != null)
        {
            teste.AppendLine(String.Format("Numero do pedido {0}", pedido.NumeroOrcamento));
            teste.AppendLine(String.Format("Total Pedido {0}", pedido.TotalPedido));
            result = true;
        }
        else
        {
            teste.AppendLine("pedido vazio");
            result = false;
        }
        System.IO.File.WriteAllText(@"c:\teste.txt", teste.ToString());

        return result;
    }

PS: Por enquanto, este método é apenas para teste.
Comment: Qual exatamente é o seu objeto nulo que você se refere? A string `json`? O `entity`? Caso for este segundo, experimente informar o *charset* no segundo parâmetro.
Comment: O objeto é reconhecido como nulo pelo Web-service.
Comment: Fabio, bem-vindo ao [pt.so]! Não parece haver nada de errado com seu código, mas pode ser um problema ou incompatibilidade com o web service. O ideal seria recuperar o log bruto de como a requisição chega no servidor para determinar se ela está chegando exatamente no formato esperado. Tem como postar o método usado no web service?
Comment: Editei a pergunta, acrescentando o método usado no Web Service.
Answer: Altere a propriedade BodyStyle do atributo WebInvoke do método PostPedido no contrato para:
BodyStyle = WebMessageBodyStyle.WrappedResponse

Enviar um objeto usando Gson


Can't login using OpenId (core) and Google profile

Question: I'm using the OpenId module (included in core v7) but can't link an OpenId to an existing account. Every time I try to add it an error occurs:

Sorry, that is not a valid OpenID. Ensure you have spelled your ID
  correctly.

I'm trying to connect using a Google profile. The URL I'm trying is "https://profiles.google.com/x" (x => my id).
Has anybody succeeded in doing this?
Answer: The following works for me in Drupal 7:
<code>https://www.google.com/accounts/o8/id
</code>
For more information, see Whats My Google OpenID URL?.
Comment: "Sorry, that is not a valid OpenID. Ensure you have spelled your ID correctly." :-(
Comment: Any chance you have a trailing space or something? I tested the URL before I posted it and it worked for me.


Invalid Image Path - No image found at the path referenced under key 'CFBundleIcons':'AppIcon20x20'

Question: REPOSTING SINCE I AM GETTING NO ANSWERS ON THIS.
I have been struggling with this issue for over a week. Whenever I try to validate a build or use application loader lately I have been getting this error:
<code>iTunes Store operation failed.
Invalid Image Path - No image found at the path referenced under key 'CFBundleIcons':'AppIcon20x20'
</code>
Now, the problem is there is no AppIcon20x20 key in my plist.
Here's my AppIcon asset and attributes settings:
AppIcon, Attributes
Nowhere is a 20x20 asset even mentioned in my Plist, as seen by the source code version here :
<code>    <?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>CFBundleIcons</key>
    <dict>
        <key>CFBundlePrimaryIcon</key>
        <dict>
            <key>CFBundleIconFiles</key>
            <array>
                <string>icon603x.png</string>
                <string>icon602x.png</string>
                <string>icon403x.png</string>
                <string>icon402x.png</string>
                <string>icon293x.png</string>
                <string>icon292x.png</string>
                <string>icon203x.png</string>
                <string>icon203x.png</string>
            </array>
        </dict>
    </dict>
    <key>NSAppTransportSecurity</key>
    <dict>
        <key>NSAllowsArbitraryLoads</key>
        <true/>
        <key>NSExceptionDomains</key>
        <dict>
            <key>https://millsfitnessapparel.myshopify.com/</key>
            <string></string>
        </dict>
    </dict>
    <key>CFBundleDevelopmentRegion</key>
    <string>en</string>
    <key>CFBundleExecutable</key>
    <string>$(EXECUTABLE_NAME)</string>
    <key>CFBundleIdentifier</key>
    <string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
    <key>CFBundleInfoDictionaryVersion</key>
    <string>6.0</string>
    <key>CFBundleName</key>
    <string>$(PRODUCT_NAME)</string>
    <key>CFBundlePackageType</key>
    <string>APPL</string>
    <key>CFBundleShortVersionString</key>
    <string>1.0</string>
    <key>CFBundleVersion</key>
    <string>1</string>
    <key>LSRequiresIPhoneOS</key>
    <true/>
    <key>UILaunchStoryboardName</key>
    <string>LaunchScreen</string>
    <key>UIMainStoryboardFile</key>
    <string>Main</string>
    <key>UIRequiredDeviceCapabilities</key>
    <array>
        <string>armv7</string>
    </array>
    <key>UISupportedInterfaceOrientations</key>
    <array>
        <string>UIInterfaceOrientationPortrait</string>
        <string>UIInterfaceOrientationLandscapeLeft</string>
        <string>UIInterfaceOrientationLandscapeRight</string>
    </array>
</dict>
</plist>
</code>
And lastly, I have googled the heck out of this topic and they all say to just add CFBundleIcons to your plist, which I did, but it's still throwing the error. I have also done this in versions of this project where there are pods, no pods, workspaces, regular xcproj. files, and even with 1 view controller and just some icons [this latest build].
I have also tried to achive this build in xcode versions 8.1, 8.2, and 8.3, all receiving the same error.
Any help here would be greatly appreciated. These are apps for a client and I am currently late on delivering because of this issue. Thanks.
Comment: I know you already got answer but its for other coming here.
You can get this issue if your app icon name aren't correct. I was using appicon.co which was generating wrong names that's why I was getting this error. Then I used "Icon Set Creator" iMac app to generate icons & everything worked fine after using them.
Answer: you can simply create your app icons asset using https://makeappicon.com/. You have to supply a 1536x1536px image for the best result. It will automatically create all the app icons for your project
Also please refer to the following:-

Check the icon file's name is exactly same as the name in your info.plist.  It's fine while running debug mode though, It doesn't work while you upload/ validate the build.
Please check your app's bundle identifier is correct.
Comment: I have posted the screenshot, its in the main message.
Comment: Here's the contents.json: `{
  "info" : {
    "version" : 1,
    "author" : "xcode"
  }
}`
Comment: The make app icon was the answer, it's now uploading. Thanks!
Comment: This actually worked for me, using AppIcon.co did not really help out, thanks man for your help
Comment: Still, you can't resolve this. Please post the screenshot of your app icon's asset folder and content.json
Comment: if Non of the above worked please check this. http://stackoverflow.com/questions/19316501/xcode-5-invalid-image-path-cfbundleicons?rq=1
Comment: makeappicon.com will automatically generate all the icons set for our app including ipad and iwatch
Comment: I have now struck the same problem. I have been using 9.3 as a deployment target and never had a problem. I changed deployment target to 11.3 - and that did not cause a problem, however, I then switched back to 9.3 and the problem occurred, I tied 10 and the problem persisted, when I switch back to 11.3 the problem disappears.
I suspect it could be an Xcode bug.
Comment: This worked for me too thanks. I think the issue was wrong names initially but using makeappicon to generate the icons worked like a charm
Comment: I don't have icons names in info.plist at all, is it suppose to add there itself when I add app icons?
Comment: @ZeeshanAhmadKhalil you don't need this if you are using xcassets.