Fragment instance is retained but child fragment is not re-attached

Question: Update: accepted answer points to explanation (bug) with a work-around, but also see my Kotlin based work-around attached as an answer below.
This code is in Kotlin, but I think it is a basic android fragment life-cycle issue.
I have a Fragment that holds a reference to an other "subfragment"
Here is basically what I am doing:

I have a main fragment that has retainInstance set to true
I have a field in the main fragment that will hold a reference to the subfragment, initially this field is null
In the main fragment's onCreateView, I check to see if the subfragment field is null, if so, I create an instance of the subFragment and assign it to the field
Finally I add the subfragment to a container in the layout of the main fragment.
If the field is not null, ie we are in onCreateView due to a configuration change, I don't re-create the subfragment, I just try to added it to the containter.

When the device is rotated, I do observe the onPaused() and onDestroyView() methods of the subfragment being called, but I don't see any lifecyle methods being called on the subfragment during the process of adding the retained reference to the subfragment, to the child_container when the main fragments view is re-created.
The net affect is that I don't see the subfragment view in the main fragment.  If I comment out the if (subfragment == null) and just create a new subfragment everytime, i do see the subfragment in the view.
Update
The answer below does point out a bug, in which the childFragmentManager is not retained on configuration changes.  This will ultimately break my intended usage, which was to preserve the backstack after rotation, however I think what I am seeing is something different.
I added code to the activities onWindowFocusChanged method and I see something like this when the app is first launched:
activity is in view
fm = FragmentManager{b13b9b18 in Tab1Fragment{b13b2b98}}
tab 1 fragments = [DefaultSubfragment{b13bb610 #0 id=0x7f0c0078}]

and then after rotation:
activity is in view
fm = FragmentManager{b13f9c30 in Tab1Fragment{b13b2b98}}
tab 1 fragments = null

here fm is the childFragmentManager, and as you can see, we still have the same instance of Tab1Fragment, but it has a new childFragmentManager, which I think is unwanted and due to the bug reported in the answer below.
The thing is that I did add the subfragment to this new childFragmentManger.
So it seems like the transaction never executes with the reference to the fragment that was retained,  but does complete if I create a brand new fragment. (I did try calling executePendingTransactions on the new childFragmentManager)

class Tab1Fragment: Fragment() {

    var subfragment: DefaultSubfragment? = null

    override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?,
                          savedInstanceState: Bundle?): View? {
        val rootView = inflater!!.inflate(R.layout.fragment_main, container, false)
        if (subfragment == null ) {
            subfragment = DefaultSubfragment()
            subfragment!!.sectionLabel = "label 1"
            subfragment!!.buttonText = "button 1"
        }
        addRootContentToContainer(R.id.child_container, content = subfragment!!)

    return rootView
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        retainInstance = true
    }

inline fun Fragment.addRootContentToContainer(containerId: Int, content: Fragment) {
    val transaction = childFragmentManager.beginTransaction()
    transaction.replace(containerId, content)
    transaction.commit()
}

Answer: Your problem looks similar to the issue described here:
https://code.google.com/p/android/issues/detail?id=74222
unfortunately this issue will probably not be fixed by google.
Using retained fragments for UI or nested fragments is not a good idea - they are recomended to be used in place of onRetainNonConfigurationInstance, so ie. for large collections/data structures. Also you could find Loaders better than retained fragments, they also are retained during config changes.
btw. I find retained fragments more of a hack - like using android:configChanges to "fix" problems caused by screen rotations. It all works until user presses home screen and android decides to kill your app process. Once user will like to go back to your app - your retained fragments will be destroyed - and you will still have to recreate it. So its always better to code everything like if your resources could be destroyed any time.
Comment: I will take a closer look at the link you posted.  I am not 100% sure this is the same issue I am having.  BTW, all I am really trying to do is have several tabs, and each tab have it's own backstack.  I have seen a lot of solutions that involve managing your own back stack,  but they were kind of old, and for the most part I think the nested fragments seem to be working (each tab has it's own childFragmentManager with it's own back stack), now is the trick part of handing device rotations.
Comment: I am going to unaccept this for now, I do see the bug, and ultimately it will prevent me from doing what I was planning,  but this __seems__ to be something different.  I will add more to my question
Comment: the issue I was having __is__ related to this bug.  I will add some ore info in my question to document what I found, but basically this "subfragment" still thinks it is part of the now dead activity.  Explicitly removing it from the activity before it is destroyed, then allows it to be added to the new activity created after the rotation.
Answer: The accepted answer to my question above points out a reported bug in the support library v4 in which nested fragments (and child fragment managers) are no longer retained on configuration changes.
One of the posts provides a work-around (which seems to work well).
The work around involves creating a subclass of Fragment and uses reflection.
Since my original question used Kotlin code, I thought I would share my Kotlin version of the work around here in case anyone else hits this.  In the end, I am not sure I will stick with this solution, since it is still somewhat of a hack, it still manipulates private fields, however if the field name is changed, the error will be found at compile time rather than runtime.
The way this works is this:

In your fragment that will contain child fragments you create a field retainedChildFragmentManager, that will hold the childFragmentManager that will be lost during the configuration change
In the onCreate callback for the same fragment, you set retainInstance to true
In the onAttach callback for the same fragment, you check to see if retainedChildFragmentManger is non-null, if so you call a Fragment extension function that re-attaches the retainedChildFragmentManager, otherwise you set the retainedChildFragmentManager to the current childFragmentManager.
Finally you need to fix the child fragments to point back to the newly created hosting activity (the bug leaves them referencing the old activity, which I think results in a memory leak).

Here is an example:
Kotlin Fragment extensions
// some convenience functions
inline fun Fragment.pushContentIntoContainer(containerId: Int, content: Fragment) {
    val transaction = fragmentManager.beginTransaction()
    transaction.replace(containerId, content)
    transaction.addToBackStack("tag")
    transaction.commit()

}
 inline fun Fragment.addRootContentToContainer(containerId: Int, content: Fragment) {

    val transaction = childFragmentManager.beginTransaction()
    transaction.replace(containerId, content)
    transaction.commit()
}

// here we address the bug
inline fun Fragment.reattachRetainedChildFragmentManager(childFragmentManager: FragmentManager) {
    setChildFragmentManager(childFragmentManager)
    updateChildFragmentsHost()
}

fun Fragment.setChildFragmentManager(childFragmentManager: FragmentManager) {
     if (childFragmentManager is FragmentManagerImpl) {
         mChildFragmentManager = childFragmentManager   // mChildFragmentManager is private to Fragment, but the extension can touch it
     }
}

fun Fragment.updateChildFragmentsHost() {
    mChildFragmentManager.fragments.forEach { fragment ->  // fragments is hidden in Fragment
        fragment?.mHost = mHost  // mHost is private also
    }
}

The Fragment Hosting the child Fragments
class Tab1Fragment : Fragment() , TabRootFragment {

    var subfragment: DefaultSubfragment? = null
    var retainedChildFragmentManager: FragmentManager? = null
    override val title = "Tab 1"

    override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?,
                              savedInstanceState: Bundle?): View? {
        val rootView = inflater!!.inflate(R.layout.fragment_main, container, false)
        if (subfragment == null ) {
            subfragment = DefaultSubfragment()
            subfragment!!.sectionLable = "label 1x"
            subfragment!!.buttonText = "button 1"
            addRootContentToContainer(R.id.child_container, content = subfragment!!)
        }
        return rootView
    }

    override fun onAttach(context: Context?) {
        super.onAttach(context)
        if (retainedChildFragmentManager != null) {
            reattachRetainedChildFragmentManager(retainedChildFragmentManager!!)
        } else {
            retainedChildFragmentManager = childFragmentManager
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        retainInstance = true
    }
}

Comment: This no longer works in newer APIs / Kotling versions (1.4.10+). Does not compile.


Is there a way to register as a developer to Amazon's SP-API using a Vendor account?

Question: I'd like to register as a developer to the new Selling Partner API (SP-API) by Amazon.
This doc says I can do so using Seller Central, but I have a Vendor account, and therefore I need to use the Vendor Central.
Is there a way to do that?
Answer: Yes, there is. You can find everything you need in the Selling Partner API Developer Guide for Vendors. In particular, the answer to your question is under the section "Registering as a developer".


Why is the current scale system so popular?

Question: Sorry if it's some trivial/already answered question, but I could not find a suitable answer online.
I am a beginner at music theory, and learning through the chords and scales made me think "Why is A4 fixed as 440hz?", and also "Why divide the scales into 12 pitches even though it is not completely natural?" (since dividing into 12 pitches will make irrational approximate pitch differences, not perfect rational differences..).
So I wonder why the current musical scale system is so popular.
Comment: "dividing into 12 pitches will make irrational approximate pitch differences" ...are you getting into tuning systems like equal temperment versus just intonation?
Comment: that's a good question. if our music would have been for centenaries built on scales of 12 semitones or even quarter tones this other scale system would be "so popular". That in our western hemisphere the minor major system has become popular may be the result of the natural overtone series, the history  (harmony and polyphony)  and the dominance (cruelty) of western culture. The winner takes it all!
Answer: Those seem to be 2 different questions and the answer for both are really hard.

why A4 is fixed as 440hz

You might be surpried that A4 is not fixed as 440Hz! Some recordings use A 446Hz instead! (apparently it's a bit more commercial and some thing it has a brighter sound). For more info: https://en.wikipedia.org/wiki/A440_(pitch_standard)
When you have different musicians playing different instruments, you need to tune them all to each other so that the sounds go together nicely. Some instruments (like guitar) are easily tuned, but others like wind instruments are not that easy to adjust. At the end of the day, it makes sense to have everybody agreeing on a single pitch, and A440Hz was the agreed convention. It is just a convention, in the same way that we agree that 1h is made up of 60 minutes instead of 100.

"why divide the scales into 12 pitches even though it is not completely natural?" (since dividing into 12 pitches will make irrational approximate pitch differences, not perfect rational differences..).

The 12 tone scale is the accepted standard in Western music. Historically, other cultures have used scales made up of more than 12 notes (what we call "microtonal scales").
Now, I don't think that you can achieve perfect rational differences. Many phenomena in physics are logarithmic in nature. Even if you chose a different separation (like the 17-interval scale known as 17-TET) you would end up with irrational pitch differences.
At the core of our scale likes the octave, which corresponds to a double frequency. I once heard that given that our inner ear is shaped like a Nautilus, 2 frequencies of the same octave are aligned with each other in the same angle. Unfortunately, I don't have a source for that.
If we take A4 = 440, this means that A5 is 880, and A3 is 220.
Now, that interval is always a different number of Hertz, so no matter in how many intervals you divide it, you will end up with a logarithmic scale of some sort. To visualize this, imagine that we divide the scale in 6 tones instead (a really bad idea, but just humour me).
Visualize the fretboard of a guitar, and now remove every other fret. Still, by having only 6 intervals to an octave, you will end up with logarithmic/irrational intervals.
At the end of the day, it boils down to how our inner ear works, whereby we perceive logarithmic frequency differences to be "equal".
Comment: Which cultures use 17 notes? I know that 17edo is a pretty "popular" microtonal scale among microtonalists, but I haven't heard of its use in "world music".
Comment: Why break it down into 12 and not, say 14? That's another question altogether. The next obvious interval is 3x original frequency, which is a 12th (higher 5th). Let's bring it down 1 octave to play with more easily, and you get the 5th. If you start jumpling following the circle of 5ths, you get a pentatonic after 5 jumps, a diatonic after 7 and the chromatic after 12.
Comment: I get the first answer, but yet I don't get the second one. If we get a suitable starting pitch (256hz, for example) and let the octave as times 4 per one octave and pitch per octave as 1, then we will have perfect rational (in terms of hertz) pitches. I heard that we are using 12 pitches (in Western culture) since Aristotle, but at the time it was rational fractions, and because of the convenience of extending notes recently we have changed into root 12 systems. Now my question was "why 12"? Is it just a convention or there is certain benefits of number 12.  (I upvoted your answer anyway :) )
Comment: The fact that an octave is 2x the original frequency is not a "decision", but rather a consequence of how our ear hears the sounds. If you visualize the sine waves, all the "nulls" (Where the wave crosses the "0" mark) are aligned, so there is something inherently similar between A4 and A5.
Comment: @awe Iotta - I actualy don't know of a culture that uses it! I read that some Eastern / Middle Eastern use scales that we considered microtonal, and I've heard that 17 TET is one of the most frequent, and I put 2 and 2 together. Bu tI don't know anyone for sure. I will edit my answer, thanks.
Comment: "Now, I don't think that you can achieve perfect rational differences": people do this all the time.  What you can't do is tune a keyboard or other fixed-pitch 12-tone instrument using perfectly tuned rational intervals and then use it to play harmony or counterpoint unless you avoid certain intervals.
Answer: The 12 equal changes in an octave is the result of equal tempered tuning system.  You are correct that it is irrational but it's not the difference in pitch that is standardized but the ratio of consecutive half steps.  This was done to make other aspects of just tuning go away.  In particular if you work out the frequency ratios of the 2nd to 1 and the 3rd to 2nd (both whole steps) you get two different ratios, 9/8 for (1, 2) and 10/9 for (2, 3).  So the whole steps are not quite equal.  This means that (among other issues) what you play for an E in the key of C might be different than E in the key of D (assuming that "D" is really they same as the 2nd note of the C scale).  The "notes" need slight altering from key to key to maintain these ratios.  Also, one has the result that a sharp 2 might not be enharmonic with a flat 3 (not necessarily a bad thing).  Our ears can hear more finely that 1/2 steps.  We can hear 1/4 steps and even finer differences.  The ratio approach in just tuning comes from the natural harmonics in a vibrating system such as a string.  The 5th/1st is 3/2 and 3rd/1st = 5/4, from this all other ratios can be determined.
Granted the 12th root of 2 is impossible to exactly calculate and there is possible some dissonance between the ET tones and the harmonics of the instrument (and ear) but for all practical purposes this is not noticeable by most people (or we've been brainwashed to accept it).  I have been told by people with perfect pitch that they can perceive this and consider 12TET "out of tune".  But most of us don't experience this.
The 12TET major scale is very close to the Just major scale.  A more basic question in my opinion is why we don't like 1/4 tones in the Western tradition.  Turkish folk music has 1/4 tones and they make fretted instruments with a 1/4 tone fret here and there.
As for 440Hz, this has evolved over the centuries.  It isn't always 440.  But we set a standard convention so we are all on the same page.  It's like choosing a definition for a meter, or kg at the international bureau of standards.
Answer: A isn't necessarily fixed at 440Hz. In some parts of the World it's different, and years ago it wasn't even a fixed Hz. It's become an 'industry standard', where if a figure is given to it, anyone anywhere can tune to that standard, and it'll be fine for playing along. Bit like measurement systems work because most people recognise and use them.
The 12tet you ask about is a compromise. It's not exactly in tune for any key, but what it does is make it possible to play a 12tet tuned instrument in any key, and it won't sound too out-of-tune. Other tuning systems are better in tune, and sound more musical, but essentially work in one specific key. If all the playable notes are tuned to that one key, everything is hunky dory, but play in other keys, and pieces will sound like some notes from them are slightly off.
Comment: You should clarify that your point about "other tuning systems...essentially work in one specific key" is rather a point about equal-tempered vs unequal ones. Higher ET systems don't have the "essentially work in one specific key" problem either. Problem is just, 31-edo is the first one that's really better than 12-edo as a meantone temperament, and 31 is already rather too many steps to seem practical.
Answer: The current scale of 12 chromatic tone with equal temperament is based on a much older systems of a 7 tone diatonic scale ABCDEFG.
There is a lot of history involved with the development of harmony and tuning systems, but you can simplify (hopefully not too gross an oversimplification) it by saying: all tones ABCDEFG can be the starting tone of a scale (a tonic) provided you include a tone one half step below each (a leading tone.)
BC and EF already have that half step below relationship. You need to add five more tones to get half steps below the remaining tones. All together that makes 12 tones.
Music often moves through various tonic centers so all of those 12 tones is needed in practice. These changes of the tonic can be called modulation or transposition depending on the particulars of the music.
This leading tone view is a minimal explanation for the 12 chromatic tones. In actuality many other tone can be involved with modulations and transpositions.
So, the current 12 tone chromatic system is popular because it accommodates 7 tone diatonic scales and their modulation/transposition.
NOTE:
You can also see how both the 7 and 12 tone scales can be created from a series of perfect fifths:
F C G D A E B orders the 7 diatonic tones by perfect fifths, but it doesn't repeat.
Gb Db Ab Eb Bb F C G D A E B F# orders the 12 chromatic tones by perfect fifths, it repeats in a circle where F# and Gb are enharmonically the same tone.
That is a point about the historic development of music, but it's an interesting way to see the chromatic system as a kind of extension of the diatonic system.
Comment: You seem to be implying that you cannot write a 5th above B (if I am misunderstanding sorry).  But this tower of 5ths goes on forever in theory.  There is nothing special about the equal tempered scale that allows this.  Unless you mean that there is no unambiguous name for it in terms of letters and accidentals.
Comment: it not that there isn't a perfect fifth above B - of course that would be F# - it just that F# isn't part of the basic gamut, it requires accidentals or you can place it the chromatic series
Comment: I am confused.  How is it that B does not have a 5th?
Comment: @ggcg, do you mean a fifth above the `B` after `F C G D A E B`?
Comment: the point is simply to arrange the letters of the gamut in ascending fifths


How do i fire a click continuously while something is hovered?

Question: Im pretty sure this has a simple solution.  I am using jCarousellite, and i want to change the behaviour of built in nav buttons to fire on hover over.
$("#carousel").jCarouselLite({

 vertical: true,
 btnNext: ".btn-down",
 btnPrev: ".btn-up",
 visible:6,
 circular: false

});

$("#carousel .btn-down").hover(function() {

 $("#carousel .btn-down").click();

});

but it only fires once when mouseover, i need it to fire continueously while mouseover.
Comment: Stating your desired effect might be a better start, continuously firing a click has never been the best solution every time this has been asked.
Comment: Ah, sry!  I want the carousel to move to the next item while hovered.  Figured using the built in functionality of jCarouselLite would be the quickest solution.
Answer: I too had the same problem with my code, then I came up with this solution..
$(document).ready(function(){
    $("someid1").hover(function a() {  //on hover over some element with id-> someid1
        $("#someid2").animate({
            width:"+=10"
        }, function(){
            a();
        });
    }); //execute animation function and call itself again and again on mouseover
});

$("someid1").mouseout(function() {
    $("#someid2").stop(); //stop the animation on mouseout.
});
});

That did the trick for me. Hope it helps you.
Answer: You can use setInterval to begin triggering the event at regular intervals on hover and use clearInterval to stop it when the user stops hovering. It'd also be cleaner to trigger the actual behavior you want instead of triggering a click event, assuming the plugin you're using supports such an API. Something like this:
var effectInterval;

$('#carousel .btn-down').hover(function() {
  effectInterval = setInterval(function() {
    $('#carousel').advanceToNextImage(); // sample API call, check your plugin's docs for how it might actually be done
  }, 5000);
}, function() {
  clearInterval(effectInterval);
});

Comment: *please* don't use strings in setInterval or setTimeout, it's bad practice and adds extra processing for no reason...it's even longer in this case: `setInterval(triggerEffect, 5000);`
Comment: @Nick - Ha, I just edited my answer to change that, then saw your comment as soon as the edit saved.
Comment: What is `advanceToNextImage`?  I think you're looking at another gallery plugin?
Comment: @Nick - it's a made up API call. It's just to show an example of calling the behavior as opposed to triggering a click event. I'll edit my answer again to make this clear... apparently edit messages don't show up on the actual answer.
Answer: var nav = function() {
  $("#carousel .btn-down").click(); // next move
  $("#carousel").data(
    'hover',
    window.setTimeout(nav, 1000); // continue in 1000 ms
  );
};
$("#carousel .btn-down").hover(
  nav,
  function() {
    window.cancelTimeout ($("#carousel").data('hover')); // stop the navigation
  }
);

Comment: this Worked perfectly.  It surprising to me that the solutions needs to be so roundt about.  Cheers mate!
Answer: You can set an interval for clicking like this, just do the same for the opposite button:
$("#carousel .btn-down").hover(function() {
  $(this).data("to", setInterval(function() { $("#carousel .btn-down").click(); }, 200));
}, function() {
  clearInterval($(this).data("to"));
});


Add Customized UIView to Scenekit's node

Question: I am beginner in Scenekit development, I am trying to add UIView as diffuse content of SCNPlane node but getting some weird crash.
Code:
   override func viewDidLoad() {
        super.viewDidLoad()
        let scene = SCNScene()
        let plane = SCNPlane(width: 0.1, height: 0.1)
        plane.firstMaterial?.diffuse.contents = getCustomView()
        let planeNode = SCNNode(geometry: plane)
        planeNode.position = SCNVector3(0, 0, 0)
        scene.rootNode.addChildNode(planeNode)
        sceneView.scene = scene
    }

    func getCustomView() -> UIView {
        let view = UIView()
        view.backgroundColor = .red
        return view
    }

Crash :

I am trying to achieve following output with designing UIView

Please let me know how I can add UIView as SCNNode's diffuse content.
Answer: Use this extension to get the image representation from the UIView
public extension UIView {
 @available(iOS 10.0, *)
 var image: UIImage {
    let renderer = UIGraphicsImageRenderer(bounds: bounds)
    return renderer.image { rendererContext in
        layer.render(in: rendererContext.cgContext)
    }
  }
}

And call it on your custom View like the following :
getCustomView().image

And finally on your SCNNode's Plane like the following :
plane.firstMaterial?.diffuse.contents = getCustomView().image

Answer: You are mixing Legos and K'Nex here.
Let's go to the documentation and see what is a valid diffuse content for SCNMaterial:

You can set a value for this property using any of the following
  types:
A color (NSColor/UIColor or CGColor), specifying a uniform color for
  the material's surface
A number (NSNumber), specifying a uniform scalar value for the
  material's surface (useful for physically based properties such as
  metalness)
An image (NSImage/UIImage or CGImage), specifying a texture to be
  mapped across the material's surface
An NSString or NSURL object specifying the location of an image file
A video player (AVPlayer) or live video capture preview
  (AVCaptureDevice, in iOS only)
A Core Animation layer (CALayer)
A texture (SKTexture, MDLTexture, MTLTexture, or GLKTextureInfo)
A SpriteKit scene (SKScene)
A specially formatted image or array of six images, specifying the
  faces of a cube map
When you examine elements of a scene loaded from a file, this value is
  always either a color object (of the NSColor or UIColor class,
  according to platform) or an image object (of the NSImage or UIImage
  class, according to platform). You can therefore use type
  introspection (the isKind(of:) method in Objective-C, or the is
  operator or let-as matching in Swift) to determine the type of the
  material property's contents.
  https://developer.apple.com/documentation/scenekit/scnmaterialproperty/1395372-contents

Let us look at what UIView is:

class UIView : UIResponder
  class UIResponder : NSObject
https://developer.apple.com/documentation/uikit/uiview
https://developer.apple.com/documentation/uikit/uiresponder

As you can see,  UIView is not a valid type.
However,  UIView does contain a CALayer

https://developer.apple.com/documentation/uikit/uiview/1622436-layer

So you should be able to use that to get what you need from your view:
func getCustomViewLayer() -> CALayer {
    let view = UIView()
    view.backgroundColor = .red
    return view.layer
}

Comment: Thanks @knightOfDragon I will check and get back to u
Comment: @knightOfDragon it's giving me same crash
Comment: Looks like something else is crashing , does it crash when your contents is nil?
Comment: It's crashing when I am setting scene to sceneView's scene
Comment: I am not familiar with scene kit, but something is pointing to nil that shouldnt be nil it looks like
Comment: I don't know nothing is nil when I debug it. added screenshot of it.
Comment: do this code in view will appear, not view did load.  I have a feeling something is not prepared on apples side
Comment: For 2022 .. I'm afraid the code presented is completely wrong, and will do nothing!  The view in question has to persist inside something in UIKit (even though the CALayer gets moved).  The simple hello world example in the answer I typed in, works perfectly, just use an IBOutlet and the rather tricky bringup sequence will work.
Comment: That is just flat out wrong.  The view does not need to persist in anything, and all that matters is the layer is extracted out of it.  The only thing that matters is that layer is somehow retained, which is something beyond the scope of the question.  Documents do not list contents as a weak reference.
Answer: To put a UIView on a SCNNode:
Superficially, it's very simple.
@IBOutlet var anyUIView: UIView!

and then ...
You have to use the layer ...
func test() {
  somePictureNode.geometry!.firstMaterial!.diffuse.contents = anyUIView.layer
}

It's that easy.
It's very difficult to get good quality though, and drawing order and layout can be strange.
Re-warning ... !
Just to repeat, you will find the layout EXTREMELY strange moving from UIKit to SceneKit! You CAN use the constraint layout engine if you are truly on your toes! My guess is that in a couple yrs (say, by 2025) Apple will put some time in to rationalize the UIKit-like layout engine in SceneKit.  Keeping track of / making layout happen is also hell!  But for simple UIView, you are all set.


Good practices for tracking multiple REST call completions within one function

Question: I am using the MKNetworkKit library to make REST calls to a server. This particular snippet sets is called when a user wants to make a photo favorite or not favorite. It is pretty straight forward objective-c block code if we are only setting favorite flag for a single photo. However I have impelmented a multiselect mechanism in the GUI so that a user can select several photos and favorite them all at once.
The function I wrote to do this works just fine, but it just doesn't feel very clean to me.
What I dislike:

Tracking all of the callbacks with a block counter. I am wondering if there is a more elegant way to handle this.
The same code exists in both completion blocks. However that is just how MKNetworkKit is used (one block for success, one for error). I suppose if I made this an instance method, I could handle it by calling another i-method, but that seems just as messy to do all the setup. I'd like to keep this as a handy class method utility.

Suggestions?
<code>+(BOOL)updateAssets:(NSArray*)assets
         isFavorite:(BOOL)isFavorite
         completion:(MyAssetCompletion)completion // (BOOL success)
{

    assert(assets);
    if (assets == nil || assets.count == 0) return NO;

    __block BOOL bError = NO;
    __block NSInteger counter = 0;  // Use a counter to track number of completed REST calls
    for(MyAsset *asset in assets){
        MyUpdateAssetForm *form = [[MyUpdateAssetForm alloc] init];
        form.isPrivate = isFavorite ? @(1) : @(0);
        [[MyRESTEngine sharedInstance] updateAssetWithUUID:asset.UUID
                                                     withForm:form
                                              completionBlock:^{
                                                  counter++;
                                                  if(counter == assets.count){
                                                      completion(bError == NO);
                                                  }
                                              } errorBlock:^(NSError *error, NSString *additionalInfo) {
                                                  bError = bError || YES;
                                                  counter++;
                                                  if(counter == assets.count){
                                                      completion(bError == NO);
                                                  }
                                              }];
    }
    return YES;
}
</code>
Comment: FYI, in the future, our server will accept a list of assets so I will need to only make one call, but until then.....
Comment: I'm with you in that it looks a bit ugly, however as far as I know this is a correct way to handle multiple callbacks.
Answer: You can try this (untested):
(By the way, your current implementation is not thread safe as the counter might be incremented from more then one thread in a non-atomic manner)
@see NSConditionLock
<code>- (BOOL) updateAssets:(NSArray*)assets
           isFavorite:(BOOL)isFavorite
           completion:(bool_block_t)completion
{
    assert(assets && [assets count]);

    __block NSMutableArray* failed = [NSMutableArray new];
    __block NSConditionLock* lock = [[NSConditionLock alloc] initWithCondition:[assets count]];
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0),
                   ^{
                       [lock lockWhenCondition:0];
                       completion([failed count] == 0);
                   });
    NSNumber* val = (isFavorite ? @1 : @0);
    for (MyAsset* asset in assets) {
        MyUpdateAssetForm* form = [[MyUpdateAssetForm alloc] init];
        form.isPrivate = val;
        [self updateAssetWithUUID:asset.UUID
                         withForm:form
                  completionBlock:^{[lock unlockWithCondition:[lock condition] - 1];}
                       errorBlock:^(NSError *error, NSString *additionalInfo)
         {
             [lock lock];
             [failed addObject:asset];
             [lock unlockWithCondition:[lock condition] - 1];
         }];
    }
    return YES;
}
</code>


Based homotopy equivalent vs homotopy equivalent for manifolds?

Question: Let $M$ and $N$ be connected (compact if you like) manifolds and let $x \in M$ and $y \in N$ be specified base points.  Suppose that $f,g : M \to N$ with $f(x) = g(x) = y$ and suppose that $f$ and $g$ are homotopic.  Does it follow that $f$ and $g$ are homotopic relative to $\{x\}$?
Answer: No. For $M = S^1$, $N = $ some surface, this is the same as asking if homotopy of loops is the same as free homotopy of loops in a surface. They are not. In the picture below, the red and green curves are freely homotopic (i.e., if you let the blue point move on one buyt not the other) but not homotopic rel the blue point. (Note that part of the green curve is dotted, indicating it is running around behind the back of the two-holed torus; sorry the dots don't show up well).


How disable notifications in Centreon through Nagios?

Question: I would like to disable some services notifications in Centreon through Nagios web interface.
Does anybody know how do that in Nagios ?
Comment: When asking questions like this it is useful to include: Nagios verstion, NDOUtils version and Centreon version. Please can you update your question to include this information. Thanks.
Answer: I am presuming you mean disabling notifications from the Service Information page for a service, i.e. the one that contains the Service State Information table with the Service Command table on the right?:

If you click on "Disable notifications for this service" and confirm the "Commit" on the following page:

...Centreon will pick this up. You need to be patient because the command is queued and may not execute immediately. On a busy Nagios server it may take several minutes for the command to execute and for Centreon to see this change. When it does eventually happen you'll see a small "splat" next to the service under Monitoring -> Services -> :

This was verified on my test environment running Nagios 3.5.0, NDOUtils 1.4b9 and Centreon 2.4.4.
You can also verify when the command was sent by tailing the Nagios log:
tail -f /usr/local/nagios/var/nagios.log

When the command is processed you'll see something like:
[1378315436] EXTERNAL COMMAND: DISABLE_SVC_NOTIFICATIONS;Buzz;HTTP

Where Buzz is my host name and HTTP is the check name.
Your log location may vary and you can find it by checking the "Log file" configuration value in Centreon under:
Configuration -> Monitoring Engines -> main.cfg

Or, if you're running an older version prior to the release of the Centreon fork of Nagios:
Configuration -> Nagios -> nagios.cfg

If this isn't happening then we'd need to see your service configuration and "Data Processing" options.


Nullity of a linear transformation

Question: Let $T:V_3 \rightarrow V_2$ maps the basis vectors as follows: $T(i)=(0,0)$, $T(j)=(1,1)$ and $T(k)=(1,-1)$
How do I determine the nullity of T and the matrix of T?
Thank you
Answer: Note that $T(j)$ and $T(k)$ are linearly independent, so the rank of $T$ is $2$. The nullity is then $1$ by rank-nullity theorem. The matrix of $T$ (assuming right-multiplication) is $$\left(\begin{array}{cc}0 & 0\\1 & 1\\1 & -1\end{array}\right).$$ Do you recognize the rows of this matrix?
Comment: Is there another way to determine the nullity ?
Comment: Well, you can always go directly, by determining the kernel (null space) of $T$. In particular, take constants $\alpha,\beta,\gamma,$ and suppose $T(\alpha i+\beta j+\gamma k)=(0,0).$ From this, you'll see that we need $\beta=\gamma=0,$ and that $\alpha$ has nothing to do with it. Thus, the kernel of $T$ is precisely the space of scalar multiples of $i$ in $V_3$. This has dimension $1$, and so $T$ has nullity $1$.

Nullity of a linear transformation


How to convert text into long text?

Question: I have a text field on my site which is becoming a problem.  Users tend to input more text than I had expected.  I need to convert this text field into a long text field.  This is problematic because there is already content.  I'm looking for a way to do the conversion as painlessly as possible.  Here is my current plan:

Create the new long text field
Use a module (probably feeds) to duplicate the data (export, then re-import)
Delete the old text field.

Is this a good idea or is there a better faster one out there?
Comment: sql statements consider an option for you?
Comment: I had to do this recently, and tried to follow [this tutorial](http://www.pixelite.co.nz/article/convert-existing-textfield-textarea-drupal-7), but I got errors (you can see my comment there, which is the latest one). I ended up creating the new long text field and then just copying over the values from the old field in the database using PHPMyAdmin. It was relatively painless.
Answer: Though the question is pretty old, I would like to add my suggestion to it. I don't think changing the field type directly in the database is a good idea.

Create a new field (long text) with the necessary settings, and add it to the content type.
Then you can use the following script to copy all the old field values (text field) to new field (long text).

<?php
// Assign value from old_field to new_field
$nodes = node_load_multiple(array(), array("type" => "your_type"));
foreach ($nodes as $node) {
  $node->field_new = $node->field_old;
  field_attach_update('node', $node);
}

Finally delete the old field and use the new field for further use.
Answer: Once a field is created from admin then it can not be edited later. Because field data is saved in Binary form and can not be edited.
e.g if we have field 'field1' then it will have table 'field_data_field_field1' and 'field_revision_field_field1' in the database. Now change its datatype directly in the database.

Export these tables as a sql file and delete the old field in the
manage field section of content type using admin.
Create the new field with the same name as it was before and choose
the appropriate datatype
Now delete the newly created table 'field_data_field_field1' and
'field_revision_field_field1' and import the file that were exported
earlier.
Other way you can create a new field and copy the data from old
tables to new table and change settings later.
Answer: That worked for me really well:
drush scr update_field_description_100.php

update_field_description.php
$field_name = "field_description_100";

$rows = db_query("SELECT id,data FROM {field_config} WHERE field_name = '{$field_name}' ")->fetchAll(PDO::FETCH_OBJ);

foreach ($rows as $row ){
 $row->data=unserialize($row->data);
 unset($row->data['settings']['max_length']);
 $row->type="text_long";
 drupal_write_record("field_config", $row, "id");
}

// Update field_config_instance
$rows = db_query("SELECT id,data FROM {field_config_instance} WHERE field_name = '{$field_name}'")->fetchAll(PDO::FETCH_OBJ);

foreach ($rows as $row ){
 $row->data=unserialize($row->data);
 $row->data['widget']['type']='text_textarea';
 unset($row->data['widget']['settings']['size']);
 $row->data['widget']['settings']['rows']=3;
 drupal_write_record("field_config_instance", $row, "id");
}

// Update the field table
db_change_field("field_data_{$field_name}", "{$field_name}_value", "{$field_name}_value", array(
 "type" => "varchar",
 "length" => "20000",
));
db_change_field("field_revision_{$field_name}", "{$field_name}_value", "{$field_name}_value", array(
 "type" => "varchar",
 "length" => "20000",
));

// Clear caches.
field_cache_clear(TRUE);

Manage fields:

Content editor:

Taken from:
http://thedombroshow.com/drupal-7-converting-a-text-field-to-a-long-text-aka-textarea-field/

How to convert text into long text?


Given a Lebesgue measurable set, how to prove its image is Lebesgue measurable

Question: I know the image of a Lebesgue measurable set need not be Lebesgue measurable, but I can across this problem and it claimed that the following is true: If $X$ is a Lebesgue measurable and bounded subset of the reals, then $Y = \{x^3 + 2x : x \in X\}$ is also Lebesgue measurable.
How do you prove this is true though?
Answer: The functions $f(x)=x^3+2x$ has bounded derivative since $X$ is bounded.
So $f$ is Lipschitz.
A Lipschitz function on the real line sends sets of measure zero to sets of measure zero and $F_{\sigma}$ sets to $F_{\sigma}$ sets
Thus it sends measurable sets to measurable sets since a measurable set is a union of an $F_{\sigma}$ set and a set of measure zero.
So $f(X)$ is measurable.
Comment: Ok, that makes since, but how do I prove a Lipschitz function sends a countable union of closed sets to a countable union of closed sets?
Comment: @Akt: In $\mathbb{R}$, a countable union of closed sets is also a countable union of **compact** sets...
Answer: Another argument that does away with the assumption "$X$ is bounded" is the fact that $f:x \longmapsto x^3+2x$ is a homeomorphism of $\mathbb{R}$. So $f(X)=(f^{-1})^{-1}(X)$ is measurable.


How to update non-property value with entity_metadata_wrapper?

Question: I wish to update values in commerce_payment_transaction entity. I am using such code:
<?php
$transaction = commerce_payment_transaction_load(58);
 $digests = array(
'DIGEST' => '456',
'DIGEST2' => '478'
);

$transaction_wrapper = entity_metadata_wrapper('commerce_payment_transaction', $transaction);
$transaction_wrapper->payload->set($digests);
$transaction_wrapper->field_my_custom_field->set(1458);
$transaction_wrapper->save();

The problem is, that such code throws me error, that payload is not property of commerce_payment_transaction entity. Although "payload" is column in database table of this entity type. But it is not set as property.
When I don't use entity_metadata_wrapper, this code works for me:
<?php
$transaction = commerce_payment_transaction_load(58);
$digests = array(
'DIGEST' => '456',
'DIGEST2' => '478'
);
$transaction->payload = $digests;
commerce_payment_transaction_save($transaction);
?>

But is it possible to use also entity_metadata_wrapper to update data of entity, that are neither properties nor fields, like payload in commerce_payment_transaction?
Answer: The payload column is a property of the commerce payment transaction type already (property is a Drupal core term for any base fields on an entity), but for whatever reason the authors of the module have chosen not to expose it to the Entity API module through commerce_payment_entity_property_info().
Fortunately you can just use hook_entity_property_info_alter() in a custom module to provide the metadata on its behalf. See hook_entity_property_info() for details of the options available.


how to construct a function which is $C^k$ but not $C^{k+1}$

Question: I have done this for $k=0,1$ like $f:\mathbb{R}\rightarrow\mathbb{R}$ given by $f(x)=x^{\frac{1}{3}}$, which is $C^0$ but not $C^1$, then $g(x)=\int_{0}^{x}t^{\frac13} dt$ is $C^1$ but not $C^2$, could any one tell me how to generalize this?
Thank you!
Comment: Have you tried just doing the same thing again?
Comment: meaning?I do not understand your statement
Comment: You should iterate your process. Let $g:\mathbb{R}\to\mathbb{R}$ be continuous but not differentiable. Then $G=\int_0^t g(s) ds$ is $C^1$ but not $C^2$. Now do the same with $G$. It's primitive is $C^2$ but not $C^3$ and so on
Comment: ahhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh Idiot! (myself)
Answer: $g_k(x)=x^{(3k+1)/3}$ is $C^k$ but not $C^{k+1}$. Or you could repeat the same idea, with $\int_0^x g(s)\,ds$ being $C^2$ but not $C^3$, and so on.


Tensorflow,ensemble learning, feed multiple datasets of different image size into Keras Model

Question: I have an image classification problem for which I'd like to combine different models
I've trained.
for example I have two models:
mobilenet_v2_100_96    = tf.keras.models.load_model("saved_model_mobilenet_v2_100_96")
mobilenet_v2_100_224    = tf.keras.models.load_model("saved_model_mobilenet_v2_100_224")

After which I lock the layers of the models and combine them into an array called "models" and create a new model to combine these like so:
ensemble_visible = [model.input for model in models]
ensemble_outputs = [model.output for model in models]

merge = tf.keras.layers.concatenate(ensemble_outputs)
merge = tf.keras.layers.Dense(200, activation='relu')(merge)
output = tf.keras.layers.Dense(200, activation='sigmoid')(merge)
model = tf.keras.models.Model(inputs=ensemble_visible, outputs=ensemble_outputs)

model.compile(optimizer=tf.keras.optimizers.SGD(learning_rate=0.005, momentum=0.9),
                loss=tf.keras.losses.CategoricalCrossentropy(from_logits=True, label_smoothing=0.1),
                metrics=['accuracy'])

As you can see I need two differently sized inputs in order to make it work.
I obtain my two datasets through the tf.keras.preprocessing.image_dataset_from_directory function.
Now I need a way to combine these two datasets. I made sure to set the seed value of both calls the same, so the images should be in the same order.
I've tried splitting the datasets via this tf_unzip (https://stackoverflow.com/a/68661507/20617581) function. And combining them like this:
model_inputs = tf.data.Dataset.zip(({"inputmobilenet_v2_100_96":train_x_96, "inputmobilenet_v2_100_224":train_x_224}, train_y_96))

When I run the model.fit function however the model is not able to learn above 1% which is way less than the original models. If I run the same model using only one input everything works as expected.
My complete code is following:
import tensorflow as tf
from utils.model import Model
from tqdm import tqdm
import numpy as np
import pandas as pd
import tensorflow_datasets as tfds

def tfdata_unzip(
    tfdata: tf.data.Dataset,
    *,
    recursive: bool=False,
    eager_numpy: bool=False,
    num_parallel_calls: int=tf.data.AUTOTUNE,
):
    """
    Unzip a zipped tf.data pipeline.

    Args:
        tfdata: the :py:class:`tf.data.Dataset`
            to unzip.

        recursive: Set to ``True`` to recursively unzip
            multiple layers of zipped pipelines.
            Defaults to ``False``.

        eager_numpy: Set this to ``True`` to return
            Python lists of primitive types or
            :py:class:`numpy.array` objects. Defaults
            to ``False``.

        num_parallel_calls: The level of parallelism to
            each time we ``map()`` over a
            :py:class:`tf.data.Dataset`.

    Returns:
        Returns a Python list of either
             :py:class:`tf.data.Dataset` or NumPy
             arrays.
    """
    if isinstance(tfdata.element_spec, tf.TensorSpec):
        if eager_numpy:
            return list(tfdata.as_numpy_iterator())
        return tfdata

    def tfdata_map(i: int) -> list:
        return tfdata.map(
            lambda *cols: cols[i],
            deterministic=True,
            num_parallel_calls=num_parallel_calls,
        )

    if isinstance(tfdata.element_spec, tuple):
        num_columns = len(tfdata.element_spec)
        if recursive:
            return [
                tfdata_unzip(
                    tfdata_map(i),
                    recursive=recursive,
                    eager_numpy=eager_numpy,
                    num_parallel_calls=num_parallel_calls,
                )
                for i in range(num_columns)
            ]
        else:
            return [
                tfdata_map(i)
                for i in range(num_columns)
            ]

    raise ValueError(
        "Unknown tf.data.Dataset element_spec: " +
        str(tfdata.element_spec)
    )

print("GPU is", "available" if tf.config.list_physical_devices('GPU') else "NOT AVAILABLE")

models = []

# mobilenet_v2_050_160    = tf.keras.models.load_model("saved_model_mobilenet_v2_050_160")
mobilenet_v2_100_96    = tf.keras.models.load_model("saved_model_mobilenet_v2_100_96")
mobilenet_v2_100_224    = tf.keras.models.load_model("saved_model_mobilenet_v2_100_224")

# models.append(mobilenet_v2_050_160)
models.append(mobilenet_v2_100_96)
models.append(mobilenet_v2_100_224)

for i, model in enumerate(models):
    for layer in model.layers:
        layer.trainable = False
        layer._name = layer.name + str(i)

    model.input._name = "input_" + str(i)
    model.input.type_spec._name = "input_" + str(i)
    # model.summary()

ensemble_visible = [model.input for model in models]
ensemble_outputs = [model.output for model in models]

merge = tf.keras.layers.concatenate(ensemble_outputs)
merge = tf.keras.layers.Dense(200, activation='relu')(merge)
output = tf.keras.layers.Dense(200, activation='sigmoid')(merge)
model = tf.keras.models.Model(inputs=ensemble_visible, outputs=output)

model.compile(optimizer=tf.keras.optimizers.SGD(learning_rate=0.005, momentum=0.9),
                loss=tf.keras.losses.CategoricalCrossentropy(from_logits=True, label_smoothing=0.1),
                metrics=['accuracy'])

def build_dataset(image_size):
    return tf.keras.preprocessing.image_dataset_from_directory(
        "img",
        validation_split=.20,
        subset="both",
        label_mode="categorical",
        # Seed needs to provided when using validation_split and shuffle = True.
        # A fixed seed is used so that the validation set is stable across runs.
        seed=123,
        image_size=image_size,
        batch_size=16
    )

batch_size = 16

def gen_datasets(image_size):
    train_ds, val_ds = build_dataset(image_size)
    class_names = tuple(train_ds.class_names)
    train_size = train_ds.cardinality().numpy()
    train_ds = train_ds.unbatch().batch(batch_size)
    train_ds = train_ds.repeat()

    normalization_layer = tf.keras.layers.Rescaling(1. / 255)
    preprocessing_model = tf.keras.Sequential([normalization_layer])
    do_data_augmentation = False  # @param {type:"boolean"}
    if do_data_augmentation:
        preprocessing_model.add(tf.keras.layers.RandomRotation(40))
        preprocessing_model.add(tf.keras.layers.RandomTranslation(0, 0.2))
        preprocessing_model.add(tf.keras.layers.RandomTranslation(0.2, 0))
    preprocessing_model.add(tf.keras.layers.RandomZoom(0.2, 0.2))
    preprocessing_model.add(tf.keras.layers.RandomFlip(mode="horizontal"))
    train_ds = train_ds.map(lambda images, labels: (preprocessing_model(images), labels))

    valid_size = val_ds.cardinality().numpy()
    val_ds = val_ds.unbatch().batch(batch_size) #self.batch_size)
    val_ds = val_ds.map(lambda images, labels:
                        (normalization_layer(images), labels))

    return train_ds, val_ds, train_size, valid_size, class_names

train_ds_96, val_ds_96, train_size, valid_size, class_names = gen_datasets([96,96])
train_ds_224, val_ds_224, train_size, valid_size, class_names = gen_datasets([224,224])

print("aquired data")

train_x_96, train_y_96 = tfdata_unzip(train_ds_96)
train_x_224, train_y_224 = tfdata_unzip(train_ds_224)

val_x_96, val_y_96 = tfdata_unzip(val_ds_96)
val_x_224, val_y_224 = tfdata_unzip(val_ds_224)

model.summary()

model_inputs = tf.data.Dataset.zip(({"inputmobilenet_v2_100_96":train_x_96, "inputmobilenet_v2_100_224":train_x_224}, train_y_96))
model_vals = tf.data.Dataset.zip(({"inputmobilenet_v2_100_96":val_x_96, "inputmobilenet_v2_100_224":val_x_224}, val_y_96))

steps_per_epoch = train_size // batch_size
validation_steps = valid_size // batch_size
hist = model.fit(
    model_inputs,
    epochs=1,
    steps_per_epoch=steps_per_epoch,
    validation_data=model_vals,
    validation_steps=validation_steps).history

model.save("joined_model")

What i've tried so far
I've tried:
splitting the dataset with:
def fit_generator(dataset,len):
  df = tfds.as_numpy(dataset)
  X_ret = np.array([])
  Y_ret = np.array([])

  for a,b in tqdm(df, total=len):
    np.append(X_ret,a)
    np.append(Y_ret,b)

  return X_ret, Y_ret

which was to slow to handle the amount of data.
I've tried using a generator, but it was not accepted by the model.fit function like this:
def fit_generator(dataset,len):
  df = tfds.as_numpy(dataset)
  X_ret = np.array(e[0] for e in df)
  Y_ret = np.array(e[1] for e in df)

  return X_ret, Y_ret

Lastly i've tried the answer provided in the problem description tf_unzip (https://stackoverflow.com/a/68661507/20617581)
But the model does not learn in any significant way.
Comment: Are we sure using merge = ...followed by merge = ...not causing an issue? And also for ensemble...shouldnt your output be output and not ensemble_outputs? I.e. you might have a typo in your model creation. ALso it should be output and not mobilenet_v2_100_224.output... See second code window.
Comment: If I train with only one input the network works well, therefore I think that the model creatin is not the problem. Thank you for pointing out the error in the outputs, I fixed it. The second code I posted was already a debbuging iteration
Comment: If you create your output as per the debug...theres is no training being done on your model......because whatever you do to your 'model' has no effect on its output ensemble_outputs....because (a) everything in the loaded models is set to false...the only trainable parts are stuff in merge etc. So if you train...merge doesnt do anything since your evaluating your model on whatever was before....
Comment: The loaded model is already trained and classifies images into 200 classes with ~80% accuracy. Now I want to put several of these together and train only some small parameters for weighting purposes like which model classifies which object best etc
Comment: Maybe we are misunderstanding each other. The typo i pointed out will mean that your model does not train. I.e even the small parameter layers as the 'fitness function' is wrong. Anyhow...did you verify that your inputs are as expected? See: https://www.tensorflow.org/api_docs/python/tf/random/set_seed
Answer: I used the ImageDataGenerator.flow_from_directory() and used a custom Generator to supply the model.fit function:
class JoinedGen(tf.keras.utils.Sequence):
    def __init__(self, input_gens):
        self.gens = input_gens

    def __len__(self):
        return len(self.gens[0])

    def __getitem__(self, i):
        x = [gen[i][0] for gen in self.gens]
        y = self.gens[0][i][1]

        return x, y

    def on_epoch_end(self):
        for gen in self.gens:
            gen.on_epoch_end()

def _build_generators(self):
        train_datagen = ImageDataGenerator(
            rescale=1 / 255.0,
            rotation_range=20,
            zoom_range=0.05,
            width_shift_range=0.05,
            height_shift_range=0.05,
            shear_range=0.05,
            horizontal_flip=True,
            fill_mode="nearest",
            validation_split=self.validation_split)

        sizes = [(96, 96), (224, 224), (299, 299), (224, 224), (160, 160)]
        train_gens = []
        val_gens = []

        for size in sizes:
            train_gens.append(
                train_datagen.flow_from_directory(
                    directory="img_enhanced",
                    target_size=size,
                    color_mode="rgb",
                    batch_size=self.batch_size,
                    class_mode="categorical",
                    subset='training',
                    shuffle=True,
                    seed=42
                )
            )
            val_gens.append(
                train_datagen.flow_from_directory(
                    directory="img_enhanced",
                    target_size=size,
                    color_mode="rgb",
                    batch_size=self.batch_size,
                    class_mode="categorical",
                    subset='validation',
                    shuffle=True,
                    seed=42
                )
            )

        return JoinedGen(train_gens), JoinedGen(val_gens)

        self.train_gens, self.val_gens = self._build_generators()

        model.fit(
            x=self.train_gens,
            epochs=1,
            steps_per_epoch=steps_per_epoch,
            validation_data=self.train_gens,
            validation_steps=validation_steps,
            batch_size=self.batch_size
        )


Ansible loops and template... again

Question: I am trying setup a playbook to generalise the setup of logfile centralisation and templates.
I want to write rsyslog.d/ config files using ansible vars through a generic template.
The vars :
  vars:
    loglist:
      - app_id: 'dsm'
        rsyslog_conf_file: '13-dsm.conf'
        ruleset: 'Centralize'
        logfiles:
          - name: /var/opt/ds_agent/diag/amEvent.log
            regex: 'zzz'
          - name: /XXXX/amEvent.log
            regex: 'xxx'
      - app_id: 'audit'
        rsyslog_conf_file: '06-auditd.conf'
        ruleset: 'Centralize'
        logfiles:
          - name: /var/log/audit/audit.log
            regex: ''

the task :
  - name: Rsyslog logs config
    template:
      src: ./templates/rsyslog.d/99-generic-template.conf.j2
      dest: /tmp/{{ item.0.rsyslog_conf_file }}
      owner: root
      group: root
      mode: '0644'
    with_subelements:
      - "{{ loglist }}"
      - logfiles

the template :
{% for val in loglist | subelements('logfiles') %}

input(type="imfile"
    File="{{ val.1.name }}"
    Tag="{{ val.0.app_id }}__"
{% if val.1.regex|length %}
    startmsg.regex="{{ val.1.regex }}"
{% endif %}
    Ruleset="{{ val.0.ruleset }}"
    addMetadata="on")

{% endfor %}

I'm getting close, but the template is going through the entire list, iterating all logfilename each time, instead of going through the current item only.
The result is 2 files with the same content :
13-dsm.conf and 06-auditd.conf :
input(type="imfile"
    File="/var/opt/ds_agent/diag/amEvent.log"
    Tag="dsm__"
    startmsg.regex="a"
    Ruleset="Centralizehorsprod"
    addMetadata="on")

input(type="imfile"
    File="/XXXX/amEvent.log"
    Tag="dsm__"
    startmsg.regex="X"
    Ruleset="Centralizehorsprod"
    addMetadata="on")

input(type="imfile"
    File="/var/log/audit/audit.log"
    Tag="audit__"
    startmsg.regex="hqhq"
    Ruleset="Centralizehorsprod"
    addMetadata="on")

Expected result is 2 files with their respective logfilename.
06-audit.conf
input(type="imfile"
    File="/var/log/audit/audit.log"
    Tag="audit__"
    startmsg.regex="hqhq"
    Ruleset="Centralizehorsprod"
    addMetadata="on")

and 13-dsm.conf
input(type="imfile"
    File="/var/opt/ds_agent/diag/amEvent.log"
    Tag="dsm__"
    startmsg.regex="a"
    Ruleset="Centralizehorsprod"
    addMetadata="on")

input(type="imfile"
    File="/XXXX/amEvent.log"
    Tag="dsm__"
    startmsg.regex="X"
    Ruleset="Centralizehorsprod"
    addMetadata="on")

Thanks
Answer: Try this
task
  - name: Rsyslog logs config
    template:
      src: ./templates/99-generic-template.conf.j2
      dest: /tmp/{{ item.rsyslog_conf_file }}
    with_items:
    - "{{ loglist }}"

template
{% for val in item.logfiles %}
input(type="imfile"
    File="{{ val.name }}"
    Tag="{{ item.app_id }}__"
{% if val.regex|length %}
    startmsg.regex="{{ val.regex }}"
{% endif %}
    Ruleset="{{ item.ruleset }}"
    addMetadata="on")
{% endfor %}

Comment: Hell yea ! Much simpler than I thought...
Comment: yes , it's not that hard ... just to provide some more information about how it works for somebody who might come across this

each time the loop runs in the task , one element in `loglist` is provided to the template , so you can access the `item`'s inside the template and loop over the `item.logfiles` (`loglist.*.logfiles`)
Comment: Forgot to say Thanks ! ;)
Comment: @Tomasito the usual way to say thanks on any stackexchange site is to upvote the answer ;)
Comment: @Zeitounator Yep, but it's a pity that 15 points are required to upvote an answer... I'm below that.
Comment: Actually the vote should be recorded but not shown until you get the necessary reputation. You're almost there...

Ansible loops and template... again


does awk support quantifiers - i want [0-9]{6,6}

Question: gawk doesn't seem to match six digit fields - or n digit fields using the {n,m} quantifiers
It does match [0-9][0-9][0-9][0-9][0-9][0-9] ok.
Doesn't seem to support \d\d\d\d\d\d either.
Do i need to turn on extended reg ex, or does it just not support that.
Tnx
Answer: You need to specify the "--re-interval" (or "-W re-interval") flag to take advantage of this behavior.
echo 12345 | gawk --re-interval '/[0-9]{5}/{print}{}'
12345
echo 12345 | gawk --re-interval '/[0-9]{6}/{print}{}'
<no output>

Answer: Expanding minimally on Pax's response, --posix also enables this behavior.  Also, you are correct that gawk does not support the character class escapes (like \d) but it does support the [[:digit:]] syntax.
Comment: sorry, I didn't see that you answered the second part about escape characters also.  thanks


Parse CONNECT requests using Akka-http

Question: Is there a way to make an HTTP CONNECT request in akka?
I am trying to write a proxy app in akka and I am getting this error for every request that I am making:

16:10:19.179 [default-akka.actor.default-dispatcher-7] WARN akka.actor.ActorSystemImpl - Illegal request, responding with status '400 Bad Request': CONNECT requests are not supported: Rejectin
g CONNECT request to 'doc.akka.io:443'
Answer: Have you tried matching the incoming HttpRequest's method with CONNECT

Parse CONNECT requests using Akka-http


C++ Simple entity component

Question: I want to create a very simple enemy class that gets attributes from components rather than inheritance. Attributes will be just health i guess for now. I need an example really simple one to start with. Still learning about the component pattern and i am lost still.
Any help would be incredible!
Comment: What kind of "component" do you have in mind? There's no such language construct in C++. Where did you get the term from (i.e. what is a component for you, what's your definition?), what intention would you have behind using them?
Comment: Game objects that receive attributes (damage, health, flammability, etc.) from component objects rather than inheritance.

That is what i am told to create... so not entirely sure. But i want one as simple that it only has health
Comment: what is a "component object" supposed to be? maybe it would help if you would given an example how you would solve the problem at hand with inheritance?
Answer: Seems like you would want to use composition.  In this case define your classes something like:
Health component:
class Health
{
public:
    Health();
    // other attributes / methods defined here
};

Skills component:
class Skills
{
public:
    Skills();
    // other attributes / methods defined here
};

Weapons component:
class Weapons
{
public:
    Weapons();
    // other attributes / methods defined here
};

The Enemy class is then defined by composition from other components:
#include "health.h"
#include "weapons.h"
#include "skills.h"
class Enemy
{
public:
    Enemy();

    Health itsHealth;
    Weapons itsWeapons;
    Skills itsSkills;
};

where the "example" components that I came up with are defined in separate classes as shown.  Each class then keeps track of its own instance variables and methods.
Your Enemy class constructor then determines how each of the components are defined when an enemy object is created.  You might also take a look at class initializer lists for examples on how to setup these components with default values.
Comment: This looks pretty good. But not sure what do the constructors do? Sorry i am still a first year student.
Comment: Constructors will recieve instances of `Helth`, `Weapons` and `Skils` (one of each) and initialize the attributes...
Answer: It all depends on how you want to go about it, do you want an ECS Architecture, where you have entities, relying on components, and systems updating the entities and component.
I usually will say each component contains:
1.an id (whether it be a string or int)
2.a vector of components
3.an entity of a parent, if null, this is a root
4.a vector of entities as children.
There will be systems for basically each component, or component type. like graphics will have a stack of images to load into a buffer to display, or a physics system that performs updates on gravity inside the world, and the change of movement (delta).

C++ Simple entity component


Windows 2008 R2 folder prompt for credentials

Question: I cannot find an answer to this question, so I am hoping someone here can help.
We have a couple folders on our NAS that only our Help Desk techs can get into for install and troubleshooting purposes.
We are looking for a way to allow the Help Desk Techs to open those folders while logged in as a regular user without having to map the drive.
Basically they browse to the NAS find the folder in the list and when they click to open it get prompted for their credentials.
Is there any way to do this in Windows Server 2008 R2?
Answer: If the regular user already has open connections to other shares on this NAS, it's not possible. You cannot have a single login session connect to an SMB server with multiple credentials.
You could solve this other ways.

Serve the directory up via a different protocol from SMB, like HTTP or FTP or NFS.
Put the share on a different server just for IT.
Give the techs a USB key with the files they need.
I haven't tested this, but on the user's workstation, the tech might be able to open a CMD window using "runas" and their credentials, and access the share via UNC from that CMD window. Worth trying.


How to change facetted plots' titles?

Question: I have this 4-variable Pareto front that I'd like to visualise. Here's the dataset: https://www.dropbox.com/s/3onja9wtsow4rl9/filtered_pareto.csv?dl=0
> head(dat)
       modu robust      apl     fiedl
1 0.3701243     35 2.151837 0.2932508
2 0.3067103     29 2.071020 0.2928233
3 0.3244840     26 2.124898 0.2646455
4 0.3396247     35 2.008980 0.3270429
5 0.2890496     29 2.010612 0.3110269
6 0.3528308     34 2.051429 0.3007537

And here's the code I use to plot all the combinations of variables:
library(ggplot2)

dat <- read.csv("filtered_pareto.csv", check.names = FALSE)

dat$modu = -dat$modu
dat$robust = -dat$robust

res <- do.call(rbind, combn(1:4, 2, function(ii)
    cbind(setNames(dat[,c(ii, setdiff(1:4, ii))], c("x", "y")),
                   var=paste(ii, collapse=".")), simplify=F))

ggplot(res, aes(x=x, y=y))+ geom_point(shape=4) + geom_smooth(method=lm) +
  facet_wrap(~ var, scales="free")

After transformation, the data looks like this:
> head(res)
          x  y       NA        NA var
1 0.3701243 35 2.151837 0.2932508 1.2
2 0.3067103 29 2.071020 0.2928233 1.2
3 0.3244840 26 2.124898 0.2646455 1.2
4 0.3396247 35 2.008980 0.3270429 1.2
5 0.2890496 29 2.010612 0.3110269 1.2
6 0.3528308 34 2.051429 0.3007537 1.2

It produces this:

In this visualization, each plot is titled with two numbers, corresponding to the variables is displays. Is there a way to use the names of the variables instead (first row of the CSV dataset). in such format for instance: "Robust/Modu" instead of "1.2" or "APL/Modu" instead of "1.3", etc.?
Thanks!
Comment: Change the values of your `var` variable in your `res` data frame to whatever you want the labels to be.
Comment: I agree seems dupe-like, but from OP's comments the real problem here is *how* to add a column to this weirdly transformed data based on original data's names. I'm too short on time now to download the CSV and  try to decode what the `do.call` with the `rbind` and the `setdiff` is doing.
Comment: If OP posted the `head` of the data pre- and post-transformation, it might generate more interest. I know I'm not the only one reluctant to download random files.
Comment: How could I go about doing this? Should I try fiddling with lapply?
Comment: Some people like `ifelse` statements, you could make a table and `merge` or `match`, you could just do a named vector.
Comment: Possible dup of http://stackoverflow.com/questions/10151123/how-to-specify-columns-in-facet-grid-or-how-to-change-labels-in-facet-wrap but I don't want to do that officially unless confirmed.
Answer: res <- do.call(rbind, combn(1:4, 2, function(ii)
        cbind(setNames(dat[,c(ii, setdiff(1:4, ii))], c("x", "y")),
              var=paste(names(dat)[ii], collapse="/")), simplify=F))

Comment: it's from this answer: http://stackoverflow.com/questions/31735920/facetting-in-ggplot2
Comment: This combn is an interesting piece of code, I will probably reuse it :-)

How to change facetted plots' titles?


Radio Button information pass with ajax

Question: I have this code which I use to post variables with ajax.
I am passing a radio button, and it takes one value, I mean it doesn't take the selected values, it takes one by default.
Here are my codes:
HTML
<input type="radio"  id="status" name="status" value="1" /> Mbyllur

<input type="radio"  id="status" name="status" value="0" /> Hapur

Javascript
 var js_status = $("#status").val();

It takes the first value. What am I doing wrong?
Thanks
PHP
$postStatus = filter_var($_POST["postStatus"], FILTER_SANITIZE_STRING);

Answer: You've given them both the same ID. When you're searching it by ID, which one is it to reference?
You want something like this:
var js_status = $('input[name=status]:checked').val()

Answer: You're selecting the radio button with an id of 'status' which will always be the first button. .val() will only give you the value of 1.
What you're looking for is the current value of the CHECKED radio button. Like below.
$('input:radio[name=status]:checked').val();

Answer: 1) Id has to be unique in your page
2) If you want the selected option use ':checked' :
var js_status = $('input[name="status"]:checked').val();

Edit : link
Answer: try
var status = $("#status input[type='radio']:checked").val();

or

var status = $("input[type='radio'][name='status']:checked").val();

Radio Button information pass with ajax


Passar parâmetros URL Ajax

Question: Preciso passar parâmetros na URL do AJAX para poder filtrar o nome do produto pesquisado. Ou seja, eu tenho um campo tipo text e quando a pessoa digita ele já mostra o produto digitado, igual a busca do Facebook.
Como que eu passo estes parâmetros?
Segue o código:
$("#buscarProduto").keyup(function (e)
  {
    e.preventDefault();
    $('.item-selecionado').fadeOut();

    var buscarProduto = $(this).val();
    var idcategoria = $(".active-button").attr("id");
    var mostraPesquisa = "";

    if(buscarProduto.length == 0)
    {

      $('.item-selecionado').fadeIn();
    }
    else
    {

      $.ajax({
        url: 'http://api.teste/store/produtos?filter[categoria_id]=' + idcategoria  + '?like[nome]=' +  buscarProduto + '',
        method: 'GET',
        dataType: 'json',
        success: function(retorno)
        {

          $.each(retorno.data, function(i, item)
          {
            alert(item.nome);
          //  mostraPesquisa += '
Nome do Lanche
';
          })

          $('.item-selecionado').fadeIn();
          $('.item-selecionado').html(mostraPesquisa);
        },
        error: function(XMLHttpRequest, textStatus, errorThrown)
        {
          alert("Status do Servidor: " + textStatus);
          alert("Erro do Servidor: " + errorThrown);
        }
      });
    }

  });

Se eu passar assim:
url: 'http://api.teste/store/produtos?filter[categoria_id]=' + idcategoria,
            method: 'GET',
            dataType: 'json',
            data: {
              queryString: "" + buscarProduto + ""
            }
retorna um array vazio. Veja a imagem:
Comment: Qual é o problema do código atual?
Comment: Ao passar: url: 'http://api.teste/store/produtos?filter[categoria_id]=' + idcategoria  + '?like[nome]=' +  buscarProduto + '', ele não retorna nada
Comment: Mas na API chegam os valores corretos?
Comment: Sim. Somente na hora de fazer a pesquisa. Quando dei aquele alert ali no foreach ele não retorna. Não sei se estou fazendo certo aquele like ali
Comment: Qual o resultado de `console.log(retorno)` dentro da *callback* `success`?
Comment: eu passaria os parâmetros no atributo `data` do ajax ao invés de passa-los via GET na URL, talvez isso tivesse relacionado ao problema.
Comment: Aliás, você utilizou `?like[nome]`, usando `?` para concatenar os parâmetros, enquanto o correto é `&`. Deveria ser `&like[nome]`
Comment: Mesmo assim dá problema, ele não retorna nada. E estou usando o [nome] , pois utilizo para listar os produtos e funcionar perfeitamente.
Answer: Já passou tanto tempo, mas eu uso a passagem de parâmetros via campo  data: dentro da tag $.ajax.
Seu exemplo:
$.ajax({
        url: 'http://api.teste/store/produtos'
        type: 'GET',
        dataType: 'json',
        data: {idcategoria  : idcategoria  , buscarProduto : buscarProduto }
        success: function(retorno)
        {
          ...
         }

Passar parâmetros URL Ajax


Using standard error instead of standard deviation for t-tests in R

Question: I have a question about t-tests. I am using the rnorm function in R (example below) to perform t-tests on the difference of two means. Traditionally, this works by telling R the sample sizes, means, and standard deviations, but a colleague wants me to plug in the standard error where you would normally put the standard deviation. Is there ever a statistical justification for this?
For reference, the code looks like this:
<code>one <- c(rnorm(9710, mean = 156958.8, sd = 3679.691))

two <- c(rnorm(9710, mean = 141639, sd = 2975.4))

t.test(one, two, var.equal = FALSE)
</code>
My colleague wants me to put the standard error, instead of the standard deviation, where the code reads "sd = x". I can't find a case where this would be required, but my stats knowledge has some holes, and I want to ensure that I have a strong basis for questioning their reasoning.
Thank you for taking the time to look at my problem!
Answer: The t-test 'uses' the standard deviation to generate the t-value, but it does so by dividing it by the square root of the sample size. In other words it 'uses' the standard error.
If you supply a number that is the standard error to a t-test function that expects the standard deviation then the t-value it calculates will be inappropriately large and the p-value inappropriately small.
It seems to me that you (or your friend) are confused by the rnorm function, as that is the only place I can see "sd=" in your code. The rnorm function samples randomly from a pseudo-population with a normal distribution with the specified mean and standard deviation. If you supply a standard error value there then the sampled population will be more narrow than you intend.
Probably you should read a little about the sd and SEM. Try here: Difference between standard error and standard deviation


Ubuntu server cannot be accessed from eth0 address on same machine

Question: I have a Ubuntu 16.04 VM and when I run curl http://192.168.254.42 (the eth0 IP address) it quickly replies with connection refused. However, the server is definitely listening on 0.0.0.0 and can be accessed by other computers on the network using that same address in the browser. curl http://192.168.254.1 returns the html of my router admin page.
Of course this wouldn't normally be a blocker, but this also means that VPN clients connected to the server cannot access the server itself using the eth0 IP address (which clients on the network use). I've never run into this problem before, and Google brings up the obvious "listening on localhost", which isn't the case here.
I can ping the eth0 ip address from the terminal (i.e. ping itself) and it responds properly. A traceroute from a VPN client also looks correct. But accessing the http://192.168.254.42 immediately responds with connection refused.
Here is netstat -tulpn output.
$ netstat -tulpn | grep :80
tcp6       0      0 :::80                   :::*                    LISTEN      5724/index-lib
$ netstat -tulpn | grep :85
tcp6       0      0 :::85                   :::*                    LISTEN      1212/server.js
$ netstat -tulpn | grep :81
tcp6       0      0 :::81                   :::*                    LISTEN      1515/apache2

Setting it to Port 86 works. And another NodeJS server is running on port 85 as well and can be accessed just fine. So it's not a problem with the NodeJS side of things.

Old info
The webserver is a single NodeJS v10.16.3 HTTP server instance listening on 0.0.0.0.
Listening on 192.168.254.42 does not work either.
More importantly, an Apache webservice listening on port 81 can be accessed just fine.
Chrome says ERR_CONNECTION_FAILED, but it does it almost instantly.
No iptables rules are set.
A NodeJS process is listening on Port 85 and can be accessed in the same manner.
Here is netstat -tulpn output.
$ netstat -tulpn | grep :80
tcp6       0      0 :::80                   :::*                    LISTEN      5724/index-lib
$ netstat -tulpn | grep :85
tcp6       0      0 :::85                   :::*                    LISTEN      1212/server.js
$ netstat -tulpn | grep :81
tcp6       0      0 :::81                   :::*                    LISTEN      1515/apache2

The command I am using to check this is
$ curl http://192.168.254.42
curl: (7) Failed to connect to 192.168.254.42 port 80: Connection refused

Port 81 and 85 return expected HTML.
Setting it to listen on port 86 makes it accessible! So it's not on the NodeJS side, I don't think.
Comment: Since you're using RFC1939 IP's, please don't redact them.  There's little point, and it may help others spot something you're overlooking. What is the IP of the physical host? And of the VM?  Are you using NAT between the physical host and the VM?  Is this a case where you're expecting to have "hairpin NAT" but your NAT daemon doesn't support it?  Also, please supply evidence such as `netstat` output to support your assertion that "the server is definitely listening."  Please [edit these omitted details into your post](https://serverfault.com/posts/989338/edit), not in comments.
Comment: It looks like the `netstat` output is all IPv6 listening ports.  Perhaps you need to tweak your setup to get it to listen on IPv4? Exclude IPv6 from netstat with the command `netstat -4tulpn` and post that command output, please.
Comment: It works fine on port 86 and 85 listening on IPv6, but doesn't work on Port 80.
Comment: But only calling eth0 IP from the same machine doesn't work. It works fine across the network.
Answer: I don't have the rep to post a comment asking for clarification so I'm just going to take a punt at the answer. You're talking about what IP address your node app is listening on however I've never had to configure this in any of my node apps. I'm guessing you have code that looks something like this:
var http = require('http');
http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/plain'});
  res.write('Hello World!');
  res.end();
}).listen(8080, 0.0.0.0);

Both the port and ip here are optional so if you want to listen on port 80 then just ditch both of them. If you're listening on a different port ditch the IP and let Node figure it out.
You mentioned an Apache server on 81, I'm presuming that you are attempting to connect to Node directly and you're not going through Apache to get to Node.
If the above doesn't help post the relevant code from your node app, cat /etc/hosts, and sudo netstat -tulpn. If you're going via Apache then post the relevant Apache configs as well (i.e. the virtual host entry in /etc/apache2/sites-enabled/).
Comment: Nope, not going through apache. The netstat is in the question. `/etc/hosts` just lists loopback addresses.
Comment: I was passing in an empty string for host and now I'm passing in undefined.
Comment: Listening on port 86 actually works fine. But not listening on port 80.
Comment: So Node is listening on port 85 but you're doing a curl on port 80... what's index-lib? (sorry if that's a dumb question)
Comment: index-lib and server.js are two Node applications. In NodeJS the .js extension is optional for the script name.
Answer: I found this line in /etc/rc.local.
iptables -t nat -A OUTPUT -o lo -p tcp --dport 80 -j REDIRECT --to-port 8080
Problem found!
This answer says why the rule did not show up in iptables -L: https://serverfault.com/a/685948/32875.

There are 5 tables (filter,nat,mangle,raw,security). You call iptables -L -t table for each.


Reference for poor sampler mixing in large bayesian models

Question: I keep seeing this in various presentations, but never saw a reference for it. Although it makes an intuitive sense why samplers potentially can face mixing issue when operating on large space of possibilities (i.e., in large Bayesian models), I wonder if there is a text book, or an article for this to cite?
Answer: When you say "large space of possibilities" do you mean when you have a large number of parameters to estimate?  The basic issue there is that probability densities get weird in high dimensions: specifically the density becomes too spread out and a sampler has a hard time coping.  Michael Betancourt has a nice introduction to Hamiltonian MCMC that also deals conceptually with some of the problems with MCMC in high-dim settings in the first few sections.  If you want more specifics you might also look at general discussions of probability in high dimensions, although you'll need to think about how this intersects with the behavior of an MCMC sampler.


Is a switch to the relative minor still called a modulation?

Question: I am recording a song which is largely written in C major. About halfway through the song, the emphasis changes to A minor, with chord progressions resolving to the Am chord specifically.
Is this something we refer to as modulation? Or does modulation require a change in the number of flats/sharps (key signature) as well?
Answer: Yes, this is a modulation to the relative minor, which shares the same key signature. In classical music, although sometimes in popular music too, accidentals would be used to create strong cadences within the minor key. For instance, the leading note of A minor would be raised to G#, particularly when used as part of chord V, to create a major V chord, and so a strong V-I cadence. So, although the key signature doesn't change, often the introduction of raised leading notes (and sometimes sixths, too), can be a clue that you have modulated to the relative minor key (when reading a score, for instance).
When first reading your question title, I thought you might be referring to a move from major to minor while retaining the same tonic note, eg. C Major to C Minor. This is quite different, and is a modulation to the tonic minor. This would require a change of key signature, to three flats in this case, along with (possibly) the characteristic raised leading notes.
Answer: @BobBroadley is right, but there's also a point of view in which this particular phenomenon is described by the term "mutation."  I don't think the "mutation" people would disagree that it's a modulation, but they find "mutation" more specific and therefore more helpful.  (I learned "mutation" myself, but I haven't studied this stuff for a long time so I don't want to speak as an expert.)
Comment: Interesting - I've never heard the term "mutation." I'd like to learn more, so is there any chance you can post a source?
Comment: Oh, dear.  I learned this from a summer course I did in 1989, so all I can remember is that the textbook was written by a guy whose last name began with K.  Kagan?  Kerman?  A Google search for "mutation" and "relative minor" produces only a very few results, so perhaps he was a renegade whose ideas are no longer in fashion--in which case I apologize!
Answer: Like Bob,from the title, I thought you meant C to Cm, the tonic or parallel minor. But, yes, it's a modulation, if a 'minor' one. Forgive the pun.The key signature won't change, although when reading the dots, there is usually the clue of the G# (in Am), as that note is not diatonic to C, but often is used in Am.
You could say that the C maj. is Ionian, compared with the Aeolian mode that Am brings. All part and parcel of the same family, but with a different centre.
Answer: A modulation is any change of tonic note or root pitch, so yes you can modulate without actually changing the key signature.
Interestingly, changing from C major to C minor is not by this definition a modulation in the strictest sense. But it is common that people will also call this dramatic change a "modulation" as well. I don't believe this is strictly correct, but if there is another term for this change in common usage then I don't know of it. Wikipedia refers to this as a parallel key modulation, but that's a bit of an oxymoron if you believe modulation refers to tonal center. But the term modulation itself comes from a time when it was not as common to write music following parallel modes while maintaining the same tonal center. So there you have it.


If $X_n$ is binomial(n,p), then for any $b>0, P(X_n\le b)\rightarrow 0$.

Question: If $X_n$ is binomial(n,p), then for any $b>0, P(X_n\le b)\rightarrow 0$.
I used Hoeffding's inequality here:
Since $EX_n=np$ and $X_n\in \{0,1\}\forall n\ge 1$, then
$$\displaystyle P(\bar{X}_n \ge b+np)\le 2\exp\left( -\frac{2nb^2}{1^2}\right) \rightarrow 0$$ as $n\rightarrow \infty$.
But I'm not sure how to show that $P(X_n\le b)\rightarrow 0$.
Answer: Binomial Random Variable $X_n$ is sum of $n$ i.i.d. Bernoulli random variables of paramter $p$:
$$
X_n=Y_1+...+Y_n
$$
For enough large $n$, there is $\epsilon>0$ such that:
$$
\Pr(X_n \leq {b})=\Pr(\frac{Y_1+Y_2+...Y_n}{n}\leq \frac{b}{n})\leq \Pr(\frac{Y_1+Y_2+...Y_n}{n}\leq p- \epsilon) (*)
$$
By weak law of large numbers,you have
$$
\lim_{n\to\infty}\Pr(\frac{Y_1+Y_2+...Y_n}{n}>p-\epsilon)=1
$$
and so the limit on the right hand side of $(*)$ goes to zero.
Comment: If you choose $n>\frac{b}{p-\epsilon}$ for$p>\epsilon$, then the inequality follows. Secondly, the WLLN says $\lim_{n\to\infty}\Pr(|\frac{Y_1+Y_2+...Y_n}{n}-p|<\epsilon)=1$. From which you have $\lim_{n\to\infty}\Pr(\frac{Y_1+Y_2+...Y_n}{n}>p-\epsilon)=1$
Comment: Thanks so much, I have two questions:
1. How the inequality part come about in terms of $\frac{b}{n}$ and $p-\epsilon$ being related? If $\forall \epsilon >0, \exists N s.t. \mid \frac{b}{N}-1\mid < \epsilon$, then we have $p-\epsilon < \frac{b}{N}$

2. WLLN says $P\left(\frac{Y_1+...+Y_n}{n}\le p+\epsilon \right)\rightarrow 1$ but in (*) we have $p-\epsilon$, why does the right hand side go to 0?


IIS cannot serve images due to impersonation?

Question: We have a brand new Windows2012R2 server. We have installed the IIS features on it (including static content).
Then we have deployed a web site on it (using copy).
When we surf to the web site, HTML, CSS and JavaScript is served up just fine.
However, requests for png and ico requests gets a response HTTP status 500, substatus 0, win32-status 1346.
The 1346 status seems to indicate an impersonation problem.
But why are we getting it for just the images?
And more importantly, how can we fix this without turning on impersonation?
EDIT: actually, it did not help to add IIS_IUSRS to Impersonate a client after authentication.
Comment: The problem disappeared when I rebooted the server. Don't you just love windows?
Anyway, I'm leaving the question here, cause I would still like to know what was wrong, because this is not the last web server that I will deploy this site on.
Comment: Have you already tried this ms suggestion? https://blogs.msdn.microsoft.com/asgoyal/2012/08/25/one-thing-you-must-do-when-getting-http-500-0-1346-error/
Comment: Are the images local to the IIS server?
Comment: @GregAskew yes.
Comment: @arana yes, it did not help
Answer: I had the exact same weird error and the most frustrating thing in the world is a reboot worked.
These are all the steps i used, maybe they help some one even though they do not supply root cause.
We set "Impersonate client after authentication" permissions via GPO in.
Computer config >> Windows settings>> Security Settings >> Local Policies >> User Rights Assignment.
I added the user we have for our site with this issue to that group, it is the user for the website and app pool.
updated GPO ensured new settings showed user permissions on the local server, but still no luck.
Then we rebooted the server and it all worked. So i dunno if these changes require more then a GPO update to resolve the issue.
Comment: Actually, after setting the "Impersonate client after authentication" permission, you only have to iisreset. No reboot necessary.


Pacemaker Virtual IP suddenly Failed

Question: I am new in cluster.
We are running SAP Application in HA Cluster (have 2 nodes in cluster) using pacemaker. Node1 if it runs as a master always restart for a few times. After we check pacemaker logs, we found resource IP float (Virtual IP) failed in node1. May I know What is the rootcause for this problem and how to mitigate this issue ??.
Comment: The logs should have more clues hinting to the root cause. The `crm_mon` output should show the failures with a timestamp. Check the logs around that time.
Comment: I already check the logs, but the clue from the logs only this : ```2022-04-29T20:43:18.863881+07:00 erpswdeapapp1 pacemaker-execd[3016]:  notice: rsc_ip_float_monitor_10000[9741] error output [ /usr/lib/ocf/resource.d/heartbeat/IPaddr2: fork: retry: Resource temporarily unavailable ]```. Why resource temporarily unavailable ??, do you have any experience about this ??.
Answer: Did you configurated 'migration-threshold' like as: https://clusterlabs.org/pacemaker/doc/deprecated/en-US/Pacemaker/1.1/html/Pacemaker_Explained/s-failure-migration.html#:~:text=Pacemaker%20allows%20you%20to%20set,no%20threshold%20defined%20by%20default.

Pacemaker Virtual IP suddenly Failed


Emulate/Simulate iOS in Linux

Question: I'm developing a web app that apparently is having problems in iOS devices. The problem is that I don't own an iOS device and I develop in Linux Ubuntu. I'm looking for a way to emulate/simulate this OS in Linux (especially the browser), but haven't found anything.
So far, what I've found is the iOS SDK's Simulator, but that is meant for the Mac. And also some emulator for Windows. Has anyone done this before?
Comment: The *web* app is intended mostly for regular browsers. However, a few users try to see it using an iPhone, and I needed to verify some problems they were having.
Comment: If it's a layout issue I recommend installing the Konqueror web browser. Then look in settings to be sure it uses Webkit layout engine (same as safari).
Comment: Here is an article wich should solve your problem - http://www.proreactnative.com/How-to-Develop-iOS-Apps-on-Linux-Using-React-Native/
Comment: [macOS VM with QEMU+kvm](https://github.com/kholia/OSX-KVM/), actively maintained
Answer: The only solution I can think of is to install VMWare or any other VT then install OSX on a VM.
It works pretty good for testing.
Comment: Is there a legal way to do this?  I stupidly bought an OSX CD thinking that I could install it in VirtualBox, but it turned out to be much more compilcated than that.  I think you need some kind of hardware image which is not strictly legal to obtain.  No?
Comment: Virtualisation of some of the mac os is often not permited. http://apple.stackexchange.com/questions/20965/does-apples-license-for-os-x-allow-it-to-be-virtualized-on-an-hp-pc
Comment: With this solution, yes.
Comment: Doing this, as no other option seems available (except for actually acquiring the mobile devices in question).
Comment: is it possible to deploy for tests an app on iphone using Linux?
Comment: I have a "hackintosh" in VirtualBox (plenty of instructions online). Apart from the licensing issues, the performance is pretty bad and graphics glitches are common. Unless you only need a CLI environment, IMHO **this option is not suitable for serious development**.
Comment: As far as I know, legally you can only install Apple OS on Apple hardware. To circumvent this issue, I've been using https://www.lambdatest.com. The downside is that you will have to deploy your web app publicly for being able to access it thorough here.
Answer: On linux you can check epiphany-browser, resizes the windows you'll get same bugs as in ios. Both browsers uses Webkit.
Ubuntu/Mint:
sudo apt install epiphany-browser
Comment: This isn't a catch-all solution. The engine may be the same, but I have encountered some ios browsers which error on pages that render fine on epiphany. YMMV
Comment: Working well for me to fixing layout bugs on cordova hybrid app
Comment: This may not be a perfect solution but it definitely helped me solve my javascript issue that was happening in Safari on iPhone without having access to one.
Comment: Thanks to epiphany I could solve some iOS bugs. Thanks so much for sharing this!
Comment: This is underrated answer. Got the same bugs as on real iOS
Comment: good idea for some (but not all) sorts of bugs, Epiphany is now officially known as "Gnome Web" browser, https://apps.gnome.org/en-GB/app/org.gnome.Epiphany/
Comment: This used to work but as of today there are too many differences.
Comment: @Besworks That's it. When I've answered this, I got into this question because I was developing something in Cordova. As I remember, I've used this to solve some layout bugs. So it may be an amend about this answer.
Comment: This is quite a quick and free solution to test most IOS bugs.. it helped me many times.. good answer..
Answer: BrowserStack.com
On this site, you can emulate a lot of iOS's devices online.
Comment: Isn't this site testing, and not actual iOS application testing?
Comment: its only for remote testing purpose ...not for actual simulator on laptop
Answer:
Run Ripple emulator(retired as of 2015-12-06) on Chrome
Run iPadian on WineHQ
Run QMole on Linux or Android
Run XCode on PureDarwin
Answer: Maybe, this approach is better, https://saucelabs.com/mobile, mobile testing in the cloud with selenium
Comment: Link not working.
Answer: You might want to try screenfly. It worked great for me.
Comment: @MiroslavGlamuzina, there is nothing else to add to my suggestion. Not a long answer required. Cheers
Comment: This is really a comment, not an answer. With a bit more rep, [you will be able to post comments](//stackoverflow.com/privileges/comment). Thanks!
Comment: @MiroslavGlamuzina Yours is neither an answer nor a comment
Answer: As far as I know, there is no such a thing as iOS emulator on windows or linux, there are only some gameengines that enable you to compile same code for both iOS and windows or linux and there is a toolchain to compile iOS application using linux. none of them are realy emulator/simulator things. and to use that toolchain you need a jailbreaked iOS device to test binary file created using toolchain. I mean linux itself can't run the binary created itself. and by the way even in mac simulator is just an intermediate program which runs mac-compiled binary, since if you change compiling for iOS from simulator or the other way, all the files are rebuild. and also there are some real differences, like iOS is a case-sensitive operation while simulator is not.
so the best solution is to buy an iOS device yourself.

Emulate/Simulate iOS in Linux


convert .txt values to lists in a Python script

Question: Imagine we have a .txt file named a.txt and it has below lines.
1, 1, 3, 2, 1, 3,0
20, 30, 40, 20, 35, 34,0
Oct1,Nov1,Dec1

now we have a python project where I am going to read above line and assign different lines in different
variables in a list format.
ex: I need to assign as below
var1=[1, 1, 3, 2, 1, 3,0]
var2=[20, 30, 40, 20, 35, 34,0]
var3=["Oct1","Nov1","Dec1"]

Could you help me on how to do this in python
Comment: Do you know how to read the file? Do you know how to take a string and split it up into the list items? Do you know how to convert strings to integers where desired? What part of this do you need help with?
Comment: @Karl Knechtel karl I know how to read the lines seperately in .txt.I know the read outputs are coming in the form of string.But I do not know to convert and to assign them to relevant variables seperately
Comment: Does https://stackoverflow.com/questions/45120726/how-to-read-csv-file-lines-and-split-elements-in-line-into-list-of-lists help?
Comment: Please show your code and explain what doesn't work.
Comment: @Karl Knechtel looks different
Comment: @rpoleski code as follows.file1 = open("a.txt","r"),llines=file1.readline(),var1=[int(lines[0])] error as follows...ValueError: invalid literal for int() with base 10: '1, 1, 3, 2, 1, 3,0\n'
Answer: You have to split line into words before applying int()
with open("a.txt") as in_data:
    var1 = [int(word) for word in in_data.readline().split(",")]
    var2 = [int(word) for word in in_data.readline().split(",")]
    var3 = in_data.readline().split(",")


Por que minha condição nunca é true?

Question: Por que o meu código não funciona? to testando uns códigos aqui , como um de advinhação, to tentando ver se funciona se adicionar numeros aleatórios em um array. mas a minha condição não funciona , nenhum objeto do array que coloco com input não dá certo. sei que devia ter algo melhor que prompt como input, mas fiz algo rápido só pra testar mesmo.

Por que minha condição nunca é true?