Show error bars in ColumnSeries of LiveCharts (LvCharts) in VB.NET

Question: I am using LiveCharts (LvCharts) for VB.NET (WPF) and I am showing values as bar series in different charts in my GUI (series type = LiveCharts.Geared.GColumnSeries).
Currently I am searching for a way to show error bars in my series (show standard deviation or min/max values) like this example:

Unfortunately I didn't found any example for that. I already checked:

https://github.com/Live-Charts/Live-Charts/tree/master/Examples/Wpf
https://v0.lvcharts.com/App/examples/Wpf/start

How could I realize that with LvCharts?
Answer: This is already supported in the latest version:
https://livecharts.dev/docs/WPF/2.0.0-rc2/samples.error.basic
Comment: @krambambuli there is no direct migration from v0 to v2, but the API is similar, v2 will also have a high-performance package, it is extremely fast, you can find some tests here: https://github.com/beto-rodriguez/LiveCharts2/releases/tag/v2.0.0-rc2
Comment: Thank's for the information! We are using LiveCharts Geared commercial version and it is already implemented in several projects. How complex is the migration from v1 to v2? And can I use geared values in v2?
Comment: It seemed to be difficult to change from v0 to v2 in a running project. I have to change a lot of functions, also in the xaml code. Especially because I was using geared values. Or am I wrong @bto.rdz?


Asymptotics to $f(2n) = f(2n-1) + \frac{f(2n-2)}{f(n)}$ or $ \ln(f(x)) = \int \frac{1}{f(x/2)} + C $?

Question: Consider the sequence $f(i)$ for integer $i>0$ :
$f(1) = f(2) = 1 $
$f(3) = 2$
define the remaining by
$f(2n) = f(2n-1) + \frac{f(2n-2)}{f(n)}$
$f(2n+1) = f(2n) + \frac{2n-1}{f(n)}$
How fast does this function grow ?
What are the best asymptotics ?
How to answer such similar questions in general ?
The sequence reminds me of the similar equation
$$ f'(x) = \frac{f(x)}{f(x/2)} $$
Or equivalently :
$$ \ln(f(x)) = \int \frac{1}{f(x/2)} + C $$
And those look familiar but I could be wrong.
Also I know the solution to the equation $g'(x) = g(x/2)$ maybe that could help ?
Does this equation or very similar occur in the literature , for instance difference-differential equations or delay-differential equations ?
Answer: I don't know anything about how one should treat the problem in general, but here's some rather rough answer for someone who doesn't care much about proofs.
The following code in Mathematica allows one to experiment with this recurrence relation:
<code>f[1] = 1;
f[2] = 1;
f[3] = 2;
f[n_Integer?EvenQ] := f[n] = f[n - 1] + N[f[n - 2]/f[n/2]];
f[n_Integer?OddQ] := f[n] = f[n - 1] + N[f[n - 2]/f[(n - 1)/2]];
</code>
Let's look at how the sequence grows:

Looks like it simply doubles, and indeed, it turns out to be a valid hypothesis:

Now that we know the answer, let's try to understand it. First af all, it's worth noticing that $\frac{f(2n-2)}{f(n)} \ll f(2n-1)$. Therefore, it certainely doesn't grow exponentially and our first estimate is that $f(n+1) \sim f(n) + \lambda (n)$, where $\lambda$ is something constant. But then $f(2n) \sim 2 f(n)$ and $\lambda \sim 2$


What kind of wall material should be used in wet areas in a bathroom?

Question: I'm replacing a one piece fiberglass tub with a two piece (tub + surround) unit.  In the bathroom right now, there's just drywall, no special material.  Should I replace the drywall with greenboard, or with a cement board material (i.e. Durock)?  How many feet adjacent to the but should be replaced with one of those two materials?  Should I also replace the material behind the vanity with one of those two?
Comment: Also see : http://diy.stackexchange.com/questions/521/what-is-the-practical-difference-between-cement-board-and-greenboard
Answer: Greenboard (or any paper faced drywall) is an unacceptable substrate for any wet application (shower or tub stalls).  Regardless of tub stall surface (tile, fiberglass, etc) you will get some moisture penetration through the shower liner and this will eventually create bigger problems.
You need to install Hardibacker or Durock (or any cementitious board) as the substrate for your tub/shower stall.  Matter of fact, in many municipalities it is required by building code.  It only needs to be installed in the area of the tub/shower, though no need to extend further out.
The rest of the bathroom can be done in greenboard though (and that isn't a bad idea).
Answer: As long as you can ensure that the surface is sealed with a waterproof layer then you don't really need to make any special modifications. The main thing you need to ensure is that there's no way water can get onto unprotected wall or floor surfaces.
In the UK baths are fitted into rooms that have normal plaster and the walls tiled to provide the water proofing.
If you have to replace any of the existing drywall then it might be worth going for a special water resistant panel (e.g. Aquapanel), but they are more expensive.
Answer: For right around the shower/tub I would use cement board since mold will not grow on that.  If you are worried about the other areas of the bathroom you could use the "green" board stuff, though if it cost a little more than regular drywall.


How do I use the JQuery Datepicker with a textbox input onclick

Question: How do I use the JQuery Datepicker with a textbox input onclick i do not want on focus and calender images
  $("#my_txtbox").datepicker({
 // options
 });

Comment: There's a check mark next to the answers to your questions that you can click when you deem an answer appropriately answered. Click it to accept an answer.
Comment: yes i want that but not showing me any option of that.
Answer: You need to download 2 JS files for that.

http://www.kelvinluck.com/assets/jquery/datePicker/v2/demo/scripts/date.js
http://www.kelvinluck.com/assets/jquery/datePicker/v2/demo/scripts/jquery.datePicker.js
Add these 2 files in page and Keep that text box in one class and using that class , u can do what u want.
Like this:
$(function()
{
     $('.date-pick').datePicker({clickInput:true})
}
);

<input id="datepicker" class="date-pick"/>
keep the classname as "date-pick".


How do you position a MudBlazor Dialog using a custom DialogPosition?

Question: Given a MudBlazor MudDialog component with a Position set to DialogPosition.Custom, the dialog will appear absolutely positioned to the top left hand corner of the viewport.
@{
   var dialogOptions = new DialogOptions
   {
     Position = DialogPosition.Custom,
   };
}
<MudDialog Options="@dialogOptions" Class="custom-dialog">
  <DialogContent>
    Hello World.
  </DialogContent>
</MudDialog>

There isn't a position property in the options. The documentation doesn't reference custom positioning at all.
Once the component has rendered, the CSS class .custom-dialog isn't applied to the dialog parent, but a static div a few levels down the tree, so positional styles cannot be applied to it.
Is there a way to set the custom position?
Answer: When you set it as DialogPostion.Custom it applies the .mud-dialog-custom class to the dialog parent.
It's an undefined class so I believe it was designed to be overridden. So you simply use that class to apply your custom position.
e.g.

<MudDialog>
  <DialogContent>
    Hello World.
  </DialogContent>
</MudDialog>

TryMudBlazor Snippet
Comment: I haven't had a chance to test this yet but just wanted to say thanks. My only query is what to do if there are multiple custom dialogs on the page, but I'll do some testing.
Comment: @NandoLorris have a look at the snippet, each overridden `.mud-dialog-custom` is in it's own dialog component. So you can have multiple different styled custom dialogs in a single page and their custom styles will be in their own component.


How to add an external library via Webpack Encore in a Symfony-Application?

Question: In a Symfony Application, we use Webpack & Encore for management of our custom javascript libraries.
However, we also want to add some external libraries like web3.js.
How to do that?
Our webpack.config.js looks like this:
Encore
  .setOutputPath('public/build/')
  .addEntry('apiPlatform', './assets/apiPlatformCustomize.js')
  .addEntry('shop-entry', './assets/shop/entry.js')
  .disableSingleRuntimeChunk()
  .cleanupOutputBeforeBuild()
  .enableSourceMaps(!Encore.isProduction())
  .enableVersioning(Encore.isProduction())
  .enableSassLoader()
  .autoProvidejQuery()
;

For injecting jQuery it is quiet easy thanks to a convinient method. But how to do other external libraries that one would install with npm install web3?
I have seen something like addExternals but could not find anything about it how to use it properly.
Any help much appreciated!
Comment: You do not add external vendor libs directly in the webpack.config.js file. Rather you add import them into the main app.js or secondary page entry files and then use them in those scripts. I recommend you watch https://symfonycasts.com/screencast/webpack-encore for a better explanation.
Answer: I would say :
Do not import it inside webpack config.
Add entry is your "js" entry file for your application.
It mean if you install external libraries you want to access using
npm install alibrary

You will import it inside you "main.js" file.
Here is a example :
Inside webpack.config.js
.addEntry('website', './assets/website.js')
.splitEntryChunks() // this line is important to avoid multiple entry for css and js but require a website.css to work properly

Then inside you main twig file :
{{ encore_entry_link_tags('website') }} // inside  tag for css

{% block javascripts %} // at the bottom of your
    {{ encore_entry_script_tags('website') }} for.js
{% endblock %}

Now your website.js is correctly imported inside your app.
Now, if you want jquery install it :
npm i jquery

Then inside your website.js
import 'jquery-form/dist/jquery.form.min'
import $ from "jquery";

Now jquery is available inside website.js and your app.
Depending on which library you want sometimes only a basic import is required.
import $ from "jquery";

Is specific to jquery in order to make it work


How do people with vision impairment access buildings requiring a swipe card?

Question: With many of the commercial and corporate buildings now having more strict control around entries and exits, I was wondering in terms of accessibility how people with vision impairment are provided ease-of-access when they need to swipe a pass or card to enter or exit.
This is because I haven't seen a standard convention when it comes to where the swipe card contact point is located (or perhaps I am not aware of it). Considering that there might be multiple points where this needs to be done, such as at the building entry and also the elevators/lifts, I am wondering if anyone is aware of what the general convention or standard is.
Comment: I would consider rephrasing your title and question. It appears you are asking "What are the general conventions or standards for access cards, particularly having to do with accessibility for the blind."  The beginning of your question wanders with a bunch of assumptions that I think are clouding your thinking.  For instance, if they have an access card, they likely have been to the building, know where they are going, and have been made aware of where the access points are and can use touch if necessary to pinpoint. If a guest, someone would have to come down and swipe them in anyway. etc.
Comment: I have always seen those at the right of the doors and more or less at the same height, so it seems that there is a convention. I have also seen one that caught my attention because it was located otherwise, but it had blinking lights and a very subtle "ding ding ding" sound. But I only saw that once, almost always saw the swipe slot in the same place to be honest
Comment: It is just like using the drive-up ATM with the Braille on it.
Comment: @nocomprende, Drive up ATMs have braille because they mass produce the same ATM for walk up and drive through.  It would be cost prohibitive to make it different only for the reason of removing braille so drivers weren't confused why you need braille on a drive up ATM.
Answer: There are keychains that you wave in front of the scanner to open the door :) No card necessary, just a key fob (or whatever it's called).
(Also, there's audio feedback when the door opens. You hear the door opening, but you also get a 'beep' from the scanner'.)
One design flaw I've seen, though, is that you can't pull an automatically opening door shut. So if you want to close the door from an attacker outside your building, good luck. It's just going to slow you down. So if you want to improve automatic doors, that's an actual need based on my experience (twice).
Edit: As per Jon W's complaint, I have a design solution. There's typically two doors and the scanner is on the OUTSIDE door. What if they put the scanner in between the two doors? Why? Because as soon as you open the first door, the scanner could start making noise for a few seconds, making it easier for the blind person to locate.
Comment: @JonW: Both a) and b) happen to me all the time even without a vision impairment.
Comment: How can you wave a keychain in-front of a scanner if a) you don't even know that there is a scanner there, and b) your vision isn't good enough to locate the scanner?
Comment: a) you probably can't if you don't know a scanner is there, but then again you have a key fob, soo....
Comment: We should just give swipe cards to the crooks, then NOT have scanners, and they would never get in!


Protocols and standards that take advantage of the huge IPv6 address space

Question: Unsure if this is the correct place for this kind of question (Server Fault is for administrators) but I'm looking for examples of (networking) protocols and standards that leverage the huge IPv6 address space towards some specific benefits.
Reason is I'm writing a paper about something that does this and I'm searching for stuff to compare it to, but I'm coming up empty even though I'm sure some have to do so.
Comment: PS: your name looks Dutch ;)  Feel free to contact me directly if you need help with your paper.
Comment: Thanks, appreciated. For context, the paper describes a way to derive multicast addresses in a pub/sub system given an IPv6 publisher address and the component one is interested in. This is only realistic for a 128-bit address since IPv4 would quickly inhibit the available options. I've even got 4 bytes left in my derived addresses without trying, which allow other information to be transmitted! The idea is not really new, but I had a hard time coming up with examples, so thanks.
Comment: I assume you know about https://tools.ietf.org/html/rfc3956
Comment: Instead of component, I meant "type of event", apologies.

I didn't actually, thanks, I'll be sure to read through it.
Answer: Probably not completely on topic here, but I'm going to answer it anyway because it might help software developers to learn what possibilities there are when developing for IPv6.

Because most protocols and applications still want to be compatible with IPv4 there aren't that many protocols that use this wonderful feature of IPv6. Most of the ones that do are IPv6-only by nature.
The first one is of course IPv6 Stateless Address Autoconfiguration often abbreviated to SLAAC. Having so many addresses available makes self-assignment of addresses so much easier.
Building on that is SEcure Neighbor Discovery (SEND) with Cryptographically Generated Addresses (CGA) which uses public key cryptography and derives the last 64 bits of the IPv6 address from the fingerprint of that public key. Because the node can create a signature with the private key that matches the public key it can prove that it is the legitimate holder of that IPv6 address. Unfortunately there are no implementations for the most common operating systems so this feature is largely unused.
And another one is the IPv6 Battleships game. It uses IPv6 addresses to encode the coordinates in the game and by sending a ping the opponent can determine of there is a ship at a certain location (address) or not. The game was written in a competition on World IPv6 Day at the IPv6 event in The Netherlands.
Answer: It has significant advantages for large Cloud deployments. For instance, Faceebook has reported 90% of its internal traffic is IPv6 (https://t.co/PPHBkUPTdt) because this way is similar to private IPv4 but serves better to v6 native customers (in the same report they claim v6 mobiles surf 30%-40% quicker than v4 ones).  Also Openstack has finally added almost-full v6 support for Juno version.
Additionally, the IoT field (when it is really IoT, I mean IP devices) is an excellent field of application. Normally, devices will use either IPv6 (when powerful enough) or 6LowPAN (an reduced IPv6 for sensor networks and supported well in OS like TinyOS, ContikiOS, mbedOS, etc).
It might be also useful for WebRTC-like applications as long as IPv6 peers would normally connect better (firewalls vs NATs seem to behave or be more easily configured).
However, with the massive deployment that has started in 2015 (in USA 17% of all traffic to Google is v6, Germany traffic to Google is 14%, all Internet traffic to Google is 7% IPv6 today) any Internet product of service has to migrate or will lose competitiveness soon.


Trying to create a custom Panel with ExtJS

Question: Can't find out why its isn't working..
 I'm trying create a custom panel for multiple uses.
Is it the way? Or am i totally wrong.
I'm a beginner in ExtJS, so i'll be happy to a little explain..
thanks
(i'm trying to run this code on the fiddle to see the immediate result - )
<code>Ext.application({

    name: 'Fiddle',

    launch: function () {
        var custom = Ext.define('Ext.BET', {
            renderTo: Ext.getBody()
        });

    }
});

Ext.define('Ext.BET', {
    extend: 'Ext.panel.Panel',
    alias: 'widget.bet',
    constructor: function (cnfg) {
        this.callParent(arguments);
        this.initConfig(cnfg);
    },
    config: {
        collapsible: true,
        frame: true,
        bodyStyle: 'background-color: #FFFFFF',
        layout: {
            type: 'hbox'
        },
        items: [{
            xtype: 'textfield',
            textarea: focus,
            id: 'tbx'
        }, {
            xtype: 'button',
            id: 'btn'
        }, {
            xtype: 'button',
            id: 'search'
        }]

    },
    afterRender: function () {
        var btn = Ext.getCmp('btn');
        var tbx = Ext.getCmp('tbx');
        var btn2 = Ext.getCmp('search');
        var totalWidth = btn2.getWidth() + btn.getWidth() + tbx.getWidth();
        this.setWidth(totalWidth);
    },
    onRender: function() {
        this.callParent(arguments);
    }
});
</code>
Comment: i cant upvote your answer because i am a new user...
Comment: You want to run this on fiddle ? Means should we correct this code or what you want ?
Comment: i'm running this code  on: https://fiddle.sencha.com/#view/editor
just to see if its work.

but i gonna use it elsewhere

just to explain the :
  "name: 'Fiddle',"
Comment: You should not use ext.define instead use ext.create.But then its breaking in afterrender event ..checking this thing , will update fiddle once it fix it.
Comment: thank you very much! i was stuck on this a lot..
Comment: yes, you should..
Comment: I have updated my answer in fiddle.Its working fully functional as you want.
Comment: Yes I forgot sorry. But did you understood changes made by me
Comment: yes, and now its work perfectly thanks to you..
Answer: You should use Ext.create instead of Ext.define.Refer this fiddle.


How to add a custom field in django model form?

Question: I'm trying to add a readonly field in a form.
The model Folder is registered in admin site. The FolderAdminForm defines the custom field statistics. There isn't statistcs field in the Folder model, I just want to put some readonly data on the form. This data is defined in the template.
But I get a error whenever the user doesn't have edit permission. If the user only have the view permission,this error is raised:
AttributeError: Unable to lookup 'statistics' on Folder or FolderAdmin

Here is my code:
class CustomWidget(forms.Textarea):
    template_name = 'widget.html'

class FolderAdminForm(forms.ModelForm):
    class Meta:
        model = Folder
        fields = ('field1', 'field2', 'field3',)

    statistics = forms.Field(
        widget=CustomWidget,
        label='Estatísticas',
        help_text='Estatísticas da pasta',
    )

Comment: Please post your `FolderAdmin` class.
Answer: According to the last part of this answer, you could try to override the forms __init__() method and assign the fields initial attribute.
This could look like:
def __init__(self, *args, **kwargs):
        # only change attributes if an instance is passed
        instance = kwargs.get('instance')
        if instance:
            self.base_fields['statistics'].initial = 'something'
        super().__init__(*args, **kwargs)

Does this work for you?
Answer: The error only occurred whenever I tried to open a folder instance without edit permission (i.e. with read only permission). Therefore, django consider the statistics field as a read only field and then search for a label for this field. Django look for this label in Model, ModelAdmin. Since none of them has the 'statistics' attribute, the error is raised.
So, this worked for me:
 class FolderAdminForm(forms.ModelForm):
    class Meta:
        model = Folder
        fields = ('field1', 'field2', 'field3',)

        labels = {'statistics': 'Estatísticas'}

    statistics = forms.Field(
        widget=CustomWidget,
        label='Estatísticas',
        help_text='Estatísticas da pasta',
    )

Therefore, whenever django looks for a label for statistics, it finds this label and the error is not raised. I don't know why it doesn't recognize the label passed as a Field parameter.


Postman does not accept `-` as an URI param for mocking server requests

Question: I get the following error response:
{
    "error": {
        "name": "mockRequestNotFoundError",
        "header": "No matching requests",
        "message": "Double check your method and the request path and try again."
    }
}

When I pass - as an URI param for a Postman request created via a mocking server unlike when I pass the same URI param value in a request not created via a mocking server it's working well!
URL: http://{{host}}/order/{{subUserId}}/{{BusinessDate}}/5
host: {mocking-server-url-without-http-keyword}
subUserId: 1
BusinessDate: 2020-01-12-17-07-21
HTTP request header: x-api-key : {{postman_secret_API_key}}
The main request by using the mocking server as a host which returns data correctly:

The mocked request by using the mocking server as a host which returns an error:
Comment: Can you update the question with the full URI, please? Are there any other headers that you're using in the examples or the request?
Answer: The mock example would need to match the path of the main request for it to be returned.
For example:

If it doesn't, it wouldn't be able to find the mock example that you're using:

I'm unsure of your particular context but you could also use different Request Headers on your main request to point to specific mock examples:
x-mock-response-code:200
x-mock-response-name:<name of the mock example>

Comment: I've created a topic on community.getpostman.com https://community.getpostman.com/t/postman-does-not-accept-as-an-uri-param-for-mocking-server-requests/10107
Comment: I am using the same path for the main request and the mocked response while the problem in passing this char `-` in URI because when I replace it with `/` I get the mocking data retuned successfully so it maybe a bug in `Postman`.
Comment: I had no problem using that character in the requests that I was making so their might be also something else that you're doing. Without any more details about the full request, it would be difficult to help. If you want to raise a question on the Postman community forum I would be able to help you more. community.getpostman.com
Comment: Do you send Postman API Key as an HTTP header `X-Api-Key` in your test case? https://learning.getpostman.com/docs/postman/postman-api/intro-api/
Comment: If the mock is private (you would have had to choose that option when you created the server) then you would need to use the `x-api-key` header.
Comment: Yes I've already made the mocking server as a private and by using the generated API Key I get the main requests working well except when I use `-` with the mocked request it is not working but when I use `-` for the main request I get it working. I think this issue maybe occured because the mocking server contains `-` involved.
Comment: What's the value of `{{host}}`? Does that also contain `https`? Not sure why you would need the `http` value that you have.
Comment: `host` contains only url without `http`
Comment: Just try this scenario with yourself by using a private mocking server with `x-api-key` http header key-value because I think it's a bug.
Comment: Can you confirm that you have no _new line_ characters in the Environment file - You wouldn't see this when you hover over the variable name. I've recreated the scenario locally and I can make it do what you're seeing when it has a new line. The variable will look like `2020-01-14-09-00-00...` in the Manage Environment section.
Comment: Environment file has no new line for any key-value param.


System goes slow randomly. Continues to run well when moving with mouse

Question: I have noticed this mainly when playing flash games in my firefox or playing x-com in dosbox.
Game just runs fine, but then suddenly it slows down to crawl. When i touch my touchpad and move the cursor around, it goes good again. But when i let go of the touchpad, it goes to crawl again.
Answer: It could be that you have set up a background process to run when the computer is idle. It could also be that your screensaver is not playing well with your configuration, and it's trying to load and slowing down the computer in the process.


How do I remove this drain pipe from my garbage disposal?

Question: I found a leak in my garbage disposal, and I think I know the source (possibly a crack in the drainpipe).
However, now I'm stuck on how to actually take off the drain pipe.
The disposal pipe (3 in the picture) seems to be getting stuck right after the threading in piece #2.
Is there a correct way to take the pipe off?
Answer: That should be a slip fit and simply pull out.
It's possible that some prior worker glued the joint between 1&2 with 3 inserted, and it got stuck that way. It's also possible that it's merely stuck with years of crud. In either case, it should pull out, twisting it while pulling may help to break whatever is sticking it loose, and if it just won't go you need a whole new set of parts 1, 2, & 3
Comment: Part-1 is **half** of a trap, probably with proprietary union-nut threads. I foresee cutting off and replacing Part-4 (the *other half* of the trap that is glued on the wall pipe).
Comment: I have not found them overly prone to being incompatible, but your mileage may vary.
Comment: So it turns out it was just a matter of pulling it off, however I chickened out and called a plumber because I was afraid of not having complete pieces in the event of needing to match them up again to get the right ones. It was very stuck on there, so I either just need to work out more, or not be afraid of breaking things I guess :)
Answer: Remove pipe #3?
If you take pipe #3 off of the disposal you can take it somewhere with space that you can really work on it.  Maybe clamp the metal piece and then force the PVC.  You suspect the PVC to be the culprit anyway so it you break it removing it no harm done.  You are replacing it anyway.
But dont mess up pipe #3 because you want it back on the disposal!
Comment: Even piece #3 can be replaced for only a few dollars. More difficult to obtain would be the metal retaining ring holding piece #3 on to the disposal, but even _that_ can be found unless the disposal is ancient. It will probably take ordering that piece online, though, instead of going to the local big-box store.
Answer: You're looking at parts that all together cost ten dollars and somewhere among them there's a leak.
Visit your local plumbing source. Obtain replacements for all the drain parts, including the disposal outlet elbow #3. They're fairly standard and it's unlikely that the one you have now needs to be carefully preserved.
The metal clamping ring which holds the outlet elbow to the disposal is the only part that's possibly special. Break or cut the drain pieces apart by any means necessary in order to recover that ring, then re-assemble with all new drain parts.
Answer: So, as several other answers indicate, Part-3 should just pull out unless glued.
Unfortunately for you, if it is glued then you have a bit of a problem because Part-1 is half of a trap and the other half looks like it is glued to the drain line coming out of the wall. Those traps often have a proprietary thread on the union nut so it is often difficult to replace just half of that type of trap. This makes it more complicated than some answers make it seem.
If you take your half of a trap to a plumbing shop and the union nut happens to fit a new trap at the shop, you are lucky and can replace parts-1, 2, and 3. If you can't find a compatible trap then you will need to replace Parts-1, 2, 3, and 4 (4 would be the other half of the trap), which requires cutting off Part- 4 (which leads to the pipe in the wall being too short, which leads to... frustration).
I hope you can get Part-3 to pull out.
Comment: P.S. this is why I always use adjustable P-traps instead of the glue on type that you have.


Probability when playing roulette

Question: A roulette from a casino contain 18 red cases, 18 black cases and 1 green cases. A player shows up with $10$dollars. He decides to bet $1$dollar on red 10 consecutives times. If it's red, he wins a dollar and if not he loses his dollar. Let $S$ be the the amount of money the player has after 10 bets. Find the value $S$ can have, then calculate $P(S<3|S\leq18)$.
So the value S can take is every natural numbers $0\leq S\leq20$
but after that I'm confused on how to proceed. I guess we could do it using a density function but i don't know how.
Any help to point me in the right direction would be greatly appreciated.
Thank you.
Comment: How should we interpretate $P(S < 3|S\leq 18)$ ? Probability that the player has less than 3 Dollars after 10 bets given that he has  less than 19 Dollars after 10 bets ?
Comment: That is what i understand from the question yes
Comment: Let $p$ be the probability of the win in a single bet. Then $S\sim 2Bin(10,p)$ which you can approximate with a normal $N$ of same mean and variance. Then $P(S<3|S\le 18)\approx \frac {P(N\le 2.5)}{P(N\le 18.5)}$.
Answer: The value of $S$ cannot take every natural number in that range; though the range itself is okay.
In ten games the count of wins will be somehow distributed.   $W$ is the count of wins in $10$ games with success probability $p$.   What is $p$, and what is the distribution of $W$.
$$\mathsf P(W=k) = \underline{\qquad}\quad[k\in\{0,1,2,3,4,5,6,7,8,9,10\}]$$
Assume the player started with $\$10$, and in each game bets one dollar and gets back two on a win.   So the amount of money $S$ taken away will be $S= \underline{\quad}$ (somehow related to $W$), and thus have distribution:
$$\mathsf P(S=s) = \underline{\qquad}\quad[s\in\{\underline{\qquad}\}]$$
Then by definition of conditional probability:
$$\begin{align}\mathsf P(S< 3\mid S\leq 18) & = \dfrac{\mathsf P(S< 3 \cap S\leq 18)}{\mathsf P(S\leq 18)} \\[1ex] & = \dfrac{\mathsf P(S< 3)}{1-\mathsf P(S> 18)} \\[1ex] & = \underline{\dfrac{(\qquad)}{(\qquad)}}\end{align}$$
Fill in the blanks and complete.
Answer: Some hints: First we can use the converse probability:
$P(S\leq 18)=1-P(S>18)=1-P(S=20)-P(S=19)$
In case of $S=20$ the player has to win 10 times. $P(S=19)$ is zero, beause it is not possible.

$P(S<3)=P(S=0)+P(S=1)+P(S=2)$
For $S=0$ the player has to loose 10 times.
$S=1$ is not possible.
For $S=2$ the player has to win once.
Bayes theorem:
$P(S<3|S\leq 18)=\frac{P(S<3 \cap S\leq 18)}{P(S\leq 18)}$
$P(S<3 \cap S\leq 18)=P(S<3)$
Therefore $P(S<3|S\leq 18)=\frac{P(S<3)}{P(S\leq 18)}$

A calculation example:
$P(S=16)=\binom{10}{8}\cdot \left(\frac{18}{37}\right)^8\cdot \left(\frac{19}{37}\right)^2$
Comment: Here's the answer i got:

$\frac{P(S< 3)}{P(S\leq 18)}=\frac{(\frac{19}{37})^{10}+(\binom{10}{1}(\frac{18}{37})(\frac{19}{37})^9)}{1-(\frac{18}{37})^{10}}\approx \frac{0.000015401}{0.99925748}\approx 0.000015516$

correct?
Comment: In general your expression is right. I have the same value for the denominator. The value for the numerator calculated by w.a. is different from yours. See here (You have to mark the whole link and then copy it): http://www.wolframalpha.com/input/?i=%28%2819%2F37%29%5E10%2B10*%2819%2F37%29%5E9*18%2F37%29
Comment: this is what i get : http://www.wolframalpha.com/input/?i=%5Cfrac%7B%28%5Cfrac%7B19%7D%7B37%7D%29%5E10%2B%28%5Cbinom%7B10%7D%7B1%7D%28%5Cfrac%7B18%7D%7B37%7D%29%28%5Cfrac%7B19%7D%7B37%7D%29%5E9%29%7D%7B1-%28%5Cfrac%7B18%7D%7B37%7D%29%5E%7B10%7D%7D
Comment: @spexel I have the same final result, $1.34\%$

Probability when playing roulette


Merging two dataframes pyspark

Question: I have 2 input files:
a) An original file ( orig_file.json ), containing records like this:
{"id": 1, "app": test_a, "description": test_app_a }
{"id": 2, "app": test_b, "description": test_app_b }
{"id": 3, "app": test_c, "description": test_app_c }
{"id": 4, "app": test_d, "description": test_app_d }
{"id": 5, "app": test_e, "description": test_app_e }

b) A 'deltas' file ( deltas_file.json ), containing records like this:
{"id": 1, "app": test_aaaxxx, "description": test_app_aaaxxx }
{"id": 6, "app": test_ffffff, "description": test_app_ffffff }

I am trying to merge two files( original + deltas ) in such way that an output like this results
{"id": 1, "app": test_aaaxxx, "description": test_app_aaaxxx }
{"id": 2, "app": test_b, "description": test_app_b }
{"id": 3, "app": test_c, "description": test_app_c }
{"id": 4, "app": test_d, "description": test_app_d }
{"id": 5, "app": test_e, "description": test_app_e }
{"id": 6, "app": test_ffffff, "description": test_app_ffffff }

*basically merging original file with deltas file by adding any new app and just update records for the ones that already exist.
.
I have tried to use different joins but could not get the solution.
Can someone guide me the approach to solve this problem?
Thanks
Answer: Left outer join and coalesce:
from pyspark.sql.functions import *

deltas.join(origin, ["id"], "leftouter") \
  .select("id",
      coalesce(deltas["app"], origin["app"]).alias("app"),
      coalesce(deltas["description"], origin["description"]).alias("description"))

Comment: when i run the above command, it shows an error that dataframe object is not callable.
Answer: Try python panda merge.
import panda as pd
# create your data frames here
pd.merge(delta_frame,orig_frame)  # Try various required arguments in function

Hope this helps !
Comment: There are multiple options in pySpark which would not require a ```toPandas()``` operation in order to accomplish the merge. ```.join()``` likely being the most appropriate.

Merging two dataframes pyspark


Where can I find TMonitor (Delphi 7) or how can I replace it with an alternative function?

Question: I have a code (Singleton- Pattern) which works with Delphi RAD 10.1
type

  TSharedData = class
  private
    FPOL: integer;
    class var FUniqueInstance: TSharedData;
    procedure SetFPol(const Value: integer);
    constructor Create;
  public
    class function GetInstance: TSharedData;
    property POL: integer read FPOL write SetFPol;
  end;

var
  Key: TObject;

implementation

{ TSharedData }

constructor TSharedData.Create;
begin
  SetFPol(1);
end;

class function TSharedData.GetInstance: TSharedData;
begin
  TMonitor.Enter(Key); // <-- error here
  try
    if FUniqueInstance = nil then
    begin
      FUniqueInstance := TSharedData.Create;
    end;
  finally
    TMonitor.Exit(Key);
  end;
  Result := FUniqueInstance;
end;

procedure TSharedData.SetFPol(const Value: integer);
begin
  FPOL := Value;
end;

initialization
  Key:= TObject.Create;
finalization
  Key.Free;

I need now the same code in Delphi 7. But the compiler said, "TMonitor isn't known".
Where can I find TMonitor or how can I replace it with an alternative function?
I thank you in advance for any information.
Comment: Use TCriticalSection instead...
Comment: Ya, I'd use a critical section for this even if monitor was available.
Comment: Or a "fixed" `TCriticalSection`, [Fixing TCriticalSection](https://www.delphitools.info/2011/11/30/fixing-tcriticalsection/).
Answer: You can use TCriticalSection from SyncObjs unit.
The approach changes just a little bit. The critical section should be used as an object. So if you want to protect an area of you object on can do something like:
type
  TSafeCounter = class(TObject)
  private
    FValue: Integer;
    FCriticalSection: TCriticalSection;
  public
    constructor Create;
    destructor Destroy; override;

    procedure SafeInc;
    procedure SafeDec;

    function CurValue: Integer;
  end;

implementation

{ TSafeCounter }

constructor TSafeCounter.Create;
begin
  FCriticalSection := TCriticalSection.Create;
end;

function TSafeCounter.CurValue: Integer;
begin
  FCriticalSection.Acquire;
  try
    Result := FValue;
  finally
    FCriticalSection.Release;
  end;
end;

procedure TSafeCounter.SafeDec;
begin
  FCriticalSection.Acquire;
  try
    Dec(FValue);
  finally
    FCriticalSection.Release;
  end;
end;

destructor TSafeCounter.Destroy;
begin
  FCriticalSection.Free;

  inherited;
end;

procedure TSafeCounter.SafeInc;
begin
  FCriticalSection.Acquire;
  try
    Inc(FValue);
  finally
    FCriticalSection.Release;
  end;
end;

If you are facing very extreme scenario (performance), you can work another kinds of implementations of critical sections, but them will also increase the complexity of working with it like the read/write critical section.


Basic ternary to if/then conversion in Javascript

Question: Would someone mind converting this line of ternary code to if/then statements. I understand ternary, but am not able to get syntax errors to go away when I convert to if/then. This is the only line of my homework I had to borrow and I'd like to make it into if/then so that I can comment on it and understand it better myself.
Original:
return n == null || isNaN(n) ? 0 : n;

My attempt:
return n == null || if(isNaN(n)){return 0;}else{return n;}

Comment: Thanks gosh there is no stackoverflow for surgeons
Answer: if (n == null || isNaN(n)) {
  return 0;
} else {
  return n;
}

Answer: You have to move the return and have a separate one for the if and the else:
if(n == null || isNaN(n)){
    return 0;
}else{
    return n;
}

Comment: Selected as correct answer since you answered first! Thanks for the help!
Answer: if (n == null || isNaN(n))
    return 0;
else
    return n;

Comment: `!n` isn't the same as `n == null`
Comment: What about the null value? Is that implied or does it need to be added somehwere?
Answer: This is what I think it is doing:
if (n == null || isNan(n))
   return 0;
else
   return n;

The || operator has higher precedence than the ? operator.
Answer: You will need to apply some grammatics here:

The original line is a statement: the return keyword with a expression, consisting of a ternary operator.
The expected result should be a if-else statement: Blocks of conditional executed statements - return statements.

The other four answers present the correct source code, I don't want to repeat it.
Answer: The problem is that return must be the first statement on any line it appears (as per the ECMA specs).
The code is easier to translate if you first add parentheses ( n == null || (isNaN(n) ? 0 : n) gives different results and is not equivalent to javascript's default parsing of un-parenthesesed code)
return (n == null || isNaN(n)) ? 0 : n;

which is equivalent to
if (n == null || isNaN(n)) {
    return 0;
} else {
    return n;
}

Comment: What would these added parenthesis change?


what is meaning $ A(O_K)$?

Question: I was reading the paper " The number of extensions of a number field with fixed degree and bounded discriminant." by Jordan S. Ellenberg and Akshay Venkatesh(https://arxiv.org/pdf/math/0309153.pdf). In the second section pg no 726 they define $ A=Spec(R)$ Later use some notation $A(O_K)$. need some help with understanding notation.
Comment: It seems like scheme-theoretic notation. You can see it as the scheme morphisms $Spec(O_K) \rightarrow A$, or, better, as the morphisms of $O_K$-algebras $A \rightarrow O_K$.
Comment: @Mindlack you should post this as an answer.
Answer: As suggested, I am posting my comment as an answer:
It seems like scheme-theoretic notation. You can see it as the scheme morphisms $Spec(O_K)→A$, or, better, as the morphisms of $O_K$-algebras $R \rightarrow O_K$.
Comment: You mean $R\to O_K$.
Comment: Yes, thank you.
Comment: @Mindlack I do not  understand  how is $R$ is $Q_K$ algebra

what is meaning $ A(O_K)$?


Eclipse EGL on GAE

Question: I created a Java servlet that works in Tomcat. All I do is to place some .jar dependencies in the lib folder of my Tomcat and create/add the following snippet in the web.xml file:
<code><?xml version="1.0" encoding="utf-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5">
    <servlet>
        <servlet-name>egl</servlet-name>
        <servlet-class>org.eclipse.epsilon.egl.servlet.EglServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>egl</servlet-name>
        <url-pattern>*.egl</url-pattern>
    </servlet-mapping>
</web-app>
</code>
I place an index.egl file in my webapps directory and whenever I call that .egl file it calls the EglServlet class (it's one of my jar files). Everything works fine in Tomcat.
I tried to create a Google App Engine and later a Heroku app following the same steps but the servlet fails. I mean that it loads the index.egl file as a plain text file. So, if the content of the file is [%="Hello World"%] it doesn't print a Hello World string as it's normal behaviour (and the behaviour I see in Tomcat) but it prints the whole command ([%="Hello World"%]).
I later realized that GAE and Heroku use Jetty and not Tomcat and I believe that I follow the wrong steps in delpoing my jars and placing the web.xml snippet. I place the index.egl file in the webapps folder. I create a WEB-INF folder in the webapps folder. A lib folder containing all my jars in that WEB-INF folder and a web.xml file with the snippet above in the WEB-INF folder. I also placed my jar files in the Jetty/lib folder.
What am I doing wrong? Is the file placement wrong?
Answer: I've found the solution. Apparently Google App Engine uses Jetty and not Tomcat as I initially thought. Although, Jetty is compatible with Tomcat it seems that there's a small inconsistency in the way Tomcat and Jetty handle leading "/" characters in URL. So, I had to change the code in my servlet to lead to the correct path.

Eclipse EGL on GAE


remove index.php codeigniter in localhost/folder/my_codeigniter/

Question: i have try a few solution from any source, but still cannot remove index.php if my project in other folder like : http://localhost/project/my_codeigniter, all .htaaccess and configuration work fine if my project in http://localhost/my_codeigniter.
hope you can help me, thanks!
Comment: `cannot remove index.php if …` how does this problem manifest?
Comment: @greybeard cannot access any controller
Answer: You can create a .htaccess file on your project root folder. File content like this;
<code>RewriteEngine on
RewriteCond $1 !^(index\.php|assets)
RewriteRule ^(.*)$ /your-project/index.php/$1 [L]
</code>
Comment: work! thanks brother! -> 'RewriteRule  ^(.*)$ /project/my_codeigniter/index.php/$1 [L]'
i have see something like this in https://stackoverflow.com/a/39673870/5614176, but forget replace 'your-project' by full project path base on localhost, thanks!
Comment: Not important. Can you mark it as an answer? Thanks.


How to prevent back flow for parallel connected tanks?

Question: Two parallel over head water tanks are connected at the same height and have the output pipes connected to a single pipe into the home. How can back flow of water from tank to tank be prevented?
Comment: Why would you want to prevent it, isn't it done that way by design?
Comment: Use a non-return valve?
Comment: The pipe dia from the tank is 3/4 inch , non-return valve will available in th emarket?
Comment: Oh all right, I'll make an answer from my comment ...
Comment: With backflow preventer? LOL
Answer: I would use a non-return valve

Diameter: 0.75 in
  Maximum Bar Pressure: 16 bar
  Type: Non-Return
  Colour: Black-Grey
  Material: PVC
Ideally used for conveying water and other fluids in urban and inter-urban infrastructure, industrial, mining, landscape, and farming applications

Note: This one seems expensive, I suspect I can buy about ten 22mm metal-bodied double-check valves for this price.
The secret to buying plumbing parts is to specify exactly what sort of pipe you are joining, materials, nominal and actual diameters, joining method, types of fluids and pressures to be carried and so on.
It is disappointing when you find your 40mm push-fit spigot won't fit into your 40mm "Multifit" compression coupling, or you find that your spare parts box has 40mm ABS solvent-weld elbows but only 40mm  MUPVC solvent-weld pipe (and your PVC-only solvent has jelled anyway). Find a local plumbing supplies outlet and try to build up a good relationship with them so you can get advice and can return parts that don't fit the way you expected.
Comment: In case you don't know what it is or how it works, a non-return valve (or "check valve" in the states, http://en.wikipedia.org/wiki/Check_valve ) only allows flow travel in one direction. They utilize various methods to accomplish this: spring loaded ball, weighted diaphragm, swinging disc, etc.


Disprove uniform convergence of $\sum_{n=1}^{\infty} \frac{x}{(1+x)^n}$ in $[0,\infty)$

Question: How would I show that $\sum_{n=1}^{\infty} \frac{x}{(1+x)^n}$ does not uniformly converge in $[0,\infty)$?
I don't know how to approach this problem.
Thank you.
Answer: We can write $\frac x{(1+x)^n}=\frac {x+1-1}{(1+x)^n}=\frac 1{(1+x)^{n-1}}-\frac 1{(1+x)^n}$ so the partial sum is $1-\frac 1{(1+x)^n}$. We only have to look at uniform convergence on $[0,+\infty)$ of $f_n(x):=\frac 1{(1+x)^n}$. It converges pointwise to the function $x\mapsto \begin{cases}1&\mbox{ if }x=0\\\ 0 &\mbox{ if }x>0\end{cases}$, which is not continuous. So the convergence cannot be uniform on $[0,+\infty)$.
Answer: This is almost the same as Davide' answer:
let
$$f_n(x)={x\over (1+x)^n},\ n\in\Bbb N^+;\ \ \text{ and }\ \ f(x)= \sum\limits_{n=1}^\infty {x\over(1+x)^n}.$$  Since, for $x>0$, the series $\sum\limits_{n=1}^\infty {1\over(1+x)^n}$ is a  Geometric series with $r={1\over 1+x}$:
$$
 f(x)=x\sum_{n=1}^\infty {1\over(1+x)^n}  =x\cdot{ 1/(1+x)\over 1-\bigl(1/(1+x)\bigr)}
=x\cdot{1\over x}=1,
$$
for $x>0$.
As  $f(0)=0$, we see that  $f(x)$ converges pointwise  to a discontinuous function on $[0,\infty)$. Since a uniform limit of a sum of continuous functions is continuous, and as each term $f_n$ is continuous on $[0,\infty)$, it follows that $f(x)$ does not converge uniformly on $[0,\infty)$.
Answer: $$ \sup_{x \in [0,\infty)} \sum_{n=m}^{2m} \frac{x}{(1+x)^n}  \geq \sup_{x \in [0,\infty)}  \frac{mx}{(1+x)^{2m}}  \geq  \frac{mx}{(1+x)^{2m}} \bigg|_{x=1/m} = \frac1{(1+ \frac{1}{m} )^{2m}}\to \frac1{e^2}.$$
Thus the series is not uniformly Cauchy on $[0,\infty).$
Comment: It seems the denominators $(1+x)^m$ should read $(1+x)^{2m}$ (with the adequate subsequent modifications, which fortunately preserve the positivity of the limit).


Inconsistent Execution Time in Python on all systems

Question: Something that's been driving me crazy with python... I used to think it was just Windows, but I was wrong. I can have the same exact code and run it multiple times and it executes in wildly different amounts of time. Take the following test code, for example:
import math
def fib(count):
    x = 0
    while x < count:
        a = int(((((1 + math.sqrt(5)) / 2) ** x) - (((1 - math.sqrt(5)) / 2) ** (x))) / math.sqrt(5))
        x+=1

if __name__ == '__main__':
    import timeit

    t = timeit.Timer("fib(1250)", setup="from __main__ import fib",)
    #print t.timeit(10)
    count = 10000
    results = t.repeat(count, 1)
    min = 0xFFFF
    max = 0
    sum = 0
    for i in results:
        i = i*1000.0
        if i < min: min = i
        if i > max: max = i
        sum+=i

    print "Min {:.3f} | Max {:.3f} | Max/Min {:.3f} | Avg {:.3f}".format(min, max, max/min, sum/count)

Basically, it generates the first 1250 elements of fibonacii 10,000 times and uses timeit to get the amount of time each run takes. I then coalesce those times and find min, max, average and variance between min and max (the spread, if you will).
Here's the results:
Windows: Min 3.071 | Max 8.903 | Max/Min 2.899 | Avg 3.228
Mac OS:  Min 1.531 | Max 3.167 | Max/Min 2.068 | Avg 1.621
Ubuntu:  Min 1.242 | Max 10.090 | Max/Min 8.123 | Avg 1.349

So, Linux is the fastest but also has the most variance. By a LOT. But all of them can have a pretty wild swing: Only 200% for Mac, but 290% for Windows and 810% for linux!
Is it actually taking that much different time to execute? Is timeit not accurate enough? Is there something else I am missing? I'm working a lot with generating animations and I need as consistent time as possible.
Comment: @AdamHaile: Python may or may not be very slow, it really depends on your code and libraries. If you are calculating things, using NumPy may make a huge difference. Python as such is not good for numerical heavy lifting. On the other hand, Python is very good with complicated data structures (dicts, sets, lists).
Comment: Depending on the timer and your implementation, measured times can be affected by other processes running on your system. This is especially true for wall clock timers.
Comment: See... that's what I was thinking (that the actual execution time is pretty constant) but the measured times are pretty consistent in how much they vary.
Comment: You are multiplying the times by 1000. Do this instead by repeating the code so that the one test runs close to 1 second.
Comment: @Adam Haile - Might want to check this out: http://stackoverflow.com/questions/15176619/timing-the-cpu-time-of-a-python-program
Comment: @AnttiHaapala - I don't think I get what you mean...
Comment: Side note... I've been running much of my python code on a console only Raspberry Pi where not much else is going on and the timings are VERY... could it be that testing this on a full UI OS is causing these weird timings? Granted, in generally I'm dissapointed by the python speed :(
Comment: I'm thought about trying NumPy but I've never found a way to make it apply specifically to the calculations I'm doing... maybe I just need to look harder ;)
Answer: You are measuring very short times, and then even a little bit of something happening somewhere has a big impact.
I ran your test script on my machine (OS X, Core i7, Python 2.7) and made this plot of results:

You can see that most of the time the timing results are very consistent, but there are isolated incidents of the algorithm taking much more time (because there is something else happening).

I made a tiny adjustment to your timing procedure:
results=t.repeat(10, 1000)

So, now we are timing runs of 1000 function calls. The total amount of time is the same, naturally (10000 calls):

Now you can see that the performance is much more predictable. It may be that part of your wobbly timings are due to the timing methodology, not due really different times to carry out anything. Millisecond-level timing is difficult in a real-world OS environment. Even when your computer is "doing nothing", it is still switching tasks, doing background jobs, etc.

I understand the original point was not to calculate the Fibonacci numbers. But if it were, then choosing the right tool makes a difference:
import numpy as np

def fib(count):
    x = np.arange(count)
    a = (((1 + np.sqrt(5))/2) ** x - ((1 - np.sqrt(5)) / 2) ** x) / np.sqrt(5)
    a = a.astype('int')

This gives:
Min 0.120 | Max 0.471 | Max/Min 3.928 | Avg 0.125

Ten-fold speed improvement.

About the images in this answer, they are plotted with matplotlib. The first one is done thus:
import matplotlib.pyplot as plt

# create a figure
fig = plt.figure()
# create axes into the figure
ax = fig.add_subplot(111)
# plot the vector results with dots of size 2 (points) and semi-transparent blue color
ax.plot(results, '.', c=(0, 0, 1, .5), markersize=2)

See the documentation of matplotlib. It is easiest to get started by using IPython and pylab.
Comment: Nice graph... how'd you make that?
So, hmmm... maybe I'm right that the reason I'm used to the timing being consistent was that I was running on a Raspberry Pi with no UI and almost no services running. My python was getting 90%+ of the CPU...
Comment: fair enough... I kind of figured that would be the case and that timing only 1 run at a time was not the best way. Problem I'm running into is that I'm trying to generate frames for animations and provide a consistent framerate. So any variance in a single frame step can make it jerky. The only way around that seems to limit the frame time to a time greater than the maximum generation time. It's smooth, but slower.
Comment: @AdamHaile: If you look at the percentual variation with longer runs, it is small. It is easy to get single-digit millisecond delays, but already a ten-millisecond delay is a long one. So it may be that you will not end up in trouble with your animation, after all. However, if you can calculate your animation a bit beforehand, you might consider having a buffer of a few frames. - And when you have your animation code running, clock the real wall-clock timestamps for the start and end of calculation for each frame. Then you'll see if there are OS-related extra delays.
Comment: `timeit.Timer` also accepts a 'number' param to quickly time a single run of X iterations.  `timed_execution = timeit.Timer("fib(1250)", setup="from __main__ import fib", number=1000)`
Answer: I made a plot similar to @drV (give him the vote, he was first!) - the difference is that I sorted results so you could see a trend line. The hint is that even though the max is high, the average is low, so there are some outliers at the end.

I used pylab by just adding this to the bottom:
from pylab import *
results.sort()
plot(range(len(results)),results)
show()

Comment: A definite +1 for the nice way of showing the distribution! (And maybe a -.01 for using `from pylab import *` interface :)


How to return a key of an array from a function where the key is an arg?

Question: I have made a simplified version of what I am trying to explain.
$array ('name' => 1, 'notname' => 1, 'anothername' => 2);

function a($name1, $name2){
  $total = $name1 + $name2;
  $winner = rand(0, $total);

  if ($winner > name2){
    $winner = $name1;
  } else {
    $winner = $name2;
  }

  return $winner;

}

echo a($array['name'], $array['notname']);

Instead of returning (and echoing) the winners number, I want to echo the name of the key for the winner.
I feel like I am making this way to hard.
Comment: Where does `odds2` come into play? You're also missing closing semi-colons for `$winner = $name1` and `$winner = $name2`
Comment: Now you're missing a `$` for `winner` in `winner = rand(0, $total);`
Comment: The key, as opposed to the value.  I don't think I am doing a good job of explaining.
Comment: `'name'` is the key. `1` is the value.
Comment: Which one do you want to echo?
Comment: I want to echo the key, I do some math on the number value in the function and I want to pull whatever the answer was from the function out as the key.
Comment: The key is either `'name'` or `'notname'`, so the result of arithmetic isn't going to be either of those.
Comment: You are not passing the key only the value of that array element.  Not sure of the practicality, maybe if you explained what you are trying to accomplish in a broader sense.
Comment: I completely edited the code to hopefully be more specific.  Obviously I tried to make the question too generic.
Comment: sorry that is out of my original code.  fixed thanks.
Comment: Better coming from me then from 20 others ;-) (*about missing chars.*)
Answer: The problem is your function a is getting the numbers (array values) and not the array keys. You cannot get an array key from its value.
So you want:
$array ('name' => 1, 'notname' => 1, 'anothername' => 2);

function a($array, $name1, $name2){
  $total = $array[$name1] + $array[$name2];
  $winner = rand(0, $total);
  if ($winner > $array[$name2]){
    return $name1;
  else
    return $name2;
}

echo a($array, 'name', 'notname');

Comment: Ohh my goodness, thank you soo much!  I did such a bad job of explaining what I was trying to do at first.

I knew I was overthinking something.  Thanks again!
Comment: You can get an array key from its value. http://uk1.php.net/array_search - not necessarily the correct one if the values aren't unique.
Answer: I'm not really sure what you want, but it sounds to me like you're either trying to find a key based on its position within the array, or a key based on the corresponding value. There are a few functions that might be useful to you.
Start from $example = array('a' => 1, 'b' => 2, 'c' => 3);. The letters are the keys and the numbers are the values.

array_keys will return a new array containing the keys of the original array, in order. array_keys($example) will return array(0 => 'a', 1 => 'b', 2 => 'c'). (You can use this to look up a key by position).
array_flip will return a new array with the keys exchanged with the values. array_flip($example) will return array(1 => 'a', 2 => 'b', 3 => 'c').
array_search will return the key of the first matching value. array_search($example, 2) will return 'b'.

Edit: It sounds like you want to pluck out a key at random?
array_keys($array)[rand(0, count($array) - 1)] ??

Edit 2: Okay, I'm guessing that you mean the values of the array are probabilities of the corresponding name winning. (?)
Here is how I would write that function:
function selectWinner($players) {
    $select = mt_rand() / mt_getrandmax() * array_sum($players);
    $position = 0;
    foreach ($players as $name => $probability) {
        if (($position += $probability) >= $select) return $name;
    }
}

Now assume we have an array:
$players = array('Bob' => 1, 'Bert' => 1, 'Betty' => 2);

Calling selectWinner($players) will return Bob or Bert 25% of the time each, and will return Betty 50% of the time. The probabilities need not be integers.
For testing:
for ($i = 0; $i < 10000; $i++) @$counts[selectWinner($players)]++;
print_r($counts);

This outputs something like:
Array
(
    [Betty] => 4907
    [Bert] => 2560
    [Bob] => 2533
)

Comment: I can't use array_flip because some of the values are the same, looking into array_keys now.
Comment: No, I want to compare two values, have one be the "winner" and return the name of the key.  The array in reality has about 70 values.
Comment: Yes, That is helpful but not quite what I wanted to do.  I wanted to put Billy and Bob against each other and have it come out 50 / 50.  Then later put Billy and Bert against each other and have it come out 1/3 to 2/3.
Answer: Since you said you're working with a more complicated problem in reality, I'm going to assume that
echo 'name';

won't do the trick.
A good way to get keys out of an array is with a foreach loop. For your example above,
foreach($array as $key => $value){ echo $key; }

would return
name notname

I don't know if that helps, but without more info its the best I can do.
Comment: right, this is essentially what I have, but I don't want to return not name.  I am trying to pull the value that was originally entered into the function.
Answer: First, you have an error in your array declaration, it should be:
$array('name' => 1, 'notname' => 2)

Second, you basically wrote a function that takes a variable as a parameter and then returns it. You are passing only the value to that function, the same as if you'd write echo a('something').
ALso, 'name' is the key of the first value in the array if you write it like this. I think you want to have 1 as the key, 'name' as the value, so you have to write it the other way around.
$array(1 => 'name)

Furthermore, I suggest taking another spin on CS basics :)
Comment: why would 'notname' not be able to hold a value of 1?

and I tried to make my question to generic (in hopes it would apply to other people) and instead confused everyone including myself.


How to disable all python linting in VSCode

Question: Using the Microsoft Python extension there doesn't appear to be a way to disable linting globally.
I don't mind linting when I am wondering where a typo is that is causing issues, but I certainly don't need it to tell me that the entire code block is bad when I start to add any code that isn't a complete line.
I have disabled every linter I can find in all the settings I can find, here's settings.json for instance:
    "python.linting.lintOnSave": false,
    "python.linting.pylintEnabled": false,
    "python.linting.pylintUseMinimalCheckers": false,
    "python.linting.enabled": false

I would think that there is a way to completely disable linting globally with one button click, but even just turning it off for python would be enough for me now. Am I asking too much?
Comment: What's the problem? You seem to have already disabled linting?
Comment: That is the problem, with that setting of linting off in everywhere that I can find I still see the error squiggles
Comment: Are your workspace settings overriding your user settings?
Comment: I have even more of them disabled there:
    "python.linting.lintOnSave": false,
    "python.linting.pylintEnabled": false,
    "python.linting.pylintUseMinimalCheckers": false,
    "python.linting.pep8Enabled": false,
    "python.linting.flake8Enabled": false,
    "python.linting.mypyEnabled": false,
    "python.linting.pylamaEnabled": false,
    "python.linting.enabled": false,
Comment: I thought I had fixed it by duplicating all the disables in all the settings.json files that I could find, however I still can't kill the linting by default. I might just have to switch to the other vscode python extension
Answer: in my case just by going to the setting and searching for lint python in the search bar of the setting page and by unchecking the
Python > linting: Enabled:

did well and disabled the linting for python scripts!
Comment: I did this and I still have lints all over. Is there something else needed?
Comment: For me it wasn't a setting, I had to disable the `Flake8` extension (there's also a Pylint extension and others).
Comment: I concur - the only thing that works is disabling the `Flake8` extension.
Answer: Using VS Code circa v1.78.2, this worked:

Navigate to Extensions
Find Pylint, click the gear icon and select Disable
Find Pylance, click the gear icon and select Disable
Restart of VS Code was required and disabling both Pylint and Pylance was required
Answer: I didn't want to disable linter for all languages, but only for Python:

Find Linter extension by Nando Vieira, click the gear icon and select Extension Settings
Click on Edit in settings.json
Find pylint inside linter.linters and switch enabled value to false

Profit!
This method is also suitable for all required languages.


Testing Symfony validation with Panther

Question: I'm testing my validations and I send wrong values in all my input :
$crawler = $this->client->getCrawler();

        $form = $crawler->selectButton('Créer')->form();

        $form->setValues([
            'Contractor[lastName]' => str_repeat('maxLength', self::OVER_MAX_LENGTH,),
            'Contractor[firstName]' => str_repeat('maxLength', self::OVER_MAX_LENGTH,),
            'Contractor[email]' => str_repeat('maxLength', self::OVER_MAX_LENGTH,).'@society.com',
            'Contractor[phone]' => str_repeat('0', self::UNDER_MIN_LENGTH,),
            'Contractor[password][password][first]' => 'first',
            'Contractor[password][password][second]' => 'second',
            'Contractor[status]' => 'admin.crud.user.field.choices.boss'
        ]);

        $this->client->submitForm('Créer');

        $this->client->waitFor('.invalid-feedback');
        $this->client->waitForVisibility('.invalid-feedback');

        $this->client->takeScreenshot('add.png');

        $totalErrors = $crawler->filter('div.invalid-feedback')->count();
        $errorExpected = 5;

        $this->assertNotCount($totalErrors, [$errorExpected]);

When I test I ask to wait until the errors are displayed. Then I count the number of errors and I compare. The problem is when this line is test $totalErrors = $crawler->filter('div.invalid-feedback')->count(); I've got an error which say :
Facebook\WebDriver\Exception\StaleElementReferenceException: stale element reference: element is not attached to the page document.
In the screenshot, the errors are displayed.
I really don't understand why because I asked to wait for the element to be in the DOM and I had no errors.
Any idea ?
Answer: It's possible that the Crawler instance you have has a "stale" HTML in its state. I don't know the exact internals, but what helped me with a similar case was to get a fresh crawler from the Client object:
// some actions that redraws the Client HTML

$crawler = $client->getCrawler();
$totalErrors = $crawler->filter('div.invalid-feedback')->count();

Testing Symfony validation with Panther


How to change an ImageView, that is part of a list item?

Question: I have a ListView that shows list items (duh). When you click on a list item, another Activity opens. Part of the list item layout is a grey star, an ImageView. When you click on this ImageView, I don't want to open another Activity, but I want to change the color of the star to green (= mark the item as favourite) or back (= mark it as not favourite). I managed to do that with an OnClickListener, loading another ImageView on Click, and refreshing the adapter. But for the ImageView to change, after clicking it I need to leave the Activity and enter again. It doesn't refresh instantly. Why, and how can I change that? I've tried lots of different versions, so far nothing works. My ListViewAdapter extends BaseAdapter. Thank you!
public class ListViewAdapterKeysAToZ extends BaseAdapter {

private ArrayList<KeyTagIntern> keyTags;
private ObservableArrayList<KeyTagIntern> list;
private Context context;
TextView name;
TextView place;
ImageView star, favoriteStar;

public ListViewAdapterKeysAToZ(Context context, ObservableArrayList<KeyTagIntern> list)

{
    this.context = context;
    this.list = list;

    keyTags = new ArrayList<>();

    for (KeyTagIntern keytag : list) {
        keyTags.add(keytag);
    }
    //(....)
}

@Override
public View getView(final int position, View convertView, ViewGroup parent) {

KeyTagIntern key = (KeyTagIntern) getItem(position);

  if (convertView == null) {
                convertView = LayoutInflater.from(context).inflate(R.layout.list_item_keys, parent, false);
            }

            name = (TextView) convertView.findViewById(R.id.text_keylist_item);
            name.setText(key.getName());

            place = (TextView) convertView.findViewById(R.id.text_keylist_item_place);
            place.setText(key.getPlace());

            star = (ImageView) convertView.findViewById(R.id.right_icon_keylist_item);
            favoriteStar = (ImageView) convertView.findViewById(R.id.right_icon_keylist_item_favorite);

if (key.isFavorite())
{
    star.setVisibility(View.INVISIBLE);
    favoriteStar.setVisibility(View.VISIBLE)

    favoriteStar.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            // This makes key.isFavourite() = false for the next time
            Paper.book().delete(FAVORIT + String.valueOf(key.getKeyTagID()));

            //Since notifyDataSetChanged() didn't work for me, I tried this - but no change
            int index = list.indexOf(key);
            list.remove(index);
            list.add(index, key);

            keyTags = new ArrayList<>();

            for (KeyTagIntern keytag : list) {
                keyTags.add(keytag);
            }
            notifyDataSetChanged();
        }
    });
}

// Then do the opposite for if (!key.isFavourite())

Und hier das xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/list_item_keys"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:background="@color/MiddleDarkGrey">

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/btn_list_item_keys"
    android:layout_width="match_parent"
    android:layout_height="@dimen/height_list_item"
    android:layout_marginBottom="3dp"
    android:layout_marginLeft="20dp"
    android:layout_marginRight="20dp"
    android:layout_marginTop="3dp"
    android:background="@drawable/white_list_item"
    android:paddingLeft="13dp"
    android:paddingRight="10dp">

    <ImageView
        android:id="@+id/icon_keylist_item"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_centerVertical="true"
        android:visibility="visible"
        app:srcCompat="@drawable/ic_key" />

    <ImageView
        android:id="@+id/icon_reserved"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_toRightOf="@+id/chb_add_key"
        android:layout_centerVertical="true"
        android:visibility="invisible"
        app:srcCompat="@drawable/ic_reservate_orange" />

    <ImageView
        android:id="@+id/icon_taken"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_toRightOf="@+id/chb_add_key"
        android:layout_centerVertical="true"
        android:visibility="invisible"
        app:srcCompat="@drawable/ic_taken_red" />

    <TextView
        android:id="@+id/text_keylist_item"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="10dp"
        android:layout_marginStart="10dp"
        android:layout_toEndOf="@+id/icon_keylist_item"
        android:layout_toRightOf="@+id/icon_keylist_item"
        android:gravity="center_vertical"
        android:layout_centerVertical="true"
        android:text="Text"
        android:textColor="@color/DarkGrey"
        android:textSize="@dimen/text_list_item" />

    <TextView
        android:id="@+id/text_keylist_item_place"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/text_keylist_item"
        android:layout_alignLeft="@+id/text_keylist_item"
        android:layout_marginLeft="2dp"
        android:layout_marginBottom="5dp"
        android:text="Where is the key?"
        android:textColor="@color/DarkGrey"
        android:textSize="@dimen/text_list_item_sub" />

    <ImageView
        android:id="@+id/right_icon_keylist_item"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentEnd="true"
        android:layout_alignParentRight="true"
        android:layout_centerVertical="true"
        app:srcCompat="@drawable/ic_fav_green" />

    <ImageView
        android:id="@+id/right_icon_keylist_item_favorite"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:srcCompat="@drawable/ic_fav_chosen"
        android:visibility="invisible"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true" />

</RelativeLayout>

Comment: Can you post the code where you actually set up the view?
Comment: Thank you Mars, I tried all of it - in the end the answer was rather stupid, as it is so often, and you couldn't have helped me since I excluded the code at the beginning of my adapter class. It actually worked the whole time, but I didn't see it, since the listitem at the very end of the list was changed, not the selected one. This was due to me declaring the variables at the beginning of the class, rather than inside the getView method.
Comment: It doesn't look like you're actually setting up your view in the getView function. We can't see what star or favoriteStar are referencing
Comment: oh, sorry - i left it out, since i didn't think there could be anything problematic in that part of the code. now i added that part.
Comment: Hmm, I don't see anything that stands out. Are you sure that you're entering the right places? Have you set breakpoints already? Specifically, is it the correct key? Is it being deleted? is the list correct, or is it set to the original list? Is isFavorite() evaluating correctly?
Comment: One more check, since I don't think it's an issue with images, but for the "opposite" code, are you connecting to the correct star? If it's invisible and the size gets set to zero, you won't be able to click it
Answer: I think your approach should be something like this.
rather hiding and displaying an image just change source of it!
if (key.isFavorite())
{
favoriteStar.setImageResource(R.drawable.aaa);

favoriteStar.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v)
    favoriteStar.setImageResource(R.drawable.bbb);
    // and vice-versa

and I don't thing you will be needing notifyDataSetChanged(); as you are making no changes in the Listdata  actually!
Comment: I don't think it matters if I change the source or set the visibility. And you should use notifyDataSetChanged() - it's the cleaner way to code here, I think.
Comment: the clear way of coding ?? really I don't think so, you have an idea why it is used?
Comment: The data has been changed - notifying the responsible adapter about it instead of merely changing the surface seems cleaner to me. And I've checked Stackoverflow extensively about this topic before posting this question, and every upvoted answer included calling notifyDataSetChanged() in one way or another
Comment: `notifyDataSetChanged()` used when you make changes in data not for change in a view I have developed similar functionality here https://play.google.com/store/apps/details?id=in.webic.moviepal
Answer: In the end the answer was rather stupid, as it is so often, and you guys couldn't have helped me since I excluded the code at the beginning of my adapter class (added it now). It actually worked the whole time, but I didn't see it, since the listitem at the very end of the list was changed, not the selected one. This was due to me declaring the variables at the beginning of the adapter class, rather than inside the getView method.
I changed it to this and now it works perfectly:
public class ListViewAdapterKeysAToZ extends BaseAdapter {

private ArrayList<KeyTagIntern> keyTags;
private ObservableArrayList<KeyTagIntern> list;
private Context context;

public ListViewAdapterKeysAToZ(Context context, ObservableArrayList<KeyTagIntern> list) {
    this.context = context;
    this.list = list;

    keyTags = new ArrayList<>();

    for (KeyTagIntern keytag : list) {
        keyTags.add(keytag);
    }
// (...)

 @Override
public View getView(final int position, View convertView, ViewGroup parent) {

    KeyTagIntern key = (KeyTagIntern) getItem(position);

    TextView name;
    TextView place;
    ImageView star, favoriteStar;

            if (convertView == null) {
                convertView = LayoutInflater.from(context).inflate(R.layout.list_item_keys, parent, false);
            }

            name = (TextView) convertView.findViewById(R.id.text_keylist_item);
            name.setText(key.getName());

            place = (TextView) convertView.findViewById(R.id.text_keylist_item_place);
            place.setText(key.getPlace());

            star = (ImageView) convertView.findViewById(R.id.right_icon_keylist_item);
            favoriteStar = (ImageView) convertView.findViewById(R.id.right_icon_keylist_item_favorite);

            if (key.isFavorite()) {
                star.setVisibility(View.INVISIBLE);
                favoriteStar.setVisibility(View.VISIBLE);
            }else {
                star.setVisibility(View.VISIBLE);
                favoriteStar.setVisibility(View.INVISIBLE);
            }

            star.setOnClickListener(v -> {
                key.setFavorite(true);
                Paper.book().write(FAVORIT + String.valueOf(key.getKeyTagID()), true);
                notifyDataSetChanged();
            });

            favoriteStar.setOnClickListener(v -> {
                key.setFavorite(false);
                Paper.book().delete(FAVORIT + String.valueOf(key.getKeyTagID()));
                notifyDataSetChanged();
            });

Comment: Does this still work? if star and favorite star are in the same place, it seems like the upper one should receive the click (or both). Also, where you declare the variables shouldn't matter...
Comment: The substantial changes that I see are your new setFavorite method (which might mean that your isFavorite method was evaluating incorrectly before), and the fact that you set onClickListeners for both stars, regardless of current favorite state
Comment: Because you weren't unsetting the onClickListener for the un-used state, if both were triggering, you were likely triggering the onClickListener on another cell as well.


Modify keys of object in javascript

Question: I have an object of objects and I want to change the keys of the objects
"opening_hours": {
  "0": {
    "close": "17:00:00",
    "is_open": true,
    "open": "09:00:00"
  },
  "1": {
    "close": "17:00:00",
    "is_open": true,
    "open": "09:00:00"
  },
  "2": {
    "close": "17:00:00",
    "is_open": true,
    "open": "09:00:00"
  },
  "3": {
    "close": "17:00:00",
    "is_open": true,
    "open": "09:00:00"
  },
  "4": {
    "close": "17:00:00",
    "is_open": true,
    "open": "09:00:00"
  },
  "5": {
    "is_open": false
  },
  "6": {
    "is_open": false
  }
}

like:"0" I want it to be 'Monday', Is this possible in Javascript?
Expected Output is :
{
  "monday": {
    "close": "17:00:00",
    "is_open": true,
    "open": "09:00:00"
  },
  "tuesday": {
    "close": "17:00:00",
    "is_open": true,
    "open": "09:00:00"
  },
  "wednesday": {
    "close": "17:00:00",
    "is_open": true,
    "open": "09:00:00"
  },
  "thursday": {
    "close": "17:00:00",
    "is_open": true,
    "open": "09:00:00"
  },
  "friday": {
    "close": "17:00:00",
    "is_open": true,
    "open": "09:00:00"
  },
  "saturday": {
    "is_open": false
  },
  "sunday": {
    "is_open": false
  }
}

Comment: @Rishab What do you mean by *"marked Flag by moderator"*?
Comment: Hello @rasika your question has been marked Flag by moderator. If you need solution you can contact me !
Answer: Create a days array which has index of an item same as the day (Eg: 0 for monday and so on). Loop through the keys of opening_hours object and add new key-value pairs to the output like this:

const days = ["monday","tuesday","wednesday","thursday","friday","saturday","sunday"],
    opening_hours = {"0":{close:"17:00:00",is_open:true,open:"09:00:00"},"1":{close:"17:00:00",is_open:true,open:"09:00:00"},"2":{close:"17:00:00",is_open:true,open:"09:00:00"},"3":{close:"17:00:00",is_open:true,open:"09:00:00"},"4":{close:"17:00:00",is_open:true,open:"09:00:00"},"5":{is_open:false},"6":{is_open:false}},
    output = {};

for(const key in opening_hours)
  output[days[key]] = opening_hours[key];

console.log(output)

You could also map the entries of the object and update the number to days[number] to get the string. Then use Object.fromEntries() to create a new object.

const days = ["monday","tuesday","wednesday","thursday","friday","saturday","sunday"],
    opening_hours={"0":{close:"17:00:00",is_open:true,open:"09:00:00"},"1":{close:"17:00:00",is_open:true,open:"09:00:00"},"2":{close:"17:00:00",is_open:true,open:"09:00:00"},"3":{close:"17:00:00",is_open:true,open:"09:00:00"},"4":{close:"17:00:00",is_open:true,open:"09:00:00"},"5":{is_open:false},"6":{is_open:false}},
    updatedEntries = Object.entries(opening_hours).map(([k, v]) => [days[k], v]),
    output = Object.fromEntries(updatedEntries);

console.log(output)

Modify keys of object in javascript


Show Login Screen for iPhone when app becomes active

Question: From other threads here I have gotten a modal view "login screen" to show whenever my app starts for the first time. What I want now is to have the login screen show whenever the app is brought back into the foreground (i.e. its running in the background and is brought up again) so the user can log back in.
Here's my code from the applicationDidFinishLaunchingWithOptions
LoginViewController *loginViewController = [[LoginViewController alloc] initWithNibName:@"LoginView" bundle:nil];

    if (lockScreenOnOff)
    {
        [self.tabBarController presentModalViewController:loginViewController animated:YES];
        [self.window makeKeyAndVisible];
    }

where the modal login view is shown if a switch (lockScreenOnOff) is on. How can I accomplish this?
Answer: Implement applicationDidEnterBackground: and applicationDidBecomeActive: in your application delegate. (UIApplicationDelegate class reference)
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    // Create all view controllers

    [self lockApplicationAnimated:NO]; // Lock on launching
    [self.window makeKeyAndVisible];

    return YES;
}

- (void)lockApplicationAnimated:(BOOL)animated
{
    [self.tabBarController presentModalViewController:self.loginViewController
                                             animated:animated];
}

- (void)applicationDidEnterBackground:(UIApplication *)application
{
    // Lock the application
    // Also, save all user data because the application might terminate soon
    [self lockApplicationAnimated:NO];
}

- (void)applicationDidBecomeActive:(UIApplication *)application
{
    // Hooray, the user returned!
    // Screen should be locked because the applicationDidEnterBackground
}

Additionally you can also use NSTimer to invalidate a session after a certain amount of time.
Comment: I tried this by adding the same code I posted originally in both of these places. The lock screen does come up again (like I hoped it would), but if you hit the home button then re-enter the app, the modal screen goes away (defeating the lock screen).
Comment: You need to call `[self.window makeKeyAndVisible]` only once, in `applicationDidFinishLaunchingWithOptions`.

Try to present the modalViewController only when `applicationDidEnterBackground`.
Comment: You are a genius, no lie. Seriously thank you for the help, been trying to get that solved for a while now!


How to start RMI via weblogic concole?

Question: i have to migrate a web application to weblogic, and this web app requires RMI to run, in my previous system, i have to execute startRMIregistry.sh which contain of:
#!/bin/sh
exist="false"
for var in `ps -ef | grep rmiregistry`
do
    if [ "$var" = "rmiregistry" ]
    then
        exist="true"
    fi
    if [ "$var" = "8206" ]
    then
        if [ "$exist" = "true" ]
        then
            echo "rmiregistry is already running."
            exit
        fi
    fi
done
CLASSPATH=.:/home/cms/server/cms.jar:/home/cms/lib/lucene-1.4.2.jar
export CLASSPATH
rmiregistry 8206 &
echo rmiregistry started
echo $! > rmiregistry.pid

and now i need to start this RMI registry via server start argument in weblogic console. I think i need to start via console to make sure RMI server run in my managed server, is this right? I need a suggestion, how can i start RMI as server mode under my managed server?
i am really sorry if my explanation quite confusing, :)
Regards
Answer: The Server Start arguments are not the correct place to run or source a script.
If you need your weblogic server to run a script beforehand, you should modify either setDomainEnv.sh or startWebLogic.sh and put in a line like:
. <path>/startRMIregistry.sh

The IBM support page also contains good information on renaming startWebLogic to startRMIReigistry.
Comment: Hi, thanks for your response, i'm trying to make connection between 2 managed server in my weblogic, but i don't know how to setup this connection. Lets say i have cms_server and home_server. I want to make connection between those managed server over RMI, how can i accomplish this? thank you very much :)

How to start RMI via weblogic concole?


Optional ending capture group

Question: I'm trying to have three total capture groups where the last is optional. I'm running into an issue where I'm not sure how to exclude the last delimiter from the last group and also have it look up to the end.
Here's my pattern
/(.+)\@(.+)\:(.+)/

Here's my example strings
test@hello // => ['test', 'hello']
test@hello:optional // => ['test', 'hello', 'optional']

Comment: Just to show how you could fix your pattern: [`^(.+)\@(.+?)(?::(.+))?$`](https://regex101.com/r/pA6rA6/1).
Answer: Use string.split
string.split(/[:@]/)

[:@] matches a colon or @ symbol then the split function splits the string according to the matched chars.

var s = 'test@hello:optiona'
alert(s.split(/[@:]/))

or

var s = 'test@hello:optiona'
alert(s.match(/[^@:]+/g))

Optional ending capture group


Best way to iterate two lists and extract few things?

Question: I have two classes as shown below. I need to use these two classes to extract few things.
public final class ProcessMetadata {
  private final String clientId;
  private final String deviceId;
  // .. lot of other fields here

  // getters here
}

public final class ProcMetadata {
  private final String deviceId;
  private final Schema schema;
  // .. lot of other fields here
}

Now I have below code where I am iterating above two classes and extracting schema given a clientId.
public Optional<Schema> getSchema(final String clientId) {
  for (ProcessMetadata metadata1 : processMetadataList) {
    if (metadata1.getClientId().equalsIgnoreCase(clientId)) {
      String deviceId = metadata1.getDeviceId();
      for (ProcMetadata metadata2 : procMetadataList) {
        if (metadata2.getDeviceId().equalsIgnoreCase(deviceId)) {
          return Optional.of(metadata2.getSchema());
        }
      }
    }
  }
  return Optional.absent();
}

Is there any better way of getting what I need by iterating those two above classes in couple of lines instead of what I have? I am using Java 7.
Comment: yes it is from guava not java 8 one :)
Comment: do you need to nest the 2 loops? isn't `clientId` unique?
Comment: but how will I get `schema` then?
Comment: you are using Optional in java7 ?
Comment: do you have Streams, too?
Comment: That I don't know. I doubt it is part of Java 7.
Answer: You're doing a quadratic* search operation, which is inneficient. You can do this operation in constant time by first creating (in linear time) a mapping from id->object for each list. This would look something like this:
// do this once, in the constructor or wherever you create these lists
// even better discard the lists and use the mappings everywhere
Map<String, ProcessMetadata> processMetadataByClientId = new HashMap<>();
for (ProcessMetadata process : processMetadataList) {
  processMetadataByClientId.put(process.getClientId(), process);
}

Map<String, ProcMetadata> procMetadataByDeviceId = new HashMap<>();
for (ProcMetadata metadata2 : procMetadataList) {
  procMetadataByDeviceId.put(proc.getDeviceId(), proc);
}

Then your lookup simply becomes:
public Optional<Schema> getSchema(String clientId) {
  ProcessMetadata process = processMetadataByClientId.get(clientId);
  if (process != null) {
    ProcMetadata proc = procMetadataByDeviceId.get(process.getDeviceId());
    if (proc != null) {
      return Optional.of(proc.getSchema());
    }
  }
  return Optional.absent();
}

In Java 8 you could write it like this:
public Optional<Schema> getSchema(String clientId) {
 return Optional.fromNullable(processMetadataByClientId.get(clientId))
     .map(p -> procMetadataByDeviceId.get(p.getDeviceId()))
     .map(p -> p.getSchema());
}

* In practice your algorithm is linear assuming client IDs are unique, but it's still technically O(n^2) because you potentially touch every element of the proc list for every element of the process list. A slight tweak to your algorithm can guarentee linear time (again assuming unique IDs):
public Optional<Schema> getSchema(final String clientId) {
  for (ProcessMetadata metadata1 : processMetadataList) {
    if (metadata1.getClientId().equalsIgnoreCase(clientId)) {
      String deviceId = metadata1.getDeviceId();
      for (ProcMetadata metadata2 : procMetadataList) {
        if (metadata2.getDeviceId().equalsIgnoreCase(deviceId)) {
          return Optional.of(metadata2.getSchema());
        }
      }
      // adding a break here ensures the search doesn't become quadratic
      break;
    }
  }
  return Optional.absent();
}

Though of course using maps ensures constant-time, which is far better.
Comment: Did you mean `processMetadataByClientId.put(process.getClientId(), process);`?
Answer: I wondered what could be done with Guava, and accidentally wrote this hot mess.
import static com.google.common.collect.Iterables.tryFind

public Optional<Schema> getSchema(final String clientId) {
  Optional<String> deviceId = findDeviceIdByClientId(clientId);
  return deviceId.isPresent() ? findSchemaByDeviceId(deviceId.get()) : Optional.absent();
}

public Optional<String> findDeviceIdByClientId(String clientId) {
  return tryFind(processMetadataList, new ClientIdPredicate(clientId))
    .transform(new Function<ProcessMetadata, String>() {
      String apply(ProcessMetadata processMetadata) {
        return processMetadata.getDeviceId();
      }
    });
}

public Optional<Schema> findSchemaByDeviceId(String deviceId) {
  return tryFind(procMetadataList, new DeviceIdPredicate(deviceId.get())
    .transform(new Function<ProcMetadata, Schema>() {
      Schema apply(ProcMetadata procMetadata) {
        return processMetadata.getSchema();
      }
    });
}

class DeviceIdPredicate implements Predicate<ProcMetadata> {
  private String deviceId;

  public DeviceIdPredicate(String deviceId) {
    this.deviceId = deviceId;
  }

  @Override
  public boolean apply(ProcMetadata metadata2) {
    return metadata2.getDeviceId().equalsIgnoreCase(deviceId)
  }
}

class ClientIdPredicate implements Predicate<ProcessMetadata> {
  private String clientId;

  public ClientIdPredicate(String clientId) {
    this.clientId = clientId;
  }

  @Override
  public boolean apply(ProcessMetadata metadata1) {
    return metadata1.getClientId().equalsIgnoreCase(clientId);
  }
}

Sorry.
Comment: I just had to give you a vote for being brave enough to admit what you did ;-)


Does a forbidden door stop thieves?

Question: I currently have a set-up in my fortress involving a small entrance filled with traps and a trade depot connected to a moat with a drawbridge. I have an alternative entrance to the depot from within my fortress, so that I can restock while the bridge is up.
The alternative entrance has one gap in which I have placed a door. Now I'm wondering, if I forbid that door, will this stop thieves?
Likewise, I'd also like to know if I link this door up to a lever so that is it open when the drawbridge is up, can thieves open a mechanism-closed door?
Answer: According to the wiki, "Most creatures will be stopped by any door or hatch, though some others can smash them...You can forbid doors to keep (most) hostile humanoids and creatures out, and your dwarves in."
Doors should stop ordinary goblin thieves and most "ordinary" creatures, like mandrills.
Creatures that can break down a door are going to be more interested in smashing than stealing.
EDIT: The comment is correct. This article clarifies that goblin snatchers can, in fact, bypass locked doors, but not floodgates, or anything similar that's secured with mechanisms and lever. Animal thieves are stopped by locked doors.
Comment: Actually I thought thieves and baby snatchers were not stopped by doors.  That's why you want to chain two war dogs inside your doors.
Comment: do note that you can control doors with levers too, which gives them the same features and disadvanages as a floodgate.

Does a forbidden door stop thieves?


Find out in what position my thread landed in a ReentrantLock

Question:
I want to find out in which position of the LockinQueue of a ReentrantLock my Thread landed in? is there some magic lock which returns the position in the queue when calling lock.lock()? Or does anyone know how to realize that?
Thanks in advance
Thomas
Answer: @toto has pointed out to me that it does provide an estimate using getQueueLength().  You could take the length before or after acquiring the lock depending why you want to know the length.
The queue is lock less so whatever the position was, it could be incorrect by the time the value has been estimated, never mind by the time the method has returned. Generally you are not interesting in the position as you should structure your code so it is rarely waiting for the lock.
Perhaps you could indicate why you are interested....
Comment: `ReentrantLock.getQueueLength()` "Returns an _estimate_ of the number of threads waiting to acquire this lock."