text:
Q: Type arguments cannot be inferred from the usage mvc3 I am trying to use the strongly typed view with extensions methods as
<% using (Html.BeginForm()) { %>
    <%: Html.ValidationSummary(true) %>
    <fieldset>
        <legend>MyUsageViewModel</legend>

            <%= Html.LabelFor(model => model.test) %>

            <input type="submit" value="Save" />

    </fieldset>
<% } %>

    <%: Html.ActionLink("Back to List", "Index") %>

I am getting the following error :

The type arguments for method
  'System.Web.Mvc.Html.LabelExtensions.LabelFor(System.Web.Mvc.HtmlHelper,
  System.Linq.Expressions.Expression>)'
  cannot be inferred from the usage. Try specifying the type arguments
  explicitly.

Help would be appreciated

A: It seems your model doesn't have 'test' property which you are trying to use in Html.LabelFor helper method.

A: Make sure your model properties are public:
public class LocationModel
{
    public double Latitude { get; set; }
    public double Longitude { get; set; }
    public string Name { get; set; }
}

A: The sample code does not show a definition for the type which could be the issue.  Make sure it's at the top of the page.  I'm on my tablet right now and don't have a sample to copy/paste but the syntax should be @model modelType
If that's not the issue, can you add the model definition and full contents of the view?

A: After moving some code around to different namespaces I was seeing this same issue even though I had updated model references etc correctly. The solution was to go to build and perform a 'Clean Solution' followed by a 'Rebuild Solution'


text:
Q: How to clear button clicks when using javascript to refresh my html page? I'm using the java script from How to automatically reload a page after a given period of inactivity to refresh my html page every 30 seconds, and it works great. The page contains a form, some buttons and some text fields.The form also contains a statuslist that is updated when the page is refreshed. When clicking on a button will the corresponding value be sent back to the server. The problem is that once I have clicked a button once, it is repeated every 30 second due to the refresh from the javascript.
How to remove the button click after the first time?
I want to keep the values in the text fields.

A: If you have a function attached to your button like
<button onclick="myFunction()">Click me</button>

then add this line to that function
clickFlag = true

otherwise add this to your button tag
<button onclick="clickFlag = true">Click me</button>

and change your refresh function as following
 var time = new Date().getTime();
 $(document.body).bind("mousemove keypress", function(e) {
     time = new Date().getTime();
 });

 function refresh() {
     if(new Date().getTime() - time >= 30000 && clickFlag)
         window.location.reload(true);
     else
         setTimeout(refresh, 10000);
 }

 setTimeout(refresh, 10000);

A: You can use meta tags .
These attributes HTTP-EQUIV,content are needed.
Ex: http://website/login">

A: I found a solution, but not by using javascript.
I added another html page, where I go to when submitting the form.
Here I extract the data from the textfields (and call some php).
Then I goes back to the first page usining the php header command, with the data attached but not the buttons.
I still uses the javascript on the first page to update the statuslist, but don't get any duplicate button clicks due to the refresh.

redpajama_set_name: RedPajamaStackExchange


text: Q: Type Hierarchy precondition and postcondition, how to know if subclass has "stronger" or "weaker "precondition and postcondition than superclass? This is the specific slide that contains the information I need answers for precondition and postcondition.


text:
Q: Could gravity be an emergent property of nature? Sorry if this question is naive. It is just a curiosity that I have.
Are there theoretical or experimental reasons why gravity should not be an emergent property of nature?
Assume a standard model view of the world in the very small. Is it possible that gravity only applies to systems with a scale large enough to encompass very large numbers of particles as an emergent property?
After all: the standard model works very well without gravity; general relativity (and gravity in general) has only been measured at distances on the millimeter scale.
How could gravity emerge? For example, it could be that space-time only gets curved by systems which have measurable properties, or only gets curved by average values. In other words that the stress-energy tensor has a minimum scale by which it varies.

Edit to explain a bit better what I'm thinking of.

*

*We would not have a proper quantum gravity as such. I.e. no unified theory that contains QM and GR at the same time.

*We could have a "small" (possibly semi-classical) glue theory that only needs to explain how the two theories cross over:

*

*the conditions and mechanism of wave packet reduction (or the other corresponding phenomena in other QM interpretations, like universe branching or decoherence or whatnot)

*how this is correlated to curvature - how GM phenomena arise at this transition point.

Are there theoretical or experimental reasons why such a reasoning is fundamentally incorrect?

A: I'm not an expert in gravity, however, this is what I know.
There's a hypothesis about gravity being an entropic property. The paper from Verlinde is available at arXiv. That said, I would be surprised for this to be true. The reason is simple. As you probably know, entropy is an emergent property out of statistical probability. If you have non-interacting, adimensional particles into one half of a box, with the other half empty and separated by a valve, it's probability, thus entropy, that drives the transformation. If you look at it from the energetic point of view, the energy is exactly the same before and after the transformation. This works nicely for statistical distribution, but when you have to explain why things are attracted to each other statistically, it's much harder. From the probabilistic point of view, it would be the opposite: the more degrees of freedom your particles have, the more entropy they have. A clump has less degrees of freedom, hence has less entropy, meaning that, in a closed system, the existence of gravity is baffling. This is out of my speculation, and I think I am wrong. The paper seems to be a pleasure to read, but I haven't had the chance to go through it.

A: You might want to look up the Weinberg-Witten theorem which shows that's not possible given certain assumptions. If the original model from which quantum gravity is supposed to emerge is an ordinary Poincaré covariant quantum field theory over flat nondynamical Minkowski space, they showed it's not possible for massless helicity $\pm 2$ particles to emerge. As a theory of quantum gravity ought to contain gravitons, this appears to rule out such models.
Of course, these assumptions are questionable. For instance, the theory from which gravity emerges might not be a quantum field theory. This is the case for superstring theory.
Another possibility might be the "fundamental" model isn't Lorentz covariant. However, we still need the low energy effective theory to be approximately Lorentz covariant. In typical condensed matter analog models, different quasiparticles couple to different metrics, and there is no universality to the gravitational couplings, or the speed of light. Unless all the quasiparticles co-emerge together, I don't see any way around this problem.
It might be a bit hard to come up with the positive energy theorem in an emergent theory of gravity. The positive energy theorem states that the ADM energy of an asymptotically flat spacetime always has to be nonnegative. In an emergent theory, the ADM energy could just as easily be negative for some states. To see this, note first that the ADM energy can be defined locally as the limit as we go to spatial infinity of a locally defined integral over an enclosing spatial surface with one spatial and one time codimension. If we assume the "fundamental" theory is local, this means the now emergent ADM flux also has to be defined locally in terms of the more fundamental fields. As the enclosing boundary becomes larger and larger, its extrinsic curvature becomes closer and closer to zero. If we have a positive ADM flux passing through a plane — as defined with respect to a choice of normal vector orientation — a reflection by the plane will give us another state where this ADM flux is now negative. So, we can certainly imagine performing some sort of approximate reflection about the enclosing submanifold on a local patchwork basis, at least for the regions at or around the enclosing surface. We then need to find an interpolation of the resulting state far into the interior, which of course, might not look anything like a reflection at all. But if the fundamental theory also satisfies local independence, that ought to be possible. But the end result of all this construction is a state with negative emergent ADM energy. I know this argument is very handwavy and nonrigorous, but it sounds plausible. But there might be some loopholes. For instance, the fundamental theory might be local, but the emergent large scale excitations — and hence emergent spacetime — might be delocalized with respect to the underlying background spacetime. Or the underlying fundamental theory might be inherently nonlocal.

A: Isn't the answer to the question of the title widely believed to be "yes"?
If you believe that searching for what high-energy theorists call a "theory of everything" is a valuable and worthwhile enterprise, then you probably also believe that gravity as we currently understand it (General Relativity, say) "emerges" from some deeper theory (in the effective field theory sense) which unifies it with all other known fundamental forces.
Of course nobody yet knows for sure what that theory is, but I'm told certain flavors of string theory are the most viable candidates as of 2010.  You can find some indication towards how gravity emerges from string theory in the first few sentences of this answer by Eric Zaslow.
Perhaps Eric Zaslow or some other expert can give more details at the level of saying, for instance, how Einstein's equations arise from string theory (I would ask this as a question on this site, except that I know I could find the answer in any book on string theory if I cared enough to look).  I'm told that it has something to do with the renormalization group equations of the conformal field theory on the worldsheet, but I'm afraid I can't reproduce or explain that argument any further for you here.

A: In December, Carlo Rovelli summarized the last twenty years of the research agenda of a group of researchers in Loop Quantum Gravity theory.  In a nutshell, LQG argues that gravity is a property of space-time rather than a quantum field theory mediated by a boson, and that space-time is fundamentally discrete with point-like locations in space-time connected by a network of connections to each other.  In this approach, described by three main equations, the number of dimensions in space-time itself is emergent and neither locality nor the number of dimensions of space-time are well defined concepts at the most fine grained level.  You are at point A and connected to points B, C and D, related by the equations, which when repeated ad infinitum are well approximated by a continuous, four dimensions space that may satisfy the properties of GR in classical approximation.  As he sums up the research agenda:
"There is substantial circumstantial evidence that the large distance limit of the theory is correctly general relativity, from asymptotic analysis and from large distance calculations of n-point functions and in spinfoam cosmology; and there are open directions of investigations to reinforce this evidence. The degrees of freedom are correct and the theory is generally covariant: the low-energy limit is not likely to be much else than general relativity. But there is no solid proof yet."

A: The question is fairly old, but new ideas have appeared in literature in the meantime.
An interesting possibility is that gravity is an emergent property of a more fundamental quantum theory. In particular, space and time are emergent from the entanglement of quantum fields and gravitation can be inferred from quantum information constraints. It's a very fascinating proposal and there is a great deal of calculations supporting this idea.
These theories makes significant use of the AdS/CFT correspondence, that is indeed a duality between a gravitational theory and a quantum theory without gravity.
A pedagogical reference

A: Despite all I wrote in my other answer, there's a very interesting attempt by Xiao-Gang Wen to come up with emergent models of gravity starting from quantum lattice models with no gravity, and only nearest neighbor interactions. His work can be found at gr-qc/0606100 and arXiv:0907.1203. He managed to show that quasiparticles with no energy gap and a helicity of $\pm 2$ can emerge without being accompanied by helicity $\pm 1$ or $0$ quasiparticles. Whether or not this model can be considered a model of gravity though is another matter.


text:
Q: Rollback SQLite transaction operations in case of failure How can I rewrite my transaction to undo changes since the beginning whenever an error condition occurs before the end?
I see this question has already been asked and I followed the link provided in that answer. It's not clear to me what the next step is. I am hoping someone can illustrate the solution with an example applied to this transaction:
BEGIN TRANSACTION;
INSERT INTO Employee(ID, Name) VALUES(1, 'John');
...
<some failure happens here>
...
END TRANSACTION;

In this case, I would like the insert into the Employee table to be undone because a failure occurs before END TRANSACTION. How do I write rules that enforce this? This is for sqlite version 3.9.2.

A: Execute a ROLLBACK TRANSACTION query, or use the ON CONFLICT ROLLBACK conflict resolution on the failable queries to let SQLite roll back the transaction for you.


text:
Q: Rails: Better syntax for respond_to (shorthand) I have the following code for the update method of a user settings controller:
def update
  @user = ...
  if @user.update_attributes(params[:user])
    flash[:success] = 'Some success message.'
    respond_to do |format|
      format.html { redirect_to some_path }
      format.js   { head :ok }
    end
  else
    flash[:error] = 'Some error message.'
    render action: 'some action'
  end
end

I'm wondering if there a way to shorten this whole method? Best option would be to reduce the number of lines for the respond_to block, if there's a way to use some shorthand syntax in there.

A: If you're not supporting a js submission you can remove the respond_to block completely.  Also, note the use of flash.now which is needed to display a flash message on a render.
def update
  @user = ...
  if @user.update_attributes(params[:user])
    flash[:success] = 'Some success message.'
    redirect_to some_path
  else
    flash.now[:error] = 'Some error message.'
    render action: 'some action'
  end
end


text:
Q: How to use Castle Windsor with ASP.Net web forms? I am trying to wire up dependency injection with Windsor to standard asp.net web forms. I think I have achieved this using a HttpModule and a CustomAttribute (code shown below), although the solution seems a little clunky and was wondering if there is a better supported solution out of the box with Windsor?
There are several files all shown together here
    // index.aspx.cs
    public partial class IndexPage : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            Logger.Write("page loading");
        }

        [Inject]
        public ILogger Logger { get; set; }
    }

    // WindsorHttpModule.cs
    public class WindsorHttpModule : IHttpModule
    {
        private HttpApplication _application;
        private IoCProvider _iocProvider;

        public void Init(HttpApplication context)
        {
            _application = context;
            _iocProvider = context as IoCProvider;

            if(_iocProvider == null)
            {
                throw new InvalidOperationException("Application must implement IoCProvider");
            }

            _application.PreRequestHandlerExecute += InitiateWindsor;
        }

        private void InitiateWindsor(object sender, System.EventArgs e)
        {
            Page currentPage = _application.Context.CurrentHandler as Page;
            if(currentPage != null)
            {
                InjectPropertiesOn(currentPage);
                currentPage.InitComplete += delegate { InjectUserControls(currentPage); };
            }
        }

        private void InjectUserControls(Control parent)
        {
            if(parent.Controls != null)
            {
                foreach (Control control in parent.Controls)
                {
                    if(control is UserControl)
                    {
                        InjectPropertiesOn(control);
                    }
                    InjectUserControls(control);
                }
            }
        }

        private void InjectPropertiesOn(object currentPage)
        {
            PropertyInfo[] properties = currentPage.GetType().GetProperties();
            foreach(PropertyInfo property in properties)
            {
                object[] attributes = property.GetCustomAttributes(typeof (InjectAttribute), false);
                if(attributes != null && attributes.Length > 0)
                {
                    object valueToInject = _iocProvider.Container.Resolve(property.PropertyType);
                    property.SetValue(currentPage, valueToInject, null);
                }
            }
        }
    }

    // Global.asax.cs
    public class Global : System.Web.HttpApplication, IoCProvider
    {
        private IWindsorContainer _container;

        public override void Init()
        {
            base.Init();

            InitializeIoC();
        }

        private void InitializeIoC()
        {
            _container = new WindsorContainer();
            _container.AddComponent<ILogger, Logger>();
        }

        public IWindsorContainer Container
        {
            get { return _container; }
        }
    }

    public interface IoCProvider
    {
        IWindsorContainer Container { get; }
    }

A: Here's a modified version of the OP's code that (i) caches injected properties to avoid repeated reflection calls, (ii) releases all resolved components, (iii) encapsulates container access so as not to expose implementation.
// global.asax.cs
public class Global : HttpApplication
{
    private static IWindsorContainer _container;

    protected void Application_Start(object sender, EventArgs e)
    {
        _container = new WindsorContainer();
        _container.Install(FromAssembly.This());
    }

    internal static object Resolve(Type type)
    {
        return _container.Resolve(type);
    }

    internal static void Release(object component)
    {
        _container.Release(component);
    }

    //...
}

// WindsorHttpModule.cs
public class WindsorHttpModule : IHttpModule
{
    // cache the properties to inject for each page
    private static readonly ConcurrentDictionary<Type, PropertyInfo[]> InjectedProperties = new ConcurrentDictionary<Type, PropertyInfo[]>();
    private HttpApplication _context;

    public void Init(HttpApplication context)
    {
        _context = context;
        _context.PreRequestHandlerExecute += InjectProperties;
        _context.EndRequest += ReleaseComponents;
    }

    private void InjectProperties(object sender, EventArgs e)
    {
        var currentPage = _context.Context.CurrentHandler as Page;
        if (currentPage != null)
        {
            InjectProperties(currentPage);
            currentPage.InitComplete += delegate { InjectUserControls(currentPage); };
        }
    }

    private void InjectUserControls(Control parent)
    {
        foreach (Control control in parent.Controls)
        {
            if (control is UserControl)
            {
                InjectProperties(control);
            }
            InjectUserControls(control);
        }
    }

    private void InjectProperties(Control control)
    {
        ResolvedComponents = new List<object>();
        var pageType = control.GetType();

        PropertyInfo[] properties;
        if (!InjectedProperties.TryGetValue(pageType, out properties))
        {
            properties = control.GetType().GetProperties()
                .Where(p => p.GetCustomAttributes(typeof(InjectAttribute), false).Length > 0)
                .ToArray();
            InjectedProperties.TryAdd(pageType, properties);
        }

        foreach (var property in properties)
        {
            var component = Global.Resolve(property.PropertyType);
            property.SetValue(control, component, null);
            ResolvedComponents.Add(component);
        }
    }

    private void ReleaseComponents(object sender, EventArgs e)
    {
        var resolvedComponents = ResolvedComponents;
        if (resolvedComponents != null)
        {
            foreach (var component in ResolvedComponents)
            {
                Global.Release(component);
            }
        }
    }

    private List<object> ResolvedComponents
    {
        get { return (List<object>)HttpContext.Current.Items["ResolvedComponents"]; }
        set { HttpContext.Current.Items["ResolvedComponents"] = value; }
    }

    public void Dispose()
    { }

}

A: I think you're basically on the right track - If you have not already I would suggest taking a look at Rhino Igloo, an WebForms MVC framework, Here's a good blog post on this and the source is here - Ayende (the Author of Rhino Igloo) tackles the issue of using Windsor with webforms quite well in this project/library.
I would cache the reflection info if you're going to inject the entire nested set of controls, that could end up being a bit of a performance hog I suspect.
Last of all spring.net approaches this in a more configuration-oriented way, but it might be worth taking a look at their implementation - here's a good reference blog post on this.

A: I've recently started at a company where there are a lot of legacy webform apps, so this looks to be a real interesting approach, and could offer a way forward if we wanted to add DI to existing web pages, thanks.
One point I noticed is that the Injection method uses the container.Resolve to explicitly resolve components, therefore I think we may need to do a container.Release on the components when the Page Unloads.
If we have transient components and don't do this then we may face memory leakages. Not sure how components with Per Web Request lifestyles would behave (i.e. would Windsor pick them up at the end of the web request, even though we explicitly resolved them) but here too may want to play safe.
Therefore the module may need to be extended to keep track of the components that it resolves and release them so that Windsor knows when to clean up.

A: One thing that was missing from the accepted answers was the fact that the http module needs to be registered in the web.config file (depending on the application) before the module will actually resolve the dependencies on the code-behind pages. What you need is :
<system.webServer>
    <modules>
      <add name="ClassNameForHttpModuleHere" type="NamespaceForClass"/>
    </modules>
  </system.webServer>

Other than that the accepted solutions worked like a charm.
Reference to the Microsoft website for adding http modules: https://msdn.microsoft.com/en-us/library/ms227673.aspx

A: Rather than doing it like this, you could also use a type resolver directly with something like:
ILogger Logger = ResolveType.Of<ILogger>();


text:
Q: Pandas how groupby and then count the number of unique items in each column? Using this code:
import pandas

df = pandas.DataFrame()

df['id']     = list('aaabbbcccdddeee')
df['gender'] = list('mmfmfmmffmfmfff')

I get a DataFrame like:
   id gender
0   a      m
1   a      m
2   a      f
3   b      m
4   b      f
5   b      m
6   c      m
7   c      f
8   c      f
9   d      m
10  d      f
11  d      m
12  e      f
13  e      f
14  e      f

How can I split df by id and then count the number of m and f in each category so that I can get a result that looks something like:
    m    f
a   2    1
b   2    1
c   1    2
d   2    1
e   0    3

A: You can use pd.pivot_table with len:
res = df.pivot_table(index='id', columns='gender',
                     aggfunc=len, fill_value=0)

print(res)

gender  f  m
id
a       1  2
b       1  2
c       2  1
d       1  2
e       3  0


text:
Q: Animate a window, sliding from right to left or from bottom to top I am trying to implement an animation for a window such that it acts as sliding from the right to the left or from the bottom to the top.
I've tried the DoubleAnimation, which works for the case from the left to the right or from the top to the bottom.
Here is what I've tried:
myWindow.Show();
DoubleAnimation myAnimation = new DoubleAnimation();
myAnimation.From = 0;
myAnimation.To = myWindow.ActualWidth;
myAnimation.SpeedRatio = 5;
myWindow.BeginAnimation(System.Windows.Window.WidthProperty, myAnimation);

If I replace myWindow.ActualWidth with myWindow.ActualHeight, and replace WidthProperty with HeightProperty, I will get the animation slides from top to bottom.
Do you know any similar and simple way to animate the window but slide from the right to the left? myWindow.Left and myWindow.Top have already been set.
Thank you so much for your help in advance. I really appreciate that.

A: Just revert the from and to values:
myAnimation.From = myWindow.ActualWidth;
myAnimation.To = 0;

Seems pretty obvious...
Edit:
You're animating the wrong property, try this:
myWindow.BeginAnimation(System.Windows.Window.LeftProperty, myAnimation);


text:
Q: How overlay image over a cup using html5 canvas I am new to HTML5 canvas. I have a image of a cup, I am rendered that in canvas.
This is image of cup :

Now I am trying render another image (My photo that is in normal rectangular size) in upload your design area of this image. How can I render this image which looks like that image on cup?
I want to get the final image like this :

I am uses canvas element to upload the image.
 <!DOCTYPE html>
 <html>
 <body>

 <canvas id="myCanvas" width="400" height="400" style="border:5px solid #c3c3c3;">
 Your browser does not support the HTML5 canvas tag.
 </canvas>

 <script src="js/test.js" type="text/javascript"></script>

 </body>
 </html>

JS
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
var imageObj = new Image();

var x = 0;
var y = 0;
var width = 290;
var height = 297;

imageObj.onload = function() {
    context.drawImage(imageObj, x, y);
};

imageObj.src = 'images/cup.jpg';

A: You want your second image to "warp" and appear as if it's wrapped around the cup.
You cannot warp your second image into a curved image using "out-of-the-box" context 2d
Using html Canvas 2d Context, you can only do quadrilateral skewing.  Therefore, after skewing an image each opposing side will always be parallel.
Therefore, you cannot get your image to warp into a curved image using "out-of-the-box" context 2d.
A few workarounds...You can use an offscreen temporary canvas to "warp" your second image into a curve.  Then you can draw that curved image on top of the cup image using context.drawImage.  Here are 2 alternatives that let you "fake" curvature of an image.
Alternative #1: Texture Mapping
You can use texture mapping to apply perspective curvature to your second image:
http://archive.gamedev.net/archive/reference/articles/article852.html
Alternative #2: Vertically slice and stretch
You can vertically slice your second image to create perspective curvature. You can use the resizing capability of context.drawImage to "stretch" pixels into your curved shape like in this previously Stackoverflow answer: How to make rooftext effect and valley text effect in HTML5 (or Fabric.js)
jsfiddle.net/AbdiasSoftware/e8hZy/


text:
Q: Google API: It's possible to authenticate on javascript and use the auth_code to get the refresh token on server side? I need to authenticate in Google Calendar, but I can't use the server-side mode, because my page can't be refreshed, so I am using the javascript API:
var SCOPES = ["https://www.googleapis.com/auth/calendar", "https://www.googleapis.com/auth/calendar.readonly", "https://www.googleapis.com/auth/userinfo.email"];

    gapi.auth.authorize({
        client_id: clientId,
        scope: SCOPES,
        immediate: false
    }, handleAuthResult);

As I can't refresh the page and I'll need the refresh_token later, I'm sending the returned auth_code by ajax to my controller, and then trying to get the refresh_token, this is the server side:
var provider = new NativeApplicationClient(GoogleAuthenticationServer.Description, "client_id", "client_secret");

IAuthorizationState state = new AuthorizationState();

state.Callback = new Uri("myURL");
state.AccessToken = clientSecret;

IAuthorizationState result = null;

try
{
     result = provider.ProcessUserAuthorization(auth_code, state);
}
catch (Exception)
{

}

When ProcessUserAuthorization is called, it returns the following error:

The remote server returned an error: (400) Bad Request.

I can't redirect the page, because the button to sync is in the end of a form, so if an user filled the form and click to authenticate, page will be redirected and he will lost every data. This is why I'm trying to do this way.


text:
Q: Is there a way to detect if a macOS app running is from the Mac App Store or not? I have this app of mine that is distributed on the Mac App Store and outside it, from my own site.
I need to detect, at run time, what version is running, so I can do some decisions inside the code.
Is there a way to detect that? How can I differentiate that? Is there a way to know if the app is signed for the App Store or not?

Edit: I have found this library but this is not good because it tells the app is not from the app store simply if the receipt is missing. But the receipt may be missing for other reasons. The lack of receipt is not a good enough reason.

A: I see two ways to do this:

*

*Make a compile-time flag. Compile it one way for submission to the App Store, the other way for distribution outside the App Store.

*Rather than just checking your app's code signature validity (as the library you found does), call SecCodeCopySigningInformation to get signature details, and look at the kSecCodeInfoCertificates array to see whether it includes your Developer ID cert or the "Apple Mac OS Application Signing" cert used by the App Store.

IMO the second option is significantly more complex and fragile; for example, if Apple changes how they sign App Store apps, your code may break. I'd go with the first option.


text:
Q: Windows batch script: Manual power up vs Wake on Lan (WOL) OK, I have a (win 7) desktop computer with WOL set up so I can turn it on remotely, it works fine. Next thing, on this computer I have a batch script, which runs at startup and starts various apps, also works well:) But sometimes, when I am physically present at the computer, I power it up manually - and I need complete different set of apps.. so I must typically close all apps started by script and then execute another, which is a bit.. low tech:)
Question is: Can we tell in which way was the computer powered on - manually or WOL, in a batch script?
I would imagine it like this:
IF %wolpowerstatus% equ 1 (
   Echo Computer powered up by WOL
   :: spam ugly dark commandline apps all over desktop
) ELSE (
   Echo Computer powered up by the user
   :: run those pretty apps with gui
)

.
Update:
I were pointed to hopefully right direction by mnmnc. This SO question seem to offer a solution. Unfortunately I cannot confirm it to work as I am completely untouched by Powershell yet :)


text:
Q: iOS - Unity build error - Durovis SDK I have just purchased an iOS developer account and I want to create iOS VR apps with Unity3D. I know that Google Cardboard SDK does not support iOS, so I downloaded and tried Durovis SDK.
Once I imported the durovis .unitypackage , I made an empty build, just so I could test out if it builds through Xcode.
The result is that Xcode fails to build when I choose "Device SDK" from Unity build settings , and succeeds when I choose "Simulator SDK" but of course then it runs on Simulator and not on my device.
I am very new to Xcode, so I don't know if I need to import anything from Xcode, after I make the build from Unity. Any help would be appreciated, since I've been making VR apps long time now for android and I recently decided to try to ios as well.
Thanks in advance

A: Make sure you have the latest version. Then press Cmd+Shift+B to bring up the PlayerSettings. Make sure company name and product name are filled in and then scroll down and click Other Settings. For the bundle identifier it has to be com.companyName.ProductName and that should be it. If that doesn't work you'll have to tweak xCode settings but that's more fragile so please respond to this with results or lack thereof.


text:
Q: Webpack errors after build when importing markdown files I setup a webpack-react-redux isomorphic app.
Also I use webpack-dev-server for development and webpack to build javascript & css files.
I want to use markdown-loader for webpack to transform markdown to html.
So I installed the markdown-loader and added it to the dev.config.webpack & the production.config.webpack file.
Now for the development server it works fine, it will import README.md and transform it to html.
When building the app to production, start it up and refresh in my browser it throws a error about not able to import './README.md';
So my question; how can I import a markdown file and use contents, when building my app for production?
Thnx in advance..!


text:
Q: How to split multi line sentences without delimiters('.','?','!')?
I have extracted text from pdf and trying to split it into sentences.
text sample in repr form -
"This is multiline text without any delimiter need to \n be considered as one sentence \n Whereas this sentence is one liner \n Slash n or first char capital is not option as sentences of \n Dhiraj's sample can contain first letter capital even its not a new sentence"

result should be like -
["This is multiline text without any delimiter need to be considered as one sentence","Whereas this sentence is one liner","Slash n or first char capital is not option as sentences of Dhiraj's sample can contain first letter capital even its not a new sentence"]

my temporary solution is to get the max length of sentence and consider it as multi line sentence and remove /n there. but it is not reliable.

A: There is a solution but it requires some handwork,

*

*Create a list that includes proper names, find all the proper names in the text
with that list, and convert them to lowercase letters with a search method.

*Then write your main code block, separating the text into sentences using the first capital letters.

*At the end re-capitalize the names in the text using the name list.


text:
Q: Excel 2016 - Calculation Speed I have recently switched to a new laptop and installed Office 2016. My Excel calculates slowly and eats up all my resources.  The same spreadsheet on an older machine with Excel 2013 recalculates quickly.
As a reference my laptop had 16GB of RAM, intel 8th generation, 6 cores/12 threads. When I monitor the CPU is running with all 12 cores at 100% @ 3.5GHZ. I run Windows 10 professional and use a NVme SSD (samsung 970 pro).
It seems that every new version of Excel things slow down. The same was true when I 'upgraded' from Excel 2010 to Excel 2013.
Has anyone experienced the same problem or any suggestions?


text:
Q: TIdHTTP GET Round Trip Request/Response Time in MSecs I'm using TIdHTTP to make HTTP GET requests to get wiki pages (executed until x >= 9 times using a for loop statement).
I am trying to use TStopWatch to measure the HTTP round trip request/response time in milliseconds of each GET requests.
I have tried somes methods, but, I still in doubt that it was right or not. So, please tell me what's the right method to do that. Thank you.
Btw, the code I have is:
//---------------------------------------------------------------------------
  int MSec = 0;
  TTimeSpan TTSpan;
  TDateTime StartTime;
  DWORD AStartTime = 0;
  DWORD CStartTime = 0;
  String ACount, Codes, Milli, Result;

//---------------------------------------------------------------------------
__fastcall TForm1::TForm1(TComponent* Owner) : TForm(Owner)
{
  IdHTTP->ConnectTimeout = 3048;
  IdHTTP->ReadTimeout = 2048;
}
//---------------------------------------------------------------------------
void __fastcall TForm1::IdHTTPWork(TObject *ASender, TWorkMode AWorkMode, __int64 AWorkCount)
{
  if (AWorkMode == wmRead)
    ACount = "size: [" + String(AWorkCount) + " bytes]";
}
//---------------------------------------------------------------------------
void __fastcall TForm1::WorkClick(TObject *Sender)
{
  static int Number = 1;
  TStopwatch SWatch = TStopwatch::StartNew();

  // CStartTime = GetTickCount();
  // DWORD Start = timeGetTime();
  // AStartTime = GetTickCount();
  // CStartTime = TTSpan.Milliseconds;

  Work->Enabled = false;
  ListBox->Items->Clear();
  ListBox->Items->BeginUpdate();

  for (int i = 0; i < 9; i++)
  {
    try
    {
      SWatch.Start();
      try
      {
        IdHTTP->Get("http://en.wikipedia.org/");
        Sleep(1000);
      }
      catch (const Exception &E)
      {
        Label1->Caption = E.Message;
      }

      SWatch.Stop();
      TTSpan = SWatch.Elapsed;
      MSec = TTSpan.Milliseconds;
      // MSec = TTSpan.Milliseconds / 10;
      // MSec = SWatch.ElapsedMilliseconds / 10;
      // TTSpan = SWatch.Elapsed;
      // MSec = TTSpan.Milliseconds - CStartTime;

      Milli = " time: [" + String(MSec) + " ms]";
      Codes = " code: [" + IdHTTP->Response->ResponseText.LowerCase() + "]";
      ListBox->Items->Add("(" + String(Number++) + "). " + ACount + Codes + Milli);

      // AStartTime = GetTickCount();
      // ListBox->Items->Add("(" + String(Number++) + "). " + ACount + Codes + Result.sprintf(L" time: [%i ms]",(aStartTime-bStartTime)));
    }
    __finally
    {
      Work->Enabled = true;
      IdHTTP->Disconnect(true);
      ListBox->Items->EndUpdate();
    }
  }
}


text:
Q: Can all contours of a function on a disk be made arbitrarily small? Denote $D=\{x^2+y^2\le1\}\subset\mathbb R^2$ a disk.
Let $f:D\to\mathbb R$ be a continuous function on it. I am interested in restrictions of simple Morse functions on $\mathbb R^2$, but I suspect the answer is the same for any continuous or any smooth function.
A contour of $f$ is a connected component of the preimage of a point, $f^{-1}(\mathrm{const})$.
The diameter of a set is the maximum distance between its points.
Can the maximum diameter of a contour be made arbitrarily small by a suitable choice of $f$?
I suspect that no; namely, I suspect that at least one contour of $f$ will have diameter greater than, say, the radius of the disk, but I can't prove it.
The diameter of the disk is not the bound: Consider a Y-shaped figure formed by three radii, and $f$ being the distance from this figure. Then the largest contour is the Y figure, with the diameter greater than the radius of the disk but smaller than the diameter of the disk.

A: Every continuous function on a unit disk $D^2$ has a level set containing a connected component of diameter at least $\sqrt{3}$; this constant cannot be increased. Generally, in case of $D^n$, $n>2$, there is a level set with a connected component of diameter at least $2$.
See the paper "Level Sets on Disks" by A. Maliszewski and M. Szyszkowski, 2014,  https://doi.org/10.4169/amer.math.monthly.121.03.222


text:
Q: Etymology of the meaning of waste as a broad expanse Merriam-Webster online dictionary says one of the meanings of "waste" is:
a broad and empty expanse(as of water)
http://www.merriam-webster.com/dictionary/waste
I'm interested in the origin of this meaning.
Let me explain why.
Here's from Hamlet, Act 1, Scene 2.

In the dead wast and middle of the night

This is from Second Quarto and First Folio.
In the modern spelling, "wast" is "waste".
However, in First Quarto, "wast" is replaced by "vast".
My wild guess is that the pronunciation of "vast" and "wast" were the same in the Elizabethan English. Hence the printers of Hamlet at that time mistook "vast" as "wast".
They say First Quarto is unreliable, but it's the oldest text of Hamlet.
In any case, my question is: What is the origin of the meaning of "waste" as a broad expanse?

A: According to the Online Etymology Dictionary, the etymology of this sense of waste is:

waste: c.1300, of land, "desolate, uncultivated," from Anglo-French and Old North French waste (Old French gaste), from Latin vastus (see waste (v.)). From c.1400 as "superfluous, excess;" 1670s as "unfit for use." Waste-paper attested from 1580s.

In other words, all that space is wasted. Because, conceptually, one or more of the following applies:

*

*No one is using it, i.e. it's more than is needed

*No one can use it, e.g. for farming, because it's unfit

*It's been used up, i.e., it is dried out, arid.

*It's covered in rubble (garbage).

Re: your speculation about vast, yes, they share a common origin in the Latin word:

vastus: a lot of empty (wasted) space.

But note the senses and etymologies of the two derived words -- vast and waste -- diverged about three centuries before Hamlet was written.

Aside: one of the most moving statements in the English language occurred when a reporter asked Buzz Aldrin (the second man on the Moon) what the Moon was like, and he replied:

Beautiful. Beautiful. Magnificent desolation.


text:
Q: How can I remove an specific button in tkinter after creating various of them with the same function? So I'm programming my first GUI with Tkinter for a project I have in mind and I'm having a lot of trouble with one essential step for this project. To summarize, I need to create a button that simply adds more buttons. Here is my code for this button:
room_frame_number = 0
def add_room_frame():
    global room_frame_number
    room_frame_number += 1

    room_Button = tk.Button(rooms_frame, text = "This is room number " + str(room_frame_number))

    add_button.pack_forget()
    room_Button.pack()
    add_button.pack()

add_button = tk.Button(rooms_frame, text = "Add", command = add_room_frame)
add_button.pack()

Now, what I'm having problems with is the following: when I click one of those newly created buttons, the command I want to activate is one that erases the clicked button.
I know I need to use the pack_forget() method at some point, but all I have tried gave me problems. Please, I would appreciate so much a bit of orientation with this issue.

A: If you want the button to be  able to delete itself, you can do it like this:
room_Button = tk.Button(rooms_frame, text = "This is room number " + str(room_frame_number))
room_Button.configure(command=room_Button.destroy)


text:
Q: Mark duplicates in MySql with php (without deleting) So, I'm having some problems with a MySQL query (see other question), and decided to try a different approach.
I have a database table with some duplicate rows, which I actually might need for future reference, so I don't want to remove. What I'm looking for is a way to display the data without those duplicates, but without removing them. I can't use a simple select query (as described in the other question).
So what I need to do is write a code that does the following:
1. Go through my db Table.
2. Spot duplicates in the "ip" column.
3. Mark the first instance of each duplicate with "0" (in a column named "duplicate") and the rest with "1".
This way I can later SELECT only the rows WHERE duplicate=0.
NOTE: If your solution is related to the SELECT query, please read this other question first - there's a reason I'm not just using GROUP BY / DISTINCT.
Thanks in advance.

A: MySQL doesn't have any ranking/analytical/windowing functionality, but you can use a variable instead:
  SELECT t.ip,
         CASE
           WHEN @ip != t.ip THEN @rank := 0
           ELSE @rank := @rank + 1
         END AS duplicate,
         @ip = t.ip
    FROM TABLE t
    JOIN (SELECT @rank := 0, @ip = NULL) r
ORDER BY t.ip

The first occurrence of the ip value will be have the value of zero in the duplicate column; all subsequent records will have value incrementing by one.  If you don't want the incrementing number, use:
  SELECT t.ip,
         CASE
           WHEN @ip != t.ip THEN 0
           ELSE 1
         END AS duplicate,
         @ip = t.ip
    FROM TABLE t
    JOIN (SELECT @ip = NULL) r
ORDER BY t.ip

You can get a list of unique IP rows from that by using it in a subquery:
SELECT x.ip
  FROM (paste either query in here) x
 WHERE x.duplicate = 0


text:
Q: Panel fullscreen fails on exit using trigger('resize') I have a popup window that automatically goes into fullscreen.
I also have a button to exit fullscreen and a button to exit(close), if the window is fullscreen the exit button works perfectly, but if it is not in fullscreen the button to exit bugs the whole page.
How can I fix this?
Code:
`$(document).ready(function () {
        var count = 1 ;
        $(".dr" + count).parents('.panel').toggleClass('fullscreen');
        $(window).trigger('resize');
    });
    document.getElementById("detalhes" + count).outerHTML = '';
}`

EDIT:
PHP Remove from code.

A: Confirm if is in fullsceem or not:

var count = 1 ;
 if ($(".dr" + count).parents('.panel').hasClass('fullscreen')) {
  //its in fullscream so trigger fullscreen again then remove

     $(document).ready(function () {
   $(".dr" + count).parents('.panel').toggleClass('fullscreen');
   $(window).trigger('resize');
  });
  document.getElementById("detalhes" + count).outerHTML = '';
   }else{´
  //isn't in fullscreen so just remove
  document.getElementById("detalhes" + count).outerHTML = '';

   }


text:
Q: official Stock api for stocks of Yahoo You may find this question repost but none of them has satisfy answer.
I want to know what is the legal and supported stock fetching php api From YAHOO FINANCE

A: Why not use YQL - yahoo query language. (http://developer.yahoo.com/yql/)
Eaxamples here -
http://developer.yahoo.com/yql/guide/yql-code-examples.html
http://www.yqlblog.net/blog/2009/06/02/getting-stock-information-with-yql-and-open-data-tables/


text:
Q: 'Unexpected token export' when using gulp / webpackstream / vue I am trying to use vue's template compiler in my project via gulp and webpack-stream. The set up is something like this:
gulp.task('js', function () {

return gulp.src('./src/js/main.js')
    .pipe(webpackStream(
        module.exports = {
            output : {
                filename: 'bundle.js'
            },
            resolve : {
                alias: {
                    "vue$": "vue/dist/vue.esm.js",
                    // bind to modules;
                    modules: path.join(__dirname, "../node_modules")
                }
            }
        }
    ))
    .on('error', function handleError() {
        this.emit('end'); // Recover from errors
    })
    .pipe(gulp.dest('./js/'));
});

the error message is this:
Uncaught SyntaxError: Unexpected token export

which is being caused by this:
export default Vue$3;

A: I believe you should remove module.exports = from your webpackStream parameter. It should be simple javascript literal object
 .pipe(webpackStream(
    module.exports = {
    ^^^^^^^^^^^^^^^^^
       output : { filename: 'bundle.js' },
  ...

Hope it helps


text:
Q: Locking nautilus bookmarks I have my nautilus directory bookmarks set up the way I want.
I don't want to accidentally "+ Other Locations" or accidentally drag and drop the bookmarks I already have, which seems to happen often.
Is there any way to "lock" the existing bookmarks in place (and get rid of the "+ Other Locations" link) until I decide I want to make changes and "unlock" its state?
Thanks!
Edit: Using Ubuntu version 18.04, screenshot attached below.

A: Ok, just a quick one for fun:
If you'd prefer not to fiddle with permissions, just run the script below in the background. Checking a text file once per five seconds adds zero to your system's burden, so no worries about that.
#!/usr/bin/env python3
import os
import time

home = os.environ["HOME"]
f = os.path.join(home, ".config/gtk-3.0/bookmarks")

text1 = open(f).read()

while True:
    time.sleep(5)
    text2 = open(f).read()
    if text2 != text1:
        open(f, "wt").write(text1)

How to use

*

*Copy the script below into an empty file, save it as fix_bookmarks.py

*Test-run it with the command:
python3 /path/to/fix_bookmarks.py

*Try to add bookmarks, they will immediately (within 5 seconds) be reverted.

*If all works fine, ad it to Startup Applications.

Explantion
Once per 5 seconds, the script checks if the bookmarks file is still in exactly the same state as when you started the script. It will revert if not.
Toggle editing bookmarks

To toggle the ability to edit your bookmarks, copy the small script below, save it as toggle_bookmarks.sh in one and the same directory as fix_bookmarks.py, and add the first one to a shortcut, or to any other way to run the toggle script.
#!/bin/bash

dr=$(dirname "$0")
f=$dr'/fix_bookmarks.py'

if ! pgrep -f "$f"
then
  "$f" &
  notify-send -i 'bookmark-new-symbolic' 'Bookmarks' 'Editing disabled'
else
  pkill -f "$f"
  notify-send -i 'bookmark-new-symbolic' 'Bookmarks' 'Editing enabled'
fi


text:
Q: What is the maximum size of file that Jackson Csv to Json library can handle? I am using Jackson to convert a csv file to json. However I get the following exception:
Exception in thread "main" com.fasterxml.jackson.core.JsonParseException: Too many entries: expected at most 71 (value #71 (0 chars) "")
 at [Source: com.fasterxml.jackson.dataformat.csv.impl.UTF8Reader@5f83bcb8; line: 149, column: 1153]
    at com.fasterxml.jackson.core.JsonParser._constructError(JsonParser.java:1487)
    at com.fasterxml.jackson.core.base.ParserMinimalBase._reportError(ParserMinimalBase.java:518)
    at com.fasterxml.jackson.dataformat.csv.CsvParser._handleNextEntryExpectEOL(CsvParser.java:643)
    at com.fasterxml.jackson.dataformat.csv.CsvParser._handleNextEntry(CsvParser.java:629)
    at com.fasterxml.jackson.dataformat.csv.CsvParser.nextToken(CsvParser.java:472)
    at com.fasterxml.jackson.databind.deser.std.MapDeserializer._readAndBindStringMap(MapDeserializer.java:470)
    at com.fasterxml.jackson.databind.deser.std.MapDeserializer.deserialize(MapDeserializer.java:342)
    at com.fasterxml.jackson.databind.deser.std.MapDeserializer.deserialize(MapDeserializer.java:26)
    at com.fasterxml.jackson.databind.MappingIterator.nextValue(MappingIterator.java:188)
    at com.fasterxml.jackson.databind.MappingIterator.readAll(MappingIterator.java:226)
    at com.fasterxml.jackson.databind.MappingIterator.readAll(MappingIterator.java:212)
    at CsvToJsonParser.readObjectsFromCsv(CsvToJsonParser.java:47)
    at CsvToJsonParser.convertCsvToJson(CsvToJsonParser.java:36)
    at MainParser.main(MainParser.java:16)

I noticed that I am getting this exception when I have a file with more than ~70 entries. However I want to convert a file with ~60000 entries!!!
Anybody has an idea what causes the limitation to the Jackson library??

A: Others have commented on misunderstanding wrt error message; but to be precise, error message indicates that there is an extra value on specified row. Looking at additional value (empty String), I am guessing you simply have an extra comma at the end of that line.


text:
Q: How to Loop right between Playbook and Role in Ansible I try to loop over the geerlingguy.nginx Role to create nginx VHosts. But I don't get it done:
Playbook.yml
- hosts: some.server
  become: true
  roles:
    - geerlingguy.nginx
  tasks:
    - name: looping vhosts
      include_tasks: vhosts.yml
      loop:
        - { name: 'vhost1.bla.com', state: 'present' }
        - { name: 'vhost1.bla.com', state: 'present' }

For this Server I create a Host_vars File:
host_vars.yml
nginx_worker_processes: "auto"
nginx_worker_connections: 768
nginx_extra_http_options: |
    gzip on;
    types_hash_max_size 2048;
    include /etc/nginx/mime.types;
    ssl_prefer_server_ciphers on;
    access_log /var/log/nginx/access.log;
    error_log /var/log/nginx/error.log;
nginx_vhosts:
  - listen: "443 ssl http2"
    server_name: '{{ item.name }}'
    server_name_redirect: " {{ item.name }} "
    root: "/var/www/{{ item.name }}"
    index: "index.php index.html index.htm"
    access_log: "/var/www/{{ item.name }}/logs/access_{{ item.name }}.log"
    error_log: "/var/www/{{ item.name }}/logs/erro_{{ item.name }}.log"
    state: "{{ item.state }}"
    template: "{{ nginx_vhost_template }}"
    filename: "{{ item.name }}"
    extra_parameters: |
      ssl_certificate     /etc/ssl/certs/ssl-cert-snakeoil.pem;
      ssl_certificate_key /etc/ssl/private/ssl-cert-snakeoil.key;
      ssl_protocols       TLSv1.1 TLSv1.2;
      ssl_ciphers         HIGH:!aNULL:!MD5;

This is the vhost.yml from the geerlingguy.nginx Role:
- name: Remove default nginx vhost config file (if configured).
  file:
    path: "{{ nginx_default_vhost_path }}"
    state: absent
  when: nginx_remove_default_vhost | bool
  notify: restart nginx

- name: Ensure nginx_vhost_path exists.
  file:
    path: "{{ nginx_vhost_path }}"
    state: directory
    mode: 0755
  notify: reload nginx

- name: Add managed vhost config files.
  template:
    src: "{{ item.template|default(nginx_vhost_template) }}"
    dest: "{{ nginx_vhost_path }}/{{ item.filename|default(item.server_name.split(' ')[0] ~ '.conf') }}"
    force: true
    owner: root
    group: "{{ root_group }}"
    mode: 0644
  when: item.state|default('present') != 'absent'
  with_items: "{{ nginx_vhosts }}"
  notify: reload nginx
  tags:
    - skip_ansible_lint

- name: Remove managed vhost config files.
  file:
    path: "{{ nginx_vhost_path }}/{{ item.filename|default(item.server_name.split(' ')[0] ~ '.conf') }}"
    state: absent
  when: item.state|default('present') == 'absent'
  with_items: "{{ nginx_vhosts }}"
  notify: reload nginx
  tags:
    - skip_ansible_lint

- name: Remove legacy vhosts.conf file.
  file:
    path: "{{ nginx_vhost_path }}/vhosts.conf"
    state: absent
  notify: reload nginx

So, when I run the playbook I got:
fatal: [some.server]: FAILED! => {
    "msg": "[{'listen': '443 ssl http2', 'server_name': '{{ item.name }}'... HIGH:!aNULL:!MD5;\\n'}]: 'item' is undefined

I try it in different ways but always get the same error, would be greate if someone could help me.

A: Your approach doesn't work, you won't get anything out of a loop at this point. Furthermore, it is not possible to define a variable or data structure and have the Jinja logic evaluate it later.
The implementation of geerlingguy provides that the variable nginx_vhosts is defined. This variable must be a list of dicts, and this list is then automatically processed.
You have two main options:
Option 1
You create nginx_vhosts as a list of dicts for all your virtual hosts.
nginx_vhosts:
  - listen: "443 ssl http2"
    server_name: "vhost1.bla.com"
    server_name_redirect: "www.vhost1.bla.com"
    root: "/var/www/vhost1.bla.com"
    index: "index.php index.html index.htm"
    error_page: ""
    access_log: "/var/www/vhost1.bla.com/logs/access_vhost1.bla.com.log"
    error_log: "/var/www/vhost1.bla.com/logs/error_vhost1.bla.com.log"
    state: "present"
    template: "{{ nginx_vhost_template }}"
    filename: "vhost1.bla.com.conf"
    extra_parameters: |
      ssl_certificate     /etc/ssl/certs/ssl-cert-snakeoil.pem;
      ssl_certificate_key /etc/ssl/private/ssl-cert-snakeoil.key;
      ssl_protocols       TLSv1.1 TLSv1.2;
      ssl_ciphers         HIGH:!aNULL:!MD5;
  - listen: "443 ssl http2"
    server_name: "vhost2.bla.com"
    server_name_redirect: "www.vhost2.bla.com"
    root: "/var/www/vhost2.bla.com"
    index: "index.php index.html index.htm"
    error_page: ""
    access_log: "/var/www/vhost2.bla.com/logs/access_vhost2.bla.com.log"
    error_log: "/var/www/vhost2.bla.com/logs/error_vhost2.bla.com.log"
    state: "present"
    template: "{{ nginx_vhost_template }}"
    filename: "vhost2.bla.com.conf"
    extra_parameters: |
      ssl_certificate     /etc/ssl/certs/ssl-cert-snakeoil.pem;
      ssl_certificate_key /etc/ssl/private/ssl-cert-snakeoil.key;
      ssl_protocols       TLSv1.1 TLSv1.2;
      ssl_ciphers         HIGH:!aNULL:!MD5;

Option 2
A bit more complicated, but I think that was your wish, with the loop.
Create a separate file for your tasks myvhost.yml with the following content:
---
- name: create directories
  file:
    path: "{{ item }}"
    state: directory
  with_items:
    - "/var/www/{{ vhost.name }}"
    - "/var/www/{{ vhost.name }}/logs"

- name: define nginx_vhosts variable
  set_fact:
    nginx_vhosts:
      - listen: "443 ssl http2"
        server_name: '{{ vhost.name }}'
        # server_name_redirect: " {{ vhost.name }} "
        root: "/var/www/{{ vhost.name }}"
        index: "index.php index.html index.htm"
        access_log: "/var/www/{{ vhost.name }}/logs/access_{{ vhost.name }}.log"
        error_log: "/var/www/{{ vhost.name }}/logs/erro_{{ vhost.name }}.log"
        state: "{{ vhost.state }}"
        # template: "{{ nginx_vhost_template }}"
        filename: "{{ vhost.name }}"
        extra_parameters: |
          ssl_certificate     /etc/ssl/certs/ssl-cert-snakeoil.pem;
          ssl_certificate_key /etc/ssl/private/ssl-cert-snakeoil.key;
          ssl_protocols       TLSv1.1 TLSv1.2;
          ssl_ciphers         HIGH:!aNULL:!MD5;

- name: include vhosts.yml from geerlingguy
  include_role:
    name: geerlingguy.nginx
    tasks_from: vhosts

Here you set the variable nginx_vhosts with new values, a list with a single dict. Then you perform the import the tasks vhosts of the role from geerlingguy.
In your playbook, on the other hand, you import your new myvhost.yml with the loop.
- name: looping vhosts
  include_tasks: myvhost.yml
  loop:
    - { name: 'vhost1.bla.com', state: 'present' }
    - { name: 'vhost2.bla.com', state: 'present' }
  loop_control:
    loop_var: vhost

Explanation of the changes
For your loop you have to rename the loop variable, otherwise there will be conflicts with loops in the vhosts.yml of geerlingguy (I had overlooked this at the beginning), see loop_var: vhost. After renaming the loop variable, you must of course also change the name in myvhost.yml from item to vhost.
Before running your task looping vhosts, the geerlingguy.nginx role should have been run once, e.g. if it is listed in your playbook under roles:.
Another change I made in myvhost.yml. Instead of include_tasks use better include_role with tasks_from: vhosts.
I commented out the server_name_redirect: setting for now, because it creates nginx config files that crash nginx. If you really need this setting you have to analyze this in more detail.
Furthermore the certificate files (ssl-cert-snakeoil) must exist before creating the VHosts.
A complete playbook might look like this:
---
- hosts: nginx
  become: true

  roles:
    - geerlingguy.nginx

  tasks:
    - name: looping vhosts
      include_tasks: myvhost.yml
      loop:
        - { name: 'vhost1.bla.com', state: 'present' }
        - { name: 'vhost2.bla.com', state: 'present' }
      loop_control:
        loop_var: vhost


text:
Q: AWS S3 IAM Access with bucket policies For an S3 bucket named my_bucket with the following Bucket Policy allow access to other IAM users with Admin access policy attached -
{
    "Version": "2012-10-17",
    "Id": "Policy",
    "Statement": [
        {
            "Sid": "Statement to allow my_user",
            "Effect": "Allow",
            "Principal": {
                "AWS": "arn:aws:iam::**********:user/my_user"
            },
            "Action": "s3:*",
            "Resource": "arn:aws:s3:::my_bucket/*"
        }
    ]
}

I ran IAM policy simulations and and received the following error -

based on my reading of Access control over view and IAM Policies and Bucket Policies and ACLs! Oh, My! since there is no explicit deny the other IAM accounts should have no problems.


text:
Q: Unusual appearance when scrolling UITableView with custom cells and selection status I have a tableview containing custom cells, which override setSelected:animated:. Sometimes, when scrolling the table containing selected cells, the appearance of the selected cells is a strange mix of the selected and unselected state.
My setSelected:animated: method looks like this:
-(void)setSelected:(BOOL)selected animated:(BOOL)animated
{
    if (selected == self.selected)
        return;

    CGFloat destinationAlpha = selected ? 1.0 : 0.0;
    NSTimeInterval duration = animated ? 0.25 : 0.0;

    for (UIView *view in self.topView.subviews)
    {
        if (![self.viewsToLeaveBackgroundAlone containsObject:view])
            view.backgroundColor = [UIColor clearColor];
    }

    [UIView animateWithDuration:duration animations:^{
        self.selectedTopViewBackground.alpha = destinationAlpha;
    }animations completion:^(BOOL finished) {
        if (!selected)
        {
            for (UIView *view in self.topView.subviews)
            {
                if (![self.viewsToLeaveBackgroundAlone containsObject:view])
                    view.backgroundColor = self.topView.backgroundColor;
            }
        }
    }];

    [super setSelected:selected animated:animated];
}

I've added logs and breakpoints and right cell is getting the right selected status sent to it. What can be going wrong?

A: It turns out that you can't rely on the completion blocks of zero-duration animations to be called immediately, which makes sense when you think about it. From my testing, the completed parameter is always YES as well.
Though it is very tempting to simply set a duration of zero for transitions that are not supposed to be animated, if the animation contains a completion block and the method is called in quick succession, you can't guarantee the order that the completion blocks are called in.
For example, whilst scrolling a table up and down, the following can happen:

*

*A selected cell is scrolled off the screen and re-used (selected:NO animated:NO)

*The selected cell is scrolled back onto the screen (selected:YES animated:NO)

Using zero length animations doesn't guarantee that the completion block from the first call is called before the completion block from the second call.
A solution is to wrap the animation operations and completion operations in two local blocks, and execute these directly or pass to the animation, depending on the animated parameter:
-(void)setSelected:(BOOL)selected animated:(BOOL)animated
{
    if (selected == self.selected)
        return;

    CGFloat destinationAlpha = selected ? 1.0 : 0.0;

    for (UIView *view in self.topView.subviews)
    {
        if (![self.viewsToLeaveBackgroundAlone containsObject:view])
            view.backgroundColor = [UIColor clearColor];
    }

    dispatch_block_t animations = ^{
        self.selectedTopViewBackground.alpha = destinationAlpha;
    };

    dispatch_block_t completion = ^{
        if (!selected)
        {
            for (UIView *view in self.topView.subviews)
            {
                if (![self.viewsToLeaveBackgroundAlone containsObject:view])
                    view.backgroundColor = self.topView.backgroundColor;
            }
        }
    };

    if (animated)
    {
        [UIView animateWithDuration:0.25 animations:animations completion:^(BOOL finished) { completion();}];
    }
    else
    {
        animations();
        completion();
    }
    [super setSelected:selected animated:animated];
}

This has the additional advantage (for more complex cases) of not having one massive call containing two huge blocks of code. Even more so if you have nested animations.


text:
Q: Is it possible R/W data to /system/bin/ from system/pri-system app in android 11/12 I am Using rock-chip device and working on  AOSP 11/12 source code.
I have created privileged system app to Read/Write data to /system/bin/ .
Tried below things :

*

*new File("/system/bin").exists() ===> Getting value is "true"

*new File("/system/bin").canRead() ===> Getting value is "false"

*new File("/system/bin").canWrite() ===> Getting value is "false"
Do we have any another way to read/write data to /system/bin?


text:
Q: Eclipse CVS Commit, ignore certain file types I have a rather large project made up of lots of...projects, each with their own Debug and Release folders along with a bunch of other files that I don't really want to commit like .rc and .user.
At the moment I right click the top folder, click commit and eclipse asks how i would like to store all these "new files" it has detected, how do i tell it I don't want to commit any of them.
So far i have read that i need a .cvsignore file but that doesn't seem to make a difference. I tried doing a "clean" of the project but there was still plenty of files i don't want.
Does anyone have any advice on how to make this at the very least less painful? I have even tried doing a search on the project for certain . files I don't want and deleting them but some of them re-create themselves....
Note: I usually just commit the files I want by selecting them individually but this time it is about 600+ files...
UPDATE
Sorry for taking so long. Thank you to everyone for their answers, they are all technically correct, none actually worked for me, but i will mark Burhan as the best answer
I have tried the cvs ignore route before and it never seemed to work, unfortunately it still didn't work for me.
The per directory approach does seem to work but its quite a painful process in this case. But khmarbaise is correct this is the documented method, and is actually correct.
The Global method Burhan mentioned seemed ideal but didn't seem to work, Perhaps i have mis-understood where CVSROOT is, i always assumed it was the "CVS" folder located in the top most directory, it includes files like "Tag", "Root" etc. is this wrong?
@thkala, the "Team->Add to .cvsignore" was always greyed out for me and therefore could not be used but again is another valid route when it does work.
However I think i have finally realized why I have so many problems with CVS and eclipse and i would like to post what finally worked for me and what may actually be the missing link for the .cvsignore route.
I always checked the project out this way: CVS Repositoris -> Right click the branch -> check out as -> check out as project in the workspace.
However the reason i was having so many problems with cvs and indexing what i should have done is:
*CVS Repositoris -> Right click the branch -> check out as -> check out as ...New Project Wizard. ->  retype branch -> Makefile Project with Existing code * (as a side note does anyone know how to specify the directory for the new project?)
Anyone who didn't do this and doesn't want to re-checkout can remove the project and re-add it using "new project"
At this point "Add to CVS ignore" was no longer greyed out. So you can now use that route if you want.
At this point however i tried something else i hadnt used before Team->synchronize with repo. This Seemed to bring up only the Changes i had made and therefore did not have any of the "new files" which was all the files i didn't want to commit. I was therefore able to simply double check the folders and then do a blanket commit on all those files in the sync view. It is really important to note that I actually had some build generated .h and .c files, so if i had succeeded in ignoring certain files, i would have still checked in these unwanted files (silver lining i suppose).
Perhaps i should rephrase the question to "large commit" to be more helpful to future cvs + eclipse newbies? anyone agree?

A: You can create a file which is call cvsignore which contains certan file types. I can't remember if it's called ".cvsignore" or "cvsignore". Check the documentation.

A: You can add a .cvsignore file on a per-directory basis containing the files in the directory that you want cvs to ignore. Note that if you want this to persist, you will have to commit that file too. @khmarbaise pointed to some documentation that talks about what kind of thing you can put in this file.
If you want to ignore certain file types on a global basis, then you should check out the CVSROOT module and make additions to the cvsignore file in that module (note that lack of a "dot" at the start of the name). Don't forget to commit this change for it to take effect.
Both .cvsignore and cvsignore files can contain the same types of information.


text:
Q: Find the path of an image file in a text file and hand over the file path to poshgram Background: I am using the file and folder watcher "DiskPulse" (Win 10) to identify a new image files (.png) in several folders. DiskPulse saves a new text file (C:\diskpulse.txt) containing an image file path, and calls a powershell (ps) script that sends the new file to telegram. I am using the poshgram module to send the new file to telgram.
Problem 1:
To send the new file, its file path and name needs to be identified first from a text file deposited by the file and folder wather DiskPulse (C:\diskpulse.txt). I only know the file extension (*.png) and the beginning of the file path (C:\*) of the new image file beforehand. Also, I am not sure if I should use -SimpleMatch or -Pattern for the search. The content of diskpulse.txt looks like this:

"03-Oct-2020 11:38:04 Modified    29.54 KB    administrator C:\local\files\snapshots\nameofimagefile.png"

Problem 2:
The identified file path needs to be handed over to poshgram (the $photo variable specifies the file path for poshgram).
This is the code for the ps-file I came up with so far:
Select-String -Path C:\diskpulse.txt -SimpleMatch "*.png"|select FileName

$token =
$chat_id =
$photo = here, the file path from the search should be inserted
Send-TelegramLocalPhoto -BotToken $token -ChatID $chat_id -PhotoPath $photo

Any pointers are highly appreciated, I am on a steep learning path here.

The solution Doug has posted works well. In addition, this is the complete solution I found myself after the comments put me on the right path (the substring after the text "administrator " is selected from the text file):
$token = " "
$chat_id = " "

$photo = (Select-String -Path C:\diskpulse.txt -Pattern "administrator (.*)").Matches.Groups[1].Value

#in case a substring should be extracted according to the character position ("61" in this particular case), use this instead:
#$photo = (Get-content -Path C:\diskpulse.txt).Substring(61)

Send-TelegramLocalPhoto -BotToken $token -ChatID $chat_id -PhotoPath $photo

A: You can use select string with an appropriate regex pattern to extract the file names.
$photo = (Select-String -path 'c:\diskpulse.txt' -Pattern 'c:.+\.png' -AllMatches).matches.value

Since you know it will always be C:\ we can match the start with c: and the end of course with .png. . in regex will match any character so we have to escape it with \ to say "literally a period"


text:
Q: access denied for HtmlElement inside class function I have a function that loops through a group of links in vb.net:
For Each category As HtmlElement In fs.cats
   fs.run_fetch(category)
   outToCSV(fs.results, "C:\Data\test.csv")
   outToCSV(fs.errors, "C:\Data\errors.csv")
Next

It works fine for the first loop but once it enters the second loop fs.run_fetch(category) gives me *Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))* when trying to run the following
Public Sub run_fetch(ByVal category As HtmlElement)
        Dim itemsonpage As HtmlElementCollection
        Dim title, id, salePrice, regPrice As String
        Dim numberOnSale, currentPage As Integer
        'navigate to category page
        loadPage(category.GetAttribute("href")) **<- error here**

A: Perhaps this may be obvious to some however, a variable defined as a HTMLElement or HTMLElementCollection in vb.net is always a reference.
As a result, when you navigate to a different page the reference to the variables is lost (ie the webpage your variables were referencing no longer exists "in memory" and the references become obsolete)
My solution was to save the links (urls that I pulled off the webpage) into a list(of strings) and as such they no longer reference the page and are in memory until you clear it.


text:
Q: Infinity error - Project Euler # 26 - Reciprocal Cycles I'm receiving an error in Eclipse when attempting to solve Problem # 26 from Project Euler.
I DO NOT WANT THE SOLUTION! Please.
If you can give me a suggestion only as to why I receive "infinity" as an output please fill me in. I've tried Googling this but it's difficult not to accidentally see the solution and I'd rather do this with as little help as possible.
The infinity error is after p=309. This may not be an 'error' at all, perhaps it's simply truncating something. I have tried long and BigInteger, but it did not seem to help.
Here is the problem posed in PE # 26:
Here's my code:
public class Reciprocal_Cycles {

    public static void main(String[] args) {
        double b = 10;
        double p;
        for (p = 1; p < 1000; p++) {
            if (p % b != 0)

            System.out.println(((Math.pow(b, p - 1) - 1)) / p + "       " + p);
        }
    }
}

A:
The infinity error is after p=309.

The largest number that a double can represent is about 1.8e+308, and Math.pow(10, 309) is larger than this. When a floating-point computation overflows like this, you get +inf.
Also, I'd be careful when using p % b != 0 with floating-point variables.


text:
Q: Mac Catalyst window position It is possible to set the size of UIWindow with windowScene.sizeRestrictions. Is it also possible to set the position on the screen of a UIWindowScene?

A: There is no public API to change the position of UIWindowScene.
If you don't mind using a private/hidden API though, you can change the position of the window by calling NSWindow.setFrameOrigin(). You can use a library like Dynamic to do the following:
let nsWindow = Dynamic.NSApplication.sharedApplication.delegate.hostWindowForUIWindow(view.window)
nsWindow.setFrameOrigin(NSMakePoint(50, 100))

Or, if you just want to center the window, you can try:
nsWindow.center()


text:
Q: How to Tie OpenEvent/ClickEvent to a particular email a subscriber actioned? I'm looking for some assistance on how to tie an OpenEvent or ClickEvent in Fuel SDK to the actual email that they took that action on.
I can pull back OpenEvent's and ClickEvent's just fine, but all it shows is when the subscriber opened something, but doesn't say what email they opened or what email they clicked a link on.
Does anyone have any assistance on correlating an open or click event to the actual email that was opened or clicked?
Thanks!
Adam

A: The Send object would be the one that ties all of that together.  In the FuelSDK for C#, this would be ET_Send.  An example has been added to the repo at:
https://github.com/ExactTarget/FuelSDK-CSharp/blob/Dot9/objsamples/Sample_Send.cs
When retrieving this object, it has a property for ID which is the same as the JobID you would see in tracking if using the ExactTarget UI.  The value of this property also corresponds to the SendID property that is available on tracking events.  In order to get to the actual Email that was sent, the Send object has a property for Email.ID.


text:
Q: Question on tower property in a book of mine it says that for sub $\sigma$-algebras $\mathbb D \subset \mathbb E$
$$
\mathrm E [X \mid \mathbb D]
=
\mathrm E [
\mathrm E [ X \mid \mathbb E ]
\mid \mathbb D ]
=
\mathrm E [
\mathrm E [ X \mid \mathbb D]
\mid \mathbb E ]
$$
The first equality I recognize as the tower property, but the later I cannot make sense of.
If $\mathbb E \not = \mathbb D$, then I can find $E \in \mathbb E$ subject to $E \not \in \mathbb D$ where it should hold that
$$
\int_E
\mathrm E [
\mathrm E [ X \mid \mathbb D]
\mid \mathbb E ]
dP
=
\int_E
E[X \mid \mathbb D] dP
$$
but $E[X \mid \mathbb D]$ is only $\mathbb D$-measurable. Can anyone help me out?

A: Recall that if $X$ is $\mathbb F-$measurable, then $$\mathbb E[X\mid\mathbb F]=X.$$
Since $\mathbb E[X\mid \mathbb D]$ is $\mathbb E-$measurable,
$$\mathbb E[\mathbb E[X\mid \mathbb D]\mid \mathbb E]=\mathbb E[X\mid \mathbb D].$$


text:
Q: Using a custom distribution to assign states for agents when create it in Anylogic I am developing a model to evaluate different interventions of population control in animals. I am trying to use a custom distribution to assign the state in which  agents should be when they are created or added later to the population.
I have done the following

*

*I have created an option list, listing all the states in my model

*I have created a custom distribution for the initial population, using the option list to assign the initial population distribution of agents per state
3 I have created a second custom distribution for immigration (since agents will be continued to be added to the population in regular intervals throughout the simulation), using the same option list but with different distribution values.

For the first 3 states which all have timeout transitions, I use the following code:
For the first timeout transition:
stateChart== state1 ? parameter1  : 0
Where StateChart is the name of the state chart in agent
State1 is the name assigned in the option list to the fist state
Parameter1 is the parameter name, that has the value use for the transtion (for example weaning duration = 2 months)
For my second timeout transition:
stateChart == state1 || stateChart == state2 ? parameter2  : 0
And so on.
However my fourth and fifth states (stete4 and state5) have rate and message transition and this codes does not work for such transitions.
As a results my agents do not appear in the fourth and fifth states at the initial population in time zero or during the immigration events.
Is there a different code I can you for the last 2 transition of my model to  make my agents appear in all the different states of my model?
Thank you

A: I have to set a State on initialisation of a population of Customers in the Market Dynamics Model for which I'm responsible, and the state is normally changed by a message. To achieve this, I use the following code for each selected Customer:
oCustomer.sc_switchingBehaviour.receiveMessage("moveOn");
oCustomer.onChange();

where the State Chart is sc_switchingBehaviour and the message that would normally cause them to change State is "moveOn".
I don't have a rate transition for which I need to do this, so can't directly answer that query however, for the purposes of State initialisation, could you not (conceptually) transform the rate to a probability and then use that?


text:
Q: Fetch value from mysql table and display value as selected in drop down menu I am developing a very simple course catalog. I am using dynamic select drop down menus to display courses being offered by an specific academy. Initially, I am displaying the full list of courses available in theses select menus with values from mysql database table named courses_selection_list.   Then I am selecting courses being offered by academy_id=15 by marking the values  selected=selected. In the Jquery/JS you will see that I am making a one time ajax call to file getCourses.php where it then displays the select menus when the page loads.
My problem is the following: I am only able to display one value of the course being offered by academy_id=15. How can I display them all? Or is there a better approach to this? DEMO
courses_offering.php

<select name="courses_offered" id="courses_offered" disabled>
    <?php
    $db_select2  = $db_con->prepare("
        SELECT      academy_id
        FROM        courses_by_academy
        WHERE academy_id = :id
        ");
    if (!$db_select2) return false;
    if (!$db_select2->execute(array(':id' => $id))) return false;
    $courses_count = $db_select2->rowCount();
    echo "<option>----Select----</option>";
    echo "<option value=\"1\"". (($courses_count=="1")?"selected=\"selected\"":"") .">1</option>";
    echo "<option value=\"2\"". (($courses_count=="2")?"selected=\"selected\"":"") .">2</option>";
    echo "<option value=\"3\"". (($courses_count=="3")?"selected=\"selected\"":"") .">3</option>";
    echo "<option value=\"4\"". (($courses_count=="4")?"selected=\"selected\"":"") .">4</option>";
    echo "<option value=\"5\"". (($courses_count=="5")?"selected=\"selected\"":"") .">5</option>";
    ?>
</select>

getCourses.php - courses values
$id = 15;
//get the course list
$course_query = $db_con->prepare("SELECT course_id, course_name FROM courses_selection_list;");
$course_query->execute();

$data = $course_query->fetchAll();
foreach ($data as $row){
    //select the courses being offered by academy_id=15
    $option = "<option value='".$row["course_id"].":".$row["course_name"]."'";
    $db_select  = $db_con->prepare("
        SELECT academy_id, course_name, course_id,
               course_start_date, course_end_date
        FROM courses_by_academy
        WHERE academy_id = :id
    ");
    if (!$db_select) return false;
    if (!$db_select->execute(array(':id' => $id))) return false;
    $results = $db_select->fetchAll(\PDO::FETCH_ASSOC);
    if (empty($results)) return false;
    foreach ($results as $value) {
        $result= $value['course_id'];
        if ($result == $row['course_id']) {
            $option .= "selected='selected'";
        }
    }
    $option .= ">". $row['course_name'] ."</option>";
    //show result
    echo $option;
}

Mysql Tables Example:
courses_selection_list
+-----------+-------------------------+
| course_id |       course_name       |
+-----------+-------------------------+
|         1 | Math                    |
|         2 | English                 |
|         3 | Science                 |
|         4 | Other- Not Listed       |
|         5 | Social Studies          |
|         6 | Home Mac                |
|         7 | Business Management     |
|         8 | Psychology              |
|         9 | Accounting              |
|        10 | Advanced Networks       |
|        11 | Information Techonology |
+-----------+-------------------------+

courses_by_academy
+----+------------+--------------------------+-----------+------------+----------+
| id | academy_id |  course_name             | course_id | start_date |end_date  |
+----+------------+--------------------------+-----------+------------+----------+
|  1 |         15 | Science                  |         3 |2013-12-04  |2013-12-25|
|  2 |         15 | Business Management      |         7 |2013-12-04  |2013-12-25|
|  3 |         15 | Information Technology   |        11 |2013-12-04  |2013-12-25|
+----+------------+--------------------------+-----------+------------+----------+

Desired Result:

A: Javascript insert into document.ready event
var option = 3,
    $course_catalog = $('#course_catalog');
showFields(option);

function showFields(option){
    $course_catalog.html('');
    // request only once
    $.ajax({
        type: "POST",
        url: "getCourses.php",
        async : false,
        data: {
            value : option
        },
        dataType : 'json',
        contentType : 'application/json',
        success: function (data) {
            for (var i = 1; i <= option; i++){
               // prepare select
                $course_catalog.append('
Course # '+i+'
'
                        +'Course Name:'
                        +'<select id="coursename_'+i+'" name="coursename_'+i+'" class="course_list">'
                        +'<option value="" >--- Select ---</option>"'
                        +'</select>

');

                var $el = $course_catalog.find('#coursename_' + i),
                    val = 0,
                    index = 1;
                for(var n in data) {
                    var o = data[n];
                    if (o.academy_id > 0) {
                        if (index == i) {
                            val = o.id + ':' + o.name;
                            $course_catalog.find('#date_'+i).html('Start at: ' + o.start_date + ' until '+o.end_date);
                        }
                        index ++;
                    }
                    $el.append('<option value="' + o.id + ':' + o.name + '">'+o.name+'</option>');
                }
                $el.val(val);
            }
        }
    });
}

PHP code:
header("Content-type: application/json");
$id = 15;
//get the course list
$course_query = $db_con->prepare("
    SELECT
        t.course_id, t.course_name, IFNULL(lj.academy_id, 0) as academy_id, lj.course_start_date, lj.course_end_date
    FROM courses_selection_list as t
    LEFT JOIN courses_by_academy as lj
        ON (lj.course_id = t.course_id AND lj.academy_id = :id)
    ORDER BY t.course_id
");
$course_query->execute(array(':id' => $id));
$data = $course_query->fetchAll();

$course_data = array();
foreach ($data as $row) {
    $course_data[] = array(
       "id" => $row["course_id"],
       "name" => $row["course_name"],
       "academy_id" => $row["academy_id"],
       "start_date" => $row["course_start_date"],
       "end_date" => $row["course_end_date"],
    );
}  // foreach ($data as $row) {
echo json_encode($course_data);

A: The reason why this doesn't work is that your SQL queries are in the wrong order. You first want to get the courses_by_academy and then get the respective course from the courses_selection_list.
Also your approach to using Javascript in this context is a bit unreasonable, so I have removed it for displaying the dropdowns.
<?php
$id = 15;

//get the course list
$db_select  = $db_con->prepare("
    SELECT academy_id, course_name, course_id,
           course_start_date, course_end_date
    FROM courses_by_academy
    WHERE academy_id = :id
");
if (!$db_select) return false;
if (!$db_select->execute(array(':id' => $id))) return false;
$results = $db_select->fetchAll(\PDO::FETCH_ASSOC);

if (empty($results)) return false;
foreach ($results as $value) {

$course_query = $db_con->prepare("SELECT course_id, course_name FROM courses_selection_list;");
$course_query->execute();

$data = $course_query->fetchAll();
$i = 0;
foreach ($data as $row){
    $i += 1;

    echo '
';
    echo 'Course # ', $i, '
';
    echo 'Course Name:';
    echo '<select name="coursename[]" class="course_list">';
    echo '<option>--- Select ---</option>"';

    echo "<option value='".$row["course_id"].":".$row["course_name"]."'";
    if ($value['course_id'] == $row['course_id']) {
        echo " selected='selected'";
    }
    echo ">". $row['course_name'] ."</option>";
}
echo '</select>

';

Note how I used coursename[] as the name for the SELECT: using this the PHP will receive this as an array in the POST request, as $_POST["coursename"], so that you can use foreach to go through them.
I assume the Javascript is meant to be able to change the number of courses? I would take a different approach here:
$("#courses_offered").on("change", function() {
    var number_of_courses_offered = $('#courses_offered').val();
    var course_divs = $("div.courses");

    if (number_of_courses_offered < 1) {
        course_divs.hide();
        return;
    }

    course_divs.show();

    // to few courses displayed: add another one until the number fits
    while (course_divs.length < number_of_courses_offered) {

        // create an empty course div by using the first one and removing the
        // selected attribute so that the first item "--- Select" is displayed
        var single_course_div = course_divs.first().clone(true);
        single_course_div.find("option:selected").removeAttr("selected");
        // fix the course number
        single_course_div.find("span").text(course_divs.length + 1);

        // insert it after the last of the divs
        course_divs.last().after(single_course_div);

        course_divs = $("div.courses"); // update for the next while loop
    }

    // too many courses displayed: remove the last ones
    while (course_divs.length > number_of_courses_offered) {
        // remove the last div
        course_divs.last().remove();

        course_divs = $("div.courses"); // update for the next while loop
    }

});

A: Assume that you have a select box that lists all the academies available:
<select name="academy" id="acadaemy">
  <option value="1">Academy1</option>
    .............................
    .............................
  <option value="15">Academy15</option>
</select>

Then you can bind an onchange event for this select to display the desired courses.
 $('#acadaemy').on('change', function() {
           var option = this.value;
                   $.ajax({
                    type: "POST",
                    url: "getCourses.php",
                    data: {
                            'ac_id': option
                    },
                    success: function (data) {
                                  $('#course_catalog').html(data);
                        }
                    });
});

And in ur getCourses.php
Step 1:  fetch the POST value (here $_POST['ac_id']) and validate it
Step 2:  Get all courses.
Step 3:  Get all courses with specified academy id
Step 4:  Iterate result from step 3 and create each select tag.
Step 5:  Iterate result from Step 2 and create option tags and set selected.
Step 6:  Echo back the result.

<?php
     $id = $_POST['ac_id'];
     //Do something here to validate the post data

    $course_query = $db_con->prepare("SELECT course_id, course_name FROM courses_selection_list;");
    $course_query->execute();

$data = $course_query->fetchAll();//All courses here
    $db_select  = $db_con->prepare("
        SELECT academy_id, course_name, course_id,
               course_start_date, course_end_date
        FROM courses_by_academy
        WHERE academy_id = :id
    ");
$resultStr = '';

if (!$db_select) return false;
    if (!$db_select->execute(array(':id' => $id))) return false;
    $results = $db_select->fetchAll(\PDO::FETCH_ASSOC); // academy specific courses here
    if (empty($results)) return false;
    foreach ($results as $value) { // iterate academy courses
    $resultStr .= '
';
    $resultStr .= '<select name="coursename[]" class="course_list">';
          foreach ($data as $row){ // iterate all courses
                        $result .= "<option value='".$row["course_id"].":".$row["course_name"]."'";
            if ($result['course_id'] == $row['course_id']) {
                $resultStr .= " selected='selected'";
            }
                        $resultStr .= ">". $row['course_name'] ."</option>";
                  }
    $resultStr .= '</select>';
    $resultStr .= '
';
    }
echo $resultStr;
exit();
?>


text:
Q: Inlining an external assembly function in C++ I have an assembly function that is contained in a .asm file. I am trying to call it as an inline function, but when I disassemble it, every occurrence of it is a function call. I have done some research, and I read that for a function to be inline, it has to exist in every translation unit that uses it, but I don't know how to make the compiler/linker do that, or if it is even possible. If there is a way, how can it be done? I am uses some features that inline assembly does not provide, so that is not an option. I am using Visual Studio 2017.
As requested by Jesper Juhl, here is a short section of the file "Random.asm" that I am working with.
.code
_Random proc
rdseed eax
jnc PseudoRandom        ;In case of failure, go to a pseudorandom number generator
ret
_Random endp


text:
Q: FutureWarning: The behavior of `series[i:j]` with an integer-dtype index is deprecated for df.min() I am simply trying to grab the earlier date in a pandas column by
df.date.min()
However I get the following warning:
FutureWarning: The behavior of `series[i:j]` with an integer-dtype index is deprecated. In a future version, this will be treated as *label-based* indexing, consistent with e.g. `series[i]` lookups. To retain the old behavior, use `series.iloc[i:j]`. To get the future behavior, use `series.loc[i:j]`.
 s = s[:max_items]

This seems like an overly complex solution for a simple problem. What should I change here?
Thanks


text:
Q: Magento Payment not working I have some problem in payment option.
Whenever I click on continue after shipping the page stays.
I think there are some JS Console errors are there.
Please can someone help me solving this.

A: One-page checkout not working after upgrading to 1.9
If you're using the one-page checkout, make sure you have the following javascript in /app/design/frontend/package/theme/template/checkout/onepage/review/info.phtml
<script type="text/javascript">
    //<![CDATA[
        review = new Review('<?php echo $this->getUrl('checkout/onepage/saveOrder', array('form_key' => Mage::getSingleton('core/session')->getFormKey())) ?>', '<?php echo $this->getUrl('checkout/onepage/success') ?>', $('checkout-agreements'));
    //]]>
</script>


text:
Q: About Grails render's doubts I wrote a simple example of filter render, the results are very disappointing, not to understand why there is this situation
who can answer for me .
1.The environment:
Grails Version:2.3.7 , JDK:1.8
2.program file:
My Fiflter:
class MyFilterFilters {

def filters = {

    all(controller:'*', action:'*') {

        before = {

            if (!controllerName) return true

            if(!session.user && controllerName !='myRender')

            {

                println "------------------------"

                render view:"/login"

                return false

            }

        }
        after = { Map model ->
        }

        afterView = { Exception e ->
        }
    }
}

}
My Controller:
class MyRenderController {
def index() {
    render text:"any message!!!"
    return
}

}
my login page(login.gsp):
This is login page

*test result:
url:http://localhost:8080/renderTest/
why???

A: With your code your login page will also get filtered so it will go in infinite loop.
def filters = {
    allExceptIndex(controller:"site",action:"index",invert:true) { // make proper change for controller and index
        before = {
        }
        after = { Map model ->
        }
        afterView = { Exception e ->
        }
    }
}