text:
Q: How to use the ssh server with PAM but disallow password auth? Many tutorials tell you to config your ssh server like this:
ChallengeResponseAuthentication no
PasswordAuthentication no
UsePAM no

but with this setup you cannot use PAM, as i plan to use 2 Factor Auth with Google Authenticator (OTP Onetime Password) i need PAM.
So how to configure a fresh debian jessie ssh deamon, if i want to prevent the login with the normal password but still allow to use PAM.
maybe the exact question is how to configure pam to disallow passwords?

Details on PAM Authentication
Disabling PAM-based password authentication is rather un-intuitive. It
  is needed on pretty much all GNU/Linux distributions (with the notable
  exception of Slackware), along with FreeBSD. If you're not careful,
  you can have PasswordAuthentication set to 'no' and still login with
  just a password through PAM authentication. It turns out that you need
  to set 'ChallengeResponseAuthentication' to 'no' in order to truly
  disable PAM authentication. The FreeBSD man pages have this to say,
  which may help to clarify the situation a bit:
Note that if ChallengeResponseAuthentication is 'yes', and the PAM authentication policy for sshd includes pam_unix(8), password
  authentication will be allowed through the challenge-response
  mechanism regardless of the value of PasswordAuthentication.

http://www.unixlore.net/articles/five-minutes-to-more-secure-ssh.html

A:
maybe the exact question is how to configure pam to disallow passwords?

Correct. You've already stumbled upon the fact that setting UsePAM no is generally bad advice. Not only does it prevent any form of PAM based authentication, it also disables account and session modules. Access control and session configuration are good things.
First, let's build a list of requirements:

*

*OTP via pam_google_authenticator.so. This requires UsePAM yes and ChallengeResponseAuthentication yes. You're prompting them for a credential, after all!

*No other form of password authentication via PAM. This means disabling any auth module that might possibly allow a password to be transmitted via keyboard-interactive logins. (which we have to leave enabled for OTP)

*Key based authentication. We need to require publickey authentication, and maybe gssapi-with-mic if you have Kerberos configured.

Normally, authenticating with a key skips PAM based authentication entirely. This would have stopped us in our tracks with older versions of openssh, but Debian 8 (jessie) supports the  AuthenticationMethods directive. This allows us to require multiple authentication methods, but only works with clients implementing SSHv2.

sshd config
Below are the lines I suggest for /etc/ssh/sshd_config. Make sure you have a way to access this system without sshd in case you break something!
# Require local root only
PermitRootLogin no

# Needed for OTP logins
ChallengeResponseAuthentication yes
UsePAM yes

# Not needed for OTP logins
PasswordAuthentication no

# Change to to "yes" if you need Kerberos. If you're unsure, this is a very safe "no".
GSSAPIAuthentication no

# Require an OTP be provided with key based logins
AuthenticationMethods publickey,keyboard-interactive

# Use this instead for Kerberos+pubkey, both with OTP
#
#AuthenticationMethods gssapi-with-mic,keyboard-interactive publickey,keyboard-interactive

Don't forget to reload sshd once these changes have been made.
PAM config
We still have to configure PAM. Assuming a clean install of Debian 8 (per your question):

*

*Comment @include common-auth from /etc/pam.d/sshd.

*Review /etc/pam.d/sshd and confirm that no lines beginning with auth are present. There shouldn't be if this is a clean install, but it's best to be safe.

*Add an auth entry for pam_google_authenticator.so.

Remember that local passwords still work.
We did not make any changes that would impact logins via a local console, or prevent users from using passwords to upgrade their privileges via sudo. This was outside the scope of the question. If you decide to take things further, remember that root should be always be permitted to login locally via password. You risk locking yourself out of the system accidentally otherwise.

A: to disallow the password request
comment this line
#auth       substack     password-auth

in /etc/pam.d/sshd
and be sure to not have nullok at the end of this line unless it will be fine to authenticate via ssh without using OTP
auth required pam_google_authenticator.so


text:
Q: CSS/HTML: Handling Fluid Layouts and Height? Here's an example demonstrating this problem:
http://jsfiddle.net/93twL/
Here's the code (same as the jsfiddle):

            Heading

                Left

                    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas quis tortor ligula. Aenean sagittis ut nibh quis hendrerit. Proin tincidunt scelerisque feugiat. Duis nunc erat, accumsan sed diam in, vulputate rutrum velit. Etiam tincidunt pretium dolor, sit amet bibendum tortor congue pulvinar. Donec convallis mauris non nunc consectetur, eget auctor nisi volutpat. Vestibulum lobortis nunc non ullamcorper faucibus. Nulla convallis justo in turpis aliquet vehicula. Donec eget turpis tempor, ornare magna nec, rhoncus orci. Sed pharetra risus orci, eu facilisis diam interdum id.

                Main

                    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas quis tortor ligula. Aenean sagittis ut nibh quis hendrerit. Proin tincidunt scelerisque feugiat. Duis nunc erat, accumsan sed diam in, vulputate rutrum velit. Etiam tincidunt pretium dolor, sit amet bibendum tortor congue pulvinar. Donec convallis mauris non nunc consectetur, eget auctor nisi volutpat. Vestibulum lobortis nunc non ullamcorper faucibus. Nulla convallis justo in turpis aliquet vehicula. Donec eget turpis tempor, ornare magna nec, rhoncus orci. Sed pharetra risus orci, eu facilisis diam interdum id.

                    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas quis tortor ligula. Aenean sagittis ut nibh quis hendrerit. Proin tincidunt scelerisque feugiat. Duis nunc erat, accumsan sed diam in, vulputate rutrum velit. Etiam tincidunt pretium dolor, sit amet bibendum tortor congue pulvinar. Donec convallis mauris non nunc consectetur, eget auctor nisi volutpat. Vestibulum lobortis nunc non ullamcorper faucibus. Nulla convallis justo in turpis aliquet vehicula. Donec eget turpis tempor, ornare magna nec, rhoncus orci. Sed pharetra risus orci, eu facilisis diam interdum id.
                Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas quis tortor ligula. Aenean sagittis ut nibh quis hendrerit. Proin tincidunt scelerisque feugiat. Duis nunc erat, accumsan sed diam in, vulputate rutrum velit. Etiam tincidunt pretium dolor, sit amet bibendum tortor congue pulvinar. Donec convallis mauris non nunc consectetur, eget auctor nisi volutpat. Vestibulum lobortis nunc non ullamcorper faucibus. Nulla convallis justo in turpis aliquet vehicula. Donec eget turpis tempor, ornare magna nec, rhoncus orci. Sed pharetra risus orci, eu facilisis diam interdum id.

                Right

                Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas quis tortor ligula. Aenean sagittis ut nibh quis hendrerit. Proin tincidunt scelerisque feugiat. Duis nunc erat, accumsan sed diam in, vulputate rutrum velit. Etiam tincidunt pretium dolor,

                Footer

html{
    min-height:100%;
    height:100%;
}
body{
    height:100%;
    width:100%;
    margin:0;
    box-shadow: inset 0 0 1px 1px black;
}
h1{
    margin-top:0;
}
#container{
    clear:both;
    width:100%;
    height:100%;
    float:left;
    box-shadow: inset 0 0 1px 1px black;
}

#header{
    min-height:12%;
    clear:both;
    float:left;
    width:100%;
    box-shadow: inherit;
}
#footer{
    min-height:10%;
    box-shadow: inherit;
    clear:both;
    float:left;
    width:100%;
}
#left{
    float:left;
    box-shadow: inherit;
    width:24.5%;
    padding:0.5%;
    min-height:50%;
}

#main{
    float:left;
    box-shadow: inherit;
    width:48%;
    min-height:50%;
    padding:0.5%;
}

#right{
    float:left;
    box-shadow: inherit;
    width:24.5%;
    padding:0.5%;
    min-height:50%;
}

As seen in the example by looking at the borders, once the content goes above 100% heigtht, the content overflows. I'd rather have the element expand.
To fix this, one would remove specifying the height. However, if there is no height specified then how am I supposed to control the height of all the content?(using percentages) I need buttons, headers, footers and so on that need a height set to it. (Without HTML and BODY having a 100% height, no other elements will be able to set a height using percentages)
In case it is not clear, I am talking about a fluid layout where the height is given in percentages.
So is this even possible or should I just give this up?

A: You can replace height with min-height: 100%. And at the end of your HTML add a div with css rule clear: both to clean up all the floating elements.
So it will look like this :

            Heading

                Left

                    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas quis tortor ligula. Aenean sagittis ut nibh quis hendrerit. Proin tincidunt scelerisque feugiat. Duis nunc erat, accumsan sed diam in, vulputate rutrum velit. Etiam tincidunt pretium dolor, sit amet bibendum tortor congue pulvinar. Donec convallis mauris non nunc consectetur, eget auctor nisi volutpat. Vestibulum lobortis nunc non ullamcorper faucibus. Nulla convallis justo in turpis aliquet vehicula. Donec eget turpis tempor, ornare magna nec, rhoncus orci. Sed pharetra risus orci, eu facilisis diam interdum id.

                Main

                    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas quis tortor ligula. Aenean sagittis ut nibh quis hendrerit. Proin tincidunt scelerisque feugiat. Duis nunc erat, accumsan sed diam in, vulputate rutrum velit. Etiam tincidunt pretium dolor, sit amet bibendum tortor congue pulvinar. Donec convallis mauris non nunc consectetur, eget auctor nisi volutpat. Vestibulum lobortis nunc non ullamcorper faucibus. Nulla convallis justo in turpis aliquet vehicula. Donec eget turpis tempor, ornare magna nec, rhoncus orci. Sed pharetra risus orci, eu facilisis diam interdum id.

                    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas quis tortor ligula. Aenean sagittis ut nibh quis hendrerit. Proin tincidunt scelerisque feugiat. Duis nunc erat, accumsan sed diam in, vulputate rutrum velit. Etiam tincidunt pretium dolor, sit amet bibendum tortor congue pulvinar. Donec convallis mauris non nunc consectetur, eget auctor nisi volutpat. Vestibulum lobortis nunc non ullamcorper faucibus. Nulla convallis justo in turpis aliquet vehicula. Donec eget turpis tempor, ornare magna nec, rhoncus orci. Sed pharetra risus orci, eu facilisis diam interdum id.
                Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas quis tortor ligula. Aenean sagittis ut nibh quis hendrerit. Proin tincidunt scelerisque feugiat. Duis nunc erat, accumsan sed diam in, vulputate rutrum velit. Etiam tincidunt pretium dolor, sit amet bibendum tortor congue pulvinar. Donec convallis mauris non nunc consectetur, eget auctor nisi volutpat. Vestibulum lobortis nunc non ullamcorper faucibus. Nulla convallis justo in turpis aliquet vehicula. Donec eget turpis tempor, ornare magna nec, rhoncus orci. Sed pharetra risus orci, eu facilisis diam interdum id.

                Right

                Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas quis tortor ligula. Aenean sagittis ut nibh quis hendrerit. Proin tincidunt scelerisque feugiat. Duis nunc erat, accumsan sed diam in, vulputate rutrum velit. Etiam tincidunt pretium dolor,

                Footer

A: I'm not entirely sure what you're attempting to do here, but how about this?
http://jsfiddle.net/9X8j2/
Only the CSS changed:
body{
    width:100%;
    margin:0;
    box-shadow: inset 0 0 1px 1px blue;
}
h1{
    margin-top:0;
}
#container{
    width:100%;
    box-shadow: inset 0 0 1px 1px gray;
}

#header{
    min-height:12%;
    clear:both;
    float:left;
    width:100%;
    box-shadow: inherit;
}
#footer{
    min-height:10%;
    box-shadow: inherit;
    clear:both;
    width:100%;
}
#left{
    float:left;
    box-shadow: inherit;
    width:24.5%;
    padding:0.5%;
    min-height:50%;
}

#main{
    float:left;
    box-shadow: inherit;
    width:48%;
    min-height:50%;
    padding:0.5%;
}

#right{
    float:left;
    box-shadow: inherit;
    width:24.5%;
    padding:0.5%;
    min-height:50%;
}

I changed the color of the box shadows to tell them apart a little easier.
Removing most of the height attributes may be what you're looking for.. including removing the CSS on the HTML tag. At least now the container does not overflow the body.
Please let me know if this is at all helpful.

A: I think what you're after is a fluid width 100% and 100% height, so that the content vertically and horizontally expands. That is a tough thing and can't be done with css alone, flexbox might be able to do it, though I don't know. I saw it recently done with CSS and jQuery using a fixed height on both the header and footer, but the rest is fluid height and width:
http://codepen.io/anon/pen/EsJHu
I made it more responsive here: http://jsbin.com/momep/7/edit
CSS
/* Reset  */
* {
    margin: 0;
    padding: 0;
}

/* Sticky footer */
html, body {
    height: 100%;
    width: 100%;
}
#page {
    height: 100%;
    height: auto !important;
    min-height: 100%;
}
#sticky-footer-wrap {
    overflow: auto;
    padding-bottom: 100px;
}
.site-main {
    overflow: hidden;
    height: 100%;
}
.site-footer {
    position: relative;
    height: 100px;
    margin-top: -100px;
    clear: both;
}

/* Header  */
.site-header {
    height: 100px;
}

@media (min-width:992px) {
/* 3 columns */
#primary {
    float: left;
    width: 50%;
    margin-left: 25%;
}
#secondary {
    float: left;
    width: 25%;
    margin-left:-75%;
}
#tertiary{
    float: left;
    width: 25%;
}
}

/* Colours */
.site-header {
    background: #C5E0DC;
}
#primary {
    background-color: #F1D4AF;
}
#secondary {
    background-color: #ECE5CE;
}
#tertiary{
    background-color: #E08E79;
}
.site-footer {
    background: #774F38;
}

HTML

Header

Primary content

Layout Features

Header (fixed height)

3 fluid columns

100% or full height columns (jQuery)

Sticky footer (fixed height)

Correct source order of columns

IE8 compatible (Modernizr)

Secondary content

Tertiary content

Footer (sticky)

jQuery
// On page load
$(window).load(columnHeight);

// On window resize
$(window).resize( function () {
    // Clear all forced column heights before recalculating them after window resize
    $("#primary").css("height", "");
    $("#secondary").css("height", "");
    $("#tertiary").css("height", "");
    columnHeight();
});

// Make columns 100% in height
function columnHeight() {
    // Column heights should equal the document height minus the header height and footer height
    var newHeight = $(document).height() - $(".site-header").height() - $(".site-footer").height() + "px";
    $("#primary").css("height", newHeight);
    $("#secondary").css("height", newHeight);
    $("#tertiary").css("height", newHeight);
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Storing username and password into a dictionary? Currently at the moment im working a small login screen in python, What i want it to do is ask a user to register if theyre isnt a account already created, But one small problem im having is how can i save the username and password into a dictionary, I would also like to know how i would save the dictionary to a .txt file that can be loaded to restore user info/variables if this is possible.
Im not too sure whether im meant to ask for help with my code or im allowed to ask questions like this, I just need a reffernce or a little help. Also just to add im not asking for someone to do it for me, Just to give me a shove in the right direction
Please dont flame me ;p
import sys
import math
user = None
password = None
store = dict()
newUser = True

while newUser == True:
    userguess=""
    passwordguess=""
    print("Hello, Please create a unique username and password.")
    user = input("USERNAME: ")
    password = input("PASSWORD: ")
    store[user] = password
    print(store)

That is what i have tried so far, I gathered the storing to dictionary from another page on here, Was just looking for a breakdown on assigning stuff to a key

A: you dont ... you save a hash into a dictionary (a hash is simpley a non reversable encoding)
eg:
md5("password") == '5f4dcc3b5aa765d61d8327deb882cf99'
however there is no real way to go from that back to the password
nothing_does_this('5f4dcc3b5aa765d61d8327deb882cf99') == "password"
(not entirely true... but close enough fo the concept)
import hashlib
def create_users()
   users = {}
   while True:
      username = raw_input("Enter Username:")
      password = raw_input("Enter Password:")
      users[username] = hashlib.md5(password).hexdigest()
      if raw_input("continue?")[0].lower() != "y":
          return users

def login(userdict):
    username = raw_input("Username:")
    password = raw_input("Password:")
    return userdict.get(username,None) == hashlib.md5(password).hexdigest()

users = create_users()
if login(users):
   print "Double Winning!!!"
else:
   print "You Lose Sucka!!!"

as pointed out md5 is not a very secure hash, there are much better ones to use sha256 is pretty good still I think, bcrypt is even better (for some definition of better) ... however md5 is a simple hash to help with understanding what they are..

A: If you already have constructed this dictionary, you can save it to a file with pickle.
pickle.dump( user_dict, open( "save.p", "wb" ) )

However, you should be aware of best practices when storing passwords and make sure you are storing a securely hashed version of the password rather than its value in plaintext.


text:
Q: examples of finitely generated semigroups that are not residually finite Does anybody know of any finitely generated semigroups that are not residually finite and whose group of units (if there is an identity) is trivial?  Basically, I'm looking for finitely generated semigroups that are not residually finite, but I don't just want to punt and look at groups (like Thompson's groups or something).  Thanks!

A: Take $S=\langle a, b, c \mid ab^na=0 \hbox{ for all prime } n, ab^ma=c \hbox{ for all composite } m\rangle$. If there exists a homomorphism of that semigroup onto a finite semigroup $F$, and $\bar x$ is the image of $x$ ($x=a,b,c$), then $\bar b^n=\bar b^{n+m}$ for some $n,m$. Therefore for every prime $p>n$, and every $k$, $\bar b^p=\bar b^{p+mk}$. For some $k$, say, $k=p$, $p+km$ is not prime. Hence
$\bar c= \bar a\bar b^{p+mk}\bar a=\bar a \bar b^p\bar a=0$. So $c$ and $a$ cannot be separated by a homomorphism to a finite semigroup. So $S$ is not residually finite. The semigroup $S$ does not have a unit.
That was just the simplest example.
There are also many finitely presented examples. For example, take a deterministic Turing machine $T$ with one tape and undecidable halting problem, tape alphabet $X$, state alphabet $Q$, commands $[U_i\to V_i]$, $i=1,...,n$ (where $U_i, V_i$ are words containing one occurrence of $Q$-letter each). For simplicity assume that the letters on the tape to the right of the state letter and to the left of the state letter are from disjoint parts of $X$. Consider the semigroup $\langle X\cup Q | U_i=V_i, i=1,...,n\rangle$. If the input and the terminal states cannot occur in the middle of computation and the terminal state can occur only when the tape is empty, it is easy to see that the semigroup will have undecidable word problem. So by McKinsey it is not residually finite. The group of units of this semigroup is also empty.
All the statements about semigroups in these two examples follow from the fact that the presentations are confluent and terminating (there are no overlaps at all), see any book on rewriting systems.

A: I think the easiest answer is the bicyclic monoid $B$ given by the presentation $\langle a,b\mid ab=1\rangle$.  Considering a unilateral shift on Hilbert space and its adjoint show that $ba\ne 1$.  But of course $ab=1\implies ba=1$ in a finite monoid so $ba$ and $1$ are inseparable in a finite monoid.  Actually, it is known that any proper image of $B$ is a cyclic group.  There are no invertible elements in $B$ since using the relation, it is easy to see that every element is of the form $b^ma^k$ with $m,k$ nonnegative integers.  If the element is invertible and not the identity, then either $a$ would have a left inverse or $b$ would have a right inverse, which would make $B$ a group.
Actually, it is known that $B$ cannot be embedded in any compact Hausdorff topological monoid.  In particular, it cannot embed in its profinite completion.
If one takes the monoid (with zero) with presentation $\langle a,b,c,d\mid ab=1=cd, cb=0=ad\rangle$ in that category, where 0 is a multiplicative zero, then one gets a monoid with no nontrivial proper images and trivial group of units, but this is a little harder to prove.

A: To generalise @BenjaminSteinberg's (by now rather old) answer, Lallement showed in 1971 that a one-relation monoid $M = \text{Mon}\langle A \mid w= w'\rangle$ where $w$ is a left and right factor of $w'$ (that is, there exist $w_1, w_2 \in A^\ast$ with $w' \equiv ww_1 \equiv w_2 w$, where $\equiv$ denotes graphical equality of words) is not residually finite if the presentation relation of the left special monoid $L(M)$ associated to $M$ is not the presentation relation of a group. In this case, it cannot be embedded into a compact semigroup, just as the bicyclic monoid.
The left special monoid comes about through so-called compression, which is a little too long to get into here, but one particular corollary is that if one takes $w \equiv \varepsilon$, then $L(M) = M$. Hence $\text{Mon}\langle A \mid w' = 1\rangle$ is not residually finite if it is not the free product of a free monoid by a group. So this includes the bicyclic monoid $\text{Mon}\langle b,c \mid bc = 1\rangle$, but also more general examples such as $\text{Mon}\langle a,b \mid ababb = 1\rangle$ and $\text{Mon}\langle a,b,c \mid abacac = 1\rangle$, both of which have trivial group of units.
One can  easily check whether or not a one-relation special monoid $\text{Mon}\langle A \mid w' = 1\rangle$ is the free product of a free monoid by a group by Adian's algorithm.


text:
Q: Where to store data common to an app in windows phone? I have a variable which is used in all my 10 pages, where should I store it so that it is accessible by all pages? The same task can be accomplished in iOS by saving the variable in APPDELEGATE. What is the solution in windows phone?

A: you should take a look at some background reading to help
Sample code for IsolatedStorageSettings
Hope this will help you
public class AppSettings
    {
        // Our settings
        IsolatedStorageSettings settings;

        // The key names of our settings
        const List<String> PropertyIdList           = null;
        const List<String> FavPropertyIdList        = null;
        const string SearchSource                   = null;
        const string[] Suggestions                  = null;
        const string PropertyId                     = null;
        const string AgentContactInfo               = null;
        const string AgentShowPhoto                 = null;

        /// <summary>
        /// Constructor that gets the application settings.
        /// </summary>
        public AppSettings()
        {
            // Get the settings for this application.
            settings = IsolatedStorageSettings.ApplicationSettings;
        }

        /// <summary>
        /// Update a setting value for our application. If the setting does not
        /// exist, then add the setting.
        /// </summary>
        /// <param name="Key"></param>
        /// <param name="value"></param>
        /// <returns></returns>
        public bool AddOrUpdateValue(string Key, Object value)
        {
            bool valueChanged = false;

            // If the key exists
            if (settings.Contains(Key))
            {
                // If the value has changed
                if (settings[Key] != value)
                {
                    // Store the new value
                    settings[Key] = value;
                    valueChanged = true;
                }
            }
            // Otherwise create the key.
            else
            {
                settings.Add(Key, value);
                valueChanged = true;
            }
            return valueChanged;
        }

        /// <summary>
        /// Get the current value of the setting, or if it is not found, set the
        /// setting to the default setting.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="Key"></param>
        /// <param name="defaultValue"></param>
        /// <returns></returns>
        public T GetValueOrDefault<T>(string Key, T defaultValue)
        {
            T value;

            // If the key exists, retrieve the value.
            if (settings.Contains(Key))
            {
                value = (T)settings[Key];
            }
            // Otherwise, use the default value.
            else
            {
                value = defaultValue;
            }
            return value;
        }
    }

A: According your comment, if you have a public property like:
public string MyStaticVariable { get; set; }
MyStaticVariable = "SomeValue";

defined in your App.xaml.cs, you can access it in every page by:
App.MyStaticVariable;

My opinion: If you are talking about 1 variable which can be defined at startup of your app, the Isolated Storage is just overkill.


text:
Q: What is better: CSS media queries or JQuery mobile? I'm newbie for developing mobile website. I very confused between two methods because I dont have any experience this it. Whats more better between two methods: css query when we using all of width device in css file or using jquery mobile that use php technique for differented user that use desktop or mobile [user->php?->mobile use jquery mobile/desktop use css standard]?
Many thanks for this answer

A: I will classify methods by their importance, from most important one to less important:
Client side detection
Using Modernizer javascript library to detect mobile / desktop environment
Server side detection
Using Modernizer Server or WURFL. Little complex then first solution but much more detailed (if you need more data about used device)
CSS media queries
Bad solution to detect desktop /mobile devices. Current mobile devices can have screen resolution equal to desktop platform
JavaScript based browser sniffing
Worst solution possible. Specially if you want to make distinction between smartphones and tablets.
To find more about this solutions, read my other article/answer with examples: https://stackoverflow.com/a/15055352/1848600

A: I have to post an answer in here since this comes first in search engines and accepted answer is not accurate.
There are two main concerns regarding responsive designs:

*

*Content: Content should be restructured based on the width/height of the view port so the user can view the content without the need of constant zooming in and zooming out. This needs to happen solely based on the resolution of the view port regardless of the device. It could be a mobile device or a small window in desktop. This mainly involved the look and feel of the website and it is absolutely fine to use media queries. Even IMHO it is the best to use media queries to have the separation of concerns between your view and logic. No web designer likes to see random width or height showing up on their html elements during debug without knowing where are they coming from. Media queries will help you to resize the elements and show or hide them; however, in some situations you may need to move elements around; I usually do these using ng-if or ng-switch in angular js in combination with modernizer.

*Functionality: If you need to turn on/off features based on the device functionalities, do not depend on the viewport specifications; use the vast libraries available in JS.

A: On a side note smartphone browsers seem to render at far lower resolution than actual device screen dimensions. Bust out a quick JS to show you your window resolution and run it on your phone.
Example: Chrome runs at 360x640px on my android screen of 1440x2560px.


text:
Q: Just one chance for a debugger session In my application, I can debug one time ! I change some lines in a "file".js.You can see what I get on the screen during my first debug session in this first copy screen.

and the second time....I receive a completely white screen...
I must precise that I don't receive the same comportement if I try the tutorial SuperHero !

A: I've seen this too and it seems to be a bug. Before running the code again, make sure you close the Debugger tab in the left side panel. If that tab is left open after debugging, subsequent debugging produces a blank code area.

A: close all debugger tabs from the studio (including the one that shows current paused threads) and open the following URL in your browser : http://127.0.0.1:8080/debugger
There is an issue currently being processed about the subject : https://github.com/Wakanda/wakanda-issues/issues/216


text:
Q: How to print strings from a list in sequence in Python? Suppose a list: s = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J"]
I understand how to print every item in the list:
for i in s:
    print (i)

which gives:
A
B
C
D
E
F
G
H
I
J

But suppose I want to split the printing in terms of n. So if n = 3:
A
B
C

D
E
F

G
H
I

J

These are my attempts:
k = 0
for i in s:
    while k < n:
        k += 1
        print (i)

and
k = 0
while k < n:
    for i in s:
        print (i)
    k += 1

I understand that my attempts are way off, but I can't seem to get it.
I know you can create sub-lists in terms of n and solve it that way, but is there a way you can do this otherwise?

A: k = 0
for i in s:
    if k == n-1:
       print i + '\n'
       k = 0
    else:
        print i
        k += 1

A: >>> s = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J"]
>>> n=3
>>> print('\n\n'.join(['\n'.join(s[i:i+n]) for i in range(0,len(s),n)]))
A
B
C

D
E
F

G
H
I

J


text:
Q: Why is Pandas Dataframe so slow when multiplying by a scalar? I've noticed that when you multiply a dataframe by a scalar, it's an order of magnitude slower than multiplying the numpy array instead.  The slowness increases more than linearly with dataframe size.  Python 3.6, Pandas 0.24.0.
Is there a better workaround?
Why is multiplying by a scalar so slow in Pandas?  It seems like a performance bug to me.
df0 = pd.DataFrame(np.random.randn(1000, 400))

# Time to make a copy
%timeit df = df0.copy();
1.25 ms ± 5.64 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

# Multiplying by a scalar is absurdly slow
%timeit df = df0.copy(); df = df * 1
64.7 ms ± 265 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)

# Using numpy is much faster
%timeit df = df0.copy(); df[:] = df.values * 1
3.54 ms ± 251 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

# Multiplying by another dataframe with the same indexes is much faster
%timeit df = df0.copy(); df = df * df0
1.68 ms ± 5.31 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

A:
Is there a better workaround?

You can working with numpy array and DataFrame constructor, if performance is important:
In [219]: %timeit df = df0.copy()
2.78 ms ± 37 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

In [220]: %timeit df = df0.copy(); df = df * 1
129 ms ± 3.74 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

In [221]: %timeit df = df0.copy(); df[:] = df.values * 1
9.35 ms ± 118 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

In [222]: %timeit df = df0.copy(); df = pd.DataFrame(df.values * 1,
                                                     index=df.index,
                                                     columns=df.columns)

4.88 ms ± 40.2 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

A: Is it really that bad?
In the following I wanted to show you how you can make your code faster. But then I realized, that it depends also on the size of the dataset in use. Nonetheless, let us first have a look at your problem. I will run the same code on my machine in order to gauge the comparison. I will do everything for a big dataset (100 times yours) and a small one (your dataset).
Pandas is slow on some numerical computations. Let's see how slow compared to equivalent numpy operations.
Using pandas 0.23.4 on Linux 32 Cores, within a jupyter notebook
(Using pandas 1.0.4 on Windows 2 Cores for the results at the end, within a jupyter notebook)
Note, that all results have been found within a jupyter notebook. I did not change any settings. It might be, that under real world conditions, the results would differ.
Measurements
In the following my measurements.
Big DataSet
import pandas as pd
import numpy as np

a = np.random.randn(10000, 4000)
df0 = pd.DataFrame(a.copy())
df = df0.copy()

Note, that I use a bit more data, 100 times more. Additionally, I use the magic %%time command for measurement instead of the %%timeit.
df.shape

(10000, 4000)

I run the following cell twice. The first time you run it, the kernel might still load libraries or compile something. It will show different results. But you can assume, that there is no internal state changed or results cached on the DataFrame when performing a simple multiplication (as it does when you perform a groupby and aggregation).
Furthermore, I do not create a copy in each cell as you did. Nonetheless, the following creates a new DataFrame and keeps the old one. It is not only a view on the left hand sides' dataframe.
%%time
_ = df * 1

CPU times: user 78 ms, sys: 90.6 ms, total: 169 ms
Wall time: 24.3 ms

If we assign the resulting DataFrame instance to the df pointer, the execution of the cell takes longer. Maybe, because the garbage collector frees the DataFrame from the left hand side: There is no reference left in the notebook to this one anymore. So be careful in your performance tests, what you are measuring!
%%time
df = df * 1

CPU times: user 84.4 ms, sys: 94.7 ms, total: 179 ms
Wall time: 31.7 ms

Or with inplace multiplication
%%time
df *= 1

CPU times: user 77.1 ms, sys: 97 ms, total: 174 ms
Wall time: 31 ms

Observations to the above: Note, that total time is higher than wall time (your wall clock or smartphone clock, nowadays). This tells us, that some multiprocessing or concurrent multithreading works in the background.

Let's continue now in how to make things faster. You tried the following, basically:
%%time
df[:] = df.values * 1.

CPU times: user 258 ms, sys: 234 ms, total: 492 ms
Wall time: 491 ms

This is not faster, because the __setitem__, which is quite sophisticated on pandas.Dataframes, is slow. The same you get for the loc.
%%time
df.loc[:] = df.values * 1.

CPU times: user 260 ms, sys: 224 ms, total: 485 ms
Wall time: 483 ms

Accessing the data directly

You can access the data directly, and set the values. This seems to be faster. (But you might have problems, if you have mixed datatypes in the DataFrame.)
%%time
df.values[...] = df.values * 1.

CPU times: user 95.7 ms, sys: 78.5 ms, total: 174 ms
Wall time: 173 ms

Or even faster, do everything inplace. (As long as df.values[...] returns a reference to the data store.)
%%time
df.values[...] *= 1

CPU times: user 43.4 ms, sys: 0 ns, total: 43.4 ms
Wall time: 42.6 ms

Can it be faster than that? Let's compare this with the following multiplications. First by multiplying the initial dataset, the numpyarray a ...
%%time
_ = a * 1

CPU times: user 45.9 ms, sys: 82.7 ms, total: 129 ms
Wall time: 128 ms

... and by performing the corresponding inplace multiplication.
%%time
a *= 1

CPU times: user 43.5 ms, sys: 0 ns, total: 43.5 ms
Wall time: 42.9 ms

It shows, that less then about 43 milliseconds cannot be expected. Therefore, accessing the data directly and operating on it is as fast as operating on numpy arrays directly.
But note, in my example, even the initial quess is faster than that. Showing, that there is some optimization taking place with pandas, which does not with numpy. Strange!
Small Dataset
Here I make the same observations as you did. The trick with accessing the data directly, works out best again (df.values[...] *= 1).
import numpy as np
import pandas as pd

a = np.random.randn(1000, 400)
df0 = pd.DataFrame(a.copy())
df = df0.copy()

df.shape
(1000, 400)

%%time
_ = df * 1
CPU times: user 4.23 ms, sys: 1.28 ms, total: 5.51 ms
Wall time: 2.83 ms

%%time
df = df * 1
CPU times: user 4.68 ms, sys: 188 µs, total: 4.87 ms
Wall time: 2.22 ms

%%time
df *= 1
CPU times: user 2.66 ms, sys: 1.76 ms, total: 4.42 ms
Wall time: 1.71 ms

%%time
df[:] = df.values * 1.
CPU times: user 4.28 ms, sys: 21 µs, total: 4.3 ms
Wall time: 3.51 ms

%%time
df.loc[:] = df.values * 1.
CPU times: user 3.77 ms, sys: 0 ns, total: 3.77 ms
Wall time: 3.13 ms

%%time
df.values[...] = df.values * 1.
CPU times: user 2.19 ms, sys: 0 ns, total: 2.19 ms
Wall time: 1.38 ms

%%time
df.values[...] *= 1
CPU times: user 211 µs, sys: 1.05 ms, total: 1.26 ms
Wall time: 681 µs

%%time
_ = a * 1
CPU times: user 1.61 ms, sys: 0 ns, total: 1.61 ms
Wall time: 818 µs

%%time
a *= 1
CPU times: user 379 µs, sys: 950 µs, total: 1.33 ms
Wall time: 671 µs

Open Questions
It looks that simple multiplications are sometimes faster with pandas as with numpy. Here for the big dataset from above.
%%timeit
_ = df * df
22.8 ms ± 590 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)

%%timeit
_ = a * a
133 ms ± 4.85 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

It does not matter whether I call timeit or time. The results are the same.
%%time
_ = df * df
CPU times: user 62.3 ms, sys: 99.2 ms, total: 162 ms
Wall time: 23.8 ms

%%time
_ = a * a
CPU times: user 57.6 ms, sys: 82.3 ms, total: 140 ms
Wall time: 139 ms

I did not expect this. And you?
I cross-checked this on Windows 10, 2 Cores with pandas 1.0.4. The results look basically the same. Althought the relative differences are not that big anymore.
%%timeit
df * df
165 ms ± 5.96 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

%%timeit
a * a
251 ms ± 9.71 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

A: Make pandas faster then numpy on simple mathematical operations
You can make pandas perform better then numpy (alone) if you install the module numexpr (and don't switch off it's usage. It is switched on by default).
Look at this for more explanations:
Why is pandas faster then numpy on simple mathematical operations?
By doing so, your example above will for sure perform better. I tested pandas'  behaviour for multiplications and other operators: left and right hand side  multiplication with scalars, row vectors, column vectors and matrices.


text:
Q: Is there a way to execute update of the updatepanel before the other function I'm programming an asp.net website so I want on a dropdownlist textchanged to update the panel and execute a function which takes the data from the DB and update the panel with this data all this things in js, But my panel update everytime that's good but with the relevant information only once at the first time.
The second time the data are filled before the panel update so when it update it's empty.
 protected void DropDownList1_TextChanged(object sender, EventArgs e)
        {
            currentPickArea = DropDownList1.SelectedItem.Text;

            UpdatePanel4.Update();

            if (currentPickArea != DROPLIST_PICK_AREA_START_TEXT)
            {

                LoadPickPlacesBySelectedPickArea();
                if (currentPickArea == "QA_Zone")
                {
                    component.processGetLocationByLocationId(currentPickArea);
                }
            }

        }

Initial view

View with panel updated correctly with right information

View when i tried to make a second update so without information get from database because the panel update after changes on the database

I want to execute the update first when the update is done or i know it will be done before the rest i let the program continue.

A: As far as I know, TextChanged is an internal event and should not be used. Change it to SelectedIndexChanged as this is the correct event to determine when the dropdown selection changes. You can also try setting the dropdown's AutoPostBack property to false and EnableViewState to true.


text:
Q: Flutter, how to get data array of object and show to ListView.builder? im new in flutter and i want to get my data from localhost phpmydmin.
here is my json:
{
    "status": true,
    "message": "Data ditemukan",
    "data": [
        {
            "id": "1",
            "username": "admin",
            "password": "d033e22ae348aeb5660fc2140aec35850c4da997",
            "nama": "admin",
            "token": "2a5c97cb31308b8d818da33a041fa47d"
        },
        {
            "id": "3",
            "username": "sani",
            "password": "86862f0600c8b9829d9ca9c8aaca3f0727b44b6e",
            "nama": "Sani Sandhika",
            "token": "661e23835d27f9d45cf371f59533f163"
        },
        {
            "id": "4",
            "username": "seno",
            "password": "d61a4fe61485d6437b698c11635d8fb8c5b79d2f",
            "nama": "Seno",
            "token": "7b9f0f54ca01c323bc810206adcaa38c"
        },
        {
            "id": "5",
            "username": "username",
            "password": "5baa61e4c9b93f3f0682250b6cf8331b7ee68fd8",
            "nama": "nama",
            "token": null
        }
    ]
}

and here is my UserModel:
import 'dart:convert';

List<User> allUsers(String str) {
  final jsonData = json.decode(str);
  return new List<User>.from(jsonData.map((x) => User.fromJson(x)));
}

class User {
  bool status;
  String message;
  List<Data> data;

  User({
    this.status,
    this.message,
    this.data,
  });

  factory User.fromJson(Map<String, dynamic> parsedJson) {
    var list = parsedJson['data'] as List;
    print(list.runtimeType);
    List<Data> dataList = list.map((i) => Data.fromJson(i)).toList();

    return User(
      status: parsedJson['status'],
      message: parsedJson['message'],
      data: dataList,
    );
  }
}

class Data {
  final int id;
  final String nama;
  final String username;

  Data({
    this.id,
    this.nama,
    this.username,
  });

  factory Data.fromJson(Map<String, dynamic> parsedJson) {
    return Data(
      id: parsedJson['id'],
      nama: parsedJson['nama'],
      username: parsedJson['username'],
    );
  }
}

this is my RestApi:
import 'package:flutter_rest_api_crud/models/models.dart';

import 'package:http/http.dart' as http;

class RestApi {
  String url = 'http://192.168.1.5/gizi/user/';

  Future<List<User>> getUsers() async {
    final response = await http.get('$url/user');
    print(response.body);
    return allUsers(response.body);
  }
}

and last here is my HomeScreen:
import 'package:http/http.dart' as http;
import 'package:flutter/material.dart';

class HomeScreen extends StatefulWidget {
  HomeScreen({Key key}) : super(key: key);

  @override
  _HomeScreenState createState() => _HomeScreenState();
}

class _HomeScreenState extends State<HomeScreen> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(),
    );
  }
}

And i want to get my data inside "data" from localhost phpmyadmin. and put it on ListView.builder. and i don't know what the next step to implement the listview to my homescreen.
anyone can help me ?

A: You can hit the API endpoint after initializing the Widget:
 List<User> _users = [];
  @override
  void initState() {
    super.initState();
    _load();
  }

  void _load() async {
    List<User> users =
        await RestApi.getUsers(); // load the users on Widget init
    setState(() => _users = users);
  }

Then display a nested ListView to display each User's Data:
    return Scaffold(
      appBar: AppBar(),
      body: new ListView.builder(
        itemCount: _users.length,
        itemBuilder: (BuildContext ctxt, int i) {
          return new Card(
            child: Column(
              children: [
                Text(_users[i].username),
                ListView.builder(
                  itemCount: _users[i].data.length,
                  itemBuilder: (BuildContext ctx, int j) {
                    return Text(_users[i]
                        .data[j]
                        .username); // display username as an example
                  },
                ),
              ],
            ),
          );
        },
      ),
    );

Follows a full example:
class _HomeScreenState extends State<HomeScreen> {
  List<User> _users = [];
  @override
  void initState() {
    super.initState();
    _load();
  }

  void _load() async {
    List<User> users =
        await RestApi.getUsers(); // load the users on Widget init
    setState(() => _users = users);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(),
      body: new ListView.builder(
        itemCount: _users.length,
        itemBuilder: (BuildContext ctxt, int i) {
          return new Card(
            child: Column(
              children: [
                Text(_users[i].username),
                ListView.builder(
                  itemCount: _users[i].data.length,
                  itemBuilder: (BuildContext ctx, int j) {
                    return Text(_users[i]
                        .data[j]
                        .username); // display username as an example
                  },
                ),
              ],
            ),
          );
        },
      ),
    );
  }
}

As your app gets more complicated, I'd suggest checking out different State Management strategies, such as BLoC.


text:
Q: How can I do custom JWT validation with Flask and flask_jwt_extended? I want to add additional verification to the token when @jwt_required is called. I want to verify one of the claims. Is there away I can do this with JWTManager?
Currently my code just calls:
jwt = JWTManager(app)

And I decorate the functions with: @jwt_required

A: Off the top of my head, my inclination would be to create a custom decorator that wraps jwt_required.
Here's a rough idea of how it might look, via the functools.wraps documentation:
from functools import wraps
from flask_jwt_extended import jwt_required
from flask_jwt_extended.view_decorators import _decode_jwt_from_request
from flask_jwt_extended.exceptions import NoAuthorizationError

def custom_validator(view_function):
    @wraps(view_function)
    def wrapper(*args, **kwargs):
        jwt_data = _decode_jwt_from_request(request_type='access')

        # Do your custom validation here.
        if (...):
            authorized = True
        else:
            authorized = False

        if not authorized:
            raise NoAuthorizationError("Explanation goes here")

        return view_function(*args, **kwargs)

    return jwt_required(wrapper)

@app.route('/')
@custom_validator
def index():
    return render_template('index.html')

Here is where you can find the source code for jwt_required.

A: Posted this in your other question, but I'll post it here too just in case others stumble upon this.
Author here. For what it's worth, flask-jwt doesn't support requiring claims either (even though it says it does). https://github.com/mattupstate/flask-jwt/issues/98
EDIT: This is now available in flask-jwt-extended. https://github.com/vimalloc/flask-jwt-extended/issues/64#issuecomment-318800617
Cheers


text:
Q: Add ID found in list to new column in pandas dataframe Say I have the following dataframe (a column of integers and a column with a list of integers)...
      ID                   Found_IDs
0  12345        [15443, 15533, 3433]
1  15533  [2234, 16608, 12002, 7654]
2   6789      [43322, 876544, 36789]

And also a separate list of IDs...
bad_ids = [15533, 876544, 36789, 11111]

Given that, and ignoring the df['ID'] column and any index, I want to see if any of the IDs in the bad_ids list are mentioned in the df['Found_IDs'] column.  The code I have so far is:
df['bad_id'] = [c in l for c, l in zip(bad_ids, df['Found_IDs'])]

This works but only if the bad_ids list is longer than the dataframe and for the real dataset the bad_ids list is going to be a lot shorter than the dataframe.  If I set the bad_ids list to only two elements...
bad_ids = [15533, 876544]

I get a very popular error (I have read many questions with the same error)...
ValueError: Length of values does not match length of index

I have tried converting the list to a series (no change in the error).  I have also tried adding the new column and setting all values to False before doing the comprehension line (again no change in the error).
Two questions:

*

*How do I get my code (below) to work for a list that is shorter than
a dataframe?

*How would I get the code to write the actual  ID found
back to the df['bad_id'] column (more useful than True/False)?

Expected output for bad_ids = [15533, 876544]:
      ID                   Found_IDs  bad_id
0  12345        [15443, 15533, 3433]    True
1  15533  [2234, 16608, 12002, 7654]   False
2   6789      [43322, 876544, 36789]    True

Ideal output for bad_ids = [15533, 876544] (ID(s) are written to a new column or columns):
      ID                   Found_IDs  bad_id
0  12345        [15443, 15533, 3433]    15533
1  15533  [2234, 16608, 12002, 7654]   False
2   6789      [43322, 876544, 36789]    876544

Code:
import pandas as pd

result_list = [[12345,[15443,15533,3433]],
        [15533,[2234,16608,12002,7654]],
        [6789,[43322,876544,36789]]]

df = pd.DataFrame(result_list,columns=['ID','Found_IDs'])

# works if list has four elements
# bad_ids = [15533, 876544, 36789, 11111]

# fails if list has two elements (less elements than the dataframe)
# ValueError: Length of values does not match length of index
bad_ids = [15533, 876544]

# coverting to Series doesn't change things
# bad_ids = pd.Series(bad_ids)
# print(type(bad_ids))

# setting up a new column of false values doesn't change things
# df['bad_id'] = False

print(df)

df['bad_id'] = [c in l for c, l in zip(bad_ids, df['Found_IDs'])]

print(bad_ids)

print(df)

A: Using np.intersect1d to get the intersect of the two lists:
df['bad_id'] = df['Found_IDs'].apply(lambda x: np.intersect1d(x, bad_ids))

      ID                   Found_IDs    bad_id
0  12345        [15443, 15533, 3433]   [15533]
1  15533  [2234, 16608, 12002, 7654]        []
2   6789      [43322, 876544, 36789]  [876544]

Or with just vanilla python using intersect of sets:
bad_ids_set = set(bad_ids)
df['Found_IDs'].apply(lambda x: list(set(x) & bad_ids_set))

A: If want test all values of lists in Found_IDs column by all values of bad_ids use:
bad_ids = [15533, 876544]

df['bad_id'] = [any(c in l for c in bad_ids) for l  in df['Found_IDs']]
print (df)
      ID                   Found_IDs  bad_id
0  12345        [15443, 15533, 3433]    True
1  15533  [2234, 16608, 12002, 7654]   False
2   6789      [43322, 876544, 36789]    True

If want all match:
df['bad_id'] = [[c for c in bad_ids if c in l] for l  in df['Found_IDs']]
print (df)
      ID                   Found_IDs    bad_id
0  12345        [15443, 15533, 3433]   [15533]
1  15533  [2234, 16608, 12002, 7654]        []
2   6789      [43322, 876544, 36789]  [876544]

And for first match, if empty list is set False, possible solution, but not recommended mixing boolean and numbers:
df['bad_id'] = [next(iter([c for c in bad_ids if c in l]), False) for l  in df['Found_IDs']]
print (df)
      ID                   Found_IDs  bad_id
0  12345        [15443, 15533, 3433]   15533
1  15533  [2234, 16608, 12002, 7654]   False
2   6789      [43322, 876544, 36789]  876544

Solution with sets:
df['bad_id'] = df['Found_IDs'].map(set(bad_ids).intersection)
print (df)

      ID                   Found_IDs    bad_id
0  12345        [15443, 15533, 3433]   {15533}
1  15533  [2234, 16608, 12002, 7654]        {}
2   6789      [43322, 876544, 36789]  {876544}

And also similar with list comprehension:
df['bad_id'] = [list(set(bad_ids).intersection(l)) for l  in df['Found_IDs']]
print (df)
      ID                   Found_IDs    bad_id
0  12345        [15443, 15533, 3433]   [15533]
1  15533  [2234, 16608, 12002, 7654]        []
2   6789      [43322, 876544, 36789]  [876544]

A: You can apply and use np.any:
df['bad_id'] = df['Found_IDs'].apply(lambda x: np.any([c in x for c in bad_ids]))

This return the bool if exist a bad_id in Found_IDs, if you want to retrieve this bad_ids:
df['bad_id'] = df['Found_IDs'].apply(lambda x: [*filter(lambda x: c in x, bad_ids)])

This will return a list of the bad_ids at found_ids, if there is 0 it returns []

A: using merge and concat whilst grouping by your index to return all the matches.
bad_ids = [15533, 876544, 36789, 11111]

df2 = pd.concat(
    [
        df,
        pd.merge(
            df["Found_IDs"].explode().reset_index(),
            pd.Series(bad_ids, name="bad_ids"),
            left_on="Found_IDs",
            right_on="bad_ids",
            how="inner",
        )
        .groupby("index")
        .agg(bad_ids=("bad_ids", list)),
    ],
    axis=1,
).fillna(False)
print(df2)

      ID                   Found_IDs          bad_ids
0  12345        [15443, 15533, 3433]          [15533]
1  15533  [2234, 16608, 12002, 7654]            False
2   6789      [43322, 876544, 36789]  [876544, 36789]

A: Use explode and groupby aggregate
s = df['Found_IDs'].explode()
df['bad_ids'] = s.isin(bad_ids).groupby(s.index).any()

For bad_ids = [15533, 876544]
>>> df
      ID                   Found_IDs  bad_ids
0  12345        [15443, 15533, 3433]     True
1  15533  [2234, 16608, 12002, 7654]    False
2   6789      [43322, 876544, 36789]     True

OR
For getting values matching
s = df['Found_IDs'].explode()
s.where(s.isin(bad_ids)).groupby(s.index).agg(lambda x: list(x.dropna()))

For bad_ids = [15533, 876544]
      ID                   Found_IDs   bad_ids
0  12345        [15443, 15533, 3433]   [15533]
1  15533  [2234, 16608, 12002, 7654]        []
2   6789      [43322, 876544, 36789]  [876544]


text:
Q: Remove characters from string builder I'm trying to run a loop to remove some  characters from a string. but when I'm running the following code I get output(I on) only from the first run. I don't get the rest of the string. Can someone please help what I need to add here ? only shows the result from the first iteration. Thanks
someStr = "I don't know this";
StringBuilder sb = new StringBuilder(someStr);
int n = 3
for (int i = n - 1; i < sb.length(); i = n + 1) {
    sb = sb.deleteCharAt(i);
}
System.out.println(sb.toString());

A: The third part of the for statement is the instruction that should increment or decrement your index.
There, it is always 4.
To be clearer :
1st iteration : i = 2 => you remove the 'd', your string is now "I on't know this"

2nd iteration : i = 4 => you remove the ''', your string is now "I ont know this"

3rd iteration : i = 4 => you remove the 't', your string is now "I on know this"

4th iteration : i = 4 => you remove the ' ', your string is now "I onknow this"

...

A: If you want to remove characters from a String I recommend you to use Regex. This is an example to replace with empty strings the characters that you need to remove:
public static String cleanWhitPattern(String sample, String , String regex) {

    if (sample != null && regex != null) {
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(sample);

        if (matcher.find()) {
            return matcher.replaceAll("");
        }

        return sample;
    }

    return null;
}

Now, you simply call this method with your required pattern:
System.out.print(cleanWithPattern("I don't know this", "o*"));

And your output should be this:
I dn't knw this

A: Why not use String.replaceAll()?
someStr = "I don't know this";
System.out.print("Output :" );
System.out.println(someStr .replaceAll("t", ""));

A: For example, if you want to remove the char "k" from your string then you can do the following
JAVA:
String someStr = "I don't know this";
StringBuilder sb = new StringBuilder(someStr);

if(sb.toString().contains("k")){
  int index = sb.indexOf("k");
  sb.deleteCharAt(index);
  System.out.println(sb.toString());
}else{
  System.out.println("No such a char");
}

KOTLIN:
val someStr: String = "I don't know this"
val sb: StringBuilder = StringBuilder(someStr)

if(sb.toString().contains("k")){
  val index: Int = sb.indexOf("k")
  sb.deleteCharAt(index)
  print(sb.toString())

  }else{
   print("No such a char")
}

Of course, you can do many combinations or many improvements depends of your desired output.


text:
Q: How do I modify the Environment.CommandLine property? For unit tests I would like to mimic different commandline arguments. How do I modify the commandLine args to my program at runtime (looked around but can't find the trick)? Basically I am trying to find a way to modify the contents of the READONLY property Environment.CommandLine.

A: You can't, this is 'hard' read-only.  It comes out of Windows, GetCommandLine API function, it doesn't allow modifying it either.  You'll have to mock it.

A: It sounds to me as if you're trying to test things the hard way. Presumably somewhere you have a function that is reading directly from Environment.CommandLine. Refactor that method to take a string parameter (which in the real application will be populated from Environment.CommandLine), and test that method independently.


text:
Q: How much time/labor is spent setting up, and publishing a cross-platform mobile app? Let me provide an imaginary scenario so that my question is fully understood.  Let's assume you are an experienced cross-platform developer for iOS, Android and Windows Mobile.
Someone asks you to make them a simple digital clock.  Nothin fancy or special and not even a specific font is required. All they want you to do is make the application using Xamarin, and publish it to the app store on behalf of their company.  Also, assume they've not published any apps before, so some of the requirement would be to setup their company on all respective app stores for application distribution.
In hours, how long would it take to complete such a barebones project?
Why do I ask?
I'm not a mobile app developer, much less a multi-platform one, but I've tinkered with some mobile app development in the past.  I do, however, work as a business developer, so I have years of coding experience.  Just not mobile app development.
A friend of mine is asking me if I'd be willing to make a dead simple app.  It's not the one I outlined above but it is about as simple.
He's willing to pay.  Since I'm completely green to multi-platform app development, I'm actually considering taking him up on this because I'd like to gain the experience of learning how to create such an app and publish it-- start to finish.  My friend also understands that I don't write mobile apps professionally, but he knows me well, my level of professionalism and integrity and would prefer that I do this, over some other software development house.
I'd like to consider an up-front charge for the application that I will derive off of an hourly rate.  This way if it takes me longer because I'm learning how to publish an application to multiple app stores or, I'm fiddling around with setting up and testing a cross-platform dev environment, I'm not charging him for the learning experience.  That's a "cost" I'm willing to cover because, again, I'd like to learn how to do this and this app is just a good excuse to sit down and do it.
To be clear, I'm not even concerned that much with the monetary compensation.  However, this friend is a business man and I think/know he'd want to give me "fair" compensation.  In order to do that, though, I need to know how long it would take to reasonably develop a dead simple application by a pro whose been doing this for at least a few years.  I can apply my own hourly rates to those estimates and give him a realistic, but fair, offer.

A:
"... and publish it to the app store on behalf of their company"

Ok so the problem with this is that it is not something you can do on behalf of a random company. It involves bank accounts, taxes company registration numbers etc.
So you need the full cooperation of the company and realistically an executive officer of that company sitting down with you and setting passwords etc.
Additionally it may require the company to take steps which rely on third parties to complete. I had to send off for a number from the US tax authorities for example when I registered my UK company on the google store. Stuff companies will not be happy letting a third party developer do for them.
However, having said all that. If your company is responsive to these requests its fairly simple to jump through the hoops and set up store accounts. I would say a week or so max.
Once you have the account. Publishing an app also requires more input that simply uploading the code.
You will need screenshots and various bits of marketing copy, icons, support email addresses etc. Again, not hard if you have them all to hand but a source of endless delay if you need to source them from a marketing dept at the last minute.
I do think its a good thing for you to do though. I would be completely up front with your friend and go through the process together as a learning experience.
Just charge for writing the code. but make sure you start setting up accounts at the start of the project. Dont wait for the code to be finished.


text:
Q: If I have two columns, how can I select all distinct values of columnA where columnB is never a specific value given that columnA is the same value? So let's say I have two columns:

A
B

1
300

1
299

2
300

2
300

3
299

3
299

I want to look for distinct values of A such that there is never a combination of A and B where B equals 300.
In my example, I would want to return the columnA value 3.
Result

A

3

How do I accomplish this with SQL?

A: What you are looking for is called conditional aggregation. You want to aggregate by A (i.e. show A values in your result) and have a check only applied on particular B values. For instance:
select a
from mytable
group by a
having count(case when b = 300 then 1 end) = 0;

A: A simple subquery will give the results.
Exclude the Rows using the NOT IN keyword
SELECT DISTINCT ColumnA
FROM TABLE
WHERE ColumnA NOT IN(
    SELECT ColumnA FROM Table WHERE ColumnB=300)

A: You can also use NOT EXISTS
SELECT DISTINCT A
FROM tbl t1
WHERE NOT EXISTS(
    SELECT 1 FROM Tbl t2 WHERE t2.A=t1.B AND t2.B=300)


text:
Q: wordpress/ visual composer shortcode not updating on mobile device This really basic shortcode works fine on PC (I.E., Firefox) ~ as in each time I reload the webpage calling the shortcode, it displays a new random number.  However it does not work on mobile device (it is just stuck on the same/first generated number all the time), even if I close the browser and re-open.  Any suggestions?
function shortcode_mytable( $atts ){
$rand_var=rand();
return $rand_var;
}
add_shortcode( 'mytable', 'shortcode_mytable' );


text:
Q: Removing comma from numbers in R My numbers have "," for 1,000 and above and R considers it as factor. I want to switch two such variables from factor to numeric (Actually both variables are Numbers, but R considers them as factor for some reason (data is imported from excel). To change a factor variable mydata$x1 to numeric variables I use the following code but it seems not to work properly and some values change, for example it changes 8180 to zero! and it happened many other values as well. Is there other ways to do so without such issues?
mydata$x1<- as.numeric(as.character(mydata$x1))

A: Since it seems as though the problem is that you have saved your numeric data as characters in Excel (instead of using format to display the commas) you may want a function like this.
#' Replace Commas Function
#'
#' This function converts a character representation of a number that contains a comma separator with a numeric value.
#' @keywords read data
#' @export
replaceCommas<-function(x){
  x<-as.numeric(gsub("\\,", "", x))
}

Then
rcffull$RetBackers <- replaceCommas(rcffull$Returning.Backers)
rcffull$NewBackers <- replaceCommas(rcffull$New.Backers)

A: The reason that G5W is asking for dput ouput is that he (we) are unable to figure out where something that displays as 8180 when it's a factor might not properly be converted with that code. It's not because of leading or trailing spaces (which would not appear in a print-version of a factor. Witness this test:
>  as.numeric(as.character(factor(" 8180")))
[1] 8180
> as.numeric(as.character(factor(" 8180 ")))
[1] 8180

And the fact that it gets converted to 0 is a real puzzle since generally items that do not get recognized as parseable R numerics will get coerced to NA (with a warning).
> as.numeric(as.character(factor(" 0 8180 ")))
[1] NA
Warning message:
NAs introduced by coercion

We really need the dput output from the item that displays as "8180" and its neighbors.


text:
Q: Возникает ошибка ERROR: stack depth limit exceeded     create or replace function get_beta_company_name(order_record orders)
    returns text as $$
begin
    return case
        when order_record.source_id = '141' then case
        when exists (
            select beta_company_name
            from v_delivery_orders
            where source_id = '141'
            and status_confirmed_at >= now() - interval '1 day'
            group by beta_company_name
            having avg(
                case when beta_company_name = '832' then 1 else 0 end
            ) > 0.7) then '831' else '832'
        end
    else case
        when order_record.is_courier = 1 then '800'
        else
            case
                when order_record.prime_cost <= 280 then '837'
                when 280 < order_record.prime_cost and order_record.prime_cost < 450 then '877'
                when 450 < order_record.prime_cost and order_record.prime_cost < 550 then '849'
                when 550 < order_record.prime_cost and order_record.prime_cost < 700 then '800'
                when 700 < order_record.prime_cost and order_record.prime_cost < 900 then '876'
                when 900 <= order_record.prime_cost then '848'
                else '800'
            end
        end
    end;
end;
$$ language plpgsql;

Помогите разобраться с ошибкой!

A: Разобрался, происходит рекурсивный вызов данной функции


text:
Q: Restricting variable use to one file Bit of a weird question but bear with me. I'm writing a small MVC framework mostly for learning purposes. When I load views, I just include the view file and then use extract($data); so I can use variables in my view. This is that it looks like in my controller:
// Assign view variables and load the views
$data = array('title' => 'testing the framework',
              'users' => $this->models['Users']->getAllUsers());
$this->loadViews(array('header', 'home', 'footer'), $data);

It works perfectly, but it just occured to me that if I have any variables elsewhere in my project that are called $title or $users, they will conflict to what I'm extract()'ing. THis hasn't become a problem yet but I have a feeling I need to deal with it now before it does.
The only solution I've found is using a prefix for the variables being extract()ed. SO I can use them in my template like <?php echo $tpl_whatever; ?> instead of <?php echo $whatever; ?>
Can anyone offer some advice? Maybe a way I can limit the variables scope?
Thanks!

A: Only variables in your method can have conflict See Variable Scope but if such happens you can resolved conflict in extract easy with extra flags such as EXTR_PREFIX_ALL.
You can also look at EXTR_PREFIX_SAME , EXTR_SKIP or EXTR_OVERWRITE to resolve possible collusion during extraction
Your Variables
$name = "Baba";
$array = array("title" => "Restricting variable use to one file",
               "name"  => "James Dawson");

Example EXTR_PREFIX_ALL
extract($array,EXTR_PREFIX_ALL,"new");
var_dump($new_title,$new_name,$name);
           ^------------------------------ it now has prifix

Output
string 'Restricting variable use to one file' (length=36)
string 'James Dawson' (length=12)
string 'Baba' (length=4)

Example EXTR_PREFIX_SAME
extract($array, EXTR_PREFIX_SAME, "prifix");
var_dump($name,$title,$prifix_name);
                           ^------------------ Only Conflict has prifix

Output
string 'Baba' (length=4)
string 'Restricting variable use to one file' (length=36)
string 'James Dawson' (length=12)

A: There will no conflict with other controller because the $data variables that you are extracting are private. Also if your variable has duplicate inside your controllers function, the last declaration will be the one to be used.


text:
Q: Flipping two UIView using CATransform3D I have created Visiting Card which has Front view & back View. When i tap on the front view it should flip the UIView & show the back side of the View.
Here is Code which I am trying:
 CATransform3D transform = CATransform3DMakeRotation(M_PI, 0, 1, 0);
 transform.m34 = 1.0/700.0;

 CABasicAnimation *rotation = [CABasicAnimation animationWithKeyPath:@"transform"];
 rotation.fromValue = [NSValue valueWithCATransform3D:CATransform3DIdentity];
 rotation.toValue = [NSValue valueWithCATransform3D:transform];
 rotation.duration = DURATION;

 CABasicAnimation *translation = [CABasicAnimation animationWithKeyPath:@"position"];
 translation.fromValue = [NSValue valueWithCGPoint:CGPointMake(self.imageview.center.x,[[self.imageview superview] center].y-45)];
 translation.toValue = [NSValue valueWithCGPoint:CGPointMake(_frame.origin.x+_frame.size.width/2,
                                                             _frame.origin.y+_frame.size.height/2)];
 translation.duration = DURATION;

 CABasicAnimation *translation = [CABasicAnimation animationWithKeyPath:@"position"];
 translation.fromValue = [NSValue valueWithCGPoint:CGPointMake(self.imageview.center.x,[[self.imageview superview] center].y-45)];
 translation.toValue = [NSValue valueWithCGPoint:CGPointMake(_frame.origin.x+_frame.size.width/2,
                                                             _frame.origin.y+_frame.size.height/2)];
 translation.duration = DURATION;
 CAAnimationGroup *group = [CAAnimationGroup animation];

 group.animations = @[ translation, rotation ];
 group.duration = DURATION;
 group.delegate = self;
 group.fillMode = kCAFillModeForwards;
 group.removedOnCompletion = NO;
 [layer addAnimation:group forKey:nil];

Above code works perfectly for single view. How to combine the 2nd view to get flipping from front & back effect.

A: Using Core Animation
You can add both front and back to a container view. The back view will have a 180 degree rotation around Y and the front will be just normal. Both layers will be single sided (by setting layer.doubleSided = NO;.
Then when you apply the rotation you would animate the rotation of the container view so that both front and back animate at the same time.
UIView transitions
Or you could just use the built in flip animation
transitionFromView:toView:duration:options:completion:

and pass either UIViewAnimationOptionTransitionFlipFromLeft or UIViewAnimationOptionTransitionFlipFromRight for the option.


text:
Q: Apply conditional formatting on few columns based on data in one column I was trying to apply conditional formatting to few cells on multiple column based on data of one column but do not get expected result.

When Name has data then I want to fill border of all column (SL, Name, Conveyance) like Expected Formatting. If Name column is blank then there should no border in corresponding row.

I have tried below formulas in different ways but no luck. Any help is greatly appreciated.
=IF(C6:C11<>"",TRUE,FALSE)
=IF(C6<>"",TRUE,FALSE)

A: To make the lines enter this in conditional formatting:
=NOT($C6="") or $C6<>""

And to remove the lines, enter this (notice I remove the side line) to this:
=$C6=""

So my final "Conditional Formatting Rules Manager" looks like this:

And the final result:


text:
Q: Best/Correct way to call an Informix stored procedure via ADO.Net Command? I have an Informix database which exposes some stored procedures, I have an abstracted data accessor that handles communicating with them but I have a problem with a null value.
Directly you can call:
execute procedure some_stored_procedure(1,2,NULL,3)

and get back correct results, I would rather there not be this nullable field, but it is out of my hands. Anyway I was originally trying to call it like so:
var command = connection.CreateCommand();
command.CommandType = CommandTypes.StoredProcedure
command.CommandText = "some_stored_procedure"
// Pass in the parameters

However doing that causes Informix to throw a syntax error, so instead I have been forced to go with the:
var command = connection.CreateCommand();
command.CommandText = "execute procedure some_stored_procedure(?,?,?,?)";
// Pass in parameters

Which works but never passes back correct results, and if I try and make parameter 3 null it gives another syntax error. Am I missing something or is there a better way to call these stored procedures?

A: try parameterizing the parameters (you can use OdbcParameters if working with the odbcdriver) and then pass DbNull.Value where Null is required.
Try this:
var command = connection.CreateCommand();
command.CommandType = CommandTypes.Text;
command.CommandText = "call some_stored_procedure(?,?,?,?)";

command.Parameters.Add(param); //add all your parameters.

A: Format the query as follow:
        strQuery = string.Format("EXECUTE PROCEDURE Cronos_UpdateStateLegacyProduct ({0})", oValidityProducts.PurchaseId);

        OdbcConnection oConnection = new OdbcConnection(this.strConnectionString);
        OdbcCommand oCommand = new OdbcCommand();
        oCommand.CommandType = CommandType.StoredProcedure;
        oCommand.CommandText = strQuery;
        oCommand.Connection = oConnection;

        oConnection.Open();

        intResult = oCommand.ExecuteNonQuery();

Best Regards

A: In case you are using an ODBC connection, when using CommandType.StoredProcedure you must use a diferent syntax for the procedure's name. In your case:
CommandText = "{ CALL some_stored_procedure(?,?,?,?)}"

Check this link for more information: https://support.microsoft.com/en-us/kb/310130


text:
Q: Chained combos in register form Joomla 2.5 Good morning.
I'm using joomla 2.5, I need add extra fields to my user form registration, I use user-profile plugin and I add 2 extra fields SQL type, at this point all is ok, but I need, that this fields work like chained combo  i.e: when I select a Departamento (Department) I need the field Municipio (Municipalitie) just display the Municipalities that belonging to that department.
Thanks

A: Since you didn't specify in which language you wanted this done in. There's a jquery plugin  you could use by Mike Tuupola which does just this. You might want to check it out.


text:
Q: Why does my CalcWorkingDays VBA Function give me two different results on the same period? First of all, I'm a beginner and still learning VBA, thank you for your consideration.
I have a CalcWorkingDays function which which calculates working days within a specific period (period defined by a query parameter).
But when it returns results, for some periods it is completely correct, and for some others it's incorrect (See example at the end)
I guess the problem is in these lines :
If Format(DateCnt, "w") <> "7" And _
    Format(DateCnt, "w") <> "6" Then

Thank you !
Public Function CalcWorkingDays(BegDate As Variant, EndDate As Variant) As Integer

 Dim WholeWeeks As Variant
 Dim DateCnt As Variant
 Dim EndDays As Integer

 On Error GoTo Err_Work_Days

 BegDate = DateValue(BegDate)
 EndDate = DateValue(EndDate)
 WholeWeeks = DateDiff("w", BegDate, EndDate)
 DateCnt = DateAdd("ww", WholeWeeks, BegDate)
 EndDays = 0

 Do While DateCnt <= EndDate
 If Format(DateCnt, "w") <> "7" And _
 Format(DateCnt, "w") <> "6" Then
 EndDays = EndDays + 1
 End If
 DateCnt = DateAdd("d", 1, DateCnt)
 Loop

 CalcWorkingDays = WholeWeeks * 5 + EndDays

Exit Function

[...]
End Function`

For example, on march 2019.
there is a total of 21 working days. We have both employees A and B
A : he's on a project from 01/01/2019 to 31/12/2019, the function gives me 21 working days for march which is correct
B : He's been assigned to a project from 01/03/2019 to 08/03/2019, it gives me 5 which is incorrect, it should give me 6 (8 total days days - 2 days for week end

A: Harassed Dad is right - if you use Format(DateCnt, "w"), Sunday will be "1", Monday "2"...
But you shouldn't use Format to get the day of the week - Format is for formatting data into strings, and there is no need to involve strings. Use the Weekday-function instead.
The default behavior for Weekday is that Sunday will be 1 (as a number, not a string), but you can change that with the 2nd parameter (FirstDayOfWeek). This defines which day you want to have as first day of the week.
So you can change your logic for example to
If Weekday(DateCnt, vbMonday) < 6 Then

A: Maybe you try to use function networkdays
=NETWORKDAYS(start_date,end_date,holidays)

holidays is optional
For example, if you have the date January 4, 2016 (a Monday) in cell B4, and January 11, 2016 (also a Monday) in cell C4, this formula will return 6:
=NETWORKDAYS(B4,C4)

for VBA in ACCESS
Sub test()
    Dim xl As Object
    Set xl = CreateObject("Excel.Application")
        BegDate = #4/11/2019#
        EndDate = #6/11/2019#
        result = xl.WorksheetFunction.NetworkDays(BegDate, EndDate) ' 44
    Set xl = Nothing
End Sub

OR
this one

A: Date arithmetic is tricky. If you are not hugely concerned about efficiency and your intervals are relatively small then a really simple function will do the trick
Public Function CalcWorkingDays(BegDate As Variant, EndDate As Variant) As Integer
    CalcWorkingDays = 0
    For i = begdate To enddate
        If Weekday(i, vbMonday) <= 5 Then
            CalcWorkingDays = CalcWorkingDays + 1
        End If
    Next
End Function

Not particularly elegant but effective, easy to understand, and easy to modify.

A:
The function gives me 21 working days for march which is correct B
He's been assigned to a project from 01/03/2019 to 08/03/2019, it
  gives me 5 which is incorrect, it should give me 6.

A diff-function will never include the last date. If you wish to include that last date, add one day to the last date before calculating:
? DateDiffWorkDays(#2019/03/01#, #2019/03/31#)
 21
? DateDiffWorkDays(#2019/03/01#, #2019/04/01#)
 21

? DateDiffWorkDays(#2019/03/01#, #2019/03/08#)
 5
? DateDiffWorkDays(#2019/03/01#, #2019/03/09#)
 6

Also, as already noted, specify Monday as the first day of the week. Further, don't use Format; Weekday is the "direct" method. Thus:
If Weekday(DateCnt, vbMonday) < 6 Then
    EndDays = EndDays + 1
End If

For an extended method that takes holidays into account, study my functions:
Option Compare Database
Option Explicit

' Returns the count of full workdays between Date1 and Date2.
' The date difference can be positive, zero, or negative.
' Optionally, if WorkOnHolidays is True, holidays are regarded as workdays.
'
' Note that if one date is in a weekend and the other is not, the reverse
' count will differ by one, because the first date never is included in the count:
'
'   Mo  Tu  We  Th  Fr  Sa  Su      Su  Sa  Fr  Th  We  Tu  Mo
'    0   1   2   3   4   4   4       0   0  -1  -2  -3  -4  -5
'
'   Su  Mo  Tu  We  Th  Fr  Sa      Sa  Fr  Th  We  Tu  Mo  Su
'    0   1   2   3   4   5   5       0  -1  -2  -3  -4  -5  -5
'
'   Sa  Su  Mo  Tu  We  Th  Fr      Fr  Th  We  Tu  Mo  Su  Sa
'    0   0   1   2   3   4   5       0  -1  -2  -3  -4  -4  -4
'
'   Fr  Sa  Su  Mo  Tu  We  Th      Th  We  Tu  Mo  Su  Sa  Fr
'    0   0   0   1   2   3   4       0  -1  -2  -3  -3  -3  -4
'
' Execution time for finding working days of three years is about 4 ms.
'
' Requires table Holiday with list of holidays.
'
' 2015-12-19. Gustav Brock. Cactus Data ApS, CPH.
'
Public Function DateDiffWorkdays( _
    ByVal Date1 As Date, _
    ByVal Date2 As Date, _
    Optional ByVal WorkOnHolidays As Boolean) _
    As Long

    Dim Holidays()      As Date

    Dim Diff            As Long
    Dim Sign            As Long
    Dim NextHoliday     As Long
    Dim LastHoliday     As Long

    Sign = Sgn(DateDiff("d", Date1, Date2))
    If Sign <> 0 Then
        If WorkOnHolidays = True Then
            ' Holidays are workdays.
        Else
            ' Retrieve array with holidays between Date1 and Date2.
            Holidays = GetHolidays(Date1, Date2, False) 'CBool(Sign < 0))
            ' Ignore error when using LBound and UBound on an unassigned array.
            On Error Resume Next
            NextHoliday = LBound(Holidays)
            LastHoliday = UBound(Holidays)
            ' If Err.Number > 0 there are no holidays between Date1 and Date2.
            If Err.Number > 0 Then
                WorkOnHolidays = True
            End If
            On Error GoTo 0
        End If

        ' Loop to sum up workdays.
        Do Until DateDiff("d", Date1, Date2) = 0
            Select Case Weekday(Date1)
                Case vbSaturday, vbSunday
                    ' Skip weekend.
                Case Else
                    If WorkOnHolidays = False Then
                        ' Check for holidays to skip.
                        If NextHoliday <= LastHoliday Then
                            ' First, check if NextHoliday hasn't been advanced.
                            If NextHoliday < LastHoliday Then
                                If Sgn(DateDiff("d", Date1, Holidays(NextHoliday))) = -Sign Then
                                    ' Weekend hasn't advanced NextHoliday.
                                    NextHoliday = NextHoliday + 1
                                End If
                            End If
                            ' Then, check if Date1 has reached a holiday.
                            If DateDiff("d", Date1, Holidays(NextHoliday)) = 0 Then
                                ' This Date1 hits a holiday.
                                ' Subtract one day to neutralize the one
                                ' being added at the end of the loop.
                                Diff = Diff - Sign
                                ' Adjust to the next holiday to check.
                                NextHoliday = NextHoliday + 1
                            End If
                        End If
                    End If
                    Diff = Diff + Sign
            End Select
            ' Advance Date1.
            Date1 = DateAdd("d", Sign, Date1)
        Loop
    End If

    DateDiffWorkdays = Diff

End Function

' Returns the holidays between Date1 and Date2.
' The holidays are returned as an array with the
' dates ordered ascending, optionally descending.
'
' The array is declared static to speed up
' repeated calls with identical date parameters.
'
' Requires table Holiday with list of holidays.
'
' 2015-12-18. Gustav Brock, Cactus Data ApS, CPH.
'
Public Function GetHolidays( _
    ByVal Date1 As Date, _
    ByVal Date2 As Date, _
    Optional ByVal OrderDesc As Boolean) _
    As Date()

    ' Constants for the arrays.
    Const DimRecordCount    As Long = 2
    Const DimFieldOne       As Long = 0

    Static Date1Last        As Date
    Static Date2Last        As Date
    Static OrderLast        As Boolean
    Static DayRows          As Variant
    Static Days             As Long

    Dim rs                  As DAO.Recordset

    ' Cannot be declared Static.
    Dim Holidays()          As Date

    If DateDiff("d", Date1, Date1Last) <> 0 Or _
        DateDiff("d", Date2, Date2Last) <> 0 Or _
        OrderDesc <> OrderLast Then

        ' Retrieve new range of holidays.
        Set rs = DatesHoliday(Date1, Date2, OrderDesc)

        ' Save the current set of date parameters.
        Date1Last = Date1
        Date2Last = Date2
        OrderLast = OrderDesc

        Days = rs.RecordCount
            If Days > 0 Then
                ' As repeated calls may happen, do a movefirst.
                rs.MoveFirst
                DayRows = rs.GetRows(Days)
                ' rs is now positioned at the last record.
            End If
        rs.Close
    End If

    If Days = 0 Then
        ' Leave Holidays() as an unassigned array.
        Erase Holidays
    Else
        ' Fill array to return.
        ReDim Holidays(Days - 1)
        For Days = LBound(DayRows, DimRecordCount) To UBound(DayRows, DimRecordCount)
            Holidays(Days) = DayRows(DimFieldOne, Days)
        Next
    End If

    Set rs = Nothing

    GetHolidays = Holidays()

End Function

' Returns the holidays between Date1 and Date2.
' The holidays are returned as a recordset with the
' dates ordered ascending, optionally descending.
'
' Requires table Holiday with list of holidays.
'
' 2015-12-18. Gustav Brock, Cactus Data ApS, CPH.
'
Public Function DatesHoliday( _
    ByVal Date1 As Date, _
    ByVal Date2 As Date, _
    Optional ByVal ReverseOrder As Boolean) _
    As DAO.Recordset

    ' The table that holds the holidays.
    Const Table         As String = "Holiday"
    ' The field of the table that holds the dates of the holidays.
    Const Field         As String = "Date"

    Dim rs              As DAO.Recordset

    Dim SQL             As String
    Dim SqlDate1        As String
    Dim SqlDate2        As String
    Dim Order           As String

    SqlDate1 = Format(Date1, "\#yyyy\/mm\/dd\#")
    SqlDate2 = Format(Date2, "\#yyyy\/mm\/dd\#")
    ReverseOrder = ReverseOrder Xor (DateDiff("d", Date1, Date2) < 0)
    Order = IIf(ReverseOrder, "Desc", "Asc")

    SQL = "Select " & Field & " From " & Table & " " & _
        "Where " & Field & " Between " & SqlDate1 & " And " & SqlDate2 & " " & _
        "Order By 1 " & Order

    Set rs = CurrentDb.OpenRecordset(SQL, dbOpenSnapshot)

    Set DatesHoliday = rs

End Function

You'll see, that in its core it's nothing but a simple loop, which is so fast that attempts to optimise won't pay off for typical usage.


text:
Q: How to generate accurate masks after prediction I am working on a segmentation task using a deep learning approach,after training I want to make predictions on my test images to do so I first load my model and my images, and then save the generated masks into a folder

,I used this code
model = load_model('..../accuracy.h5')#loading the model
TEST_PATH = ''#path to my test images
PRED_PATH = ''#path to where I want to save my generated masks
#this block is used to read my test images and save them into X
test_ids  = os.listdir(TEST_PATH)
X = np.zeros((len(test_ids), IMG_HEIGHT, IMG_WIDTH, IMG_CHANNELS), dtype=np.uint8)
ctr=0
for n, id_ in tqdm(enumerate(test_ids), total=len(test_ids)):
    path = TEST_PATH + id_
    image_file = os.listdir(path + '/images/')
    X[ctr]  = imread(path+'/images/'+image_file[0])[:,:,:IMG_CHANNELS]
    ctr=ctr+1

preds_test = model.predict(X, verbose=1)#predictions on my images
#this block is used to save the generated mask intoa folder
ctr=0
for i in range(len(test_ids)):
    file_name=test_ids[i]+'pred.png'
    img=preds_test[ctr]
    imsave(PRED_PATH+file_name,img)
    ctr= ctr+1

this is an exemple of the generated mask !
the quality of the mask isn't good I don't know if I am missing somehting in the prediction process! could any one help me please!


text:
Q: Map-only job is not running. Stuck at Running job I have streamed data through Apache Flume and the data has been stored in a temp file in my hdfs folder at: user/*****/tweets/FlumeData.1643626732852.tmp
Now I am trying to run a mapper only job which will be pre-processing the job by way of url removal, # tag removal, @ removal, stop word removal etc.
However, the mapper only job is stopped at Running job.
Mapper job code:
 hadoop jar mr-job-jars/SentimentAnalysisPreprocessingJob.jar com.hadoop.poc.sentimentAnalysis.phase1.SentimentAnalysisPreprocessingDriver /user/*****/tweets/ FlumeData.1643626732852.tmp /output

Execution output:
2022-01-31 06:16:18,151 INFO client.RMProxy: Connecting to ResourceManager at /0.0.0.0:8032
2022-01-31 06:16:18,611 WARN mapreduce.JobResourceUploader: Hadoop command-line option parsing not performed. Implement the Tool interface and execute your application with ToolRunner to remedy this.
2022-01-31 06:16:18,666 INFO mapreduce.JobResourceUploader: Disabling Erasure Coding for path: /tmp/hadoop-yarn/staging/aviparna/.staging/job_1643615018627_0004
2022-01-31 06:16:18,996 INFO input.FileInputFormat: Total input files to process : 1
2022-01-31 06:16:19,108 WARN hdfs.DataStreamer: Caught exception
java.lang.InterruptedException
    at java.lang.Object.wait(Native Method)
    at java.lang.Thread.join(Thread.java:1252)
    at java.lang.Thread.join(Thread.java:1326)
    at org.apache.hadoop.hdfs.DataStreamer.closeResponder(DataStreamer.java:986)
    at org.apache.hadoop.hdfs.DataStreamer.endBlock(DataStreamer.java:640)
    at org.apache.hadoop.hdfs.DataStreamer.run(DataStreamer.java:810)
2022-01-31 06:16:19,168 INFO mapreduce.JobSubmitter: number of splits:1
2022-01-31 06:16:19,449 INFO mapreduce.JobSubmitter: Submitting tokens for job: job_1643615018627_0004
2022-01-31 06:16:19,451 INFO mapreduce.JobSubmitter: Executing with tokens: []
2022-01-31 06:16:19,794 INFO conf.Configuration: resource-types.xml not found
2022-01-31 06:16:19,794 INFO resource.ResourceUtils: Unable to find 'resource-types.xml'.
2022-01-31 06:16:19,935 INFO impl.YarnClientImpl: Submitted application application_1643615018627_0004
2022-01-31 06:16:20,035 INFO mapreduce.Job: The url to track the job: http://ubuntu:8088/proxy/application_1643615018627_0004/
2022-01-31 06:16:20,038 INFO mapreduce.Job: Running job: job_1643615018627_0004

What do I need to do to solve this problem? Please help.
Also, for any added information required please inform me. I will try to provide them as soon as possible.
Adding screenshot of the YARN UI:

A: Solved my problem by changing the mapreduce.framework.name from yarn to local in mapred-site.xml.
The problem seemed to be happening due to resource crunch in the machine.
Also after changing the properties, restart Hadoop services once again.


text:
Q: mod_wsgi: Reading POSTed file content remains empty I don't get it, I don't understand.
In a self-developed Python web framework I'm posting a file form element to the server using JavaScript.
var formData = new FormData();
formData.append('file', document.getElementById('file').files[0]);
var request = new XMLHttpRequest();
request.open("POST", url, true);
request.send(formData);

The server, sporting mod_wsgi, receives the request like so:
if environ['REQUEST_METHOD'] == 'POST':
    post_env = environ.copy()
    post_env['QUERY_STRING'] = ''
    form = cgi.FieldStorage(
            fp=environ['wsgi.input'],
            environ=post_env,
            keep_blank_values=True)

Then, when I want to access the form field's content to save it to a file, the following will return an empty result:
form['file'].file.read()

(All code has been edited for simplicity)
What puzzles me is that the form field will show the correct file name and MIME type, only file.read() remains empty.
Also all other information from other input text fields comes through and is accessible.
I also checked that environ['REQUEST_METHOD'] is actually POST.
As to HTTP Headers for encoding (such as multipart/form-data), I thought that the XMLHttpRequest object will take care of that, once formData.append() receives a file input as the value.

A: Okay, here's the solution:
I can't explain it, but the file form fields get emptied on first read, which I found out by accident. Maybe a bug, who knows.
I assumed that they would stay intact (like any other variable) and can be read multiple times.
What I ignored was that I had in fact addressed them several times.
So the solution was to first store the file's content in a variable, and then use that multiple times.


text:
Q: Nginx subdomains with www I have Nginx configured in a Amazon EC2 server.
Right now both www.myserver.com, .myserver.com works perfect.
What I need, is configure www..myserver.com. I need to redirect the user to .myserver.com. I mean, I need to rewrite the url or something.
How can I do that?

A: server {
    listen       80;
    server_name  www.myserver.com;
    return       301 http://myserver.com$request_uri;
}

You don't need "rewrites" in nginx. Leave them to apache, and read the docs:

*

*http://nginx.org/en/docs/http/server_names.html

*http://nginx.org/en/docs/http/request_processing.html

*http://nginx.org/en/docs/http/converting_rewrite_rules.html
Upd:
That is not clear from your question (who knows, what do you mean by double dots). But if you have ever tried to read the docs, you would easily modify the example for your needs:
server {
    listen       80;
    server_name  ~^www\.([^.]+\.myserver\.com)$;
    return       301 http://$1$request_uri;
}


text:
Q: Why is my bcrypt authorization always return true I setup a simple bcrpyt authorization on python. The hash matches every single time regardless of what the password is. I can't for the life of me figure out why it's doing this.
I for the life of me can't understand why it's doing this.
if bcrypt.hashpw(password, user.password) == user.password:
    uj = user_json(str(user.user_id), user.email, user.firstname, user.lastname, user.state, user.city)
    self.write(uj)
else:
    self.write(error_json(cna="cannot authorize user"))

Again regardless of the password I enter. The hash always returns something matching.


text:
Q: Does deleting my own question or answer attract penalty? I have read lot of questions related to deleted questions or answers to be available for users to see in their profiles, but my question is, does excess deletion of our own questions and answers attract penalty from the owners/moderators of SO?
Sometimes what happens is, when we see a question, we don't understand it properly but jump into them to answer to get early upvotes and later (when we get downvoted) we realize our mistake and would want to delete our own answers. The reason could be any of the following:

*

*The answer is just not reasonable enough for the question asked.

*To save your reputation points and avoid further downvotes.

*Your answer has 0 upvotes and a better answer is already available for the question.

*The question gets edited and your answer is no longer valid. New people would not know that the question has been edited and they start downvoting your answer since it's no longer relevant.

In doing this we might go to extreme cases, maybe in the range of deleting hundreds of our answers. So is there an upper limit for the number of answers we can delete in order to avoid penalty (if there is any such penalty for deletion)?

A: We shouldn't discourage people from fixing their answers when they discover mistakes. Sometimes, the answer is fundamentally wrong, and deleting is the best answer; although I tend to edit the answer to say something like "WARNING: when i wrote this, i was wrong." for future reference.

A: No. If the post was downvoted, deleting a question  helps you recover the reputation on the next recalc. So if you feel like deleting a post, go ahead. If you try to delete a question with answers or a post with comments, you may not be able to delete it by yourselves.
However if your post had upvotes, you will lose the reputation on recalc, this may come across as "penalty"
Abusive behavior for example asking a question and then deleting it after you get an answer is bad, because the intention of SO is to help the community gain from each other. However if you are only deleting bad, incorrect, duplicate questions, I think you have nothing to fear.

A: Yes, excess deletion of our own questions might get you suspended (this is not automated though). Or if the reason is that many of your questions are really bad, then you might run into the dreaded Sorry, we are no longer accepting questions from this account (which is automated).
So, if you find yourself deleting a lot of your own posts, then please consider giving things some more thought before posting. When writing a question you'll see a link "asking help", which itself has some nice links in the "related" part in its right column. Read those!
Deleting surely is allowed, but should rarely be needed!


text:
Q: Convert curl url to pyurl python curl http://model.dbpedia-spotlight.org/en/annotate  \
  --data-urlencode "text=President Obama called Wednesday on Congress to extend a tax break
  for students included in last year's economic stimulus package, arguing
  that the policy provides more generous assistance." \
  --data "confidence=0.35" \
  -H "Accept: application/json"

A: url = 'http://model.dbpedia-spotlight.org/en/annotate'
data = {"text": query,"confidence":"0.35" ,"Subject": "Pycurl", "TextBody": "Some text"}
headers = {"Accept" : "application/json"}
res = req.get(url, params=data, headers=headers)
#print res.content
j = json.loads(res.content)