text:
Q: Background overlay on hover Is it possible to have markup like this but also background overlay on hover?

I tried placing background-color: #333 on .gallery-icon on hover, but only something like border-bottom appears?
http://codepen.io/filaret/pen/NRpVyr

A: You need to understand your markup works. Your image will be displayed on top of everything, and when you put a background colour on .gallery-icon that background colour will be under the image, and since the anchor link doesn't has a width and height, it only take a little bit of portion, that's why it showing a border bottom.
To create a background overlay on hover, you need to position it to be on top of the image.
Using pseudo element to create a background overlay:
&:hover .gallery-icon {
  &::before {
    content: '';
    background-color: #333;
    display: block;
    position: absolute;
    top: 0;
    left: 0;
    bottom: 0;
    right: 0;
    opacity: 0.2;
  }
}

The pseudo element has a position absolute so it will displayed on top of the image. top, left, right and bottom 0 to tell the pseudo element to stretch it self as tall and as wide as the parent element.
Hope this helps.

A: You are definitely on the right track. Since you are using an :after element for the icon, you should leave that element alone since it's already positioned and defining its own width+height (based off the icon).
The reason the :after selector positions itself correctly is because it's not relying on its parent containers dimensions. You only have it as absolute from the top and left, which is fine. But it doesn't know about how tall it should be, because its parent has no defined height! If you use absolute positioning, you need to define the parent containers dimensions so that the child knows where its bounds are.
So first off, .gallery-icon is already a block element, so you don't need to define its width (its already 100% by nature), just the height:
 .gallery-icon {
    position: relative;
    height: 100%;
 }

Second, you should use a :before element to define a background, so that you don't have to mess with the :after icon:
 &:before {
    content: '';
    position: absolute;
    height: 100%;
    width: 100%;
    top: 0;
    left: 0;
    background-color: #333;
    opacity: 0;
    transition: opacity 0.3s ease-in-out;
 }

Now, you just have to add the opacity change on hover!
 &:hover {
    .gallery-icon {
       &:before {
          opacity: .5;
       }
       &:after {
          opacity: 0.6;
       }
    }

Hope that helps, here is a codepen forked off your original: http://codepen.io/anon/pen/JRWqxX
Edit: I also noticed that your img tag is causing it to go below the visual bottom of the container, a quick fix is just to add:
  .gallery-icon {
     img {
        display: block;
     }

A: I've tried to simplify the code a little bit. I hope it's what you've tried to achieve.
The trick is to place a as a independent element to img.

http://codepen.io/anon/pen/LRWoaR

A: The image (http://placehold.it/300x300) has a solid background colour, no?
That will block anything happening behind itself.


text:
Q: asp.net mvc 4 localization resource path too long I've created a class library in which I store my resource files for my asp.net mvc4 localization. I've been following the same folder structure as my Views.
I'm ending up having to reference strings such as:
@Resource.QuoteArea.Quote.Auto.DriverInfo

That is very long and tedious to type. Plus it makes my Views hard to read. Is there a better (neater) way for doing localization in mvc 4 ? Perhaps using a third-party library ? I already use mvccontrib for my model localization, so that's sorted. However for non-model related things, I'm facing the aforementioned issue.

A: You can change the resource namespace in the resource properties, to make it shorter.  This blog post was very helpful for me, and will be for you to.
http://adamyan.blogspot.co.uk/2010/02/aspnet-mvc-2-localization-complete.html

redpajama_set_name: RedPajamaStackExchange


text:
Q: get part of string with php split i want get part of value from a database
i know i must use split code but its going to remove from php
so i must use what now
for example i have
<html>
<header>
<body>
<?php
$value = "10-20-30-40-50-87";
//i want to get 30 for example
?>

i know i can use
$aryStr = split("#", $string);
 print "$aryStr[0]<br>";
 print "$aryStr[1]";

but its give me a error in php5.3
so what i must use now for get 40 from value

A: Use PHP explode function to split the $value into an array of Strings.
$value = "10-20-30-40-50-87";
$pieces = explode("-", $value);
echo $pieces[0]; // 10
echo $pieces[1]; // 20


text:
Q: No definition found in vscode for system libraries I'm new to vscode so I'm not sure if this is possible, but in visual studio you can cmd+click into a method and see the definition. In VS code, when I try to see the definition, it says no definition found. For example
using System.Collections;

when I try to see the definition for "Collections", it says "no definition found". How can that be? This is a system library. Does VS code even support this feature of jumping into a library?

A: I think I misunderstood what VSCode is. I expected it to be an IDE but it's really just a glorified text editor. I don't think what I'm asking is possible.


text:
Q: The way to redirect from Visualforce page to LWC component along with data I have a LWC component where I am calling a VF page in an iframe for the payment so when the payment completes it redirects me inside the iframe which I don't want instead it should redirect to LWC component along with some data and from there I want to redirect it.
I have not find anything useful how can I achieve this
Well right now I am redirecting to my VF from LWC component like this:
    <template>
           <template if:false = {showPopUp}>
    <lightning-button variant="brand" label={payNowText} icon-name="utility:moneybag" class="slds-m-left_x-small" onclick={payByStripe}>
    </lightning-button></template>
<template if:true = {showPopUp}></template>
</template>

JS:
payByStripe(){
    this.vfHost = 'sandbox_URL/checkoutPayment?orderId='+this.order_id;
    this.showPopUp = true;
}

it is redirecting to my VF page and I am able to successfully transact but how can do the reverse. I mean how can I redirect back to my LWC component after successful component.
*The above iframe renders in a modal so when I am trying to redirect it is redirecting me inside the modal not the main component or parent component
Right now what I am trying to do for communication
in my apex
public static boolean showAlert{get;set;}
if(statusCode == 200){
        showAlert = true;
    }

VF page
<apex:outputText rendered="{!showAlert}">

        </apex:outputText>

so it should invoke this JS method but it is not invoking what I am doing wrong here
Now in my LWC
receivedMessage = '';
error;

// Wire getVFOrigin Apex method to a Property
vfOrigin = "https://fun-java-6633-dev-ed.cs90.my.salesforce.com/apex/checkoutPayment";

handleVFResponse(message) {
    if (message.origin === this.vfOrigin.data) {
        this.receivedMessage = message.data;
        console.log('Fire this');
        console.log(message.data);
    }
}

connectedCallback() {
    try {
        window.addEventListener("message", this.handleVFResponse.bind(this));
        console.log('Order Id = '+this.order_id);
    } catch (error) {
        console.error(error);
    }
}

HTML
<template if:true={receivedMessage}>

 Message Received from VF =

                    <lightning-formatted-text value={receivedMessage}></lightning-formatted-text>

                </template>


text:
Q: How to await till counter finishes I need the app to wait till counter finishes its job so it could return full array of values so the next function could use it instead of 'null'
Moving counter to other method works but sadly it's not an option.
        String[] rows;
        parser.beginParsing(file);
        String[] firstRow = parser.parseNext();
        while ((rows = parser.parseNext()) != null) {
            String lastRow = rows[0];
            content = rows;
            data.add(content);
            Double[] points = new Double[data.size()];
            for (int i = 0; i < data.size(); i++) {
                rows = data.get(i);
                points[i] = new Double(Double.parseDouble(rows[1]));
            }
            XYSeries dataSeries = new SimpleXYSeries(Arrays.asList(points), SimpleXYSeries.ArrayFormat.Y_VALS_ONLY, "Series1");
            SampledXYSeries sampledSeries = new SampledXYSeries(dataSeries, OrderedXYSeries.XOrder.ASCENDING, 2,10);
            lineFormatter = new FastLineAndPointRenderer.Formatter(LINE_COLOUR, null,  null);
            csvPlot.addSeries(sampledSeries, lineFormatter);
        }

I expect the thread to await till counter finishes so 'points' will contain actual parsed data. Now it returns 'null' and calling sampledSeries crashes the app.

A: If you just need a counter of a specific number of seconds, you can post a runnable with below snippet
// Fill your array here

new Handler().postDelayed(new Runnable() {
    @Override
    public void run() {
        // work to be done after 6000 msec
        Toast.makeText(MainActivity.this, "6 sec passed", Toast.LENGTH_SHORT).show();
    }
},6000); // time in msec

but I believe that you need another approach like AsyncTask or AsnycTaskLoader, that is because in most of cases when you want to do something after something else; you actually don't know when the first operation will over, or in your case when your array will entirely be occupied with data; please let me know if you need some help for this.


text:
Q: uiautomation recorded scripts save location I can't seem to figure out how to save recorded scripts in the "UI Automation" tool in Instruments.
I launch my iphone app with "Profile" select the "UI Automation" tool, add a "New Script" and start the script recording.  I click around and I can replay the script and watch the iPhone app behave correctly.
If I save the Instrument's trace file, it just has debug data but no Scripts.  How do you save those scripts and where do they end up?
Thanks!

A: Scripts that are created in the automation tool and not exported exist as part of the saved Instruments trace document. Re-opening the trace document should list any scripts created.
You can export scripts as stand-alone .js files if you'd prefer by right-clicking on the script editor and choosing Export.


text:
Q: Scale 3D-Points in Plane I have some points (3D) all on the same (known) plane. Now I want to scale these points within the plane as opposed to the whole 3D space.
Is there some quick solution for this e.g. a modified scaling matrix?
Can someone help me?
Thanks.
EDIT: I'm more looking for an idea/pseudocode how to do this. If you want use MatLab or some convenient language

A: Your plane can be known by three non-collinear points P0, P1, P2, or by its implicit equation,
A.x + B.y + C.z + D = 0

In the first case, consider the vector P0P1 and normalize it (U = P0P1/|P0P1|). Then compute a second vector orthogonal with the first, V = P0P2 - (P0P2.U).U and normalize it.
In the second case you can take the three intersection points with the axes, (-D/A, 0, 0), (0, -D/B, 0), (0, 0, -D/C) and you are back in the first case (but mind degenerate cases).
Use the two vectors to compute the desired 2D coordinates of any point P = (X, Y, Z) by the dot products
(x, y) = (P.U, P.V)

(This transform is a rotation that makes P0P1 parallel to the x axis and brings P0P1P2 in the plane xy.)


text:
Q: Wifi automatically turns off when ethernet connects I have a need for Wifi and ethernet to be up and connected at the same time.  The Wifi is connected to the internet and the ethernet is connected to other computers on the local ethernet.  The local ethernet has the ip set manually.
The Wifi is on 192.168.1.X (subnet 255.255.255.0) and the ethernet is 192.168.5.X (subnet 255.255.255.0).  This should allow me to connect to both and have proper routing.
This works for about 30 seconds and then the Wifi disconnects.  I set the service order so that Wifi was the highest but that doesn't fix anything.  Everytime I turn the Wifi back on it will connect and then automatically disconnect 30-60 seconds later.
I searched and can't seem to find a setting to keep the Wifi from disconnecting when the ethernet connects


text:
Q: BuddyPress: How to get info of users filtered by some x-profile data? I want the list of users with their email IDs, filtered by some x-profile data.
For example, I want to send an email to users who have checked a checkbox on their profile.
How can I get the info of users filtered by the x-profile data?

A: You will want to use the $wpdb class to execute a query for users with a certain x-profile field value.
I'm no MySQL expert, so someone else likely has a better way to write this query (if you do, please share it and I'll update my code), but here's one approach to it.
This approach assumes you know the ID of the the BuddyPress profile field you are wanting to run the report on, if you don't, you can alter the query to check the [prefix]_bp_xprofile_fields table for a specific field and use it's ID for the rest of the query.
This approach also assumes you are looking for the email address associated with the users' WordPress accounts and not some other email field you've defined in BuddyPress, if you are looking for one in BuddyPress, you'll need to perform a somewhat more complicated query because the [prefix]_bp_xprofile_data table will have the value you want to check against and the value you want to return under the value field in the table.
//create a simple function that will retrieve your desired results
function wpse97684_get_desired_users($field_id, $field_val) {
    //$field_id: (int) this is the ID of the field you'd like to check against
    //$field_val: (str) this is the value you want those users to have in the field

    global $wpdb;
    $bp_table = $wpdb->prefix . 'bp_xprofile_data';

    $query = $wpdb->prepare(
        "SELECT U.user_email " .
        "FROM $bp_table B, $wpdb->users U " .
        "WHERE B.user_id = U.ID " .
        "AND B.field_id = %d " .
        "AND B.value = %s"
       , $field_id
       , $field_val
    );

    $get_desired = $wpdb->get_results($query);

    if(count($get_desired)) {
        return $get_desired;
    } else {
        return false;
    }
}

//to call this function, just pass the desired field ID and the desired value
wpse97684_get_desired_users(4, 'Yes'); //example

Now, I'm not certain how you'll be using this data or where you'll be implementing it, so I left it in the raw object format that the $wpdb class returns.
You'd probably want to put this into a plug-in and format the returned value into a CSV or something if you plan to feed it into an email campaign system (you'd also probably want to check the usermeta table for the first and last name fields because most of the email systems I've worked with require those, too).
But, this should get you going in the right direction.

A: According to the buddypress xprofile loop you can query all the user profile data with
<?php if ( bp_group_has_profile( 'user_id=10' ) ) : ?>

And then in the loop you can search for a specific profile data And do What you want, something like:
         <?php while ( bp_profile_fields() ) : bp_the_profile_field(); ?>

              <?php if ( bp_field_has_data() ) : ?>

                <?php if (bp_the_profile_field_name() == 'yourCheckboxFieldId') && bp_the_profile_field_value() == 'checked'){
//SEND EMAIL!
    }

     ?>

              <?php endif; ?>

            <?php endwhile; ?>

Maybe this can help!

A: when i create a group on buddypress,by the group name(kanpur) automatically select the group name members from xprofile data.
ie it select kanpur members from xprofile data automatically after creating the group.


text:
Q: How I make the search only work when I hit enter? I have search box and I'm using this code to show the results from mysql databse with almost 9,000,000 raw
But becuse I have big database I want it to only show the results when someone type a word and then hit enter, and no data rendering when someone open the page.
By defults it's live search box right now
This is my code: but it doesnt work?
$('#search_text').keyup(function(){
    var search = $(this).val();
    if(search != '')
    if (event.key === "Enter")
    {
        load_data(search);
    }
    else
    {
        load_data();
    }

});

A: Just remove the load_data call in your else and return out of the function:
$('#search_text').keyup(function(){
  var search = $(this).val();
  if(search != '') {
    if (event.key === "Enter") {
      load_data(search);
    } else {
      return;
    }
  }
});


text:
Q: How to integrate $f(x)$? I've been asked to integrate $\int{f(x)}^2 dx$ between the ranges of $L$ and $-L$.
I'm stuck! I understand how to integrate a constant or a function as in $x^2$ or something, but the $f(x)$ format is not something I'm familiar with. Please could someone explain this to me and perhaps guide me?
This is not the actual question I'm trying to solve. I think it might help if I put the above in context, so here's the question I'm trying to solve (I'm not asking anyone to do my homework, this isn't homework...):

Show that for a periodic function, defined over the integral $x=-L$ to $x=L$:
$$\frac1{L} \int_{-L}^L{f(x)}^2 dx = \frac{a_0^2}{2} + \sum_{n=1}^{\infty}(a_n^2 + b_n^2)$$
where $a_0$, $a_n$ and $b_n$ are Fourier coefficients of $f(x)$.

A: First, you don't know anything about $f$ other than that it's periodic and has Fourier coefficients $a_n,b_n$. This means the exercise is not about integrating a particular function, like $x^2$ or $\cos(x)$, it's about integrating a general Fourier series.
So, second, what can we do? All we know is that $f(x)$ is periodic of period $2L$ and has Fourier coefficients. So really the only thing you can do is write down a Fourier expansion of $f$ and integrate its square:
$$f(x) = \sum_{n=0}^\infty a_n\cos(2\pi nx/L) + b_n\sin(2\pi nx/L),$$
so
\begin{align*}f(x)^2 &= \sum_{n=0}^\infty\sum_{m=0}^\infty\bigg(a_n\cos(2\pi nx/L) + b_n\sin(2\pi nx/L)\bigg)\bigg(a_m\cos(2\pi nx/L) + b_m\sin(2\pi nx/L)\bigg)\\
&=\sum_{n,m}\bigg(\mbox{product of the two factors}\bigg)\\
&= \mbox{etc ...}
\end{align*}
I'll leave the details for you to work out. Don't forget the most important theorem of Calculus II: $$\int_{-1}^1 \cos(2n\pi x)\sin(2m\pi x)\ dx = \delta_{nm} = \begin{cases}0, & n\neq m\\ 1, & n=m.\end{cases}$$
Third, for a general perspective, note that we can regard $f$ as an element of $L^2[-L,L]$, which has an orthonormal basis of integral-frequency cosines and sines. The Fourier coefficients of $f$ are the coordinates of $f$ with respect to this basis. Since the inner product is integration, your integral is just the square of the norm of $f$:
$$\int_{-L}^L f^2\ dx = \|f\|^2_{L^2}.$$
This suggests that, indeed, your integral will evaluate to the sum of the squares of the Fourier coefficients of $f$.


text:
Q: Python 3D cube with 4 perspectives The other day I built a volumetric display almost identical to the one in this link (http://hackaday.com/2011/01/18/glimpses-of-a-3d-volumetric-display/)
It's attached to a VGA monitor, and while it's easy enough to display an image on one of the four pyramid slopes, I'm attempting to display a 3d image from four different angles for each of the four slopes simultaneously and in sync.  I'm currently using the 3D cube Pygame example found here http://codentronix.com/2011/05/12/rotating-3d-cube-using-python-and-pygame/ modified to display multiple cubes.
"""
 Simulation of a rotating 3D Cube
 Developed by Leonel Machava <leonelmachava@gmail.com>

 http://codeNtronix.com
"""
import sys, math, pygame
from operator import itemgetter

class Point3D:
    def __init__(self, x = 0, y = 0, z = 0):
        self.x, self.y, self.z = float(x), float(y), float(z)

    def rotateX(self, angle):
        """ Rotates the point around the X axis by the given angle in degrees. """
        rad = angle * math.pi / 180
        cosa = math.cos(rad)
        sina = math.sin(rad)
        y = self.y * cosa - self.z * sina
        z = self.y * sina + self.z * cosa
        return Point3D(self.x, y, z)

    def rotateY(self, angle):
        """ Rotates the point around the Y axis by the given angle in degrees. """
        rad = angle * math.pi / 180
        cosa = math.cos(rad)
        sina = math.sin(rad)
        z = self.z * cosa - self.x * sina
        x = self.z * sina + self.x * cosa
        return Point3D(x, self.y, z)

    def rotateZ(self, angle):
        """ Rotates the point around the Z axis by the given angle in degrees. """
        rad = angle * math.pi / 180
        cosa = math.cos(rad)
        sina = math.sin(rad)
        x = self.x * cosa - self.y * sina
        y = self.x * sina + self.y * cosa
        return Point3D(x, y, self.z)

    def project(self, win_width, win_height, fov, viewer_distance, offsetX=0, offsetY=0):
        """ Transforms this 3D point to 2D using a perspective projection. """
        factor = fov / (viewer_distance + self.z)
        x = self.x * factor + win_width / 2
        y = -self.y * factor + win_height / 2
        return Point3D(x + offsetX, y + offsetY, self.z)

class Simulation:
    def __init__(self, win_width = 640, win_height = 480):
        pygame.init()

        self.screen = pygame.display.set_mode((win_width, win_height))
        pygame.display.set_caption("Simulation of a rotating 3D Cube (http://codeNtronix.com)")

        self.clock = pygame.time.Clock()

        self.vertices = [
            Point3D(-1,1,-1),
            Point3D(1,1,-1),
            Point3D(1,-1,-1),
            Point3D(-1,-1,-1),
            Point3D(-1,1,1),
            Point3D(1,1,1),
            Point3D(1,-1,1),
            Point3D(-1,-1,1)
        ]

        # Define the vertices that compose each of the 6 faces. These numbers are
        # indices to the vertices list defined above.
        self.faces  = [(0,1,2,3),(1,5,6,2),(5,4,7,6),(4,0,3,7),(0,4,5,1),(3,2,6,7)]

        # Define colors for each face
        self.colors = [(255,0,255),(255,0,0),(0,255,0),(0,0,255),(0,255,255),(255,255,0)]

        self.angle = 0

    def run(self):
        """ Main Loop """
        while 1:
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    pygame.quit()
                    sys.exit()

            self.clock.tick(50)
            self.screen.fill((0,32,0))

            # It will hold transformed vertices.
            t1 = []
            t2 = []

            for v in self.vertices:
                # Rotate the point around X axis, then around Y axis, and finally around Z axis.
                r = v.rotateX(self.angle).rotateY(self.angle).rotateZ(self.angle)
                #r = v.rotateX(self.angle).rotateY(self.angle).rotateZ(self.angle)
                # Transform the point from 3D to 2D
                p = r.project(self.screen.get_width(), self.screen.get_height(), 256, 4, offsetY=-150)
                # Put the point in the list of transformed vertices
                t1.append(p)

            for v in self.vertices:
                # Rotate the point around X axis, then around Y axis, and finally around Z axis.
                r = v.rotateX(self.angle + 180).rotateY(self.angle).rotateZ(self.angle + 180)
                #r = v.rotateX(self.angle).rotateY(self.angle).rotateZ(self.angle)
                # Transform the point from 3D to 2D
                p = r.project(self.screen.get_width(), self.screen.get_height(), 256, 4, offsetY=150)
                # Put the point in the list of transformed vertices
                t2.append(p)

            # Calculate the average Z values of each face.
            avg_z1 = []
            avg_z2 = []
            i = 0
            for f in self.faces:
                z = (t1[f[0]].z + t1[f[1]].z + t1[f[2]].z + t1[f[3]].z) / 4.0
                avg_z1.append([i,z])
                z = (t2[f[0]].z + t2[f[1]].z + t2[f[2]].z + t2[f[3]].z) / 4.0
                avg_z2.append([i,z])
                i = i + 1

            # Draw the faces using the Painter's algorithm:
            # Distant faces are drawn before the closer ones.
            for tmp in sorted(avg_z1,key=itemgetter(1),reverse=True):
                face_index = tmp[0]
                f = self.faces[face_index]
                pointlist = [(t1[f[0]].x, t1[f[0]].y), (t1[f[1]].x, t1[f[1]].y),
                             (t1[f[1]].x, t1[f[1]].y), (t1[f[2]].x, t1[f[2]].y),
                             (t1[f[2]].x, t1[f[2]].y), (t1[f[3]].x, t1[f[3]].y),
                             (t1[f[3]].x, t1[f[3]].y), (t1[f[0]].x, t1[f[0]].y)]
                pygame.draw.polygon(self.screen,self.colors[face_index],pointlist)
            for tmp in sorted(avg_z2,key=itemgetter(1),reverse=True):
                face_index = tmp[0]
                f = self.faces[face_index]
                pointlist = [(t2[f[0]].x, t2[f[0]].y), (t2[f[1]].x, t2[f[1]].y),
                             (t2[f[1]].x, t2[f[1]].y), (t2[f[2]].x, t2[f[2]].y),
                             (t2[f[2]].x, t2[f[2]].y), (t2[f[3]].x, t2[f[3]].y),
                             (t2[f[3]].x, t2[f[3]].y), (t2[f[0]].x, t2[f[0]].y)]
                pygame.draw.polygon(self.screen,self.colors[face_index],pointlist)

            self.angle += 1

            pygame.display.flip()

if __name__ == "__main__":
    Simulation().run()

However, I'm having a little trouble wrapping my head around the 3D projections and rotations required to project the cube from four sides.  Am I on the right path with my math here, or will I need to do more than just an angle offset for the projection function?


text:
Q: How to create a random sample from a vector of elements? I used this code to create a random sample for the numbers 0 to 49. Now I want to create a random sample for a custom set of values. For example: select a sample of 5 from [1, 2, 3, 4, 9, 10, 11, 14, 16, 22, 32, 45]. How can I do this?
use rand::{seq, thread_rng}; // 0.7.3

fn main() {
    let mut rng = thread_rng();
    let sample = seq::index::sample(&mut rng, 50, 5);
}

A: You can use IteratorRandom to get a much shorter solution. This is an extension trait for iterators, it offers convenience functions such as choose_multiple and choose_multiple_fill:
use rand::{seq::IteratorRandom, thread_rng}; // 0.6.1

fn main() {
    let mut rng = thread_rng();
    let v = vec![1, 2, 3, 4, 5];
    let sample = v.iter().choose_multiple(&mut rng, 2);

    println!("{:?}", sample);
}

A: Sounds like you can use a permutation from the permutate crate:
extern crate permutate; // 0.3.2

use permutate::Permutator;
use std::io::{self, Write};

fn main() {
    let stdout = io::stdout();
    let mut stdout = stdout.lock();
    let list: &[&str] = &["one", "two", "three", "four"];
    let list = [list];
    let mut permutator = Permutator::new(&list[..]);

    if let Some(mut permutation) = permutator.next() {
        for element in &permutation {
            let _ = stdout.write(element.as_bytes());
        }
        let _ = stdout.write(b"\n");
        while permutator.next_with_buffer(&mut permutation) {
            for element in &permutation {
                let _ = stdout.write(element.as_bytes());
            }
            let _ = stdout.write(b"\n");
        }
    }
}


text:
Q: Clearing Cache in DocumentDB | Managing Ram Usage in AWS DocumentDB Is it possible to clear the cache in DocumentDB of AWS?
I tried using the mongoShell using the db.gainlosses.getPlanCache().clear() command but I'm getting this as a result:
MongoServerError: Feature not supported: planCacheClear
so DocuemntDB doesn't support it like many other operations...
I'm having trouble with Memory Usage the server's memory is filled and make it crash....
A serious issue.
I am also getting the FreeableMemory metrics of the documentdb cluster from cloudwatch but I cannot manage it because it is not in real-time...

A: You could try clearing the cache by rebooting the instance, or changing the instance type. But, currently there's no api call to clear the cache in Amazon DocumentDB.


text:
Q: Gradle Multi Module Project: Apply module dependency to all subprojects except for itself My application is a Gradle Multi Module Project, consisting of multiple services with one service-common module.
I´ve pulled all dependencies that all modules have in common out into the root build.gradle, and I also want to include the service-common module in all subprojects, which in theory works, but I´m getting a circular dependency issue because it is included in itself.
apply plugin: 'java'

group = 'com.myapplication'

ext {
    set('springCloudVersion', "2.2.0.RELEASE")
    set('springBootVersion', "2.2.2.RELEASE")
}

allprojects {

    repositories {
        jcenter()
        mavenCentral()
        maven { url 'https://repo.spring.io/milestone' }
    }

}

buildscript {
    ext {
        springBootVersion = "2.2.2.RELEASE"
    }

    repositories {
        maven { url 'https://repo.spring.io/plugins-snapshot' }
        jcenter()
        mavenCentral()
    }

    dependencies {
        classpath 'io.spring.gradle:dependency-management-plugin:1.0.7.BUILD-SNAPSHOT'
        classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
    }
}

subprojects {
    version = '1.0'

    apply plugin: 'org.springframework.boot'
    apply plugin: "io.spring.dependency-management"
    apply plugin: 'java'

    ext {
        springCloudVersion = "2.2.0.RELEASE"
        springBootVersion = "2.2.2.RELEASE"
    }

    test {
        useJUnitPlatform()
    }

    repositories {
        mavenCentral()
        jcenter()
        maven { url 'https://repo.spring.io/milestone' }
    }

    dependencyManagement {
        imports {
            mavenBom "org.springframework.cloud:spring-cloud-dependencies:${springCloudVersion}"
        }
    }

    dependencies {
        compile group: 'org.springframework.boot', name: 'spring-boot-starter', version: "${springBootVersion}"
        compile group: 'org.springframework.boot', name: 'spring-boot-starter-actuator', version: "${springBootVersion}"
        compile group: 'org.springframework.boot', name: 'spring-boot-starter-security', version: "${springBootVersion}"
        compile group: 'org.springframework.boot', name: 'spring-boot-starter-data-jpa', version: "${springBootVersion}"
        compile group: 'org.springframework.boot', name: 'spring-boot-starter-jdbc', version: "${springBootVersion}"
        compile group: 'org.springframework.boot', name: 'spring-boot-starter-web', version: "${springBootVersion}"
        compile group: 'org.springframework.boot', name: 'spring-boot-starter-logging', version: "${springBootVersion}"
        compile group: 'org.springframework.cloud', name: 'spring-cloud-starter', version: "${springCloudVersion}"
        compile group: 'org.springframework.cloud', name: 'spring-cloud-starter-kubernetes', version: '1.1.1.RELEASE'

        compile group: 'io.micrometer', name: 'micrometer-registry-prometheus', version: '1.3.2'

        compile group: 'com.github.piomin', name: 'logstash-logging-spring-boot-starter', version: '1.2.2.RELEASE'

        compile group: 'io.springfox', name: 'springfox-swagger2', version: '2.9.2'
        compile group: 'io.springfox', name: 'springfox-swagger-ui', version: '2.9.2'

        compileOnly 'org.projectlombok:lombok:1.18.10'
        annotationProcessor 'org.projectlombok:lombok:1.18.10'

        testCompile group: 'com.h2database', name: 'h2', version: '1.4.200'
        compile group: 'org.postgresql', name: 'postgresql', version: '42.2.9'

        testCompile group: 'org.springframework.cloud', name: 'spring-cloud-stream-test-support', version: "${springCloudVersion}"

        implementation project(":service-common")
    }

}

configurations {
    compileOnly {
        extendsFrom annotationProcessor
    }
}

repositories {
    mavenCentral()
}

How can I exclude implementation project(":service-common") for the service-common module?

A: You can do something like:
subprojects {
    dependencies {
        if (!project.name == "service-common") {
            implementation(project(":service-common"))
        }
    }
}


text:
Q: Having trouble calling a bash script from another bash script I have written a script for the purpose of calling it from other scripts and am having issues doing so.
The script I wish to call from other scripts works correctly:
#!/bin/bash

####################################################################################################
# This script will compare two directories given as args.
#
# exit status: 0 --> if directories are the same
#              1 --> if directories are not the same
#              2 --> incorrect number of args
#              3 --> one or more of the directories does not have read permissions
#              4 --> one or more of the directories does not exists
#              5 --> one or more of the directories is not a directory
####################################################################################################

[ $# -ne 2 ] && exit 2

[ ! -r "$1" ] || [ ! -r "$2" ] && exit 3
[ ! -e "$1" ] || [ ! -e "$2" ] && exit 4
[ ! -d "$1" ] || [ ! -d "$2" ] && exit 5

dir_1="$1"
dir_2="$2"
sha1_dir_1=$(find "$dir_1" -type f \( -exec sha1sum {} \; \) | awk '{print $1}' | sort | sha1sum)
sha1_dir_2=$(find "$dir_2" -type f \( -exec sha1sum {} \; \) | awk '{print $1}' | sort | sha1sum)

[ "$sha1_dir_1" = "$sha1_dir_2" ] && exit 0
[ "$sha1_dir_1" != "$sha1_dir_2" ] && exit 1

I have tested it by calling it from the command line. Below is a test script which I cannot seem to call the above script from successfully:
#!/bin/bash

dir_1="~/test"
dir_2="~/test1"
directories_are_same="$(~/bin/compare_directories "$dir_1" "$dir_2")"

{
    if [ $directories_are_same -eq 3 ]; then
        echo "One of the directories $dir_1 and $dir_2 does not have read permissions!"
        exit 1
    elif [ $directories_are_same -eq 4 ]; then
        echo "One of the directories $dir_1 and $dir_2 does not exist!"
        exit 1
    elif [ $directories_are_same -eq 5 ]; then
        echo "One of the directories $dir_1 and $dir_2 is not a directory!"
        exit 1
    fi
} >&2

if [ $directories_are_same -eq 0 ]; then
    echo "The directories $dir_1 and $dir_2 contain identical content"
    exit 0
elif [ $directories_are_same -eq 1 ]; then
    echo "The directories $dir_1 and $dir_2 do not contain identical content"
    exit 0
else
    echo "Something went wrong" >&2
    exit 1
fi

The output from the test script I am getting is:
/home/astral/bin/updates_dir_if: line 8: [: -eq: unary operator expected
/home/astral/bin/updates_dir_if: line 11: [: -eq: unary operator expected
/home/astral/bin/updates_dir_if: line 14: [: -eq: unary operator expected
/home/astral/bin/updates_dir_if: line 20: [: -eq: unary operator expected
/home/astral/bin/updates_dir_if: line 23: [: -eq: unary operator expected
Something went wrong

I have tried using the full path to the script, the relative path from the test script which would be ./, and the way that it currently is ~/bin/scriptname. All give the same results.
I have read some posts which seem to imply that what I am doing should work, such as:
StackOverflow post

Quote your args in Testscript 1:
echo "TestScript1 Arguments:"
echo "$1"
echo "$2"
echo "$#"
./testscript2 "$1" "$2"

What am I doing incorrectly?

A: I figured it out. The exit status is what I need, so I need to call it and set the variable to the exit status stored in $?. The issue is that I was catching the stdout of the other script and storing it in the variable directories_are_same as if it were a return value that I was expecting, when what I needed was its exit status. I could echo something from the other script and then treat the stdout as a returned string, but that is not how this script was designed.
Here is the working test script:
#!/bin/bash

dir_1=~/test
dir_2=~/test1
~/bin/compare_directories "$dir_1" "$dir_2"
directories_are_same="$?"

{
    if [ "$directories_are_same" -eq 3 ]; then
        echo "One of the directories $dir_1 and $dir_2 does not have read permissions!"
        exit 1
    elif [ "$directories_are_same" -eq 4 ]; then
        echo "One of the directories $dir_1 and $dir_2 does not exist!"
        exit 1
    elif [ "$directories_are_same" -eq 5 ]; then
        echo "One of the directories $dir_1 and $dir_2 is not a directory!"
        exit 1
    fi
} >&2

if [ "$directories_are_same" -eq 0 ]; then
    echo "The directories $dir_1 and $dir_2 contain identical content"
    exit 0
elif [ "$directories_are_same" -eq 1 ]; then
    echo "The directories $dir_1 and $dir_2 do not contain identical content"
    exit 0
else
    echo "Something went wrong" >&2
    exit 1
fi

Now when the directories are different I get:
The directories /home/astral/test and /home/astral/test1 do not contain identical content

and when they are the same I get:
The directories /home/astral/test and /home/astral/test1 contain identical content


text:
Q: Button Grid spacing I have some problems with a button arrangement where I have several buttons forming a grid.
The problem I am encountering is, that as soon as there is more than one line of text inside the button it gets shifted downwards.

I think you see what the problem is.
<button class="boxed" dummy="0" name="x" type="submit" value="x">
  SEGEBERGER ZTG.DO
</button>

corresponding CSS
button {
  background:#fff;
  border: 1px solid #c1c1c1;
  padding-left:11px;
  padding-right:11px;
  height:29px;
  margin-top: 5px;
  white-space: normal;
}

.boxed {
  margin-left:1px;
  padding-top:10px;
  padding-left:10px;
  width:100%;
  max-width:150px;
  height:150px;
  font-size: 10pt;
  word-break: break-all;
}

I looked around but did not find anything that fixed it.
https://jsfiddle.net/k1vvsx2h/
Hope someone has a hint on how to fix this.
Have a good one :)

A: Adding a float:left will fix this issue.
.boxed {
    float: left;
    margin-left: 1px;
    padding-top: 10px;
    padding-left: 10px;
    width: 100%;
    max-width: 150px;
    height: 150px;
    margin-right: 5px;
    font-size: 10pt;
    word-break: break-all;
}

button {
    background: #fff;
    border: 1px solid #c1c1c1;
    padding-left: 11px;
    padding-right: 11px;
    height: 29px;
    margin-top: 5px;
    white-space: normal;
}

Here also a jsFiddle for you: https://jsfiddle.net/hb8ydyba/1/. Make sure you're using a clearfix with this solution.
If you're looking for a more flexible solution maybe a CSS Framework like Bootstrap or UIKit and their Gridsystems will work out well for you.


text:
Q: ExtJS: Redirecting from one page to another page with post json data At my application I need to redirect user from one page to another with sending POST json data between this 2 pages.
POST Im need because json data really long and I cant put it at GET-param
REDIRECT(NB not AJAX) Im need because at second page user get the file, generating by server (with json data what he gets).
Im searching for solution on ExtJS, but if there are no clear way it may be simple JavaScript.
Thx!

A: Sorry for necroposting, but I faced this problem and I've found this page. May be this will help someone.
You can create form using JavaScript and then call form.submit();
var form = document.createElement("form");
form.setAttribute("method", "post");
form.setAttribute("action", "http://target.com");
form.appendChild(this.createInput("name", "value")); // your params
document.body.appendChild(form);
form.submit();

And createInput function:
createInput: function(name, value) {
    var field = document.createElement("input");
    field.setAttribute("name", name);
    field.setAttribute("value", value);
    field.setAttribute("type", "hidden");
    return field;
}

A: Here is the code you need:
Ext.Ajax.request({
url: 'YourUrl.php',    // To Which url you wanna POST.
success : function() {
window.location = './account/login'; //the location you want your browser to be  redirected.
},
params: { foo: 'bar' }  // Put your json data here or just enter the JSON object you wannat post
});

Default method for sending data using Ext.Ajax is POST and you dont need to set the method to POST.
As soon as data is successfully submitted to the server, the page will be automatically redirected.


text:
Q: Websphere 8.5 and Hibernate 3.2.7 User TransactionManager Error We have a pretty old application which uses Hibernate 3.1.3.We are upgrading to Hibernate 3.2.7(i know its still old version of hibernate , eventually we plan to move to 4.x).
i am getting this exception.We are using our custom "manager_lookup_class" which calls the Transactionmanagerfactory to get the transaction manager
    used by: org.hibernate.TransactionException: Could not find UserTransaction in JNDI [java:comp/UserTransaction]
at org.hibernate.transaction.JTATransactionFactory.getUserTransaction(JTATransactionFactory.java:172)
at org.hibernate.transaction.JTATransactionFactory.createTransaction(JTATransactionFactory.java:148)
at org.hibernate.jdbc.JDBCContext.registerSynchronizationIfPossible(JDBCContext.java:172)
at org.hibernate.jdbc.JDBCContext.<init>(JDBCContext.java:76)
at org.hibernate.impl.SessionImpl.<init>(SessionImpl.java:214)
at org.hibernate.impl.SessionFactoryImpl.openSession(SessionFactoryImpl.java:574)
at org.hibernate.context.JTASessionContext.buildOrObtainSession(JTASessionContext.java:114)
at org.hibernate.context.JTASessionContext.currentSession(JTASessionContext.java:80)
at org.hibernate.impl.SessionFactoryImpl.getCurrentSession(SessionFactoryImpl.java:591)
at com.dataaccess.utility.hibernate.impl.SessionManagerImpl.getSession(SessionManagerImpl.java:319)
at com.dataaccess.handler.hibernate.impl.HandlerAdapter.getSession(HandlerAdapter.java:83)
at com.dataaccess.handler.hibernate.impl.BatchProcessingHandlerImpl.flush(BatchProcessingHandlerImpl.java:344)
at com.dataaccess.handler.hibernate.impl.BatchProcessingHandlerImpl.batchDelete(BatchProcessingHandlerImpl.java:406)
... 34 more

   Caused by: javax.naming.NameNotFoundException: Name "comp/UserTransaction" not found in context "java:".
at com.ibm.ws.naming.ipbase.NameSpace.lookupInternal(NameSpace.java:1229)
at com.ibm.ws.naming.ipbase.NameSpace.lookup(NameSpace.java:1142)
at com.ibm.ws.naming.urlbase.UrlContextImpl.lookupExt(UrlContextImpl.java:1436)
at com.ibm.ws.naming.java.javaURLContextImpl.lookupExt(javaURLContextImpl.java:477)
at com.ibm.ws.naming.java.javaURLContextRoot.lookupExt(javaURLContextRoot.java:485)
at com.ibm.ws.naming.java.javaURLContextRoot.lookup(javaURLContextRoot.java:370)
at org.apache.aries.jndi.DelegateContext.lookup(DelegateContext.java:161)
at javax.naming.InitialContext.lookup(InitialContext.java:436)
at org.hibernate.transaction.JTATransactionFactory.getUserTransaction(JTATransactionFactory.java:162)
... 46 more

A: I think the exception speaks for itself:
Caused by: javax.naming.NameNotFoundException: Name "comp/UserTransaction" not found in context "java:".

You are performing a jndi lookup, and the resource does not exist, at least not under that name. Double check your configuration to make sure whatever you are looking for is registered in the jndi context under the name you are using.


text:
Q: Why AndEngine's CollisionHandler produces multiple events in one collision? I am writing a GameActivity of a swinging pendulum (in AndEngine).
While applying CollisionHandler, this will produce a series of collision events in the instead of one?? Actually, I'd like it is executed once only when sprites collide.
My case: when the movingBall collides with the mLeftWall, it called 5 times of onCollision(); It was abnormal, I expected only one time.
Should I use ContactListener instead and register with PhysicsWorld? Here's my Code:
MyGameActivity.java:
/** List of objects to check collision of any animating objects. E.g: walls  */
private ArrayList<IShape> mCollidingTargetList = new ArrayList<IShape>();

/** user-defined collision handler */
PendulumCollisionCallback collideActionCallback = new PendulumCollisionCallback();

@Override
public Scene onCreateScene()
{
    final Scene scene = super.onCreateScene();

    final VertexBufferObjectManager vertexBufferObjectManager = this.getVertexBufferObjectManager();

    //Create walls
    mWallLeft = new Rectangle(0, 0, 2, mCameraHeight, vertexBufferObjectManager);
    mWallRight = new Rectangle(mCameraWidth - 2, 0, 2, mCameraHeight, vertexBufferObjectManager);
    PhysicsFactory.createBoxBody(mPhyscisWorld, mWallLeft, BodyType.StaticBody, mWallFixtureDef);
    PhysicsFactory.createBoxBody(mPhyscisWorld, mWallRight, BodyType.StaticBody, mWallFixtureDef);
    scene.attachChild(mWallLeft);
    scene.attachChild(mWallRight);

    //Create movingBall - the pendulum ball
    final AnimatedSprite movingBall = new AnimatedSprite(mCenterX, mCenterY, this.mCircleFaceTextureRegion, this.getVertexBufferObjectManager());
    final Body ballBody = PhysicsFactory.createCircleBody(this.mPhysicsWorld, movingBall, BodyType.DynamicBody, mObjectFixtureDef);
    movingBall.setUserData(ballBody); // for getting the body attached with UI

    //..... Stuff to create anchorBody and RevoluteJoint with the movingBall

    //list of bodies where sprites collide
    this.mCollidingTargetList.add(mWallLeft);
    this.mCollidingTargetList.add(mWallRight);

    //Manage user-defined collision handler: movingBall collides with walls
    CollisionHandler pendulumCollideHandler = new CollisionHandler(collideActionCallback, movingBall, mCollidingTargetList);
    scene.registerUpdateHandler(pendulumCollideHandler);

    return scene;
}

PendulumCollisionCallback.java:
public class PendulumCollisionCallback implements ICollisionCallback
{
    public PendulumCollisionCallback()
    { }

    /**
     * @param animatedShape
     *      Entity to check collision with other targets
     * @param pTargetShape
     *      Target to check the collision
     * @return true to proceed, false to stop further collosion-checks.
     */
    @Override
    public boolean onCollision(IShape animatedShape, IShape pTargetShape)
    {
        String pendulPos = String.format("Pendul:x=%f, y=%f", animatedShape.getX(), animatedShape.getY());
        Log.d("COLLIDE", pendulPos);
        return false;
    }
}

A: I found the issue. This is because of separated Physics Handler and Scene's UpdateHandler work sequence.
While PhysicsWorld is still controlling body collision, the body is still moving forward for a few frames => so that the position of UI sprite (attached with this body) is in junction with colliding object. During these frames, the updateHandler produces collision events by CallbackHandler.
The solution is a tricky method of adding Boolean flag which is set at first colliding and unset when finish colliding (though this is not nice).
P/S: my frame rate observed form FPSLogger is ~88,9 FPS.


text:
Q: Detect A Substream "The MS-XLS file format contains streams, substreams, and records." -Understanding the Excel MS-XLS Binary Format
Given an xls file stream:
FileStream stream = System.IO.File.Open(filePath, FileMode.Open, FileAccess.Read);
var xs = new List<int>();
for(int i = 0; i < stream.Length;i++)
{
 xs.Add(stream.ReadByte());
}

How would I go about detecting substreams? Is the name deceiving in that the substreams are actually included in the stream in some sort of sequence?

A: XLS (and other MS Office formats from before Office 2007) is a structured storage file aka compound binary file (see https://en.wikipedia.org/wiki/COM_Structured_Storage). Structured storage is like a filesystem inside of a file, where files are referred to as "streams", and directories are called "storages". A structured storage file has a single root "storage", which can contain streams and other storages, and it appears that's where all the streams in an xls file reside (which is probably why their documentation skips over the concept of "storages" and refers to streams as "substreams").
Normally, you would access structured storage using the IStorage interface (see http://msdn.microsoft.com/en-us/library/windows/desktop/aa380015%28v=vs.85%29.aspx), but that may not be the most convenient method in .NET.
For accessing the data in structured storage in .NET, I'd suggest using OpenMCDF - http://sourceforge.net/projects/openmcdf/ - but I haven't tried it myself so I can't make any promises regarding its quality.
"Records" are not part of the structured storage file format, and I think you will need to parse them out of streams yourself.
Depending on what you're trying to do, it may be appropriate to use a higher-level interface instead of worrying about the details of the XLS format.

A: "OLE compound file: A form of structured storage, as described in [MS-CFB]. A compound file allows independent storages and streams to exist within a single file." -MS
Basically, this stream is reflecting the structure used to store the file and the term "substream" should at least be defined in the MSDN library.
All files can be represented as byte arrays read from streams, and structuring the streams is very common. In .NET a filestream is used to gather this data, and can be used on any file such as a .xls, .jpg, .doc, etc.


text:
Q: How do I loop through dictionaries values having different datatypes using .title()? I want to loop through a dictionary which has values in both string and integers. Here is I have done so far:
person={'fname':'harry','lname':'max','age':22,'city':'ktm'}
    for value in person.values():
        print(str(value.title()))

My desired output is :
Harry
Max
22
Ktm
The error I am getting is:

AttributeError: 'int' object has no attribute 'title'

A: We can not do int.title(), so we should do str(int).title().
Change:
print(str(value.title()))

To:
print(str(value).title())

A: You need to turn 22 (which is an int in the dict) into a string before you can use the .title() method
person={'fname':'harry','lname':'max','age':22,'city':'ktm'}
for value in person.values():
    print(str(value).title(), end=" ")

Output:
Harry Max 22 Ktm

A: That's because age is an integer, and it you cannot call .title() function on it. you need to convert it to a string first. try to use the following code instead :
print(str(value).title())

A: You dont even need iteration here in python3
person={'fname':'harry','lname':'max','age':22,'city':'ktm'}
print(f"{person['fname']} {person['lname']} {person['age']} {person['city']}")

You can make it a function
def print_dict(person):
    print(f"{person['fname']} {person['lname']} {person['age']} {person['city']}")

and pass the dict as an argument


text:
Q: Class parameter asynchronous affectation hope you're doing good.
I wanted to know if it was possible to affect an async value to a class parameter in javascript, something like this :
export class MyClass {
static myParam = await myAsyncFunction();
}

It doesn't seem to work, and I would like to know how could I set it differently
Thank you in advance


text:
Q: Using "and" to end a list with an "and" phrase I'm proofreading a document in which the author ends a lot of lists with phrases like this:
We analyzed the responses of students studying: health, sciences and technology, law and economics, and human and social sciences.
Usually when I come across lists that end with two words that need to be connected by "and", I usually just substitute "as well as" or something like that. But I'm not sure if there's a standard rule for these kinds of situations. In this particular paper, there are many examples that aren't very easy to fix this way.
What's the rule?

A: Using "and" in this case is correct, though could perhaps be clarified by reworking the list. "As well as" is not equivalent to "and", and would be incorrect here (Chicago Manual of Style 6.18):

Note that the phrase as well as is not equivalent to and.

The team fielded one Mazda, two Corvettes, and three Bugattis, as well as a battered Plymouth Belvedere.

not

The team fielded one Mazda, two Corvettes, three Bugattis, as well as a battered Plymouth Belvedere

In this particular case, it may be that the list needs to be reworked. It reads awkwardly entirely apart from the dual "and". "Sciences and technology" is an odd phrasing, as is "human and social sciences". One would expect either "science and technology" or "sciences, technology", and "humanities and social sciences". This might not be possible to change, however, if the study itself or the school(s) at which it was conducted divide the subjects in this manner.

Regardless of whether you change the "and", you definitely want to keep the Oxford comma.

A: Modern devices are:

We analyzed the responses of students studying: health, sciences &
  technology, law & economics, and human & social sciences.

//

We analyzed the responses of students studying: health, sciences &
  technology; law & economics; and human & social sciences.

(Depending on whether 'health, sciences & technology' is considered as a single grouping or two groupings).

A: We analyzed the responses of students studying health, sciences & technology, law & economics and human & social sciences.


text:
Q: How to create an Android library plugin system that updates parent package's app permissions? I would like to create a plugin system for my Android project, so that you can plug in different modules as needed.
The thing is: Some modules require app permissions, so the AndroidManifest.xml also needs to change based on what module you import.
For example, importing a location related module will require <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/> inside the manifest, etc.
Is there a way to express this inside each module so that the parent project doesn't have to know about these additional permissions and everything about the library module is self-contained within the library?


text:
Q: Settimeout for a function and retry if timedout I  have two fetch calls on my typescript code, one to get access token and other to call the actual API.
I need to set time out(1 second) for second API call. If timed out, a retry should be made and while retrying, access token should be retrieved again.
What is the best approach to achieve this?

A: I think is it useful to just try and catch your code, then if the error you have is instance of TimeoutError or something like this it is depend on what package you are using, so call your function again
for example, if your are using axios, it would be something like this
async function fn() {
const response = await axios.post("/auth/login");
// get your token here.

try {
  const result = await axios.get("/second/api");
} catch (error) {
  if (error.code === "ECONNABORTED") {
    // just call your function again.
    fn();
  }
}

axios timeout error is defined by ECONNABORTED error code
DO NOTE that this function is going to call itself forever if there is always timeout error, so you could apply some mechanism to avios this, like storing number of tries in a variable

A: You can wrap the 1 second timer into a promise and then use Promise.race to detrime which promise (timer or the actual request) resolves faster. If the timer expires faster then restart the process otherwise return the result of the api call:
async function run() {
    const accessToken = await getAccessToken();
    const retry = new Promise((resolve) => {
        setTimeout(() => {
            resolve('EXPIRED')
        }, 1000)
    });
    const resp = apiCall(accessToken);
    const result = await Promise.race([retry, resp]);
    if (result === 'EXPIRED') {
        return run();
    }
    return result;
}


text:
Q: I want to store each group in the below output into separate vectors or arrays. If not any other way to store the each group individually I have tried code as below:
#include <iostream>
#include <iomanip>
#include <vector>
#include <algorithm>
#include <numeric>
using namespace std;
template<typename T>
std::vector< std::vector<T> > split(std::vector<T> vec, uint64_t n) {
std::vector< std::vector<T> > vec_of_vecs(n);

uint64_t quotient = vec.size() / n;
uint64_t reminder = vec.size() % n;
uint64_t first = 0;
uint64_t last;
for (uint64_t i = 0; i < n; ++i) {
if (i < reminder) {
last = first + quotient + 1;
vec_of_vecs[i] = std::vector<T>(vec.begin() + first, vec.begin() + last);
first = last;
}
else if (i != n - 1) {
last = first +  quotient;
vec_of_vecs[i] = std::vector<T>(vec.begin() + first, vec.begin() + last);
first = last;
}
else
vec_of_vecs[i] = std::vector<T>(vec.begin() + first, vec.end());
}

return vec_of_vecs;
}

#define Nsta 30
#define NGroups 5

int main(void)
{
std::vector<uint64_t> vector(Nsta);
std::iota(std::begin(vector), std::end(vector), 1);

std::vector<std::vector<uint64_t>> vecs(NGroups);
vecs = split(vector, NGroups);

for (uint64_t m = 0; m < vecs.size(); ++m)
{
for (auto i : vecs[m])
{
    std::cout << std::setw(3) << i << " ";
}
std::cout << std::endl;
}
 return 0;
}

Output of this code:
1 2 3 4 5 6
 7 8 9 10 11 12
 13 14 15 16 17 18
 19 20 21 22 23 24
 25 26 27 28 29 30
What i want is:
This is only small part  in my work. I would like to use each group based on work conditions.
please help with this!

A: Your loop body does something else. Bellow is the code that follows your requirements.
template<typename T>
std::vector< std::vector<T> > split(std::vector<T> vec, size_t n) {
  std::vector< std::vector<T> > vec_of_vecs(n);

  size_t quotient = vec.size() / n;
  size_t reminder = vec.size() % n;
  size_t first = 0;
  size_t last = quotient;
  for (size_t i = 0; i < n; ++i, first += quotient, last += quotient) {
    vec_of_vecs.push_back(std::vector<T>(&vec[first], &vec[last]));
  }
  if (reminder > 0) {
    vec_of_vecs.push_back(std::vector<T>(vec.begin() + first, vec.end()));
  }
}


text:
Q: calling a method from controller when $locationChangeStart is broadcasted In my controller I changed the url with varying parameters depending on geolocation changes of my map. This is my setLocation method:
$scope.setLocation = function(lat,lng){
   $location.search('lat',lat);
   $location.search('lng',lng);
   $scope.$apply();
};

I have another method that loads location data on the map. This is my getProjectsByCenter:
$scope.getProjectsByCenter = function(){
   var center = getProjectsByCenter();
   $scope.setLocation(center.lat(),center.lng());
};

Once the location starts changing the browser saves all these url changes in its history, but when I click on the back button I can't figure out how to call my controller's method. Back Button does change the $location and the following broadcast listener is called. In fact the following broadcast listener is called everytime I setLocation(), but in this case everything is working as it should.
app.run(['$rootScope', '$location',
function ($rootScope, $location) {

    //Client-side security. Server-side framework MUST add it's
    //own security as well since client-based "security" is easily hacked
    $rootScope.$on('$locationChangeStart', function (event, next, current) {

        if( next !== current && (hasBackButtonBeenClicked() || scopeFunctionWasNotCalled()) ){
            // fetch project again.
            // $state.reload();
            // $rootScope.$apply(); <--- doesn't work
            console.log("location has changed...now find a way to call controller's $scope.getProjectsByCenter()...");
        }

    });

}]);

Any suggestions?

A: You can capture the change event in the following manner.
Add this controller in the destination page. The below method will capture the change event and you should be able to trigger the controller.
.controller('MyController', function() {
    $scope.$on('$routeChangeSuccess', function () {
        // Do your work
    });
})

Hope this is what you are looking for.


text:
Q: How to share packages I have locally created a document and used some packages for that. Is it possible to share this environment with my colleagues, without having them to install miktex and the packages?
Solved:
I used the portable version of miktex (http://miktex.org/portable) and put it to a shared networkfolder. After installing all required packages, all of my team mates are able to compile the document without problems.


text:
Q: Factorial calculation is not right in my C program? #include <stdio.h>
#include <conio.h>

int main()
{
  long signed fact=1;

  int c, n ;

  printf("Factorial to be calculated: ");
  scanf("%d", &n);

  for (c = 1; c <= n; c++)
  fact = fact * c;

  printf("Factorial of %d = %ld\n", n, fact);
  getch();
  return 0;
}

In the C program above, when I run, I can not get 13! correct. It's output is true for 12. How can I fix this?
I thought long unsigned will be enough for 13.

A: It's possible that long is 32-bit on your platform (you can find out by printing the value of sizeof(long)).  13! is greater than 2^32-1 (the largest possible value for a 32-bit unsigned value), so it overflows.
Try using uint64_t (from <stdint.h>) instead.

A: What Oli said is correct -- the C standard guarantees that long is at least 32 bits. On some platforms it might be more.
You could use unsigned long long. This would be at least 64 bits, but it would still only let you calculate up to 20!.
The C FAQ has an excellent overview on integer sizes: How should I decide which integer type to use? You'll probably want to look for an arbitrary-precision library.
Otherwise, if you only want to approximate larger factorials, perhaps you could use Stirling's formula.


text:
Q: Automatic deletion of downvoted answers when associated user account is deleted According to Marc Gravell's comment on the answer to this question, a regular delete of an account also deletes anything that is negatively voted.  However, this question has two answers from deleted accounts that are downvoted but not deleted.
How does that happen?  Is it a bug?  Or were the downvotes accumulated after the accounts were deleted?  And if it was after they were deleted, is there any mechanism for auto-deleting those negative posts (perhaps 7 days after it gets negatively voted)...or should there be?  Or should I just flag those for moderator deletion?

A: Judging by the post timeline those posts did not receive their first downvotes until Dec 22 '09, about a year after they were first posted. I see two possibilities here:

*

*Their account deletion predates those first downvotes.

*Their account deletion predates the auto-deletion script and their answers survived because of that. -- Sklivvz discounted this option.
In any case, I've voted to delete both, they do not add anything useful.
Negatively voted answers are generally not auto-deleted (so outside of the deleted account mechanism), so I don't think there is any auto-deletion for answers downvoted after the owner has been deleted.
These two posts were otherwise ripe for flagging. One was a reply from the original question asker, so Not An Answer applies there, the other post a link-only answer with a dead link. A moderator would have deleted both had you flagged them, for those reasons alone.
Both posts have now been deleted without moderator intervention, each received 3 deletion votes by higher-rep users.

A: The "delete nukes negatively scored posts" dates back to Sept. 18th, 2008 and as such the user must have been deleted when the posts were at 0 score, sometime between Dec '08 and Dec '09.
The down votes must have been cast after the user was deleted.


text:
Q: How to perform operations on randomly selected entry of a matrix in R? Given a 10 by 10 (or any square) matrix how to randomly select an entry and subtract that value from itself and then add the value of that randomly selected entry to the value of another randomly selected entry of the same matrix?

A: You can treat a matrix like a vector in this respect.
set.seed(69)
my_mat <- matrix(1:100, nrow = 10)
i <- sample(length(my_mat), 1)
j <- sample(length(my_mat), 1)
my_mat[j] <- my_mat[i] + my_mat[j]
my_mat[i] <- 0
my_mat
#>       [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
#>  [1,]    1   11   21   31   41   51   61   71  177    91
#>  [2,]    2   12   22   32   42   52   62   72   82    92
#>  [3,]    3   13   23   33   43   53   63   73   83    93
#>  [4,]    4   14   24   34   44   54   64   74   84    94
#>  [5,]    5   15   25   35   45   55   65   75   85    95
#>  [6,]    6   16   26   36   46   56   66   76   86     0
#>  [7,]    7   17   27   37   47   57   67   77   87    97
#>  [8,]    8   18   28   38   48   58   68   78   88    98
#>  [9,]    9   19   29   39   49   59   69   79   89    99
#> [10,]   10   20   30   40   50   60   70   80   90   100

Here, you can see that we have taken element 96 and added it to element 81 (both selected at random). Presumably when you say "take the number away from itself", you mean make the entry 0.
Created on 2020-06-14 by the reprex package (v0.3.0)

A: another way, using "mask" matrices, might be this:
set.seed(0)
x <- matrix(1:100, nrow = 10)

# one for element to substract 0 everywhere else
a<-ifelse(row(x)==sample.int(nrow(x),1),1,0)*ifelse(col(x)==sample.int(ncol(x),1),1,0)

# one for element to add 0 everywhere else
b<-ifelse(row(x)==sample.int(nrow(x),1),1,0)*ifelse(col(x)==sample.int(ncol(x),1),1,0)

# and the answer: substract from someplace and add to another place
x - a*x + b*sum(a*x)

      [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
 [1,]    1    0   21   31   41   51   61   71   81    91
 [2,]    2   12   22   32   42   52   62   72   82    92
 [3,]    3   13   23   33   43   53   63   73   83    93
 [4,]    4   14   24   34   44   54   64   74   84    94
 [5,]    5   15   25   35   45   55   65   75   85    95
 [6,]    6   16   26   36   46   56   66   76   86    96
 [7,]    7   17   27   37   47   57   67   77   87    97
 [8,]    8   18   28   38   48   58   79   78   88    98
 [9,]    9   19   29   39   49   59   69   79   89    99
[10,]   10   20   30   40   50   60   70   80   90   100

row 1, column 2 and row 8, column 8 are the affected cells


text:
Q: OwlCarousel2 - Add Item + Update Carousel I've been having difficulty adding the Owl Carousel to our app, and was hoping that the latest 2.0.0-beta.2.4 version would be easier, but I am not able to just get the basic feature of adding an item and updating the carousel to work.
Is there something I am doing wrong here?
Here is the code I am using:
$('#insert').on('click', function () {
    owl.trigger('add.owl.carousel', '

D

').trigger('update.owl.carousel');
});

Along with a demo:
http://jsfiddle.net/52r9B/11/
The documentation (http://www.owlcarousel.owlgraphic.com/docs/started-welcome.html) doesn't seem to include anything - unless I'm missing something obvious.
Any help would be appreciated.

A: This is an other way to do that, this solution work's for me and it's very simple:
// appends an item to the end
$('.owl-carousel').owlCarousel('add', '
foo
').owlCarousel('update');
// adds an item before the first item
$('.owl-carousel').trigger('add.owl.carousel', [$('
bar
'), 0]).trigger('refresh.owl.carousel');

Work's perfectly.
Regards!

A: Since the last months OwlCarousel 2.0 is under heavy re-factoring. So the version you have used (2.0.0-beta.2.4) is already outdated.
Here is a working Codepen of your demo. Your first mistake was that you have used the event API to add a new item without putting the arguments into an array:
// Right
$('.owl-carousel').trigger('add.owl.carousel', [first, second])
// Wrong
$('.owl-carousel').trigger('add.owl.carousel', first, second)

Alternatively you could use the plugin method like this:
$('.owl-carousel').owlCarousel('method', first, second, third, ...)

The main difference is that the event API only provides a subset of all public methods.
The second mistake was that you have tried to call update over the event API which is not possible (see above). Use refresh instead.
To checkout the latest development you need to build it at your own until the next pre-release is coming. But please be patient this is still beta!

A: You can simply use add & update options with the position specified.
// appends an item as the first item
$('.owl-carousel').owlCarousel('add', '
foo
', 0).owlCarousel('update');

// appends an item as the 2nd item
$('.owl-carousel').owlCarousel('add', '
foo
', 1).owlCarousel('update');

// appends an item as the 4rth item
$('.owl-carousel').owlCarousel('add', '
foo
', 3).owlCarousel('update');

// appends an item as the last item - if you don't specify it will add to the end
$('.owl-carousel').owlCarousel('add', '
foo
').owlCarousel('update');


text:
Q: Как лучше сделать чтобы не получить фильтр от Google/Yandex? Сейчас у каждого сайта есть моб. версия. Как лучше сделать чтобы не получить фильтр от поисковой машины?
К примеру <input type="text" class="search">
Лучше поле с поиском скрывать c помощью display: none; но так получаеться на странице должно быть 2 поля с поиском, и в css прописывать display: block; для десктопной версии сайта, и display: none; для мобильной. И наоборот в случае с мобильной версией.
Или
Показывать нужное с помощью php чтобы google и yandex сообще ничего не видели.


text:
Q: GraalVM native JavaFX application visual bugs I have created a new GraalVM + JavaFX project with simple interface, but instead of this:

I can see only this:

I have compiled my project with/on:

*

*Solus OS (Linux) with kernel 6.1.5

*Java 17 provided by GraalVM SDK (below)

*GraalVM v22.1.0.1 redistributed by Gluon

*Using GluonFX Maven Plugin v1.0.16

You can easily reproduce it:

*

*Clone my GitHub repo with all project related code

*Download GraalVM release for your host system

*Install (unpack) it anywhere and change path to SDK in pom.xml (graalvm.home property)

*Just run mvn clean install to run metadata collecting agent, build native image and run it

A: During all that day I have tested native AOT compilation of this test project.
Binaries is working fine on Windows and Mac OS hosts, but not at all Linux hosts, and it's so sad :(
I will use the next 'partially native' app distribution solution:

*

*Linux: app-image (jlink) + launch4j.

*Mac OS: native-image using Liberica NIK.

*Windows: native-image using Liberica NIK.

Thanks a lot to José Pereda for any help and instant answers.


text:
Q: jQuery - Masonry layout First time using jquery and im trying to get the basic masonry style to work, i've got the following code in my html...
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">

<title>_Box</title>

<link href="styles.css" rel="stylesheet" type="text/css">

and the following in my css file...
html {
  height:100%;
}

body {
  width:950px;
  height:100%;
  margin:0 auto;
  margin-top:100px;
  background-image: url(images/gridbg.png);
}

.item{
    float: left;
    padding: 5px;
    margin: 5px;
}

any help would be great as ive pretty much followed the tutorial yet its not working
this is what it looks like

if it helps, the images are different widths and height.
Question: How do i get the layout to what masonry is supposed to do, that being flow into one another nicely; examples on masonry site.

A: You should add a columnWidth:
$(window).ready(function() {
    $("#container").masonry({
          itemSelector: '.item',
          columnWidth: 240,
          isAnimated: !Modernizr.csstransitions
        });
});

Also, make sure that you have properly included both jQuery script and the masonry.js script.
And add the following CSS to your code:
.item{
    float: left;
    padding: 10px;
    margin: 10px;
}


text:
Q: how to give format DateTime.Date? DateTime dt = DateTime.Now
dt.Date is created to  31.10.2012 00:00:00 .it is created to  dd.mm.yyyy format but i need dd/mm/yyyy. Can i use:  return new DateTime(d.Year, d.Month, d.Day, 0, 0, 0); it will create to me dd/mm/yyyy solution?Please dont translate String.i need datetime...

A: Just the way to convert to string, DateTime itself has no format:
var result = DateTime.Now.Date
                     .ToString("dd/MM/yyyy", CultureInfo.InvariantCulture);

A: The DateTime struct doesn't store any formatting information internally. If you want to output the DateTime instance as a formatted string, you just need to call ToString() with the proper format string:
var date = DateTime.Now;
var formattedString = date.ToString("dd/MM/yyyy", CultureInfo.InvariantCulture);

If you need more information on exactly which specifiers to use in your format string, check out:
MSDN - Custom Date and Time Format Strings

A: var dt = DateTime.Now;
var stringDt = dt.Date.ToString("dd/MM/yyyy");

A: System.DateTime does not have any format. You can view its string representation in format.
Try this
Console.WriteLine(DateTime.Now.Date.ToString("dd'/'MM'/'yyyy"));

A: In you case you can simply use :
dt.ToString("dd/MM/yyyy");

Anyway there al the string format you can use with DateTime : Here.

A: DateTime, numeric types and most other types do not store their values in a formatted way. Rather they store their data using a binary representation. If you want to display this data to the user, you must convert it to a string. This conversion involves formatting the data.
string formattedDate = DateTime.Now.ToString("dd/MM/yyyy",
                                             CultureInfo.InvariantCulture);

Or
Console.WriteLine("Date = {0:dd/MM/yyyy}", DateTime.Now);

Console.WriteLine converts the date into a string in order to write it to the console.

A: DateTime structure always has the Date and Time stored in it. If you need to extract the date alone as text you can do the following.
var date = DateTime.Now.ToString("d");
Console.WriteLine(date);

This will print the date as in the format as specified by the culture set in the system. The list of standard datetime format strings supported by dotnet framework can be found here


text:
Q: Column found in more than one table error I'm getting the following error

Error while compiling statement:
  FAILED: SemanticException Column episodeid Found in more than one tables/subqueries [SQL State=42000, DB Errorcode=40000]

Would anyone be able to help me reconfigure?
Thanks!
This is the code in question:
select
    papid, count(distinct episodeid) as epicount,
    episovcountcesarean, sum(episovspendcesarean),
    count(claimnumber) as claimcount,
    sum(allowedamount) as spend
from
    3pdcoe_tc_dm_eoc_nep_peri.star_output_episodes e
join
    3pdcoe_tc_dm_eoc_nep_peri.dbo_claimpatientservice cps on cps.episodeidd = e.episodeid
join
    3pdcoe_tc_dm_eoc_nep_peri.star_output_aggregate a on a.episodeid = e.episodeid
where
    aggtype = 'Window' and agggroup = 'Trigger'
    and eeany = 0
    and year(episodeend) = '2016'
    and episovcountcesarean = 1
group by
    papid, episovcountcesarean, episovspendcesarean;

A: In your select list you must specify your target table
select
  papid, count(distinct a.episodeid) as epicount,
  episovcountcesarean, sum(episovspendcesarean),
  count(claimnumber) as claimcount,
  sum(allowedamount) as spend

OR
select
  papid, count(distinct e.episodeid) as epicount,
  episovcountcesarean, sum(episovspendcesarean),
  count(claimnumber) as claimcount,
  sum(allowedamount) as spend


text:
Q: Given, $f(x+y) =xf(x) +2f(y)-x-y$. If $f(2019)=\frac{a}{b}$, then $a+b=?$
Question:
$\text{Given, } f(x+y) =xf(x) +2f(y)-x-y\text{. If } f(2019)=\frac{a}{b}, \text{then } a+b\text{ = ?} $

I started solving by replacing $y\to-x$, which yields
$$f(0) = xf(x) +2f(-x)$$
then, replace $x\to-x$
$$f(0)=-xf(-x)+2f(x)$$
on solving, I get,
$$(x+2)f(0)=(x^2+4)f(x)$$
But, I'm stuck here. How to move on?

A: If $x=0$ we get $f(y)=y$ for all $y$. Pluging this in to starting equation we get $$x+y=x^2+2y-x-y$$
which should be valid for all $x,y$. Since $x^2=2x$ ony for $x=2$ and $x=0$ this FE has no solution unlesss $f$ is defined on the set $\{0,2\}$.


text:
Q: CKeditor save filename not dirname I am trying to save an image with ckeditor, using kcfinder. But I want to save only the filename on save. Not src='/dir/dir/file.jpg' but src='file.jpg'.
I do not know where to start looking for such a function.

A: Have you tried substr? So $filename = substr($src, strrpos($src, '/'));


text:
Q: Rebuilding a Site: How to Show Several Category Posts in Woo Framework Theme? I am having a hard time managing a big site with 2000+ pages.
Right now, I am restructuring the site architecture. So, for example, if there are categories like x, y, z... I want to put them under "A."
This A can be a page or a blog, but it should have a pagination (should update dynamically whenever a new post is added under x, y, z category).
Similarly, I want to put several other categories in "B."
I have tried various plugins, like posts to page, posts for page... and even List Categories with Pagination plugin. What I am looking for is another archive/blog page that lists the posts from defined categories.
Any help is highly appreciated.
Here is the template-blog.php file, if it helps.
   <?php
 /**
  * Template Name: Blog
  *
  * The blog page template displays the "blog-style" template on a sub-page.
  *
  * @package WooFramework
  * @subpackage Template
  */

  get_header();
  global $woo_options;
 ?>

<?php woo_content_before(); ?>

        <?php woo_main_before(); ?>

        <?php get_template_part( 'loop', 'blog' ); ?>

        <?php woo_main_after(); ?>

        <?php get_sidebar(); ?>

    <?php get_sidebar( 'alt' ); ?>

<?php woo_content_after(); ?>

 <?php get_footer(); ?>

Edit: Going through Codex.WordPress, I see that there is a possibility:
$query = new WP_Query( 'cat=2,6,17,38' );

I wonder how to incorporate this code into my blog file.
Edit 2: Modified it this way, still doesn't work. Check edit 3.
Edit 3: Here is the loop-blog.php template.
<?php
/**
 * Loop - Blog
 *
 * This is the loop file used on the "Blog" page template.
 *
 * @package WooFramework
 * @subpackage Template
 */
global $more; $more = 0;

woo_loop_before();

// Fix for the WordPress 3.0 "paged" bug.
$paged = 1;
if ( get_query_var( 'paged' ) ) { $paged = get_query_var( 'paged' ); }
if ( get_query_var( 'page' ) ) { $paged = get_query_var( 'page' ); }
$paged = intval( $paged );

$query_args = array(
                    'post_type' => 'post',
                'paged' => $paged
            );

$query_args = apply_filters( 'woo_blog_template_query_args', $query_args ); // Do not     remove. Used to exclude categories from displaying here.

remove_filter( 'pre_get_posts', 'woo_exclude_categories_homepage', 10 );

query_posts( $query_args );

if ( have_posts() ) { $count = 0;
?>

<?php
while ( have_posts() ) { the_post(); $count++;

    woo_get_template_part( 'content', get_post_type() );

} // End WHILE Loop
} else {
    get_template_part( 'content', 'noposts' );
} // End IF Statement

woo_loop_after();

woo_pagenav();
?>

A: This looks wrong:
if ($query->have_posts()) { $count = 0;
    while ($query->have_posts()) { the_post(); $count++;

Use this:
 if ($query->have_posts()) { $count = 0;
    while ($query->have_posts()) { $query->the_post(); $count++;


text:
Q: Why doesn't exception handling work if I give only one argument to this function? Here is a function:
def add(a, b):
try:
  return a + b
except TypeError:
  print('Error: It takes exactly 2 arguments')

This runs perfectly:
print(add(5,2))

This does not print the message I expect:
print(add(5))

Why?

A: Your message doesn't get printed because the function is never called.
Here's a simpler example which doesn't try to catch any exceptions, to show what's going on:
# add_test.py

def add(a, b):
    return a + b

If you save this as a module add_test.py and then import it from an interactive Python session, you can try a couple of things out:
>>> from add_test import add
>>> add(5, 2)
7

This works as expected.
>>> add(5, 'x')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/z/add_test.py", line 4, in add
    return a + b
TypeError: unsupported operand type(s) for +: 'int' and 'str'

This raises TypeError inside the add() function (on line 4, as the traceback above tells you), because you can't add the integer 5 and the string 'x' together.
If you wanted to, you could catch this exception and print some kind of message:
# add_test_2.py

def add_exc(a, b):
    try:
        return a + b
    except TypeError:
        print("cannot add %r and %r." % (a, b))

… and it would behave as expected:
>>> from add_test_2 import add_exc
>>> add_exc(5, 'x')
cannot add 5 and 'x'.

However, when you miss out an argument completely, something different happens:
>>> add(5)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: add() missing 1 required positional argument: 'b'

This raises TypeError immediately, without even trying to execute the code in add(), because when you defined add() you specified that it takes exactly two arguments: a and b. Your function is saying "I can only be called with two arguments", so Python follows that rule.
Since you haven't given Python a value for b in the second example, the function simply wouldn't make any sense if it were called, and Python knows that, so it refuses to try to do something that doesn't make any sense.
One way of looking at this is that you're getting two different kinds of TypeError in the two examples above:

*

*When you call add(5, 'x') the problem is that 5 and 'x' are types of things that can't be added together, and you get a TypeError at the exact moment you break that rule.

*When you try to call add(5), the problem is that add() is a type of function that must be called with two arguments, and you get a TypeError at the exact moment when you break that rule, which is before the function can even start.


text:
Q: Подсчёт количества сообщений от пользователя в телеграмм боте Хочу подсчитать сколько раз пользователи отправляли сообщения моему боту (в том числе и нажатий на кнопки).
Можно ли это реализовать использую обычную глобальную переменную-счётчик в функции обработчика? И если да, то как?

A: Можно использовать JSON.
Сохранять туда id пользователя и count messages.
count += 1 делать когда пришло сообщение(ну и проверку на id).

A: counter = {} # {user_id: int}

@bot.message_handler()
def blabla():
    global counter
    ...some code...
    counter[message.from_user.id] = counter.get(message.from_user.id, 0) + 1

@bot.callback_query_handler(func=lambda call: True)
def callback_worker(call):
    global counter
    ...some code...
    counter[call.message.from_user.id] = counter.get(call.message.from_user.id, 0) + 1

Насчет второго counter'a не уверен, но если не будет работать - напишите в комменты, посмотрю как сделать.
Объяснение:
Мы создаем словарь, в котором для каждого id пользователя считается кол-во отправленных им сообщений. counter.get(.from_user.id, 0) нужна для того, чтобы если этот пользователь еще не отправлял сообщений не вылазила ошибка, а возвращался default, равный 0.


text:
Q: Discord Bot shuts down whenever a user sends it a dm My bot saves chat logs, it works perfectly until someone dms the bot. Here is the code that logs messages.
console.log(message.author.username, "||", message.channel.name, "-", message.content);
        let channel = message.channel.name;
        var readmessagefile = fs.readFileSync('./txt-files/logs.txt', 'utf-8');
        var writemessagefile = fs.writeFileSync('./txt-files/logs.txt', 'Time - ' +
        message.createdAt + ' Channel: ' + channel + " ||" + ' User - ' + message.member.user.username + ': ' +
        message.content + "\n" + readmessagefile);

I'm trying to figure out a way to completely ignore dms so it doesn't mess anything up.
Here is the error:
C:\Documents\Projects\DiscordBot\commands\logs.js:11
        message.createdAt + ' Channel: ' + channel + " ||" + ' User - ' + message.member.user.username + ': ' +
                                                                                ^

TypeError: Cannot read property 'user' of null

A: You did not initiate the user field (It's a Null) in object member that it a field in the var message

A: According to the message.member docs:

Represents the author of the message as a guild member. Only available if the message comes from a guild where the author is still a member

The problem is that DMs are not sent in a guild, and thus message.member returns null. You should be using message.author which also has a username property, and is available globally.
message.member.user and message.author technically return the same thing. message.author is the User object of whoever authored the message. message.member is the GuildMember object of whoever authored the message. GuildMember.user is the User object of a GuildMember.
They both return the same thing, but one takes an extra step to do so.
Author >> User (message.author)
Author >> GuildMember >> User (message.member.user)

Also, you can improve your code readability using template literals
var writemessagefile = fs.writeFileSync(
 './txt-files/logs.txt',
 `Time - ${message.createdAt} Channel: ${channel} || User - ${message.author.username}: ${message.author.content}\n${readmessagefile}`
);


text:
Q: How to change the HTML type of a column using Javascript There is 3 issues in my code:

*

*Infinite while loop I dont understand why, I'm just trying to test if the prompt is a number or not (If not -> Prompt again until it is) [SOLVED]

*If min/max are correct, they should be added to all the cells from that column
From :
<input type=text...
To :
<input type=number min=... max=...
Currently, they are not even added and the type is indeed converted to number but for the full table, not for that specific column, which is not what I want obviously
What I want is to, when I press that "nbr" button from that specific column, convert all the cells' type from that column from text to nbr (and add min and max values to it) [SOLVED]

*When I press that "nbr" button, it changes all the input fields from all the tables from text fields into number fields. What I'm trying to do is only changing the text fields from that column into "nbr" fields, only that column. [SOLVED]

This is the part that doesn't work as intended :
//change column type to number
  $('body').on('click', '.nbr-col', function(event) {
    // ...
    // Here I'm trying to add the min attribute to all the number fields from that specific column
    $('input[type=\'number\']', event.delegateTarget).prop('min',($('#min').val()));

    // Here I'm trying to add the max attribute to all the number fields from that specific column
    $('input[type=\'number\']', event.delegateTarget).prop('max',($('#max').val()));

    // Here I'm trying to convert all the text fields to number fields for that specific column (it kinda works, but it converts all the text fields from all the table to number fields, that's not what I want to do
    $('input', event.delegateTarget).prop('type','number');
  });

So the result should be (for example) :

*

*Create as much columns and rows as I want

*Press the "nbr" button from column 2

*Should convert all the text fields from column 2 into number fields :
Convert this :
<input type="text" class="form-control">

To this :
<input type='number' min=value_from_prompt max=value_from_prompt class="form-control">

For each cells from column 2
Here is a picture :
nbr press converting all the  into "number" from all the table, not only the column in question
Here's a full code fiddle: https://jsfiddle.net/wh9y05qt/
Here's my full code snippet :

// Code goes here

$(document).ready(function() {
  // add row
  $('body').on('click', '.add-row', function() {
    var tr = $(this).parents('.table-content').find('.table tbody tr:last');
    if (tr.length > 0) {
      var clone = tr.clone();
      clone.find(':text').val('');
      tr.after(clone);
    } else {
      var cols = $(this).closest('.table-content').find('th').length,
        tr0 = $('
');
      tr0.html('x	 <input type="text" class="form-control"> 	');
      for (var i = 2; i < cols; i++) {
        tr0.append(' static element 	')
      }
      $(this).closest('.table-content').find('.table tbody').append(tr0);
      //$(this).closest('.table-content').find('.table tbody').append('
 x	 <input type="text" class="form-control"> 	 static element 	 static element
');
    }
  });

  // delete row
  $('body').on('click', '.remove-row', function() {
    $(this).parents('tr').remove();
  });

  // add column
  $('body').on('click', '.add-col', function() {
    $(this).parent().find('.table thead tr').append('<input type="text" class="form-control pull-left" value=""> x text nbr 	');
    $(this).parent().find('.table tbody tr').append('<input type="text" class="form-control">	');
  });

  // change column type to text
  $('body').on('click', '.text-col', function(event) {
    // Get index of parent TD among its siblings (add one for nth-child)
    //var ndx = $(this).parent().index() + 1;
    // Find all TD elements with the same index
    $('input', event.delegateTarget).prop('type','text');
  });

  // change column type to number
  $('body').on('click', '.nbr-col', function(event) {
   // Get index of parent TD among its siblings (add one for nth-child)
    //var ndx = $(this).parent().index() + 1;
    // Find all TD elements with the same index
    var filter = /^[0-9]*$/g;
    var cond = false;
    var min = prompt('Valeur minimum :');
    while (cond == false)
    {
     if (min.match(filter))
      {
       cond = true;
      }
      else {
       var min = prompt('Valeur minimum incorrect, réessayez :');
      }
    }

    var cond = false;
    var max = prompt('Valeur maximum :');
    while (cond == false)
    {
     if (max.match(filter))
      {
       cond = true;
      }
      else {
       var max = prompt('Valeur maximum incorrect, réessayez :');
      }
    }
    $('input[type=\'number\']', event.delegateTarget).prop('min',($('#min').val()));
    $('input[type=\'number\']', event.delegateTarget).prop('max',($('#max').val()));
    $('input', event.delegateTarget).prop('type','number');
  });

  // remove column
  $('body').on('click', '.remove-col', function(event) {
    // Get index of parent TD among its siblings (add one for nth-child)
    var ndx = $(this).parent().index() + 1;
    // Find all TD elements with the same index
    $('th', event.delegateTarget).remove(':nth-child(' + ndx + ')');
    $('td', event.delegateTarget).remove(':nth-child(' + ndx + ')');
  });
});
/* Styles go here */

.table-content {
  padding: 20px;
}
.remove {
  margin-left: 10px;
  color: red;
}
.remove:hover {
  cursor: pointer;
}

.text {
  margin-left: 10px;
  color: blue;
}
.text:hover {
  cursor: pointer;
}

.nbr {
  margin-left: 10px;
  color: green;
}
.nbr:hover {
  cursor: pointer;
}
.form-control {
  width: 90px;
}

<link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css" rel="stylesheet">

      <button class="btn btn-link add-col">Add Column</button>

              Define

              x

                <input type="text" class="form-control">

      <button class="btn btn-link add-row">Add row</button>

A: After reading this long question, that what you really want is to just select all inputs from second td of the table body and set min, max and type="number", if is this, then I think that what you need is:
$(".table tbody tr td:nth-child(3) input")

check below snippet, is it what you need?

$(document).ready(function() {
  // add row
  $('body').on('click', '.add-row', function() {
    var tr = $(this).parents('.table-content').find('.table tbody tr:last');
    if (tr.length > 0) {
      var clone = tr.clone();
      clone.find(':text').val('');
      tr.after(clone);
    } else {
      var cols = $(this).closest('.table-content').find('th').length,
        tr0 = $('
');
      tr0.html('x	 <input type="text" class="form-control"> 	');
      for (var i = 2; i < cols; i++) {
        tr0.append(' static element 	')
      }
      $(this).closest('.table-content').find('.table tbody').append(tr0);
    }
  });

  // delete row
  $('body').on('click', '.remove-row', function() {
    $(this).parents('tr').remove();
  });

  // add column
  $('body').on('click', '.add-col', function() {
    $(this).parent().find('.table thead tr').append('<input type="text" class="form-control pull-left" value=""> x text nbr 	');
    $(this).parent().find('.table tbody tr').append('<input type="text" class="form-control">	');
  });

  // change column type to text
  $('body').on('click', '.text-col', function(event) {
    $('input', event.delegateTarget).prop('type', 'text');
  });

  // change column type to number
  $('body').on('click', '.nbr-col', function(event) {
    var filter = /^[0-9]*$/g;
    var cond = false;
    var min = prompt('Valeur minimum :');
    while (cond == false) {
      if (min.match(filter)) {
        cond = true;
      } else {
        var min = prompt('Valeur minimum incorrect, réessayez :');
      }
    }

    var cond = false;
    var max = prompt('Valeur maximum :');
    while (cond == false) {
      if (max.match(filter)) {
        cond = true;
      } else {
        var max = prompt('Valeur maximum incorrect, réessayez :');
      }
    }
    let colToModify = $(this).parent().index() + 1;
    let inputsCol = $(".table tbody tr td:nth-child(" + colToModify + ") input")
    inputsCol.attr("type", "number").prop("min", min).prop("max", max)
    console.log("modified columns index: " + colToModify)
  });

  // remove column
  $('body').on('click', '.remove-col', function(event) {
    var ndx = $(this).parent().index() + 1;
    $('th', event.delegateTarget).remove(':nth-child(' + ndx + ')');
    $('td', event.delegateTarget).remove(':nth-child(' + ndx + ')');
  });
});
/* Styles go here */

.table-content {
  padding: 20px;
}

.remove {
  margin-left: 10px;
  color: red;
}

.remove:hover {
  cursor: pointer;
}

.text {
  margin-left: 10px;
  color: blue;
}

.text:hover {
  cursor: pointer;
}

.nbr {
  margin-left: 10px;
  color: green;
}

.nbr:hover {
  cursor: pointer;
}

.form-control {
  width: 90px;
}

<link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css" rel="stylesheet">

  <button class="btn btn-link add-col">Add Column</button>

          Define

          x

            <input type="text" class="form-control">

  <button class="btn btn-link add-row">Add row</button>


text:
Q: How do I fit/re-size Windows Form to any screen resolution? I know this is duplicated question but I checked all other related question and their answers did not help ( the result still the same as shown in screenshot 2)

I am new to c# windows forms. As shown in screenshot1, I have Form1 with some controls and each group of controls were put in a panel. I designed the application in PC1 as shown in Screenshot1 which is fit the screen resolution and worked well.

My application was  developed in 1366 x 768 screen resolution (as shown in Screenshot1) but when I run this application in different computer (PC2) with different monitor size and different screen resolution the form appeared too big and part of the application is missing or is out of the screen.
However I solved this issue using Anchors but another issues came up which is: the user control does not re-size itself ( as shown in screenshot2) and part of it is cut or went under panel1 . I do not know if the problem is related to user control or related to all controls in Form1 (they should resize themselves)
I even tried the following code but the result still the same:
this.WindowState = FormWindowState.Maximized;
this.Location = new Point(0, 0);
this.Size = Screen.PrimaryScreen.WorkingArea.Size;
Screen.PrimaryScreen.WorkingArea

I have been searching to solve this issue the whole day yesterday but I failed, Please help me with any idea/suggestion it might work. Thank you

A: If you are working with Windows Forms and you cannot switch to WPF then you will prefer to do all the design in the lowest resolution at which you must run.
In WinForms you are setting the Size of every element so they will not re size according to the app size. What they will do is to be distributed along the empty space (if you program them to do so) increasing the free space between them, that's all.
Another option are LayoutPanels as Sinatr said as they try to offer the WPF panel functionality.

A: By default in WinForms, all controls that you place on the form while designing it have a fixed size. If you don't do anything special, whatever size the controls are when you place them are the size that they are always going to have, no matter what machine you're running on.
As you've noticed, that isn't always going to give good results. The way you work around it is to use a fluid layout, with liberal use of the TableLayoutPanel and/or FlowLayoutPanel container controls, as well as the Anchor and Dock properties for individual child controls. If you take special care to lay out the controls on your form correctly, they can be dynamically resized and rearranged to fit the available screen space.
This code
this.WindowState = FormWindowState.Maximized;
this.Location = new Point(0, 0);
this.Size = Screen.PrimaryScreen.WorkingArea.Size;
Screen.PrimaryScreen.WorkingArea

doesn't do anything. The only thing you need there is the very first line. Once you make the form maximized, it will fill the entire screen. You don't need to force it by setting its Size or Location properties. In fact, those have no effect on a maximized form.
The problem is presumably that the controls placed on your form do not resize themselves automatically (as discussed above). If you had a big enough screen, you'd see empty space where the form was filling the screen but had no controls on it. You have the opposite problem: on a smaller screen, controls don't fit and therefore overlap each other.
It isn't a perfect situation. Even if you code up a perfect dynamic layout, if you try to run the application on a system with a screen that is significantly smaller than your design intended, you're going to end up with buttons that are too small to poke. That's why applications are not, in general, designed this way. A screenful of buttons is terrible UI. The only time this kind of design is acceptable is when you're designing for a touch screen UI, like a restaurant POS. And in that case, you already have a pretty good idea what size screens your clients are going to be using, since it's all specialty hardware.