text:
Q: Auto-Open Accordion When Visible On Screen I'm trying to enhance the visual impact of a JS accordion by enabling each accordion item to Auto-open as the user scrolls down the page. They do not need to auto-close.
The accordion I am using performs 2 Actions when 'Clicked':

*

*Accordion parent 'div' Element: class .is-open is applied

*Accordion child 'div' Content:
 a.) Attributes removed aria-hidden="true" & hidden
 b.) Attributes applied aria-hidden="false"
How can I accomplish coercing these two actions to fire on Scroll / is Visible, rather than on Click?
My JS knowledge is limited. I cannot arbitrarily write JS, but can understand and manipulate it.

SEMI-WORKING CONCEPT (based on sticky header) – It does execute, but is not the proper way to achieve the desired result.

    jQuery(function($) {
      var acdn = $(".bdt-accordion-item");
        $(window).scroll(function() {
            var scroll = $(window).scrollTop();

            if (scroll >= 50) {
                acdn.addClass("bdt-open");
            } else {
                acdn.removeClass("bdt-open");
            }
        });
    });

    jQuery(function($) {
      var con = $(".bdt-accordion-content");
        $(window).scroll(function() {
            var scroll = $(window).scrollTop();

            if (scroll >= 50) {
                document.getElementsByClassName("bdt-accordion-content")[0].setAttribute("aria-hidden", "false");
                document.getElementsByClassName("bdt-accordion-content")[0].removeAttribute("hidden");
            } else {
                document.getElementsByClassName("bdt-accordion-content")[0].setAttribute("aria-hidden", "true");
                document.getElementsByClassName("bdt-accordion-content")[0].setAttribute("hidden");
            }
        });
    });

A: This worked. Please feel free to suggest how to Clean it up.
<script type="text/javascript">
  jQuery(function($) {
  var acdn = $("#bdt-accordion-a189677 .bdt-accordion-item");
    $(window).scroll(function() {
    var scroll = $(window).scrollTop();

    if (scroll >= 400) {
        acdn.addClass("bdt-open");
    } else {
        acdn.removeClass("bdt-open");
    }
});
});

jQuery(function($) {
   var con = $("#bdt-accordion-a189677 .bdt-accordion-content");
   $(window).scroll(function() {
    var scroll = $(window).scrollTop();

    if (scroll >= 400) {
        document.getElementsByClassName("bdt-accordion-content")[0].setAttribute("aria-hidden", "false");
        $('#bdt-accordion-a189677 .bdt-accordion-content').attr("hidden",false);
        con.addClass("animated");
        con.addClass("fadeIn");
    } else {
        document.getElementsByClassName("bdt-accordion-content")[0].setAttribute("aria-hidden", "true");
        $('#bdt-accordion-a189677 .bdt-accordion-content').attr("hidden",true);
        con.removeClass("animated");
        con.removeClass("fadeIn");
    }
});
});


text:
Q: Is there a better way to smoothen this curve with python? I want to smoothen the oscillations from this data and let only the higher values stay in the curve. I have written a code for that and it seems to work. However, it feels like a fix rather than a solution. I was wondering if there is a more proper way to smoothen this curve and choose only the higher values in the oscillations stay?
here you can see the code and the results.
def smoothingfunction(xarr, yarr):

import numpy as np

#x0_42, y0_42

New_y = np.zeros(0)
New_x = np.zeros(0)

for i in np.arange(15, len(yarr[15:]), 1):
    if yarr[i]>yarr[i-1] and yarr[i]>yarr[i-2] and yarr[i]>yarr[i-3] and yarr[i]>yarr[i-4] and yarr[i]>yarr[i-5] and yarr[i]>yarr[i-6]:

        New_y = np.append(New_y, yarr[i])
        New_x = np.append(New_x, xarr[i])

return  np.concatenate((xarr[0:15], New_x)) , np.concatenate((yarr[0:15],New_y))

Sx0_4nous1, Sy0_4nous1 = smoothingfunction(x0_4nous1, y0_4nous1)

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to create particular animation Hi i have a question about shapes and animation of the shapes.
I would like to understand what is the best practice to create these kind of shapes (shapes that are presented on images around buttons).
Previous investigation shows that usage of the UIBezierPathis required but I am interest in how to create this kind of path and constantly animate it? Or probably should i use SpriteKit for that?

A: I think Spritekit is not necessary. You make this kind of animation just by acting on the CALayer masks.
If you writing a series of masks based each time on a different ellipse ( and build an animations based on it), you can re-produce this effect in your button.
Some useful code examples:
var shape = CAShapeLayer()
shape.fillColor = UIColor(white: 0.90, alpha: 1).CGColor
var image = UIImage(named: "some_image")
shape.contents = image?.CGImage

var ovalPath = UIBezierPath(ovalInRect: CGRectMake(160, 160, 240, 320))


text:
Q: How to use calibration parameters from KITTI? I'm working on stereo vision and I am using data from The KITTI Vision Benchmark Suite, The calibration parameters they use are very different from the parameters that the stereo camera calibrator toolbox produce and I couldn't find a way to use their data in MATLAB.
I also tried to use their calibration images in stereo camera calibrator toolbox which looks like this:
Calibration Toolbox MATLAB
But when I run the calibration it fails saying
Calibration fails:

unable to estimate camera parameters. images may contain severe less
  distortion or the 3-D orientations of the calibration pattern are too
  similar across images, if calibration pattern orientations are too
  similar, try removing very similar images or adding additional images
  with pattern in invalid orientations

Please help me if you have any idea on how to solve this


text:
Q: Computing norms of polynomials of operator in Hilbert space and generalized von Neumann inequality Let $T$ be an operator $l^2({\mathbb{Z}_{\geq 0}}) \to l^2({\mathbb{Z}_{\geq 0}})$, $e_n \mapsto \sqrt{1 - q^{2(n+1)}}e_{n+1}  $, where $0<q<1$. I want to compute $\|f(T,T^{*}) \|$  (operator norm) for any $f \in \mathbb{C} [z,  \bar z]$. Operator $T^{*}$, of course, is the Hilbert conjugate and $T^{*}e_0 = 0$, $T^{*}e_n = \sqrt{1-q^{2n}}e_{n-1}$ for $n >0$.
I am not sure if that computation even possible and I would be happy just to show that $\|f(T,T^{*})\| \to \sup\limits_{|z| \leq 1} f(z, \bar z)$ as $q$ goes to 1 because it is actually why I need to compute norms in the first place.
I think that there is some generalization of the von Neumann inequality like $q$-analogue  or something (there are a lot of generalizations) because the usual inequality proves this for polynomials  $g \in \mathbb{C}[z]$ (without $\bar z$).
Question: does anyone know some useful facts or inequalities related to my question? Something that might help.


text:
Q: What is a word to describe a graduate with the highest graduation score? If you happen to come on top of all your university colleagues in terms of your overall grades, what would you be called? Is there a word for "the first among his class" especially a class that has graduated from university?

A: I don't know of a specific word, but idiomatically, we often say "he was first in his class."
It's also usually (although not always) true that the first-in-class receives the title of valedictorian.

A: In the U.S. and Canada, at least, the highest ranked graduate was traditionally granted the honor of giving the valediction (i.e. farewell address) at the commencement exercises, and thus the student with the highest grade point (or whatever other mechanism is used to rank the students) became known as the valedictorian. The second-ranked graduate was given the honor of giving the salutation (i.e. greeting address) at commencement, and thus became known as the salutatorian.
I think nowadays the salutatory address is rare, and the valedictory is not necessarily made or made by the top-ranked student. For one, by educational philosophy, many want to de-emphasize scores as the sole measure of one's scholarship. For another, because of hypercompetitiveness or grade inflation depending on your social outlook, the local high school where I grew up once recorded no fewer than 16 graduates tied for #1. They had received perfect scores in the honors track in all classes. Suffice to say, there was no room in the commencement program for 16 speeches to be given.
Moreover, class rank, while still prominent in secondary education, is not commonly calculated at the university level; diplomas with distinction may be classed as summa cum laude (or with highest honors), magna cum laude (or with high honors), and/or cum laude ( with honors) in some programs at some institutions, but the criteria vary and such distinctions are not made everywhere.
I do not believe either set of terminology has much use in the rest of the Anglophone world. More generically, you may say someone was ranked first in her class or that she was top-ranked.


text:
Q: Minimal polynomial and directsum of vector spaces $T_1,T_2$ be linear maps on $V$ and $W$ respectively which are finite dimensional vector space over Reals with minimal polynomials respectively $x^3+x^2+x+1,x^4-x^2-2$, let $T:V\bigoplus W\to V\bigoplus W, T(v_1,v_2)=(T_1(v_1),T_2(v_2))$ and let $f$ be the minpoly then
$1. \text{ Deg}(f)=7$
$2. \text{ Deg}(f)=5$
$3. \text{ Nul}(T)=0$
$4. \text{ Nul}(T)=1$
Could anyone help me to solve this one? Guess: Minpoly for $T$ will be lcm of minpoly of $T_1,T_2$?

A: For sure it will be the LCM because the matrix of $T$ in a suitable basis will be of the block form $\begin{pmatrix}A&0\\0&B\end{pmatrix}$
As a consequence, a polynomial $p$ annihilates $T$, iff it annihilates $T_1$ as well as $T_2$ iff the minimal polynomial of $T_1$ and that of $T_2$ both divide $p$.
So get the degree!


text:
Q: Subscription status not called for auto renewable subscription in iOS I am facing issues with my auto-renewing subscription for an iOS app that offers auto-renewable subscription.
The Subscription Status URL is at times, not being called when the subscription is renewed. This is making it difficult for us to track the user's subscription status. Funnily, this behaviour is completely arbitrary at times it is called and everything works smoothly, but at times it is not called at all.
Also, once the user's subscription is renewed, at times the user is not charged on his/her credit card instantly. Is this behaviour normal?

A: You have to follow basic rules for subscription based application.

*

*Whenever you buy any auto renew subscription, in success verify your receipt and verify expiry date.

*On every application launch very receipt and verify subscription. On depending result you can notify your server.

In sandbox environment for monthly subscription it will auto renew for every 5 mins. It will auto renew for 5 times. So you can check your test cases. After that it will be expire.
In real world case subscription will auto renew before 24 hours of renew date. So if user cancels subscription before that.
If you are using SwiftyStorekit than it will be very much easy for you to handle each and every steps. Let me know you if you want more coding approach in this case.I will share example code details if you want.

A: The Subscription Notifications are pretty unreliable and the descriptions of how they work aren't very clear. For example:

RENEWAL events aren't sent when a subscription renews. ... RENEWAL
  is sent when a subscription has expired, then later, the user starts
  the subscription again.
CANCEL does not mean a user normally cancelled their subscription. It only is sent when a user cancels their subscription via customer
  support. This is also known colloquially as a refund.

Source: RevenueCat (Disclaimer: I work there)


text:
Q: Dynamically generated generic type not working properly the following code works without any issue:
 Dim SubmodelElement = New BaSyx.Models.Core.AssetAdministrationShell.Implementations.SubmodelElementTypes.[Property](Of Double)() With {
                .IdShort = "TestProperty1",
                .[Set] = Function(prop, val)
                             Return _test = val
                         End Function
        }
    SubmodelElement.[Get] = Function(prop)
                                Return 4711
                            End Function

What I am trying to do is to create those submodel elements dynamically for each property of my class with the following code:
For Each Eigenschaft As PropertyInfo In Me.GetType().GetProperties()
            If Eigenschaft.CanRead = True Then
                Dim Eigenschaftstyp As Type = Type.GetType(Eigenschaft.PropertyType.FullName)

                Dim GenerischerTypBasysProperty As Type = GetType(BaSyx.Models.Core.AssetAdministrationShell.Implementations.SubmodelElementTypes.Property(Of)).MakeGenericType(Eigenschaftstyp)
                Dim BasysEigenschaft = Activator.CreateInstance(GenerischerTypBasysProperty)

                BasysEigenschaft.IdShort = Eigenschaft.Name
                BasysEigenschaft.[Get] = Function(prop)
                                             'Return Eigenschaft.GetValue(Me)
                                             Return 4711
                                         End Function
                BasysEigenschaft.Set = Sub(ByVal Prop, ByVal Wert)
                                           Eigenschaft.SetValue(Me, Wert)
                                       End Sub
                MyBase.SubmodelElements.Add(BasysEigenschaft)
            End If
        Next

As seen in the debugger both objects (SubmodelElement and BasysEigenschaft are of same type).
screenshot of values of submodelElement and BasysEigenschaft
Unfortunally the assigning of the [Get]-function, doesnt work in the second code snipet. I get this error
System.InvalidCastException: "Method invocation failed because 'Public Overrides Property Get() As BaSyx.Models.Core.AssetAdministrationShell.Generics.SubmodelElementTypes.GetPropertyValueHandler(Of Double)' cannot be called with these arguments:
Argument matching parameter 'value' cannot convert from 'VB$AnonymousDelegate_0(Of Object,Integer)' to 'GetPropertyValueHandler(Of Double)'."
screenshot of error message
Any help will be greatly appreciated

A: I discussed the issue with the creator of the SubmodelElemenntTypes.Property -Class.
Like Craig suggested Activator.CreateInstance-method does not create the type exactly as the new Property (of T) constructor. The following lines solve the problems.
        For Each Eigenschaft As PropertyInfo In Me.GetType().GetProperties()

        If Eigenschaft.GetCustomAttributes(Of BasysPropertyAttribute).Count > 0 Then

            If Eigenschaft.CanRead = True Then

                If Eigenschaft.CanRead = True Then
                    Dim Eigenschaftstyp As Type = Type.GetType(Eigenschaft.PropertyType.FullName)

                    Dim BasysDataTypeXsd As DataType = DataType.GetDataTypeFromSystemType(Eigenschaftstyp)
                    Dim BasysEigenschaft As BaSyx.Models.Core.AssetAdministrationShell.Implementations.SubmodelElementTypes.Property = DirectCast(SubmodelElementFactory.CreateSubmodelElement(ModelType.Property, BasysDataTypeXsd), BaSyx.Models.Core.AssetAdministrationShell.Implementations.SubmodelElementTypes.Property)

                    BasysEigenschaft.IdShort = Eigenschaft.Name
                    BasysEigenschaft.[Get] = Function(BasysProperty As Object)
                                                 Return New ElementValue(Eigenschaft.GetValue(Me), BasysDataTypeXsd)
                                             End Function
                    BasysEigenschaft.[Set] = Sub(ByVal BasysProperty As Object, ByVal Wert As ElementValue)
                                                 Eigenschaft.SetValue(Me, CTypeDynamic(TypeDescriptor.GetConverter(Eigenschaftstyp).ConvertFromString(Nothing, Globalization.CultureInfo.InvariantCulture, Wert.Value), Type.GetType(Eigenschaft.PropertyType.FullName)))
                                             End Sub
                    MyBase.SubmodelElements.Add(BasysEigenschaft)

                End If

            End If

        End If

    Next

Thanks to Craig for your help!


text:
Q: Where is Banach Lemma used? Banach's Lemma:
Let $C\in\mathbb R^{n\times n}$ with $|C|<1$, then $I+C$ is invertible and
$\dfrac{1}{1+|C|}<|(I+C)^{-1}|<\dfrac{1}{1-|C|}$
How can we prove it? And exactly i don't understand this lemma where can it be used?

A: Suppose $(C+I)x=0$ for some $x\in\mathbb R^n$. Then, $Cx = -x$. However, $\|C\|< 1$ implies $|Cx|<|x|$. Contradiction. Thus, $C+I$ is invertible.
Morevoer, $$\|(C+I)^{-1}(C+I)\| = 1\implies\|(C+I)^{-1}\|\ge \frac1{\|I+C\|}\ge \frac1{\|I\|+\|C\|}=\frac1{1+\|C\|}$$
Similarly, $(C+I)^{-1}C +(C+I)^{-1}= I$ implies
$$\|(C+I)^{-1}\|=\|I-(C+I)^{-1}C\|\le \|I\|+\|(C+I)^{-1}\|\|C\|\implies \|(C+I)^{-1}\|\le \frac1{1-\|C\|}$$


text:
Q: How to notify user caps lock is turned on within a password field in C#? I'm not a pro, but What i want in my Login panel (a windows form) which hass a pasword Text field,
I want to apply the same idea here, 'window Xp password text field had', in which if Caps lock is on, a small String gets to Popup saying CAPSLOCK is On, `
private void txtPass_TextChanged(object sender, EventArgs e)
    {
        txtPass.PasswordChar= '*' ;
    }

`
this is my Password button.

A: The magic happens in this line
 Application.EnableVisualStyles();

If this line is missing then you loose that functionality together with the flat appearance of many controls and so on.
The line should go before any attempt to create user interface objects and usually is present in the Main static method that starts your application
[STAThread]
static void Main()
{
     Application.EnableVisualStyles();
     Application.SetCompatibleTextRenderingDefault(false);
     Application.Run(new yourStartupForm());
}


text:
Q: Dispatching Custom Events From a Validator I have what should hopefully be a rather simple question for someone.  Basically I am trying to create a string Validator which requests a new language from its controller by dispatching an event upon its creation.
The example below is a straight copy from the Flex3 component explorer  - the only diffrence being that I have created the validator as a custom component which dispatches an event upon its creation.
The problem is that my main Application cannot hear the event being dispatched and I don't know why.
Here is the example
MyValidator.as
        package components
{
    import flash.events.Event;
    import mx.validators.StringValidator;

    /**
     * ...
     * @author Beaker
     */
    public class MyValidator extends StringValidator
    {

        public function MyValidator()
        {
            trace(">>MyValidator:MyValidator--")
            var _event:Event = new Event("getLanguage", true)
            dispatchEvent(_event)
        }

    }

}

Main.MXML
    <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" xmlns:comp="components.*" creationComplete="onComplete(event)">
     <mx:Script>
         <![CDATA[
                    import flash.events.Event;
                    import mx.controls.Alert;
                    protected function onComplete(evt:Event):void
                    {
                        trace(">>Main:onComplete--")
                        systemManager.addEventListener("getLanguage",onTest)
                    }
                    protected function onTest(evt:Event):void
                    {
                        trace(">>Main:onTest--")
                        Alert.show("getLanguage");
                    }
         ]]>

    </mx:Script>

    <comp:MyValidator source="{fname}"
        property="text"
        tooShortError="This string is shorter than the minimum allowed length of 4. "
        tooLongError="This string is longer than the maximum allowed length of 20."
        minLength="4" maxLength="20"
        trigger="{myButton}" triggerEvent="click"
        valid="Alert.show('Validation Succeeded!');"/>

    <mx:Panel title="StringValidator Example" width="75%" height="75%"
        paddingTop="10" paddingLeft="10" paddingRight="10" paddingBottom="10">

            <mx:Form>
                <mx:FormItem label="Enter a name between 4 and 20 characters: ">
                    <mx:TextInput id="fname" width="100%"/>
                </mx:FormItem>

                <mx:FormItem >
                    <mx:Button id="myButton" label="Validate" />
                </mx:FormItem>
            </mx:Form>
    </mx:Panel>

</mx:Application>

Pardon the formatting if this isnt showing up correctly!

A: Your MyValidator is not DisplayObject, so its events do not bubble. You should add listeners directly to MyValidator instance.
Variant #1:
<comp:MyValidator source="{fname}"
        property="text"
        id="validator"
        tooShortError="This string is shorter than the minimum allowed length of 4. "
        tooLongError="This string is longer than the maximum allowed length of 20."
        minLength="4" maxLength="20"
        trigger="{myButton}" triggerEvent="click"
        valid="Alert.show('Validation Succeeded!');"/>

and
validator.addEventListener("getLanguage", onTest);

Variant #2:
In MyValidator.as add the following metadata before class declaration:
[Event(name="getLanguage", type="flash.events.Event")]

and usage:
<comp:MyValidator source="{fname}"
        property="text"
        getLanguage="onTest(event)"
        tooShortError="This string is shorter than the minimum allowed length of 4. "
        tooLongError="This string is longer than the maximum allowed length of 20."
        minLength="4" maxLength="20"
        trigger="{myButton}" triggerEvent="click"
        valid="Alert.show('Validation Succeeded!');"/>


text: Q: How does Truecaller open webpage on uninstall? I installed TrueCaller today and after uninstall was complete, my chrome opened with a wufoo form to collect feedback. I did not know such a thing was possible! How can I do the same ?


text:
Q: Setup mail server in Docker with FreeIPA and Roundcube I try to setup my own mail server with authentication against a Ldap(FreeIPA). All of them must running within a docker container. I don't know what I'm doing wrong. Maybe it's my ldap configuration.
version: '3.9'

services:
  freeipa:
    image: freeipa/freeipa-server:centos-9-stream-4.10.0
    container_name: ipa
    restart: unless-stopped
    tty: true
    stdin_open: true
    hostname: ipa
    domainname: ipa.example.local
    #read_only: true
    networks:
      priv_network:
        ipv4_address: 172.16.1.10
    extra_hosts:
      - "ipa.example.local:172.16.1.10"
    environment:
      - IPA_SERVER_HOSTNAME=ipa.example.local
      - IPA_SERVER_IP=172.16.1.10
      - TZ=Europe/Berlin
    command:
      - --realm=example.local
      - --domain=example.local
      - --ds-password=secret123
      - --admin-password=secret123
      - --no-host-dns
      - --setup-dns
      - --auto-forwarders
      - --allow-zone-overlap
      - --no-dnssec-validation
      - --unattended
      - --skip-mem-check
      - --auto-forwarders
      - --auto-reverse
    sysctls:
      - net.ipv6.conf.all.disable_ipv6=0
      - net.ipv6.conf.lo.disable_ipv6=0
    volumes:
      - ./vol/freeipa/data:/data
      - ./vol/freeipa/logs:/var/logs
      - ./vol/freeipa/config:/root/pw-portal/config
      - /sys/fs/cgroup:/sys/fs/cgroup:ro
    tmpfs:
      - /run
      - /var/cache
      - /tmp
    cap_add:
      - SYS_TIME
      - NET_ADMIN
    ports:
      - 443:443
      - 389:389

  roundcubemail:
    image: roundcube/roundcubemail:latest
    container_name: roundcubemail
    volumes:
      - ./vol/roundcube/www:/var/www/html
      - ./vol/roundcube/db/sqlite:/var/roundcube/db
    ports:
      - 9002:80
    environment:
      - ROUNDCUBEMAIL_DB_TYPE=sqlite
      - ROUNDCUBEMAIL_SKIN=elastic
      - ROUNDCUBEMAIL_DEFAULT_HOST=tls://172.16.1.11
      - ROUNDCUBEMAIL_SMTP_SERVER=tls://172.16.1.11
    networks:
      priv_network:

  mailserver:
    image: docker.io/mailserver/docker-mailserver:latest
    container_name: mailserver
    hostname: mail
    domainname: mail.example.local
    restart: unless-stopped
    volumes:
      - ./vol/mailserver/data/:/var/mail/
      - ./vol/mailserver/state/:/var/mail-state/
      - ./vol/mailserver/logs/:/var/log/mail/
      - ./vol/mailserver/config/:/tmp/docker-mailserver/
      - /etc/localtime:/etc/localtime:ro

    environment:
      - ENABLE_SPAMASSASSIN=0
      - ENABLE_CLAMAV=0
      - ENABLE_FAIL2BAN=0
      - ENABLE_POSTGREY=0
      - ACCOUNT_PROVISIONER=LDAP
      - LDAP_SERVER_HOST=ldap://ipa
      - LDAP_BIND_DN=uid=admin,cn=users,cn=accounts,dc=example,dc=local
      - LDAP_BIND_PW=secret123
      - LDAP_SEARCH_BASE=cn=users,cn=accounts,dc=example,dc=local
      - LDAP_QUERY_FILTER_DOMAIN=(mail=*@%s)
      - LDAP_QUERY_FILTER_USER=(mail=%U@%s)
      - LDAP_QUERY_FILTER_ALIAS=(|) # doesn't match anything
      - LDAP_QUERY_FILTER_GROUP=(|) # doesn't match anything
      - LDAP_QUERY_FILTER_SENDERS=(mail=%s)
      - SPOOF_PROTECTION=1
      - ENABLE_SASLAUTHD=1
      - SASLAUTHD_MECHANISMS=ldap
      - SASLAUTHD_LDAP_FILTER=(&(mail=%U@example.local)(objectClass=inetOrgPerson))
      - ONE_DIR=1
      - PERMIT_DOCKER=host
      - DOVECOT_USER_FILTER=(&(objectClass=inetOrgPerson)(mail=%u))
      - DOVECOT_PASS_ATTRS==password=%{ldap:userPassword},=user=%{ldap:uid}
      - DOVECOT_USER_ATTRS==home=/var/mail/%{ldap:uid},=mail=maildir:~/Maildir,uidNumber=uid,gidNumber=gid
    cap_add:
      - NET_ADMIN
    networks:
      priv_network:
        ipv4_address: 172.16.1.11

networks:
  priv_network:
    name: ext_priv_network
    driver: bridge
    ipam:
      driver: default
      config:
        - subnet: 172.16.1.0/24
          gateway: 172.16.1.1

I created an user and logged into IPA for the first time to set password. If I try to login into my Roundcube then I get just a login failure. The Mail Server printed the following message.
Dec 25 08:59:52 mail dovecot: auth: ldap(test.user,172.16.1.2,<m+/uPaPw4pasEAEC>): unknown user (SHA1 of given password: f2b14f)
Dec 25 08:59:54 mail dovecot: imap-login: Disconnected (auth failed, 1 attempts in 2 secs): user=<test.user>, method=PLAIN, rip=172.16.1.2, lip=172.16.1.11, session=<m+/uPaPw4pasEAEC>
Dec 25 09:00:39 mail postfix/pickup[1906]: 517F864B0E: uid=101 from=<root>
Dec 25 09:00:39 mail postfix/cleanup[1910]: 517F864B0E: message-id=<20221225090039.517F864B0E@mail.mail.example.local>
Dec 25 09:00:39 mail postfix/cleanup[1910]: warning: dict_ldap_lookup: Search error 2: Protocol error
Dec 25 09:00:39 mail postfix/cleanup[1910]: warning: ldap:/etc/postfix/ldap-aliases.cf lookup error for "postmaster@mail.example.local"
Dec 25 09:00:39 mail postfix/cleanup[1910]: warning: 517F864B0E: virtual_alias_maps map lookup problem for postmaster@mail.example.local -- message not accepted, try again later
Dec 25 09:00:39 mail postfix/pickup[1906]: 5228D64B0E: uid=0 from=<root>
Dec 25 09:00:39 mail postfix/cleanup[1923]: 5228D64B0E: message-id=<20221225090039.5228D64B0E@mail.mail.example.local>
Dec 25 09:00:39 mail postfix/cleanup[1923]: warning: dict_ldap_lookup: Search error 2: Protocol error
Dec 25 09:00:39 mail postfix/cleanup[1923]: warning: ldap:/etc/postfix/ldap-aliases.cf lookup error for "postmaster@mail.example.local"

What's the correct LDAP Syntax for Dovecot DOVECOT_USER_FILTER, DOVECOT_PASS_ATTRS and DOVECOT_USER_ATTRS?


text:
Q: Automating Configuration of VMware's vSwitch (OpenStack/libvirt/Nova) There's a lot of talk now about VMware integrating with OpenStack now.
I've noticed that Nova network service is working with VMware's standard and vDS.
Deploying a full OpenStack instance is not currently viable in our environment, but we would like to use whatever technology they are for Standard vSwitch automation. I can't find any way to do this with libvirt other than using Open vSwitch which is not ideal for our existing setups.
Currently we're controlling vSphere standard network switches using VMware's virtual machine assistant (vMA) but would like to move to a technology that is more platform independent.
So I was wondering if anyone knows what tool/API Nova is using to automate VMware's vSwitches. Does anyone have an idea?

A: It can be done through PowerCLI (VMwares Powershell extension), see the following command reference;
https://pubs.vmware.com/vsphere-51/topic/com.vmware.powercli.cmdletref.doc/Set-VirtualSwitch.html


text:
Q: Duplicate identifier when declaring types with same name in different files I have a simple TypeScript 'snippets' project, and I've run into an issue where multiple .ts files will have the same type names (eg. Foo).
//file-a.ts

type Foo = {

}

//file-b.ts

type Foo = {

}

If I try compile this I get:
 error TS2300: Duplicate identifier 'Foo'.

This doesn't make sense to me - as these typings should be specific to the module.
I'm using typescript version 3.7.5, and my tsconfig.json has these properties (everything else defaults):
{
  "compilerOptions": {
    "target": "es5",                          /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019' or 'ESNEXT'. */
    "module": "commonjs",                     /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'. */
    "outDir": "./dist",                        /* Redirect output structure to the directory. */
    "rootDir": "./src",                       /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */
    "isolatedModules": true,               /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */
    "strict": true,                           /* Enable all strict type-checking options. */
    "esModuleInterop": true,                  /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */
    "forceConsistentCasingInFileNames": true  /* Disallow inconsistently-cased references to the same file. */
  }
}

What's going on here here? The actual code here.

A: Since 4.7 TypeScript has a configuration option for this: the compiler option moduleDetection can be set to "force", which

ensures that every non-declaration file is treated as a module.

This will treat all inputs as modules (even if they contain no import or export statement).

A: If you do not export anything from a TypeScript file, it gets compiled in the global scope. To make a .ts file an enclosed module you need to export at least one thing.


text:
Q: Mail showing wrong submitted message I have setup a CF7 form with some CSS customization for theme as shown below:

        Your Name
        [text* your-name id:your-name class:input class:et_pb_contact_name class:chewy_input placeholder "Name"]

        Your Email
        [text* your-email id:your-email class:input class:et_pb_contact_email class:chewy_input placeholder "Email"]

        Mobile No.
        [text* phone id:phone class:input class:et_pb_contact_name class:chewy_input placeholder "Mobile No."]

    Question One:

Lorem ipsum dolor sit amet, consectetuer adipiscing elit.

    [textarea* question-1 id:question-1 class:et_pb_contact_message class:input class:chewy_textarea placeholder "Answer Question One Here"]

    Question Two:

Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor?

    [textarea* question-2 id:question-2 class:et_pb_contact_message class:input class:chewy_textarea placeholder "Answer Question Two Here"]

[submit class:chewy_pb_contact_submit "Submit"]

My mail's message body is:
From: [your-name] <[your-email]>
Mobile: [phone]

Answer to Question One:
[question-1]

Answer to Question Two:
[question-2]

The problem is, in my mail, instead of the submitted text in [question-1] and [question-2] fields by the user, the paragraph texts written under the question 1 and question 2 labels are showing. Example:

From: Example
  Mobile: 01770000000
Answer to Question One:
  Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor?
Question Two:
Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor?
Answer to Question Two:
  Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor?

Can anyone tell me what I am doing wrong?
Thanks


text:
Q: Testing sidekiq worker using rspec-sidekiq not working This is my test code:
require 'rails_helper'

describe CookCookieWorker do
  let(:user) { FactoryGirl.create(:user) }
  let(:oven) { user.ovens.first }

  it { is_expected.to be_processed_in :cookies }

  it 'enqueues the cook cookies worker to be processed in 5 seconds' do
    oven.cookies.create!({ fillings: 'Vanilla' })
    cookie = oven.cookies.last

    expect(CookCookieWorker).to have_enqueued_sidekiq_job(cookie.id).in(5.seconds)
  end
end

And this is the result I get
expected to have an enqueued CookCookieWorker job
         arguments: [1]
         options: {"in"=>5 seconds}
       found
         arguments: []
         options: []

Just to clarify, I have an after_save callback in the Cookie model that calls the worker this way:
CookCookieWorker.perform_in(5.seconds, id)
at the beginning I thought that probably I could not test the worker this way, probably the model callbacks doesn't have effect? However I tried to manually call the worker in the test:
require 'rails_helper'

describe CookCookieWorker do
  let(:user) { FactoryGirl.create(:user) }
  let(:oven) { user.ovens.first }

  it { is_expected.to be_processed_in :cookies }

  it 'enqueues the cook cookies worker to be processed in 5 seconds' do
    oven.cookies.create!({ fillings: 'Vanilla' })
    cookie = oven.cookies.last

    CookCookieWorker.perform_in(5.seconds, cookie.id) # Calling it manually
    expect(CookCookieWorker).to have_enqueued_sidekiq_job(cookie.id).in(5.seconds)
  end
end

But I get the same result, the test fails. Any idea?


text:
Q: I am trying to write a code for fahrenheit to celcius using functions in c I am trying to use a function to convert from Fahrenheit to Celsius. I wish to know where I made a mistake.
#include <stdio.h>

void degrees_Fto_C(float f){
    float c;
    c=(5/9)*(f–(32));
    printf("%f",c);
}

int main(){
    float temp;
    printf("Enter the temperature in Fahrenheit: \n");
    scanf("%f",&temp);
    degrees_Fto_C(temp);
    return 0;
}

The error message is:
C:\Users\Pranavs\Desktop\Untitled1.cpp  In function 'void degrees_Fto_C(float)':
C:\Users\Pranavs\Desktop\Untitled1.cpp  [Error] 'f' cannot be used as a function

A: You have the wrong character after the f in line 4. c=(5/9)*(f–(32)) needs to be c=(5.0/9) * (f-(32)).  Your minus sign is a unicode character, and you need ASCII. If you backspace it and replace it with a normal minus sign, it will compile.
Also, you're doing integer arithmetic, and you'll always get zero.  It will work better if you add a decimal point after the 5 or the 9.
Here's a working version of your program:
#include <stdio.h>
void degrees_Fto_C(float f) {
    float c;
    c = (5.0 / 9) * (f - (32));
    printf("%f", c);
}
int main() {
    float temp;
    printf("Enter the temperature in Fahrenheit: \n");
    scanf("%f", &temp);
    degrees_Fto_C(temp);
    return 0;
}


text:
Q: C# - How to pass string from WebBrowser back into a form How can I read string from WebBrowser form into another form using C#?

A: You can use the DOM. For example, if your WebBrowser shows a page with the following markup:
<div id="t">
    ....
</div>

You can receive its text just like you're doing it in JavaScript:
webBrowser.Document.GetElementById("t").InnerText


text:
Q: How to change the pandas dataframe 'unnamed 0' column datatype from int64 to string or object I am working on small project where i am trying to send the pandas dataframe to mysql database.
My Dataframe contain default unnamed column which I want to send on mysql server. My sql schema contain id column with varchar(255) datatype.
create table users_sample(
    id varchar(255) NOT NULL PRIMARY KEY,
    #other_columns)

when i try to send the code on server i am getting the below errror

sqlalchemy.exc.OperationalError: (pymysql.err.OperationalError) (1364,
"Field 'id' doesn't have a default value")

When i serach for the solution it was suggesting that to change the datatype from varchar to int and put auto_increment constraint.
plz provide the solution.
Thanks in advance.

A: maybe help you
d1[['colname']] = d1[['colname']].astype(float)


text:
Q: How do I get a particular (older) version of a file from git repository without wiping out later versions? I should think that getting a previous version is one of source control's premier features, and should be simple, yet it seems like a treasure hunt finding git solution.
I came across stackoverflow question How can I check out a particular version of one file in Git?.  To paraphrase the key thing:
git checkout <commit hash from git log output>

As I expected it to happen, the file in the working directory was replaced/updated with the requested older version, but I lost the later versions in the repository, got a message like "... detached head...".
Any guiding principles here would be appreciated.  Thanks.

A: If you have a special commit like abc123456 and in that commit the file was good, you just need to ...
git checkout abc123456 path/to/file

with this command you will find in stage that version of the file.
You can also use branches:
git checkout old-branch-name path/to/file

A: When you just use git checkout <somehash>, then you will get into a detached HEAD. This happens because git checkout by default just switches branches, and specifying a commit instead of a branch gets you into a "branchless mode" (that's what detached HEAD means).
If you want to get a single file from a different version, you also need to specify the path, i.e. git checkout <somehash> -- path/to/file. This will keep everything as it is and just replace the file at path/to/file with its version from <somehash>.
So this does overwrite the file. If you want to keep the current version as well, you should rename it first. Otherwise, you can also use a special syntax of git show for this
git show <somehash>:path/to/file > new_filename.ext

This will essentially get the contents of the file from <somehash> and print it, so if you pipe it to file, you can extract a file from a different version into a different filename.


text:
Q: Lazy creation of auto variables inside C function I`m curious about such C code:
void test(int y){
   if (y) {
      int x = 1;
      printf("Test: %d", x + y);
   }
   // other important code (don`t use x var)
}

Necessity of x variable depends on y.
For instance: if we call test(0), we don't need to allocate space for x variable, for test(1) invocation x variable must exist in memory.
Does this kind of technique used by modern compilers?

A: A more likely optimization by the compiler is
void test(int y){
   if (y) {
      printf("Test: %d", 1 + y);
   }
   // other important code (don`t use x var)
}

and then we don't need x in either case.

A: As Sourav Ghosh says, "Nothing you can be certain of!", however, let me give some possibilities a compiler might use.
First, syntactically speaking, a variable in a block only is known within the block. Outside the block the compiler (language) has forgotten all about it. So you can use this block construct to have a temporary variable.
What can the compiler do?
Probably a compiler will calculate the maximum storage of all blocks (that is, the automatic variables declared upon function entry (function scope) plus the size of the largest block, plus the size of the largest nested block,... etc.) and allocate that amount on the stack. When a block is exited, the compiler knows its variables do not exist anymore and can re-use that space (on the stack) for any following block. In Fortran this is called an overlay and it is comparible to a union in C.
Equally posible, a compiler might allocate new space on the stack (e.g. sub sp, 12) upon entering a block, and release it upon leaving the block (e.g. add sp, 12).
And there may be other strategies that I don't know of.

A: What the compiler does will vary based on optimization level but one would expect at the highest optimization level a modern compiler would do everything in registers with x being constant folded away since it is a constant 1 and we can see from this godbolt session gcc does just that:
test:
    testl   %edi, %edi
    jne .L4
    rep ret
.L4:
    leal    1(%rdi), %esi
    xorl    %eax, %eax
    movl    $.LC0, %edi
    jmp printf

at the lowest optimization level we don't expect anything clever and in this case gcc allocates for both x and y without checking if x is actually required:
subq    $32, %rsp


text:
Q: PHP Syntax for webpage radio buttons Currently I have the following table in my database
|AnswerID|QuestionID|AnswerText|
|21|2|User|
|22|2|Admin|
|23|2|Guest|
|24|2|User2|

and written the following php script
$questionID=0;
while ($list = mysql_fetch_assoc($result))
{
echo $list['QuestionID'] . ":" . $list['QuestionText'] . "
";
$questionID=$list['QuestionID'];
}
$optionsquery="SELECT AnswerText,AnswerID FROM Options Where QuestionID=".$questionID;
$optionsresult=mysql_query($optionsquery) or die ('Query failed:'. mysql_error());
while($row = mysql_fetch_array($optionsresult))
{
  'Display the multiple choices
   associating the AnswerID with the appropriate AnswerText.'

   E.g. echo "<input type='radio' name='QuestionID'
              value='AnswerID'/>"
              corresponding AnswerText given the AnswerID;

   E.g for the first radio button:

   echo "<input type='radio' name='2' value='21'/> User;

}

Could I get help with the PHP syntax for the radio buttons?

A: You could do:
echo "<input type='radio' id='radio-" . $row["QuestionID"] . "-" . $row["AnswerID"] . "' name='" . $row["QuestionID"] . "' value='" . $row["AnswerID"] . "' /> " . $row["AnswerText"] ."
";


text:
Q: How to circumvent SSL/TLS trust validation failure in C# c lient code? I have written a C# client to make a multipart-form data post to a server on the internet. While testing my code, I started getting exceptions as follows:
{System.Net.WebException: The underlying connection was closed: Could not establish trust relationship for the SSL/TLS secure channel. ---> System.Security.Authentication.AuthenticationException: The remote certificate is invalid according to the validation procedure.
I tried accessing the web resource using my browser and realized that there is an issue with the SSL certificate of the website. The website is owned by a third part and I don't know when they will fix this problem.
Is there any way I can ignore this security exception and make some change in my code so that it keeps working?
I am using the HttpWebRequest class to perform http posts.

A: At the crudest level:
ServicePointManager.ServerCertificateValidationCallback = delegate
     { return true; }; // WARNING: accepts all SSL certificates

You should probably be a bit more granular though, looking at the certificate/chain a bit.


text:
Q: Is Visualization of Data a Subject of Mathematical Research? Please excuse my naive question, but what kind of rôle does the visualization of (especially high-dimensional) data play in mathematical research?
I know, that it plays an important rôle in the analysis and interpretation of data and utilizes advanced mathematics, but, apart from being a servant to mathematical research, are there also examples, where mathematical research is solely dedicated to data-visualisation or, where data-visualisation brought up questions, that initiated important mathematical research?
A prominent example of mathematical research that has been initiated by data visualisation is Guthries observation, that apparently four colors suffice to color every map; hat observation had very fruitful consequences for mathematics.

Questions:

*

*what are further examples of problems that originated in data-visualization and became the subject of mathematical research?

*are there examples of mathematical research, that is dedicated to improving the visualization of data, i.e. to make features of interest, that are "burried" in the data, more "prominent"?

A: This is a rather open-ended question, so let me respond by offering some observations in the same spirit, focusing primarily on posets, graphs and simplicial complexes.
In a very general way, graphs and digraphs are used throughout mathematics to represent relations and other structures with metric, topological and enumerative-combinatorial properties, such as the diameter, connectedness and the number of subgraphs with prescribed properties reflecting some of the deeper or less obvious features of the represented structure. (These relations may originate from a mathematical model or be innate to a mathematical theory.) Advanced examples along these lines are provided by the order complexes of posets and Stanley-Reisner complexes of square-free ideals, where the complex both visualizes the underlying structure and brings forth its important features. In a different direction, diagrams in category theory and quivers in algebra, including advanced constructions such as the Auslander-Reiten quiver, are types of visualizations.
Here is a specific illustration already firmly within mathematical setting. The notion of Hasse diagram of a partially ordered set provides an important visualization of this structure that has been used to study its properties. For example, it is easy to see that the diamond lattice $M_3$ and the pentagon lattice $N_5$ are not distributive. In fact, a lattice is distributive if and only if it does not contain a sublattice isomorphic to $M_3$ or $N_5$. On a more rudimentary level, the fundamental concepts such as maximal and minimal elements, chains and maximal chains of a poset can be thought of as visualizations. Some research directions in group and module theory deal with the structure of groups/modules based on their properties of their subgroup/submodule lattice and one can argue that, for example, uniserial modules (where all submodules form a single chain) first became objects of interest because of this visualization aspect. Later, the success of this theory motivated investigating more complicated cases.
Finally, going beyond combinatorial and algebgraic structures, configuration spaces and moduli spaces of all kinds fit into a visualization paradigm: they "visualize" the totality of objects or "states of a system" and can be used to study generic or typical properties, statistics and often dynamics (when the configuration or moduli space arises from geometry).


text:
Q: Angular file-upload scope is getting undefined here is directive.
 app.directive("fileInput", function($parse){
  return{
       link: function($scope, element, attrs){
            element.on("change", function(event){
                 var files = event.target.files;
                 $parse(attrs.fileInput).assign($scope, element[0].files);
                console.log(element[0].files);//this shows file
                 $scope.$apply();
            });
       }
  }
});

HTML part:
<input class="inputFile"  type="file" id="files" file-input="files">
<button type="button" ng-click="uploadFile();">Submit</button>

Controller function:
$scope.uploadFile = function(){
        console.log($scope.files);//this is undefined
        if(!$scope.files){
            alert("select file");//prog is getting stuck here
        }else{/*some code*/}

$scope and every dependency is defined is controller, still not getting file.
please tell me where i am doing wrong because same code is running in other modules.
uploadFile();

lies under some child controller..


text:
Q: cancel element drag by attribute I need to disable some elements from draging by their attribute. I do
$( ".main_table tbody" ).sortable({
    start: function(event, ui) {
        var level = ui.item.attr('level')
        $( ".main_table tbody" ).sortable("option", "cancel", '[level!='+level+']');
    }
});

But it: 1. applies cancel after stop; 2. applies cancel to all element. http://fiddle.jshell.net/vQL8h/ So I need to disable drag on 8,9 when drag 1st or 2nd row


text:
Q: How to fix jumping footer? i just finished building eshop, but i have problem with footer, when there is not product in category, footer keep jumping. You can see it there: https://www.anjelska-predajna.sk/product-category/liturgicke-predmety/tymian/
Any idea, how to fix it ? Thank You. ;)

A: First off, the site is amazing, and as i am from Czech republic, I understood it just fine :)
Secondly, your site is made in WordPress. I recommend trying to update your plugins or styling your footer to stay at the bottom like so:
footer { bottom: 0; }


text:
Q: Deploying a laravel app with a node js app in nginx I have a node.js app running using pm2. When I go to my endpoint it works, i see things. But then when I try to do an action that connects to the backend api at laravel, then nothing happens.
This is how I have my nginx config configured:
server {
    listen 80;
    server_name make.tube;
    root /maketube/api/public;

    # This is the "last resort" nginx will direct to when no other matches with location have been found.
    # This will proxy pass to another website (should be tested with http://localhost:3000 in your case).
    location / {
        proxy_pass http://localhost:3000;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
    }

    # All requests that start with /api are directed to the laravel location.
    # It will only look for a file named index.html
    location /api {
        index index.html;
    }
}

When I try to perform an action that should connect to the backend (like sign in) then it fails to work try the signin function on make.tube (http://localhost:3000/api/auth/login/).
Does anyone know how I can get this working so when I perform the sign in it connects to my laravel backend?

A: By playing around on my local environment I came up with the following simplified version:
server {
    listen 80;
    server_name test.test;
    root /home/vagrant/test;

    # This is the "last resort" nginx will direct to when no other matches with location have been found.
    # This will proxy pass to another website (should be tested with http://localhost:3000 in your case).
    location / {
        proxy_pass http://node.test/;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
    }

    # All requests that start with /api are directed to the laravel location.
    # It will only look for a file named index.html
    location /api {
        index index.html;
    }
}

I managed to proxy_pass a request like http://test.test to another website http://node.test, which displayed the correct content "I am node." Also all request that started with /api like http://test.test/api where directed to the file in /home/vagrant/test/api/index.html which shown "I am api".
In my answer on 54775192 I indeed made an error in the location block. The following:
location /api {
    root /location/of/laravel;
    index index.php;
}

Will result in an error that nginx tries to get a file named /location/of/laravel/api, which does not exist, instead of the intended /location/of/laravel/api/index.php.
Not sure why at this moment.
This is just how Nginx works. We can make use of alias to prevent this from happening.


text:
Q: Allocating a block of memory with malloc() I've got a rather unusual question.
I've seen two variants of passing arguments to malloc. Let's say we've got:
int *arr = (int *) malloc(sizex * sizeof(*arr));
Some people say that using sizeof(*arr) is bad and you should use sizeof(int) (in this example) instead.
Could you explain what's the difference and what's better to use?

A: There is no difference. Both allocate the same amount of memory -
int *arr = (int *) malloc(sizex * sizeof(*arr));
// equivalent to
int *arr = (int *) malloc(sizex * sizeof(int));

However, there are some things to note.

*

*You should not cast the result of malloc. It's not useful and can actually cause problems if you forget to include the header stdlib.h which contains its prototype. Please read this - Do I cast the result of malloc?

*I prefer the first version above because there's no repetition of the type information. Also, it's more maintainable in the sense that if you change the type, then you need to change it only once where as in the second case, you need to change it in two places.
It should be noted that sizeof needs parentheses for its operand only when it's a type. Therefore, it can be written more succinctly as
int *arr = malloc(sizex * sizeof *arr);
// equivalent to
int *arr = malloc(sizex * sizeof(*arr));  // preferred way


text:
Q: How to update GUI continuously with multithreading I have made a minimal representation of my full program to show what I need help with, the program consists of a JFrame, the main class, and a task class.
The task class generates random integers that are used to paint strings onto the GUI. I made it so that the user can use any number of threads that each perform this same task.
My goal is to display the ending "solution" which for now is not a real solution. But, as each thread generates integer values, I want to continuously update the GUI so that it can keep showing solutions until it reaches the final "true" solution.
How can I do this?
When I try to pass the GUI through it only updates once. I tried looking into Swing Workers but I want to use my own thread implementation, and I cannot figure out how to implement it correctly, or how exactly it would work in a concurrent implementation.
import java.util.*;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

class Task extends Thread {

    private static Lock taskLock = new ReentrantLock();
    private Random rand = new Random();
    private static int y;
    static volatile ArrayList<Integer> finallist = new ArrayList<>();
    private GUI g;

    Task(GUI g) {
        this.g = g;
    }

    private void generatePoint() {
        taskLock.lock();
        y = rand.nextInt(1000);
        taskLock.unlock();
    }

    public void run() {
        generatePoint();
        int copy = y;
        finallist.add(copy);
        g.setData(copy);
    }
}

public class Main {
    public static void main(String[] args) throws InterruptedException {

        GUI g = new GUI();
        g.setVisible(true);
        Scanner input = new Scanner(System.in);
        System.out.println("Please input the number of Threads you want to create: ");
        int n = input.nextInt();
        System.out.println("You selected " + n + " Threads");

        Thread[] threads = new Thread[n];
        for (int i = 0; i < threads.length; i++) {
            threads[i] = new Task(g);
            threads[i].start();
        }

        for (int j = 0; j < n; j++) {
            threads[j].join();
        }

        for(Integer s: Task.finallist) {
            if(s > 30) {
                g.setData(s);       //in full program will find true solution
            }
        }
    }
}

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

    public class GUI extends JFrame implements ActionListener {
        private boolean check;
        private int y;
        GUI()  {
            initialize();
        }

        private void initialize()  {
            check = false;
            y = 0;
            this.setLayout(new FlowLayout());
            this.setSize(1000,1000);
            this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        }

        @Override
        public void actionPerformed(ActionEvent e) {

        }

        @Override
        public void paint(Graphics g) {
            super.paint(g);
            if(check) {
                g.drawString("here",500,y);
            }
        }

        void setData(int y) {
            check = true;
            this.y = y;
            repaint();
        }

    }

A: One of the important aspects you need to keep in mind is that Swing is not thread safe, this means you should not update the UI or update any value that the UI is reliant on from outside of the context Event Dispatching Thread.
There are a number of ways you deal with this.  SwingUtilities.invokeLater, but you really should only use it if the number of times it would be called are small or the time between them is relatively larger (seconds).  The main reason for this, is it's very easy to overload the EDT, which can cause the UI to "stall".
Another approach is to use Swing Timer, but this is really only useful if you want to update the UI on a regular based (like animation).
Another approach is to use a SwingWorker.  This is a "fancy" wrapper around a Executor which allows you to perform work on a background thread and then publish the results to the EDT which can then safely be processed for the UI.
But why do this?  Well, one of things that SwingWorker does is, if your Thread is generating a lot of data in a small amount of time, it will squeeze a number of results into a List and reduce the number of calls made back to the UI, helping maintain some level of performance.
However, in your case, it's probably just a really nice exercise, as you are creating a single thread/worker to do a single job and not getting a single worker/thread to do all the jobs.
In that case, I might consider using a Swing Timer to probe a model of the data instead of having the Thread/worker try and update the UI itself, this way you gain control over the number of updates which are occurring to the UI.
There are pros and cons to all these and you will need to investigate which one(s) work best for your particular scenario
SwingWorker example
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingWorker;

public class GUI {

    public static void main(String[] args) {
        new GUI();
    }

    public GUI() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                JFrame frame = new JFrame();
                frame.add(new TestPane(10));
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public static interface Consumer {

        void setData(int value);
    }

    public static class WorkerTask extends SwingWorker<Void, Integer> {

        private static Lock taskLock = new ReentrantLock();
        private Random rand = new Random();
        private static int y;
        // I'd prefer this was a model object passed into the worker
        static volatile ArrayList<Integer> finallist = new ArrayList<>();

        private Consumer consumer;

        public WorkerTask(Consumer consumer) {
            this.consumer = consumer;
        }

        private int generatePoint() {
            taskLock.lock();
            int copy = 0;
            try {
                copy = rand.nextInt(200);
                y = copy;
                // Array list isn't thread safe ;)
                finallist.add(copy);
            } finally {
                taskLock.unlock();
            }
            return copy;
        }

        @Override
        protected Void doInBackground() throws Exception {
            // And a random delay
            // You should now be able to see the text change
            Thread.sleep(rand.nextInt(1000));
            publish(generatePoint());
            return null;
        }

        @Override
        protected void process(List<Integer> chunks) {
            if (chunks.isEmpty()) {
                return;
            }
            int last = chunks.get(chunks.size() - 1);
            consumer.setData(last);
        }

    }

    public class TestPane extends JPanel {

        private boolean check;
        private int y;

        private CountDownLatch latch;

        public TestPane(int count) {
            latch = new CountDownLatch(count);
            for (int i = 0; i < count; i++) {
                WorkerTask task = new WorkerTask(new Consumer() {
                    @Override
                    public void setData(int value) {
                        // This is on the EDT, so it's safe to update the UI with
                        TestPane.this.setData(value);
                    }
                });
                task.addPropertyChangeListener(new PropertyChangeListener() {
                    @Override
                    public void propertyChange(PropertyChangeEvent evt) {
                        WorkerTask task = (WorkerTask) evt.getSource();
                        if (task.getState() == SwingWorker.StateValue.DONE) {
                            latch.countDown();
                        }
                    }
                });
                task.execute();
            }

            // This only matters if you want the result to be delivered
            // on the EDT.  You could get away with using a Thread otherwise
            SwingWorker waiter = new SwingWorker<Void, List<Integer>>() {
                @Override
                protected Void doInBackground() throws Exception {
                    System.out.println("Waiting");
                    try {
                        latch.await();
                    } catch (InterruptedException ex) {
                        ex.printStackTrace();
                    }
                    System.out.println("All done here, thanks");

                    publish(WorkerTask.finallist);

                    return null;
                }

                @Override
                protected void process(List<List<Integer>> chunks) {
                    if (chunks.isEmpty()) {
                        return;
                    }
                    List<Integer> values = chunks.get(chunks.size() - 1);
                    completed(values);
                }

            };
            waiter.execute();
        }

        @Override
        public Dimension getPreferredSize() {
            return new Dimension(200, 200);
        }

        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);

            Graphics2D g2d = (Graphics2D) g.create();
            if (check) {
                g2d.drawString("here", 100, y);
            }
            g2d.dispose();
        }

        void setData(int y) {
            check = true;
            System.out.println(y);
            this.y = y;
            repaint();
        }

        protected void completed(List<Integer> values) {
            // And executed on the EDT
            System.out.println("All your value belong to us");
            for (int value : WorkerTask.finallist) {
                System.out.println(">> " + value);
            }
        }

    }

}

I recommend looking at:

*

*Concurrency in Swing

*Worker Threads and SwingWorker

*Executors if you're really interested in understanding how SwingWorkers work

A: Before I explain the solution to your problem, I would like to point out some issues with your code.

*

*You only do one operation in each thread, and it does not seem to be a long-running one (The run method is only called once, in case you don't know). I'm not sure if you just put it for the sake of having it as a placeholder, or if it's actually part of your code. But if you don't have a long running operation, is it worth doing it in a separate thread? Think about the trade-offs.

*No need to join the threads, as they will probably finish almost immediately in your code.

Now to the solution, this documentation explains that Swing is not thread-safe, but there is a way to make changes on the GUI. You should use this method to make any changes: SwingUtilities.invokeLater(..).
public static void main(String[] args) throws InterruptedException {

    GUI g = new GUI();
    g.setVisible(true);
    Scanner input = new Scanner(System.in);
    System.out.println("Please input the number of Threads you want to create: ");
    int n = input.nextInt();
    System.out.println("You selected " + n + " Threads");

    Thread[] threads = new Thread[n];
    for (int i = 0; i < threads.length; i++) {
        threads[i] = new Task(g);
        threads[i].start();
    }

    for (int j = 0; j < n; j++) {
        threads[j].join();
    }

    for(Integer s: Task.finallist) {
        if(s > 30) {
            // here you submit a Runnable to the event-dispatcher thread in which the Swing Application runs
            SwingUtilities.invokeLater(() -> {
                 g.setData(s);
            });
        }
    }
}

The same should also be done in your run method:
public void run() {
    generatePoint();
    int copy = y;
    finallist.add(copy);
    SwingUtilities.invokeLater(() -> {
        g.setData(copy);
    });
}


text:
Q: Can the apply function on a pandas dataframe produce a scalar? I read the documentation on Pandas apply function which states that the apply function works on the rows or columns of a dataframe and returns a series or a dataframe. Is it possible to write the code in such a way that it returns a scalar? Or will it be necessary to further chain a .pipe function with it. I tried writing the following functions on a sample dataframe that has been provided in the documentation:
df = pd.DataFrame({'one' : pd.Series(np.random.randn(3), index=['a', 'b', 'c']),
    'two' : pd.Series(np.random.randn(4), index=['a', 'b', 'c', 'd']),
    'three' : pd.Series(np.random.randn(3), index=['b', 'c', 'd'])})

def my_func1(x):
    min_of_x = x[['one', 'two']]
    return min_of_x['one']

def my_func2(x):
    min_of_x = x[['one', 'two']]
    return min_of_x['one'].iloc[0]

def my_func3(x):
    min_of_x = x[['one', 'two']]
    return min_of_x.max()

def my_func4(x, elem_pos=0):
    return x.iloc[elem_pos]

When I run:
df.apply(my_func1, axis=1)

It works fine and gives me a Series as expected. But suppose I would like the first element or for that matter some calculation of the Series value that results in a scalar:
df.apply(my_func2, axis=1)

I get the error "AttributeError: ("'numpy.float64' object has no attribute 'iloc'", 'occurred at index a')". If I use my_func3 which calculates the max:
df.apply(my_func3, axis=1)

It works ok again returning a Series. The only way to return a scalar seems to be to chain another function using a .pipe:
df.apply(my_func1, axis=1).pipe(my_func4, 2)

So I just wanted to conclude whether the apply function produces only a Series or a DataFrame and any attempt to return another value produces this error. Would this be the case? This is just in case I wanted to run some calculation on the result which can't be done by in-built Panda and NumPy functions.

A: The fundamental thing to understand is that a pd.Series object is always passed to apply. What gets passed depends on what axis you call it with.
For example, axis=1 will pass this:
one      ...
three    ...
two      ...
Name: a/b/c/d, dtype: float64

And, axis=0 will pass this:
a    ...
b    ...
c    ...
d    ...
dtype: float64

In either case, this is a pd.Series object.
In my_func1, you slice the series like this: x[['one', 'two']] which also results in a series object. Indexing an individual item such as x['one'] will return a float object, so it naturally makes sense that a float object will not have an .iloc attribute associate with it. This is why my_func2 throws the AttributeError.

As an exercise, try running this code:
In [891]: def my_func1(x):
     ...:     print(type(x['one']))
     ...:     min_of_x = x[['one', 'two']]
     ...:     return min_of_x['one']

In [892]: df.apply(my_func1, axis=1)

This gives:
<class 'numpy.float64'>
<class 'numpy.float64'>
<class 'numpy.float64'>
<class 'numpy.float64'>


text:
Q: How can I connect to an HSQL database using PHP? I would like to manipulate an HSQL database using PHP. I have read the documentation regarding HyperSQL and it only shows an example of connecting using Java. How can I connect to an HSQL database in PHP?

A: You can use the ODBC driver for HSQLDB. The installer is available here.


text:
Q: How to use x64 Interlocked Operations against MemoryMappedFiles in .net I need to use Interlocked Operations (CompareExchange, Increment etc.) against memory in MemoryMappedFiles in .NET.
I found this answer to a very similar question. The problem is that Interlocked Operations are not exported from kernel32 (or any other) dll on 64 bit OS (see e.g. http://blog.kalmbachnet.de/?postid=46).
Is there any other way how I can call Interlocked functions on a block of memory in a 64bit .NET process?

A: Write yourself a small C++/CLI helper library that provides interlocked operations consumable by managed code.
I believe the fastest interop path would be to expose a managed class that internally calls into an unmanaged function which itself makes use on the interlocked intrinsics. That way you don't even have to go through PInvoke.


text:
Q: Store the output values from a random sample I am new to programming. I am defining x and y as random samples(as mentioned). Then I define a function h (of x and y). Now I want to get output values of h multiple times at once. I want to store them and use them later to plot a histogram. I have written this code.
I want to store these values in a single array (rather than in different arrays as I'm getting here in output) and use them later.
Please help me out!!!


text:
Q: lldb process launch fails to resolve ~/path-to-filename In .lldbinit in macOS 10.13.3 I define an alias:
command alias pl process launch --stop-at-entry --

so that inside lldb run from the command line I can say something like:
pl ~/path-to-filename

However, when I examine argv I see that lldb has not performed path expansion on the ~.
Of course, the session fails, lldb can't find the file, but if at the bottom I rerun the session with r, the ~ resolves to the absolute path.
The alias is not the issue because if I run process launch inside lldb
with:
process launch --stop-at-entry -- ~/path-to-filename

lldb still refuses to resolve ~. And, it seems bizaare to me, lldb does the expected right thing, resolve ~, when doing r to rerun the debug session. Is this a bash issue, a bug in lldb, a feature or pilot error? I don't know whether this behavior also occurs in the Xcode gui, because I don't use it. It makes me wan't to barf.

A: (lldb) help pro lau
     Launch the executable in the debugger.

[...]
       -X <boolean> ( --shell-expand-args <boolean> )
            Set whether to shell expand arguments to the process when launching.

(lldb) help r
'r' is an abbreviation for 'process launch -X true --'


text:
Q: How to use MercurialEclipse? I have been using the built in mercurial support in NetBeans for a while now and its great. I just recently installed MercurialEclipse from http://cbes.javaforge.com/update so I can start using Mercurial for my Flex projects as well.
I can't seem to figure out how to use it.
I watched the video, when I right click files in the Package Explorer and go to tools I only have 2 or 3 options: Apply Patch, Share Project [, Show Local History]
When I click show local history, it says:

No local history for selected resource.

My project is a repository and I have made some changes since the last commit. I would like to see a diff of those changes so I can review them before committing.
Is this possible?

A: You need to click "Share Project" and enable Mercurial support for this project.


text:
Q: how to read data from arraylist that is inside linkedlist I have an arraylist of year and value. this arraylist is place in a linkedlist as one of element in the linkedlist.
linkedlist elements -> countrycode, indicatorName, indicatorCode and data (arraylist)
how can i retrieve the value from the arraylist when i search for the indicator code and then the year?
segments of my code from application class:
while(str2 != null ){
     StringTokenizer st = new StringTokenizer(str2,";");
     ArrayList <MyData> data = new ArrayList();

     String cCode = st.nextToken();
     String iName = st.nextToken();
     String iCode = st.nextToken();

     for (int j = 0; j < 59; j++){
          String v = st.nextToken();
          int year = 1960 + j;

          d1 = new MyData (year,v);
          data.add(d1);
    }

    Indicator idct1 = new Indicator (cCode,iName,iCode,data);
    bigdata.insertAtBack(idct1);
    str2 = br2.readLine();
}

//search
String search2 = JOptionPane.showInputDialog("Enter Indicator Code");

boolean found2 = false;
Indicator idct3 = (Indicator)bigdata.getFirst();

while (idct3 != null){

     if ( idct3.getICode().equalsIgnoreCase(search2)){
              int search3 = Integer.parseInt(JOptionPane.showInputDialog("Enter year"));
              found2 = true;
              searchYear(bigdata,search3);
     }
     if (!found2) {
              System.out.println("Indicator Code is not in the data");
     }
     idct3 = (Indicator)bigdata.getNext();
}

public static void searchYear (myLinkedList bigdata, int searchTerm) {
        Indicator idct4 = (Indicator)bigdata.getFirst();
        boolean found = false;
        while(idct4 != null){
            if(idct4.getDYear() == searchTerm) {
                found = true;
                System.out.println(idct4.getDValue());
            }
            idct4 = (Indicator)bigdata.getNext();
        }
        if (!found){
            String message = "Error!";
            JOptionPane.showMessageDialog(new JFrame(), message, "Dialog",JOptionPane.ERROR_MESSAGE);
        }
}

indicator class:
    public Indicator(String cCode, String iName, String iCode,ArrayList <MyData> DataList){
        this.cCode = cCode;
        this.iName = iName;
        this.iCode = iCode;
        this.DataList = DataList;
    }

    public String getCCode(){return cCode;}
    public String getIName(){return iName;}
    public String getICode(){return iCode;}
    public int getDYear(){return d.getYear();}
    public String getDValue(){return d.getValue();}

    public void setCCode(String cCode){this.cCode = cCode;}
    public void setIName(String iName){this.iName = iName;}
    public void setICode(String iCode){this.iCode = iCode;}

    public String toString(){
        return (cCode + "\t" + iName + "\t" + iCode + "\t" + DataList.toString());
    }
}

MyData class:
    public MyData(int year, String value){
        this.year = year;
        this.value = value;
    }

    public int getYear(){return year;}
    public String getValue(){return value;}

    public void setYear(int year){this.year = year;}
    public void setValue(String value){this.value = value;}

    public String toString(){
        return (value + "(" + year + ")");
    }

A: I can't add a comment yet, but here's what I'm assuming.
Here it's getting a matching Indicator code (iCode), so let's pass the Indicator object (idct3) into searchYear method instead to focus on its ArrayList < MyData > DataList:
String search2 = JOptionPane.showInputDialog("Enter Indicator Code");

boolean found2 = false;
Indicator idct3 = (Indicator)bigdata.getFirst();

while (idct3 != null){

     if ( idct3.getICode().equalsIgnoreCase(search2)){
              int search3 = Integer.parseInt(JOptionPane.showInputDialog("Enter year"));
              found2 = true;
              searchYear(idct3,search3); // Indicator passed in here
     }
     if (!found2) {
              System.out.println("Indicator Code is not in the data");
     }
     idct3 = (Indicator)bigdata.getNext();
}

Let's change searchYear method to take the Indicator class and search its DataList:
public static void searchYear (Indicator indicator, int searchTerm) {
    for (int i = 0; i < indicator.DataList.size(); i++) {
        if (indicator.DataList.get(i).getYear() == searchTerm) { // Sequentially get MyData object from DataList and its year for comparison
            System.out.println("Found year " + searchTerm + " with Indicator code " + indicator.getICode() +  " having value " + indicator.DataList.get(i).getValue());
            return; // Exit this method
        }
    }
    System.out.println("Not Found");
}


text:
Q: A theoretic question about cosine general solution. I have to find the extremas of: $f(x)=x-\tan({x\over 2})$ .$(\pi\le x\le\pi)$
Last result is $\cos({x\over 2})=\pm{1\over \sqrt{2}}$.
I get that: ${x\over 2}=\pm{\pi\over 4}+2\pi k$ which derives: $x=\pm {\pi\over 2}+4\pi k$. My question is: should I write $x=\pm {\pi\over 2}+2\pi k$, or it is important to keep it $4$?
I would appreciate your help.

A: $$\cos\dfrac x2=\pm\dfrac1{\sqrt2}\iff\cos x=2\cos^2\dfrac x2-1=0$$
$x=(2m+1)\dfrac\pi2$ where $m$ is any integer

A: Your solution of $x/2 = \pm \pi/4 + 2 \pi k$ is equivalent only to $cos(x/2) = 1/\sqrt2$.
For $cos(x/2) = -1/\sqrt2$, $x/2 = \pm 3 \pi /4 + 2 \pi k$.
Combining them, we get
$x/2 = \pm \pi /4 + \pi k$
,or $x/2 = \pi /4 + \pi k/2$
,or $x = \pi /2 + \pi k$
PS: Try imagining/drawing angles in Quadrants of Cartesian coordinates if you are confused in any steps.


text:
Q: Slow kinetic.js drawing in Firefox i have some problems with Kinetic.js (5.0.1) in Debian with firefox (in Windows works well, in chromium works well). I'm trying to do a drawing board but is very slow. Any solution to improve performance?
Thank you.
PD: here is my code.
var initializeDrawings = function() {
    var myExistingLine;
    var currentLine = [];
    var mouseDrag = false;
    var stage;
    var background;
    var backgroundlayer = new Kinetic.Layer();
    var mylayer = new Kinetic.Layer();
    var lineColor = 'black';
    var lineWeight = 5;
    var allmoves = [];
    // Create an invisible shape that will act as an event listener
    stage = new Kinetic.Stage({
        container: 'container',
        width: 600,
        height: 600
    });
    var imageObj = new Image();
    imageObj.onload = function() {
        background = new Kinetic.Image({
            width: stage.getWidth(),
            height: stage.getHeight(),
            image: imageObj
        });
        // Attach handlers
        background.on('mousedown touchstart', function(e) {
            var position = getPosition("container", e);
            mouseDrag = true;
            myExistingLine = new Kinetic.Line({stroke: lineColor, strokeWidth: lineWeight});
            mylayer.add(myExistingLine);
            currentLine.push(position.x);
            currentLine.push(position.y);
        });
        background.on('mousemove touchmove', function(e) {
            if(mouseDrag === true) {
                var position = getPosition("container", e);
                currentLine.push(position.x);
                currentLine.push(position.y);
                myExistingLine.setPoints(currentLine);
                mylayer.batchDraw();
            }
        });
        background.on('mouseup touchstop', function(e) {
            allmoves.push ({ color: lineColor, grosor: lineWeight, points: currentLine });
            mouseDrag = false;
            currentLine = [];
        });
        stage.add(backgroundlayer.add(background));
        stage.add(mylayer);
    }
    imageObj.src = "summoners-map.png";
};

A: Use mylayer.batchDraw instead of mylayer.drawScene.
batchDraw redraws your line only once per refresh cycle instead of attempting many redraws.
...And, don't do console.log in an active event handler like mousemove.


text:
Q: How can I get previous month name using `switch`?

var month_name;
switch(new Date().getMonth()) {
    case 0 :
        month_name = "January";
    break;
    case 1 :
        month_name = "February";
    break;
    case 2 :
        month_name = "March";
    break;
    case 3 :
        month_name = "April";
    break;
    case 4 :
        month_name = "May";
    break;
    case 5 :
        month_name = "June";
    break;
    case 6 :
        month_name = "July";
    break;
    case 7 :
        month_name = "October";
    break;
    case 8 :
        month_name = "September";
    break;
    case 9 :
        month_name = "October";
    break;
    case 10 :
        month_name = "November";
    break;
    case 11 :
        month_name = "December";
    break;
}
console.log(month_name - 1);

The result of this code is NaN.
I am trying to get to get previous month name, but the result is not a number.
How to get name of previous month?

A: Not clear why you would need a switch
To get the name of months you can do

const months = ["January", "Febtruary", "March", "April", "May", "June", "July", "August", "September", "October", "November", "Dececember"];
const getMonthName = offset => {
  let d = new Date();
  d.setHours(15, 0, 0, 0); // normalise
  return months[d.getMonth()+offset];
};
const prevMonth = getMonthName(-1);
const thisMonth = getMonthName(0);
const nextMonth =getMonthName(+1)
console.log("\n",
"Last month was", prevMonth,"\n",
"This month is", thisMonth,"\n",
"Next month will be", nextMonth
)

Alternatively use intl

const getMonth = offset => {
  let d = new Date();
  d.setFullYear(d.getFullYear(),d.getMonth()+offset,15,15, 0, 0, 0); // normalise to mid month at 3pm
  return new Intl.DateTimeFormat('en-US', { month: 'long' }).format(d)
};

const lastMonth = getMonth(-1);
const thisMonth = getMonth(0);
const nextMonth = getMonth(+1);

console.log("\n",
"Previous month was",lastMonth,"\n",
"This month is",thisMonth,"\n",
"Next month will be",nextMonth,"\n",
)

To get yesterday

const getDayName = offset => {
    let d = new Date();
    d.setHours(15, 0, 0, 0); // normalise
    d.setDate(d.getDate() + offset);
    return new Intl.DateTimeFormat('en-US', {weekday: 'long' }).format(d);
 };

console.log("\n",
"Yesterday was", getDayName(-1),"\n",
"Today is", getDayName(0),"\n",
"Tomorrow will be", getDayName(1),"\n"
)

If you insist on switch. deduct the month first:

const getMonthName = offset => {
  let d = new Date(), month_name;
  d.setMonth(d.getMonth()+offset); // this will wrap to 12 from January
  switch (d.getMonth()) {
    case 0:  return "January";
    case 1:  return "February";
    case 2:  return "March";
    case 3:  return "April";
    case 4:  return "May";
    case 5:  return "June";
    case 6:  return "July";
    case 7:  return "October";
    case 8:  return "September";
    case 9:  return "October";
    case 10: return "November";
    case 11: return "December";
  }
}
console.log("\n",
"Last month",getMonthName(-1),"\n",
"This month",getMonthName(0),"\n",
"Next month",getMonthName(1),"\n"
)

A: Change the switch statement to:
 switch(new Date().getMonth() - 1) {

and add case -1 : to December.

var month_name;
switch(new Date().getMonth() - 1) {
    case 0 :
        month_name = "January";
    break;
    case 1 :
        month_name = "February";
    break;
    case 2 :
        month_name = "March";
    break;
    case 3 :
        month_name = "April";
    break;
    case 4 :
        month_name = "May";
    break;
    case 5 :
        month_name = "June";
    break;
    case 6 :
        month_name = "July";
    break;
    case 7 :
        month_name = "October";
    break;
    case 8 :
        month_name = "September";
    break;
    case 9 :
        month_name = "October";
    break;
    case 10 :
        month_name = "November";
    break;
    case 11 :
    case -1 :
        month_name = "December";
    break;
}
console.log(month_name);


text:
Q: Generic to Specific list returns "Cannot cast error" in c#
I am using .NET 4.6 and I am trying to create a specific list from a generic one. Code(the generic list):`
var clients = (from a in accounts
                       group j by new
                       {
                           a.Code,
                           a.Name,
                           a.AddressLine1,
                           a.Postcode,
                           a.City,
                       }
                       into g
                       select new
                       {
                           g.Key.Code,
                           g.Key.Name,
                           g.Key.AddressLine1,
                           g.Key.PowerTools,
                           g.Key.Internetportal,
                           g.Key.Huisvestingsplanning,
                           g.Key.Werkplanning,
                           g.Key.Vervoersplanning
                       }).ToList();

The specific List(Customer.cs):
struct Customer
{
    public string Code { get; set; }
    public string Name { get; set; }
    public string Address { get; set; }
    public double PowerTools { get; set; }
    public double Internetportal { get; set; }
    public double Huisvestingsplanning { get; set; }
    public double Werkplanning { get; set; }
    public double Vervoersplanning { get; set; }

}
Conversion:
customers = clients.Cast<List<object>>().Select(x => new Customer(){
            Code = (string)x[0],
            Name = (string)x[1],
            Address = (string)x[2],
            PowerTools = (double)x[3],
            Internetportal = (double)x[4],
            Huisvestingsplanning = (double)x[5],
            Werkplanning = (double)x[6],
            Vervoersplanning = (double)x[7]}).ToList();

The error this conversion throws:
Unable to cast object of type '<>f__AnonymousType68 [System.String,System.String,System.String,System.Double,System.Double,System.Double,System.Double,System.Double]' to type 'System.Collections.Generic.List1[System.Object]'.
Thanks

A: Your code appears to be trying to convert some object into a list of its properties - this isn't going to work, C# isn't JavaScript. It's doable, but completely unnecessary.
What you really need is to just use the anonymous type in the way it's meant to be used:
clients.Select(x => new Customer { Code = x.Code, Name = x.Name, ... }).ToList();

Depending on the actual LINQ provider you're using, it might even be possible to skip the middle man and select directly into your own type - consult the documentation.
Also, just for clarity - both of those lists are generic. The difference is that the first one is a generic list of an anonymous type, while the second one is a generic list of a named type.


text:
Q: how to detect WIFi Disk through SAMBA API in android I want to create a application which detect WIFI disk or WIFI portable Drive through SAMBA API .
when we start the application it search for the WIFI disk and display disk name in list view or any view .
user can access those disk.
Thanks in advance


text:
Q: Resuming download progress after UI is destroyed I have an app that allows a user to do multiple downloads.

*

*For example, the user clicks an icon, a fragment comes up starting the download and shows the progress by updating the progress bar every second.

*The user can press the back button, the fragment is destroyed and can click a different button, downloading a different item in parallel.

*If the user goes back to click the first icon, and the download is still ongoing, the requirement is that the progress bar will be shown automatically so that the user knows the download is not done yet.

My problem is #3 where if the user presses back and the Asynctask loses the UI, the progress updates stop on resume. How do I get the updates for the correct item being downloaded, since the feature is multiple parallel downloads?
Currently, I am wrapping the AsyncTask in a fragment to retain the instance. Could anyone advise on what is the proper way to do this (minimizing memory leaks as much as possible)?
class DownloadTaskFragment : Fragment() {

    private var mCallbacks: TaskCallbacks? = null
    private var mTask: DummyTask? = null

    interface TaskCallbacks {
        fun onPreExecute()
        fun onProgressUpdate(progress: Int)
        fun onCancelled()
        fun onPostExecute()
    }

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

        mTask = DummyTask(this)
        mTask!!.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR)
    }

    fun setCallBackInterface(taskCallback: TaskCallbacks) {
        mCallbacks = taskCallback
    }

    override fun onDetach() {
        super.onDetach()
        mCallbacks = null
    }

    class DummyTask// only retain a weak reference to the activity
    internal constructor(context: DownloadTaskFragment) : AsyncTask<String, Int, Int>() {

        private val reference: WeakReference<DownloadTaskFragment> = WeakReference(context)
        private var mCallbacks: TaskCallbacks? = reference.get()!!.mCallbacks

        override fun onPreExecute() {
            if (mCallbacks != null) {
                mCallbacks!!.onPreExecute()
            }
        }

        override fun doInBackground(vararg params: String?): Int {
            var i = 0
            while (!isCancelled && i < 80) {
                SystemClock.sleep(100)
                publishProgress(i)
                i++
            }

            return 1
        }

        override fun onProgressUpdate(vararg values: Int?) {
            super.onProgressUpdate(*values)
            if (mCallbacks != null) {
                mCallbacks!!.onProgressUpdate(values[0]!!)
            }
        }

        override fun onPostExecute(result: Int?) {
            if (mCallbacks != null) {
                mCallbacks!!.onPostExecute()
            }
        }

        override fun onCancelled() {
            if (mCallbacks != null) {
                mCallbacks!!.onCancelled()
            }
        }
    }

}

A: In order to make sure that the task continues in the background (especially with the increased restrictions in API 26+) you will need to create a foreground service. Note: you MUST show an accompanying notification (this can simply be a progress bar)
As a foreground service, your task will run separately from the main UI and therefore will not be effected by any changes to the UI. You can also update the UI from the service (see here for more information)

A: I would strongly recommend to use WorkManager for this.
Guidelines on the usage of it can be found here.
If you need to communicate between WorkManager and Fragment you can use LiveData<T> for this.
Here is the article which describe the case.


text:
Q: How to programatically grant "Log on as a service" to a virtual account I'm following this guide on using virtual accounts for Windows services:  https://technet.microsoft.com/library/dd548356%28v=ws.10%29.aspx?f=255&MSPPError=-2147217396
Accordingly, these types of accounts are not manually created but simply used implicitly.  This guide does not mention it, but it's also required to grant the "Log on as a service" right to the non-existent virtual accounts.
For example, SQL Server Express 2014 uses virtual accounts for its services and runs them as a user much like NT Service\MSSQL$SQLEXPRESS.  Once installed, you can find the account names in the "Log on as a service" account listing.
The problem is that I am not sure how to programmatically grant this right to a virtual account.  I've looked at using the LsaAddAccountRights function using pinvoke but it requires specifying the SID of the account.  I do not believe that a virtual account has an SID.
How can I grant logon as a service rights to a virtual account, the way Microsoft does with SQL Server Express?

A: As it turns out, virtual service accounts do not explicitly need the "Log on as a service" right granted.
The problem was that the logon name had to match the exact name of the service for which it was used.  So for a service named MyService, the logon name had to be exactly "NT Service\MyService".  It can't be an arbitrary account name.
EDIT:
Technically, they do need "Log on as a service" permission, but this is granted by default as the NT Service\ALL SERVICES right.  It's possible that this permission might have been modified by the user however.

A: By default, the "log on as a service" right is granted to ALL SERVICES so as your self-answer says you don't need to add each service explicitly.  However, you might need to do so if the configuration has been modified.  (That's presumably why the SQL installer does so.)
Virtual service accounts do have SIDs, which have a 1:1 correspondence with the service name.  There is even a command line tool that can calculate them in advance if you need to:
C:\>sc showsid xyzzy

NAME: xyzzy
SERVICE SID: S-1-5-80-1601682549-2674398373-2289982826-1892655095-2161370298

I can't find an API to do this calculation in advance, once you have installed the service (note that the logon right is only needed in order for the service to start successfully, not in order to install it) you can look up the SID in the same way you would look up any other SID, e.g., LookupAccountName().


text:
Q: Why doesn't this for-comprehension, starting with Option, compile in Scala? Given these definitions:
val guys = List("Albert", "Tom")
val girls = List("Mary", "Stacy", "Josie")

val optRoom: Option[String] = Some("Room 303")

This evaluates to me expected List[String]:
for {
  guy <- guys
  girl <- girls
  room <- optRoom
} yield {
  s"$guy dances with $girl in $room"
}

Turning things a bit inside the loop, I would expect this to evaluate to an Option[List[String]], but it does not even compile:
for {
  room <- optRoom
  guy <- guys
  girl <- girls
} yield {
  s"$guy dances with $girl in $room"
}

Why not? What am I missing? (I know I can convert optRoot to a sequence / list / iterable, but it's not what I want)
How should I rewrite my code to get Option[List[String]]?

A: Your second example is equivalent to
optRoom flatMap { room =>
  guys flatMap { guy =>
    girls map { girl =>
      s"$guy dances with $girl in $room"
    }
  }
}

Which doesn't work because you're not returning an Option to optRoom.flatMap.
If you want an Option[List[String]], then you want to be calling optRoom.map, not flatMap, because you want the result wrapped in an Option:
for {
  room <- optRoom
} yield for {
  guy <- guys
  girl <- girls
} yield {
  s"$guy dances with $girl in $room"
}

A: You can do:
optRoom.map(room => for {
  guy <- guys
  girl <- girls
} yield s"$guy dances with $girl in $room")

Your 2nd for gets roughly translated to:
optRoom.flatMap(room => guys.flatMap(guy => girls.map(girl => s"$guy dances with $girl in $room")))

Since you have optRoom.flatMap(room => ...) it is expected that the parameter is a Function from String => Option[B], but guys.flatMap(...) is not of type Option.


text:
Q: Looking for example/explanation of why some basics results about variance/MGF are important My Professor had mentioned in my intro to probability course that there are some important properties about variance
let $X$ be a random variable, a and b constants,
then $$Var(aX+b)=a^2Var(x)$$
and most importantly,
$$M_{aX+b}=e^{tb}M_{x}(at)$$ ( referring to moment generating function).
However, as I work homework and problems and such I have never seemed to need to use either of these.
Can anyone provide any insight on these, are they really that important? and is there any basic problems that using these will help with?
Thanks everyone


text:
Q: Why do the border colors change on click? I'm trying to make a search -box with categories, like Amazon. The problem is that, when I click inside the text area, the borders change color creating a bad view effect. How can I stop it?
Here is the code:

$border-color: orange;
#form-wrapper {
  width: 50%;
  height: 40px;
}

.nav-list {
  padding: 10px 25px 10px 5px;
  position: relative;
  float: left;
  border: 1px solid $border-color;
  border-top-left-radius: 4px;
  border-bottom-left-radius: 4px;
}

#dropdown {
  cursor: pointer;
  position: absolute;
  height: 100%;
  left: 0;
  top: 0;
  border-top-left-radius: 4px;
  border-bottom-left-radius: 4px;
  border: 1px solid $border-color;
}

#dropdown:hover {
  background-color: lightgray;
}

.current-selection {
  display: inline-block;
  font-size: 14px;
}

.in-wrap {
  overflow: hidden;
  height: 100%;
}

#search-box {
  width: 100%;
  height: 36px;
  border: 1px solid $border-color;
  border-left: none;
  border-right: none;
  line-height: 25px;
  font-size: 18px;
  padding-left: 100px;
}

.go-button {
  float: right;
  height: 100%;
  background-color: orange;
  border: 1px solid $border-color;
  border-top-right-radius: 4px;
  border-bottom-right-radius: 4px;
  margin: 0;
  padding: 0 15px;
}

.go-button:hover {
  background-color: rgb(255, 115, 0);
  cursor: pointer;
}
<link href="http://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.4.0/css/font-awesome.min.css" rel="stylesheet"/>

  <button class="go-button fa fa-search"></button>

  <select id="dropdown">
    <option value="books-and-ebooks">Books & eBooks</option>
    <option value="audiobooks">Audiobooks</option>
    <option value="dvds">DVDs</option>
    <option value="other-resources">Other Resources</option>
    <option value="random">Random</option>
  </select>

    <input type="text" name="query" id="search-box">

Now I realized that on JSFiddle is not working the same way as on codepen, so here is on codepen: http://codepen.io/1z10/pen/QEbjBx

A: It was happening because the browsers add outline on input field, to fix this you need to remove on input:focus the attribute outline, declaring this equals none. Like this CSS code:
#search-box:focus{
  outline:none;
}

A: Try this it may help you. I just changed the height...

<link href="http://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.4.0/css/font-awesome.min.css" rel="stylesheet"/>

  <button class="go-button fa fa-search"></button>

  <select id="dropdown">
    <option value="books-and-ebooks">Books & eBooks</option>
    <option value="audiobooks">Audiobooks</option>
    <option value="dvds">DVDs</option>
    <option value="other-resources">Other Resources</option>
    <option value="random">Random</option>
  </select>

    <input type="text" name="query" id="search-box">

A: add this to your css:
#search-box:focus {
  outline: none;
}

A: Please, don't use outline:none; for disabling the focus outline. You are killing accessibility of the web if you do this. There is a accessible way of doing this.
Check out this article that I've written to explain how to do this correct without breaking you page for a certain segment of your users.


text:
Q: Text cut off for TText Controls Delphi xe5 Android Developing for Android via Delphi xe5.Text on TText and TLabel controls are not displaying properly. Seems as if the last line of text is being cut short per character.
This is my issue i believe but not applicable to Delphi xe5
Android: Last line of textview cut off
Here is a QC report I found describing my issue.
http://qc.embarcadero.com/wc/qcmain.aspx?d=121356
Note: The workaround listed in the QC report does not work for me because I am dynamically creating a lot of text controls ( thus can not create in design builder ) and changing the autosize property does not do anything for me.
Any work around or way to resolve this issue? Text displays correctly for iOS, but not for Android.
Thanks !