text:
Q: Background Images In UITableView Sections Hides Section Titles I am using the following method to set titles in the section's header of UITableView, works fine.
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    NSString *sectionHeader = nil;

    if (section == 0)
    {
        sectionHeader = nil;
    }
    if(section == 1)
    {
        sectionHeader = @"Categories";
    }
    if (section == 2) {
        sectionHeader = @"General";
    }
    return sectionHeader;
}

Using the following method, i am setting the height for header in section, works fine.
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 20;
}

BUT, as soon as i set the background images in the section header using the following method, the titles in section's header disappears and become empty but of course with the image place.
- (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{

    UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, tableView.bounds.size.width, 20)];
    UIImageView *headerImage = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"section_background.png"]];

    headerImage.frame = CGRectMake(0, 0, tableView.bounds.size.width, 20);

    [headerView addSubview:headerImage];

    return headerView;
}

How can i set the titles in section headers without removing the background images in it. Can somebody be kind enough to point it out. Thanks in advance.

A: It happening because your headerView overlap on you title of Header. so Best way is...also add UILabel To your headerView. and give text of label as your title os header in section.
I try with following code .. use it as your way, may be helpful in your case.
- (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{

    UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, tableView.bounds.size.width, 20)];
    UIImageView *headerImage = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"1.png"]]; //set your image/

    UILabel *headerLbl = [[UILabel alloc] initWithFrame:CGRectMake(15, 0, 205, 15)];//set as you need
    headerLbl.backgroundColor = [UIColor clearColor];
    headerLbl.text = [self.listOfHeader objectAtIndex:section];
    [headerImage addSubview:headerLbl];

    headerImage.frame = CGRectMake(0, 0, tableView.bounds.size.width, 20);

    [headerView addSubview:headerImage];

    return headerView;
}

A: Another approach by setting dimensions of CGRect directly from image H, W,
 - (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {

 UIImage *myImage = [UIImage imageNamed:@"header.png"];
 UIView *tempView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, myImage.size.width, myImage.size.height)];

 UIImageView *imageView = [[UIImageView alloc] initWithImage:myImage];
 imageView.frame = CGRectMake(0,0,myImage.size.width, myImage.size.height);

  headerLabel = [[UILabel alloc] initWithFrame:CGRectMake(15, 5, 300, 25)];
  headerLabel.font = [UIFont fontWithName:@"TrebuchetMS-Bold" size:15.0];
  headerLabel.backgroundColor = [UIColor clearColor];

  NSString *myString = [NSString stringWithFormat:@"This is Header ;)"];
  NSLog(@" headerLabel.text: %@", myString);
  headerLabel.text = myString;
 [imageView addSubview:headerLabel];

 [tempView addSubview:imageView];

 return tempView ;

 }

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
 return 50;
 }


text:
Q: Density of primes containing specific digits I suspect that primes containing certain digits (e.g. $1$, $3$) are way more common than primes containing other digits e.g. containing $2,4$ since my intuition tells me the latter combination is divisible by so many numbers: For example $13$ and $31$ are prime while neither $24$ or $42$ is (I take here the trivial null case of $2$'s and $4$'s for illustrative purposes).
This came to my mind as I was playing around with $1$'s and $3$'s trying to guess a prime number consisting of these two digits. To my surprise I guessed the following primes (tested with PrimeQ[...] of Mathematica) quite easily (the first ones in a couple of guesses while that last one took a dozen):
$$ 11131, \\ 111311131 \\ 11131113113131111 \\ 11131113111111111111131311 $$
How come? Is this pure luck? I have a hard time believing it be pure luck due to the Prime Number Theorem.
(For the last number in the list I basically put in $1$'s and $3$'s randomly a dozen of times until I hit a prime.)

A: This is not so surprising: An improvement to the P.N.T. implies that the number $\pi(x)$ of primes $\leq n$ is given by the (offset) logarithmic integral function, $$\operatorname{Li}(x) := \int_2^x \frac{dt}{\log t} .$$ Heuristically, the probability that a given random integer $\approx N$ is prime is $$\left.\frac{d}{dx}\right\vert_N \operatorname{\operatorname{Li}(x) = \frac{1}{\log N}},$$ but all primes $> 2$ are odd, so (again heuristically) the probability that a given random odd integer $\approx N$ is twice that, $$\frac{2}{\log N}.$$ For the largest number $N_0 := 11131113111111111111131311
11131$ in your list, computing gives
$$\frac{2}{\log N_0} = 0.034679\!\ldots \approx \frac{1}{29} ,$$
so, naively, one would have to try $29$ odd numbers of that magnitude to find a prime, and one would find one in the first dozen attempts $> \frac{1}{3}$ of the time. One could derive a similar approximation using just the P.N.T., but the math for this better approximation is a little easier.

A: As you have Mathematica you could simply create all numbers made of 1s and 3s of a certain length then determine which ones are prime then divide by the number of possible numbers. Here is a function which can do that:

f[n_]:=Count[Map[PrimeQ[FromDigits[#]]&,Tuples[{1,3},n]],True]/2^n

Lets break it down:
Tuples[{1,3},n] creates all possible lists of length n made from the digits 1 and 3. Then the functions PrimeQ and FromDigits is Mapped over all these lists to firstly convert each list to an actual number then test if its prime. The True results of this mapping is then counted and finally this number is divide by the total number of permutations.
Comparing to your situation we see:

f[5]=$\frac{9}{32}$
f[9]=$\frac{75}{512}$
f[17]=$\frac{9461}{131072}$
f[26]=$\frac{?}{67108864}$ = too hard for my computer to process

A: Your question, whether or not primes containing some digits are more common than primes containing others can be made into a precise question in various different ways. One obvious way is the following: does the quantity
$$
\lim_{N \to \infty} \frac{\#\{p < N \mid \text{$p$ prime and $p$ contains digit $d$}\}}{\#\{p < N \mid \text{$p$ prime}\}}
$$
always exist, and if so, does it differ for different digits $d$?
The answer to this question is no, and in fact the limit above always exists and always equals 1. The reason comes down to the following informal facts: there are quite many primes, while there are very few numbers which do not contain all 10 digits.
In their paper on the Copeland-Erdős constant, Copeland and Erdős prove the following result (paraphrased, and specialized to our situation):

Lemma: There is a $\delta < 1$ such that for sufficiently large $N$, the number of numbers below $N$ which do not contain all 10 digits is less than $N^\delta$.

Let's fix such a $\delta$. From the prime number theorem, we know that the number of primes less than $N$ is approximately $\frac N{\log N}$ for large enough $N$. Thus, the number of primes below $N$ which contain all 10 digits is certainly at least
$$
\frac N{\log N} - N^\delta
$$
for $N$ sufficiently large. But then we have for any digit $d$
\begin{align*}
1 &\geq \lim_{N \to \infty} \frac{\#\{p < N \mid \text{$p$ prime and $p$ contains digit $d$}\}}{\#\{p < N \mid \text{$p$ prime}\}}\\
& \geq\lim_{N \to \infty} \frac{\#\{p < N \mid \text{$p$ prime and $p$ contains all digits $d$}\}}{\#\{p < N \mid \text{$p$ prime}\}}\\
&\geq \lim_{N \to \infty} \frac{\frac N{\log N} - N^\delta}{\frac N{\log N}}\\
&= 1.
\end{align*}
This argument can be extended without too much effort to different bases, and to different substrings (instead of just single digits).

redpajama_set_name: RedPajamaStackExchange


text:
Q: mongodb find or aggregate matching an object inside an array of a document I'm trying to figure out how I can search for all documents which has the same combination of "tags" like the following document.
Meaning that I would like to find all documents which has tags {brand:"bosh", type:"fridge"} && {type:"freezer", color:"white"} or any other combination of the tags. Is this possible in  mongo? How can I do that or is there a good explanation somewhere that explains this?
{
"_id" : ObjectId("53bd7837156aa38914f55176"),
"user_id" : "53bd1a0d237e7d44120a51d1",
"tags" : [
    {
        "brand" : "bosch",
        "type" : "fridge",
        "color" : "black"
    },
    {
        "brand" : "electrolux",
        "type" : "freezer",
        "color" : "white"
    }
]
}

A: You need to use$elemMatch operator to match the subdocument and $all operator to combine multiple $elemMatch operators:
db.coll.find({
    "tags" : {
        "$all" : [
            {"$elemMatch" : {"brand": "bosch", "type" : "fridge"}},
            {"$elemMatch" : {"type": "freezer", "color": "white"}}
        ]
    }
});

This query will find all documents that have subdocuments that have specified values in both fields (i.e. brand && type and type && color).
The following document will NOT be matched by the above query (notice that the value of the type fields are reversed):
{
    ...
    "tags" : [
        {
            "brand" : "bosch",
            "type" : "freezer"
        },
        {
            "brand" : "electrolux",
            "type" : "fridge"
        }
    ]
}


text:
Q: AS3: Handle BulkLoader.COMPLETE event on AS3 Preloader I am trying to use BulkLoader (https://github.com/arthur-debert/BulkLoader) to preload all assets of my AS3/Flex application. Right now it is working and I am able to access the contents everywhere on my Main module (where my BulkLoader instance lives).
My problem: I need to handle the BulkLoader.COMPLETE event from my preloader (pre.as living next to Main.mxml on src/), to allow the user to exit the preloader and enter the application ONLY after BulkLoader.COMPLETE was fired.
Thanks!

A: Why not pass the reference to the BulkLoader instance?
Somethinglike this:
preloader.setLoader(_bulkLoaderInstance or name)

or
var preloader:Preloader = new Preloder(_bulkLoaderInstance or name)

BTW, the LoaderMax from Greensock is better (fewer bugs, more reliable events, nicer API).


text:
Q: Raspberry piTFT display gui with python tkinter I am using raspberry pi tft display from adafruit. What setting is required for raspberry piTFT display to work with python tkinter?

A: Python tkinter need XWindow system. You could start it on the PiTFT using :
FRAMEBUFFER=/dev/fb1 startx -- -dpi 60

There is a nice tutorial here: http://raspi.tv/2014/texys-2-8-inch-touchscreen-with-raspicamcorder-step-1
Next you can start python tkinter script using :
DISPLAY=:0 python <your script>

It will be displayed on PiTFT screen.


text:
Q: What is the average value of P(x) for all the permutations of 1234567? Let $P(x)$ be the length of the longest decreasing subsequence in a permutation $x$ such that the first element of $x$ is a part of that subsequence.
What is the average value of $P(x)$ for all the permutations of $1234567$?
Here's  the current sketch of my solution
Let $N$ be the sum of all $P(x)$ over permutations of $1234567$
The digit $7$ can only add $1$ to our count of $N$ if it is the first number in the list. The number of times $7$ is first in the list is $6!$
The digit $6$ can only add $1$ to our count of $N$ if it is the first or second number in the list. The number of times $6$ is first in the list is $6!$. When 6 is second in the list 7 must be first in the list if we want it to add to our count so the total count for 6 is $6!+5!$.
The digit $5$ can only add to our count if its in position 1,2,3(with some restrictions). The number of ways this can happen is $6!+2*5!+4!$
The digit $4$ can only add to our count if its in position 1,2,3,4. The number of ways this can happen is $6!+3*5!+3*4!+3!$
(looking a lot like pascals)
But this method is still much slower than I would like to be so anyone have any ideas on how to solve this problem more efficiently.

A: Hint:  A permutation either starts with the largest element or not.  If it does, the length is one more than the function on the rest.  If not, the length is the same as if the largest element is not there.  This should suggest a recurrence.
Added:  If we want to evaluate $P(x)$, we have $x!$ permutations.  In $(x-1)!$ of those the largest element comes first, adding $1$ to the length of the permutation of the rest which follows.  In the rest, the largest element comes somewhere later and is not part of the longest decreasing subsequence, so we can ignore it.  This gives $P(x)=\frac {(x-1)!}{x!}(1+P(x-1))+\left(1-\frac {(x-1)!}{x!}\right)P(x-1)=\frac 1x(P(x-1)+1)+\frac{x-1}xP(x-1)=P(x-1)+\frac 1x$  Given $P(1)=1$ we have that $P(x)=\sum_{i=1}^x\frac 1i=H_x$ the $x^{\text{th}}$ harmonic number.


text:
Q: Is there a way to get Swashbuckle to add OData parameters to Web API 2 IQueryable endpoint? I have an ASP.Net Web API 2 endpoint that supports OData queries. It is as such:
[HttpGet, Route("")]
public IQueryable<Thing> Get()
{
    return _thingsRepository.Query();
}

The OData $filter parameter and such work great. I just wish they would show up in Swagger like they do for actual OData controllers.
I am using Swashbuckle.OData ... but I'm really not sure that it's buying me anything in this case.

A: It turns out it's pretty easy to add whatever parameters you want to Swagger using SwashBuckle using an IOperationFilter. You can add it in your Swagger Configuration using c.OperationFilter<ODataParametersSwaggerDefinition>();. I created one that adds some OData Parameters to all IQueryable endpoints in my API:
/// <summary>
///     Add the supported odata parameters for IQueryable endpoints.
/// </summary>
public class ODataParametersSwaggerDefinition : IOperationFilter
{
    private static readonly Type QueryableType = typeof(IQueryable);

    /// <summary>
    ///     Apply the filter to the operation.
    /// </summary>
    /// <param name="operation">The API operation to check.</param>
    /// <param name="schemaRegistry">The swagger schema registry.</param>
    /// <param name="apiDescription">The description of the api method.</param>
    public void Apply(Operation operation, SchemaRegistry schemaRegistry, ApiDescription apiDescription)
    {
        var responseType = apiDescription.ResponseType();

        if (responseType.GetInterfaces().Any(i => i == QueryableType))
        {
            operation.parameters.Add(new Parameter
            {
                name = "$filter",
                description = "Filter the results using OData syntax.",
                required = false,
                type = "string",
                @in = "query"
            });

            operation.parameters.Add(new Parameter
            {
                name = "$orderby",
                description = "Order the results using OData syntax.",
                required = false,
                type = "string",
                @in = "query"
            });

            operation.parameters.Add(new Parameter
            {
                name = "$skip",
                description = "The number of results to skip.",
                required = false,
                type = "integer",
                @in = "query"
            });

            operation.parameters.Add(new Parameter
            {
                name = "$top",
                description = "The number of results to return.",
                required = false,
                type = "integer",
                @in = "query"
            });

            operation.parameters.Add(new Parameter
            {
                name = "$count",
                description = "Return the total count.",
                required = false,
                type = "boolean",
                @in = "query"
            });
        }
    }
}

A: Direct steal of the accepted answer, but, with extra null check.
This will not touch your existing OData queryable endpoints which may already have parameters defined, but, will only enhance your queryable ApiController endpoints.
Updated AspNetCore / Net 5, Net 6 Answer
using Microsoft.AspNetCore.Mvc.ApiExplorer;
using Microsoft.OpenApi.Models;
using Swashbuckle.AspNetCore.SwaggerGen;
using System;
using System.Collections.Generic;
using System.Linq;

namespace My.Corporation.Api
{
    /// <summary>
    /// Help your swagger show OData query options with example pre-fills
    /// </summary>
    public class ODataParametersSwaggerDefinition : IOperationFilter
    {
        private static readonly Type QueryableType = typeof(IQueryable);
        private static readonly OpenApiSchema stringSchema = new OpenApiSchema { Type = "string" };
        private static readonly OpenApiSchema intSchema = new OpenApiSchema { Type = "integer" };

        public void Apply(OpenApiOperation operation, OperationFilterContext context)
        {
            var hasNoParams = (operation.Parameters == null || operation.Parameters.Count == 0);
            var isQueryable = context.MethodInfo.ReturnType.GetInterfaces().Any(i => i == QueryableType);

            if (hasNoParams && isQueryable)
            {

                operation.Parameters = new List<OpenApiParameter>();
                operation.Parameters.Add(new OpenApiParameter
                {
                    Name = "$filter",
                    Description = "Filter the results using OData syntax.",
                    Example = OpenApiAnyFactory.CreateFor(stringSchema,"ProductName eq 'YOGURT'"),
                    Required = false,
                    In = ParameterLocation.Query,
                    Schema = stringSchema

                });
                operation.Parameters.Add(new OpenApiParameter
                {
                    Name = "$select",
                    Description = "Trim the fields returned using OData syntax",
                    Example = OpenApiAnyFactory.CreateFor(stringSchema, "Id,ProductName"),
                    Required = false,
                    In = ParameterLocation.Query,
                    Schema = new OpenApiSchema { Type = "string" }
                });
                operation.Parameters.Add(new OpenApiParameter
                {
                    Name = "$orderby",
                    Description = "Order the results using OData syntax.",
                    Example = OpenApiAnyFactory.CreateFor(stringSchema, "Price,ProductName ASC"),
                    Required = false,
                    In = ParameterLocation.Query,
                    Schema = new OpenApiSchema { Type = "string" }
                });
                operation.Parameters.Add(new OpenApiParameter
                {
                    Name = "$skip",
                    Description = "The number of results to skip.",
                    Example = OpenApiAnyFactory.CreateFor(intSchema, 100),
                    Required = false,
                    In = ParameterLocation.Query,
                    Schema = intSchema
                });
                operation.Parameters.Add(new OpenApiParameter
                {
                    Name = "$top",
                    Description = "The number of results to return.",
                    Example = OpenApiAnyFactory.CreateFor(intSchema, 50),
                    Required = false,
                    In = ParameterLocation.Query,
                    Schema = intSchema
                });
            }
        }
    }
}

Original WebAPI 2 Answer
 /// <summary>
 /// Adds the supported odata parameters for IQueryable endpoints
 /// ONLY if no parameters are defined already.
 /// </summary>
 public class ODataParametersSwaggerDefinition : IOperationFilter
 {
    private static readonly Type QueryableType = typeof(IQueryable);

    /// <summary>
    /// Apply the filter to the operation.
    /// </summary>
    /// <param name="operation">The API operation to check.</param>
    /// <param name="schemaRegistry">The swagger schema registry.</param>
    /// <param name="apiDescription">The description of the api method.</param>
    public void Apply(Operation operation, SchemaRegistry schemaRegistry, ApiDescription apiDescription)
    {
        var responseType = apiDescription.ResponseType();

        if (responseType.GetInterfaces().Any(i => i == QueryableType))
        {
            if (operation.parameters == null)
            {
                operation.parameters = new List<Parameter>();

                operation.parameters.Add(new Parameter
                {
                    name = "$filter",
                    description = "Filter the results using OData syntax.",
                    required = false,
                    type = "string",
                    @in = "query"
                });

                operation.parameters.Add(new Parameter
                {
                    name = "$orderby",
                    description = "Order the results using OData syntax.",
                    required = false,
                    type = "string",
                    @in = "query"
                });

                operation.parameters.Add(new Parameter
                {
                    name = "$skip",
                    description = "The number of results to skip.",
                    required = false,
                    type = "integer",
                    @in = "query"
                });

                operation.parameters.Add(new Parameter
                {
                    name = "$top",
                    description = "The number of results to return.",
                    required = false,
                    type = "integer",
                    @in = "query"
                });

                operation.parameters.Add(new Parameter
                {
                    name = "$count",
                    description = "Return the total count.",
                    required = false,
                    type = "boolean",
                    @in = "query"
                });
            }

        }
    }
}

A: Using Swashbuckle.AspNetCore v. 6.2.3 it can look like this:
public void Apply(OpenApiOperation operation, OperationFilterContext context)
{
    if (context.MethodInfo.ReturnType.GetInterfaces().Any(i => i == typeof(IQueryable)))
    {
        operation.Parameters.Add(new OpenApiParameter()
        {
            Name = "$filter",
            Description = "My $filter filter",
            Required = false,
            In = ParameterLocation.Query,
        });

        operation.Parameters.Add(new OpenApiParameter()
        {
            Name = "$top",
            Description = "My $top filter",
            Required = false,
            In = ParameterLocation.Query,
        });

        operation.Parameters.Add(new OpenApiParameter()
        {
            Name = "$expand",
            Description = "My $top filter",
            Required = false,
            In = ParameterLocation.Query,
        });
    }
}


text:
Q: Electron app can't find resources when openAtLogin is set I have app that set app.setLoginItemSettings({openAtLogin: true}) but when i reload my machine i have error of files dont found, but when i launch app from shortcut all files is founded and dont trow error.
In background.js i have:
const image = nativeImage.createFromPath('resources/img/logo.png');

/**
 * ->openAtLogin: true
 * image is empty
 *
 * ->run from shortcut
 * image set
 */

In vue.config.js i have:
(...)
        electronBuilder: {
            builderOptions: {
                (...)
                // to copy resources from project to package resources folder
                extraResources: [
                    {
                        from: "resources",
                        to: ""
                    }
                ],
            }
        }
(...)

A: The proplem that on autolaunch root folder is C:\Windows\system32 and not app folder.
Becuase of that is necessary to get resources_path.
Example:
const isDevelopment = process.env.NODE_ENV !== "production";
const resources_path = isDevelopment? path.resolve('./'): path.dirname(process.execPath);
const image = nativeImage.createFromPath(`${resources_path}/resources/img/logo.png`);


text:
Q: Postgres Trigger and Function to auto complete table Can't find the solution to make a trigger to fill the pass and success_rate rows
CREATE TABLE en_testes_automatizados (
dia DATE NOT NULL,
id_projeto integer NOT NULL REFERENCES jira3.en_projeto (id_projeto),
total integer NOT NULL,
pass integer,
fail integer,
success_rate DOUBLE PRECISION,
result_link character);

I need to fill the pass row with the expression (total - pass) and the success_rate with ((pass/total) x100)

A: It seems a little long winded just to auto update a column but first you will need to create a function that the trigger will run using something like this that will set the value of that column
CREATE OR REPLACE FUNCTION en_testes_automatizados_success_rate()
RETURNS TRIGGER AS
$$
BEGIN
    NEW.success_rate := (pass / (pass + fail)) * 100;

    RETURN NEW;
END
$$
LANGUAGE PLPGSQL;

Then create a trigger for the table
CREATE TRIGGER ON en_testes_automatizados
BEFORE INSERT FOR EACH ROW
EXECUTE PROCEDURE en_testes_automatizados_success_rate();


text:
Q: Deleting emails from an Outlook client connecting to POP mailbox I have POP setup so I can check my rocketmail.com webmail in Outlook Express.  I signed up to a high volume mailing list that filled up my inbox with several thousand emails.
I deleted them from Outlook but when I go to sync with rocketmail it starts downloading all the deleted mails again.
Any way to stop this without deleting them on the webmail side and would this happen with IMAP protocol?
thanks

A: The simple answer is yes, but in application, probably no.
I'm going to go back to basics to try and explain what's going on. I'd say that this is from memory and might not be 100% technically accurate, but should be enough to make sense. No doubt the community will correct me (and fill in an gaps) :)
If we go back to the 90's (and I suppose earlier) when email and "the internet" was taking off, email systems are comparable to the postal system at a university with pidgin holes. POP3 is the Post Office Protocol (version 3).
EG:

*

*The Sender write a letter and wrap it in an envelope ready for sending.

*The Sender then takes the letter to a postbox.

*The letter gets routed to the recipients university's mail room.

*The mail-room staff put the letter into the correct pidgin hole for the recipient.

*The Recipient goes to the mail room to check their pidgin hole for mail.

*The Recipient takes any mail back up to his dorm room to read through it.

so looking at our computers now

*

*The Sender writes an email in your mail client and specify an address and other attributes within the header (envelope).

*The Sender connects to your SMTP server and send give sent it the mail.

*The Sender's SMTP server will work out the recipients mail server and deliver the email to them.

*The Recipient's mail server routes the email to the correct mailbox for the username.

*The Recipient checks for mail. Connecting to the POP3 server we check our inbox for mail.

*If we find any email, we download it for reading.

Ok, so POP3 lets is access our pidgin hole and grab everything in there. It was absolutely fine when people were keeping all their post at home on the one computer.
Shortly after, we find ourselves in a situation where people suddenly want to access the same data from multiple devices in multiple locations; person with multiple email clients on different devices (phone, work, home...) and also this whole cloud computing jango where we access everything via the web, or even worse, where we want all three.
This is where POP3 falls on its ass. Although as you've realised, you can set it not to delete the email once it downloads it, you're actually overriding the default functionality and this leads to interesting problems.
Its like getting the university mail room to take a photocopy of all of your letters. They will, but when you next come to collect your post they have no way of knowing whats new or what you already have a copy of. It can also be slow and bad tempered.
So, we get IMAP(4) coming along which helps to fix this problem.
Instead of your mail client grabbing everything from the remote server and dumping it into some specified local folder (inbox) IMAP is working with a remote set of folders and files and just keeping a local cache updated with whats going on on the server.
With all of your email staying on the server it means its always available to access on multiple devices or via webmail. The other bonus is that when you're downloading mail via IMAP rather than POP, its a lot more clever about synchronisation so you don't end up re-downloading the same emails all the time. You can set up different sync options for different folders which can make managing lots of emails easier.

So, in closing:

Any way to stop this without deleting them on the webmail side

On the webmail side, I would try and create a new folder and then move all of the emails from this mailing list into it. Hopefully outlook will only be downloading your 'inbox' folder and will therefore skip all those other emails.
If you can create email rules or filters in your webmail then you might be able to set it up to do this automatically.

and would this happen with IMAP protocol?

If you were using IMAP then when you deleted all those emails from outlook they would have been deleted on the server as well (as its just synchronised folders).
There is a good chance that your web host won't let you do server side filtering, so you would have to go and sort through manually in the webmail each time. Using IMAP means that you could create server side folders in outlook and use that to move mail into correct folders.
The other bonus, is that you could tell outlook to use the server side "sent" and "drafts" folders, so you could start drafting something in outlook and finish it in the webmail, or view mail sent through the webmail in outlook.
Hope this makes some sense :S

A: You can do this in the advanced account options in Outlook Express:

*

*Go to Tools -> Accounts

*Highlight the rocketmail account and click Properties

*Go to the Advanced tab.

*Click the box that says "Leave a copy of messages on server".  It should already be checked since you mentioned that's what you were already doing.

*Check the box that says "Remove from server when deleted from 'Deleted Items'"

As long as you permanently delete your messages (delete them from Deleted Items), Outlook Express will login in to the POP3 server and delete those messages.
Another one I like to use is the other check box on that page that says: "Remove from server after X days"  Set X to whatever makes sense for you.  In your case, I would set it to however long it takes you to read the 1000's of messages per day.
Regarding IMAP, it will work better for Synchronizing your messages, but you will notice that it requires a good solid connection to the Internet.  Even though there is a local copy of the mailbox on your machine, it still trys to check into the server a lot to see if it needs to change things.  This will make OE slow down noticeably.  Also, depending on how big these messages are, Rocketmail is going to limit how many messages you can keep since IMAP stores the messages on their server.
The other thing annoying about IMAP is you can't change the pre-defined folders and you can't subfolder under those pre-defined folders.  Hard to explain here, unless you try for yourself.


text:
Q: Paste multiple commands to Putty - process serially? I have about 3000 individual commands that I need to execute on a system via Putty.  I am doing this by copying ~100 of the commands and pasting them into a putty SSH session.  It works, however the issue is that Putty does not process them serially and the output gets garbled.
Is there a way to make Putty process each command, wait for a return and then process the next?  The Windows command prompt does this and I'm thinking there is a way to do so with Putty.
Yes, I know I could put this in a bash script, but due to circumstance outside my control, this has to be done using SSH and in a manner that can be monitored as we go and logged.

A: I do this all the time.  Put your commands in a ( ) block, which will run it as a subshell, perfectly everything within serially.  I'm running Windows PuTTY and connecting to Linux and AIX servers.  Try it.
(
Command1
Command2
Command3
)

In practice, I might have a huge load of many 100s of statements I want to run, in Notepad++ or whatever.  So I copy them to clipboard, and then in PuTTY:
(
 paste in your wad here
)

EDIT: If you want to log the output from each of your statements individually, you might do something like this:
(
Command1 > /home/jon/command1output.txt
Command2 > /home/jon/command2output.txt
Command3 > /home/jon/command3output.txt
)

or if you just want one big stream of output, you could interleave separators for easier reading later:
(
echo "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"
echo "[`date`]  Now running Command1 ..."
Command1
echo "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"
echo "[`date`]  Now running Command2 ..."
Command2
echo "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"
echo "[`date`]  Now running Command3 ..."
Command3
)

EDIT2: Another variation using an inline function.  All paste-able into PuTTY, with perfect serial running, logging as command1:output1,command2:output2,... , and capable of driving SQL*Plus.
(
  function geniusMagic() {
    echo " "
    echo "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"
    date
    echo "RUNNING COMMAND:"
    echo " "
    echo "$*"
    echo " "
    echo "OUTPUT:"
    echo " "
    sh -c "$*"
  }

  geniusMagic df -m /home
  geniusMagic 'printf $RANDOM | sed "s/0//g"'
  geniusMagic 'echo "select count(*)
                     FROM all_tables;
                 " | sqlplus -s scott/tiger'
)

Sample output:
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Wed Jun 25 17:41:19 EDT 2014
RUNNING COMMAND:

df -m /home

OUTPUT:

Filesystem    MB blocks      Free %Used    Iused %Iused Mounted on
/dev/hd1        1024.00    508.49   51%     3164     3% /home

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Wed Jun 25 17:41:19 EDT 2014
RUNNING COMMAND:

printf $RANDOM | sed "s/0//g"

OUTPUT:

2767
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Wed Jun 25 17:41:19 EDT 2014
RUNNING COMMAND:

echo "select count(*)
                     FROM all_tables;
                 " | sqlplus -s scott/tiger

OUTPUT:

  COUNT(*)
----------
        48

A: Just an idea here, Putty comes with a command-line tool called Plink. You could write a script on your windows machine that creates a connection to the remote server with Plink, then parses your list of commands one at a time and sends them.
This should look exactly the same to the remote server (which I assume is what's doing the logging), while letting you have a bit more control than copy-pasting blocks of commands.

A: I'm not sure why you could not use Plink, but you could make a batch file with Notepad++.
plink <hostname> -l <login_name> -pw <password> <command 1>
plink <hostname> -l <login_name> -pw <password> <command 2>
plink <hostname> -l <login_name> -pw <password> <command 3>
...
plink <hostname> -l <login_name> -pw <password> <command 3000>

Run the batch file:
filename.bat > log.txt 2>&1

Notepad++: http://notepad-plus-plus.org/
Plink: http://www.chiark.greenend.org.uk/~sgtatham/putty/download.html
Batch files: http://www.robvanderwoude.com/batchfiles.php

Display & Redirect Output: http://www.robvanderwoude.com/battech_redirection.php

A: Maybe the answer you are looking for is here.
Here a copy of the answer I think may be interesting for you :
   // Wait for backup setting prompt
    Repeat Until %D1% = 1
      Activate Window: "DAYMISYS1.qdx.com - PuTTY"
      Mouse Move Window 12, 11                        <-------  Moves mouse to upper left corner to activate menu options
      Mouse Right Button Click
      Delay 0.1 Seconds
      Text Type: o                                    <-------  Activates Copy All to Clipboard command
      Delay 0.2 Seconds
      If Clipboard Contains "or select a number to change a setting:"      <-------  Look for text of prompt that I am waiting for
      Repeat Exit                                     <-------  If found, exit loop and continue macro
      End If
      Delay 1 Seconds                                 <-------  If prompt is not found, continue loop
    Repeat End

A: In the putty I have, I just paste into it and it works.
Open notepad
Type out your list of commands
Highlight notepad
ctr + c (or right click, copy)
click on your putty window
right-click once, into where you type your commands
You should see all of the commands inserted into your entry  box
hit enter
Note: I used this to enter multiple lines into cin prompts from C++ program compiled on linux. I don't know if it will work directly into the terminal.


text:
Q: Will a script added with insertBefore (async=false) loaded next? Let's asume I put this script directly after the starting head-tag:
(function () {
     var a = document.createElement('script');
     var m = document.getElementsByTagName('script')[0];
     a.async = !1;
     a.src = 'loader.js';
     m.parentNode.insertBefore(a, m);
 })();

Can I be sure, that the loader.js will be executed right after the above function block?
Although the loading of the loader.js is inserted before the current position the browser is executing.

A: According to MDN:

Script-inserted scripts execute asynchronously in IE and WebKit, but
  synchronously in Opera and pre-4.0 Firefox. In Firefox 4.0, the async
  DOM property defaults to true for script-created scripts, so the
  default behavior matches the behavior of IE and WebKit. To request
  script-inserted external scripts be executed in the insertion order in
  browsers where the document.createElement("script").async evaluates to
  true (such as Firefox 4.0), set .async=false on the scripts you want
  to maintain order.


text:
Q: Can the speed of light become complex inside a metamaterial? The speed of light in a material is defined as $c = \frac{1}{\sqrt{\epsilon \mu}}$. There are metamaterials with negative permittivity $\epsilon < 0$ and permeability $\mu < 0$ at the same time. This leads to a negative refractive index of these materials.
But do (meta-) materials exist with only negative $\epsilon < 0$ and positive $\mu > 0$ or vice versa? This would lead to a complex speed of light inside such materials.
What would be the consequences of a complex speed of light? Could particles reach unlimited speed inside these materials? Would there still be Cherenkov radiation?

A: Complex quantities always denote loss. So if the velocity is imaginary, it is impossible for a wave to travel from one point to another. If you look at the Drude model, for some certain frequency the signal will pass so it behaves like a dielectric at that time, but for frequencies lower than the Plasma frequency it will behave like a metal where no transmission is possible and at that time permittivity is less than zero, so at that time the velocity of the wave is imaginary.
So, in my opinion, imaginary velocity means no transmission.

A: Technically, all of these materials will have (effective) complex dielectric and/or magnetic properties.  Thus, you'll be dealing with complex wave speeds.
Complex speed means lossy transmission.
The amplitude of the wave will decay with a decay constant that is inversely proportional to the imaginary part of the square root of the speed.
Note that if this term is small, or the material is thin enough, then you can have transmission.

A: Since there's only one square root, one would end up with an imaginary velocity rather than the more general case of a complex velocity.
In physics, one occasionally deals with complex energies. I don't know what imaginary velocities will mean and there's not a lot of references in the literature. One paper is "Velocities" in Quantum Mechanics


text:
Q: Example of using Python wtform datetime with sqlalchemy and sqlite I am trying to create a form using wtform datetime that accepts a date with a date picker.
form.py
class RegistrationForm(FlaskForm):
    eventname = StringField('Event Name', validators=[DataRequired()])
    eventstart = DateField(
        'Enter start date and time', id='datepick', validators=[DataRequired()]
     )

This renders the date and time picker correctly.  However, I am not understanding how to get it into the correct format using sqlalchemy and sqlite.  It doesn't seem to be validating on submit.  When I add a print(events), the output is {}.
view.py
@events_blueprint.route('/add', methods=['GET', 'POST'])
def register():

    form = RegistrationForm()
    print(form.errors)

    if form.validate_on_submit():
        event = Events(
            eventname=form.eventname.data,
            eventstart=form.eventstart.data,
            # eventstop=form.eventstop.data,
        )

        db.session.add(event)
        db.session.commit()
        flash("Thank you for registering your event.")

    return render_template('add.html', form=form)

class Events(db.Model):

    __tablename__ = 'events'
    id = db.Column(db.Integer, primary_key=True)
    eventname = db.Column(db.Text(64), unique=True, index=True)
    eventstart = db.Column(db.Text, nullable=False)
    #  This is a one-to-many connection with Eventdetails database
    details = db.relationship('Eventdetails', backref='event', lazy='dynamic')

    def __init__(
        self, eventname, eventstart
    ):
        self.eventname = eventname
        self.eventstart = eventstart

    def __repr__(self):
        return f"{self.eventname}"

Any help pointing me in the right direction would be greatly appreciated.  Ultimately, I would like to factor in the timezone and event end time so I have a time range.


text:
Q: How do I create a button, that on press, triggers a refresh to the sheet? The title is basically it. I've seen it done before, all in google apps script and only on google sheets. I just can neither find the reference nor any other material matching what I'm trying to do. I know very little about google apps script, but I tried using this (I swear I tried.)
function myFunction() {
var sheet = SpreadsheetApp.getActiveSheet()
 if(sheet.getRange('H7') == true) {
   SpreadsheetApp.flush
 }
}


text:
Q: Network Monitoring and Filtering As the IT administrator for my company I have been tasked with deciding what traffic to filter, shape, and othewise monitor on our network.  What protocols, applications, and other network traffic do you commonly look for?  Top items on our list for throttling or blocking based on bandwidth consumption and legality are bit-torrent, p2p, iTunes, blatant porn browsing, etc.  From a technical standpoint this will be done using Cisco equipment such as a SCE or IPS.

A: Well, IMHO the best practice (for individual ports/protocols) is to filter EVERYTHING, and then selectively allow things. That will knock out a ton of stuff, and force your users to justify why they need X, Y, or Z.
Web filtering will have to be done via some sort of content filter (like Websence or similar), and those can be configured to death to block pretty much anything you want to block.
I personally hate content filters, but I can afford to be sanguine about them, since these days I'm always high enough on the tech totem pole to circumvent them. It's never a popular step, but it makes sense from both a security and a utilization standpoint.

A: Add in streaming media (YouTube/etc) although it may be more difficult to detect, depending on the solution you're using.  It's also possible that someone somewhere may be able to give you a legit business case for some of these things (I'm of the belief that one can construct a legit business case for almost anything if one is sufficiently determined) so being able to define exceptions should be a prereq.

A: I use only SNMP enabled switches/routers and do MRTG graphs for everything.  Then I use a Linux box as my gateway, and force all port 80 traffic to a Squid proxy via iptables, and use SARG reporting to see where people are surfing.  You can block bittorrent ports, that can be defeated by tech-savvy users.  I'd set up an iptables rule to look for "BitTorrent protocol" and force that through Squid.

A: DENY first, ALLOW second. only open the ports up that are critical to business (80/443, mail, etc). you can also run OpenDNS to do a lot of content blocking.

A: if you were tasked with deciding what traffic to filter, then you should look at your company's usage pattern instead, and make decisions based on that, and not on what others are doing and certainly not follow the "deny everything first" foolishness.
To help yourself with that you can start collecting network flows from your border router(s)  during normal (non-filtered) usage and use them to analyze your utilization.
So here are some links to get you started:

*

*http://code.google.com/p/flow-tools/

*http://www.qosient.com/argus/

*http://www.mindrot.org/projects/

*http://www.caida.org/tools/utilities/flowscan/flow.xml


text:
Q: my images are not showing when i upload them, they apear as placeholders the image has a the correct format.
the image url is correct
but some how the image is not showing
this error happened after website was migrated
Please help

A: I suggest the following things:

*

*Please install the Regenerate Thumbnails plugin and regenerate your thumbnails and check it again.

*Also check the WordPress Media files type for your WordPress and any other image related (Image Type) plugins installed.

*WordPress used GD image Library in your Server. Contact your hosting module and check that module is installed and enabled on your server.


text:
Q: adding a table attribute as an paramater in sql query? i want to calculate tax from already made table through stored procedure
 name,   ssn,      salary
'harsh', '49892', '40000'
'nitin', '48539', '55000'
'param', '48999', '75000'
'kd',    '84998', '120000'

i want to use parametrized way of doing it if not possible then tell some other way
/*CREATE DEFINER=`root`@`localhost` PROCEDURE `compute tax`(out tax varchar(10), in salary double)*/

something like this that can take value of salary into parameters and then can create a table using if else statements


text:
Q: Eclipse Milo 0.2.0: Support for writing custom datatypes I am evaluating Eclipse Milo 0.2.0 with the Unified Automation server and have successfully read&decoded my own custom structures (by registering appropriate codecs). However client.write keeps returning with status code Bad_WriteNotSupported. I could write the structure node with another client, though.
Does Milo not support writing custom structures yet? If not, when is this feature scheduled?
THX for your answers

A: The Milo Client SDK does support reading and writing custom structures. If they are registered correctly with the server you don't have to register them with Milo; it reads the datatype dictionaries from the server upon connecting.


text:
Q: Has Many Through in django? class Post(models.Model):
    ...

class Comment(models.Model):
    post = models.ForeignKey(Post,on_delete=models.CASCADE)

class Tag(models.Model):
    comment = models.ForeignKey(Comment,on_delete=models.CASCADE)

How to use post object to get all tags???
Like laravel framework hasManyThrough?

Except this way

for comment in post.comment_set.all():
    for tag in comment.tag_set.all():
        print(tag)

A: Since this is reverse lookup, you can use prefetch_related.
Post.objects.filter(your_condition)
.prefetch_related(Prefetch("comment_set"),
 queryset=Comment.objects.prefetch_related("tag_set"))

You can set the querysets based on your conditions.


text:
Q: conditional select stmnt in table query ssrs 2005 I am using SSRS 2005 using SQL Server.
I have 2 tables:
Order - contains open (unshipped) orders
Order_History - contains closed (shipped and invoiced) orders
I am using a UNION ALL to get data from both tables.  However, I would like to add 1 multivalue parameter OrderType with "open", "closed", "both" for the values so the user can say they ONLY want open, ONLY want closed, or BOTH.
Is there a way in the the dataset query (that the table uses) to put an IF or CASE so that the query runs only one select statement depending on what's chosen?
IN other words, something like:
"IF (@OrderType) = 'OPEN' select field a,b from Order;
 ELSEIF (@OrderType) = 'CLOSED' then select field a,b from Order_History;
 Else select field a,b from Order UNION ALL select field a,b from Order_History".

A: You could add a column to both selects in the UNION with 'open' and 'closed' respectively and then do an outer query around it to select only the values that you want with a case statement on the @orderType:
SELECT *
FROM (
  SELECT *, 'open' AS STATUS
  FROM order
  UNION ALL
  SELECT *, 'closed'
  FROM Order_History
  ) a
WHERE STATUS = CASE
    WHEN @OrderType = 'both' THEN STATUS
    ELSE @OrderType
    END;

sqlfiddle demo


text:
Q: Cloning and remounting sd card I have a micro sd card that contains these partitions:
Disk /dev/sdb: 29,7 GiB, 31914983424 bytes, 62333952 sectors
Units: sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disklabel type: dos
Disk identifier: 0xa6202af7

Device     Boot  Start      End  Sectors Size Id Type
/dev/sdb1         8192   122879   114688  56M  c W95 FAT32 (LBA)
/dev/sdb2       122880 10608639 10485760   5G 83 Linux

I would like to clone it but just cloning those two partitions, not the entire 29,7GB. So I used this command:
dd bs=1M count=$((5431623169 / (1024*1024) + 1)) if=/dev/sdb of=myimage.img
truncate -s 5431623169

This should create a image with the two partitions. Now I would like to mount the second partition of myimage.img to modify it. I'm therefore running the command:
sudo mount -t ext4 -o loop,offset=62914560 myimage.img mount/

however this produces the following output:
mount: wrong fs type, bad option, bad superblock on /dev/loop1,
       missing codepage or helper program, or other error

       In some cases useful info is found in syslog - try
       dmesg | tail or so.

sdb1 instead mounts just fine. I'm sure it is ext4 as blkid returns that.
This micro sd card is a comlpete firmware for a Raspberry Pi Linux system. If I flash myimage.img to a new sd card and run it, the system seems to work properly, which means it is able to mount it.
Any idea why I'm not able to mount it manually using the mount command as I shown above?

A: Problem was that I didn't copy the last 512 bytes of the last sector. This way the last partition was incomplete. By copying one more sector everything mounted properly.


text:
Q: Capturing Audio In Media Foundation - ReadSample Never Returns I am trying to capture audio from my microphone in Media Foundation. The issue I am having is that when I go to ReadSample, the function never returns. All my HRESULT checks pass. This happens for any device I try. I tried changing the MFT SUBTYPE to other formats as well. Without any actual errors, I'm not exactly sure what I should be looking for.
main.cpp
#include "../../lib/audio_utils.h"
#include "../CaptureAndDisplayVideoDevice/AudioDeviceCapturer.h"

static HRESULT stub_function()
{
    HRESULT hr = S_OK;

    std::vector<audio_device_info> audio_devices_information;
    if (FAILED(hr = get_audio_devices_info(audio_devices_information)))
        return hr;

    IMFMediaSource* media_source;
    if(FAILED(hr = get_device_source_from_audio_device_info(audio_devices_information[0], &media_source)))
        return hr;

    AudioDeviceCapturer* adc = new AudioDeviceCapturer(media_source);

    DWORD stream;
    DWORD flags;
    LONGLONG timestamp;

    while (true)
    {
        CComPtr<IMFSample> sample = nullptr;
        // this is reading in syncronous blocking mode, MF supports also async calls
        hr = adc->m_source_reader->ReadSample(MF_SOURCE_READER_FIRST_AUDIO_STREAM, 0, &stream, &flags, &timestamp, &sample);

        if (flags & MF_SOURCE_READERF_STREAMTICK)
            continue;

        CComPtr<IMFMediaBuffer> buffer;
    }
}

int main()
{
    stub_function();
}

AudioDeviceCapturer.h
#pragma once

#define COBJMACROS
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <mfapi.h>
#include <mfidl.h>
#include <mfreadwrite.h>

#include <stdio.h>
#include <intrin.h>

#include <atlbase.h>

// std
#include <iostream>
#include <string>

#pragma comment (lib, "ole32.lib")
#pragma comment (lib, "mf.lib")
#pragma comment (lib, "mfplat.lib")
#pragma comment (lib, "mfuuid.lib")
#pragma comment (lib, "mfreadwrite.lib")

class AudioDeviceCapturer
{
public:
    IMFMediaSource* m_device_source;
    IMFSourceReader* m_source_reader;

    AudioDeviceCapturer(IMFMediaSource* device_source) : m_device_source(device_source)
    {
        HRESULT hr = S_OK;

        ATLENSURE_SUCCEEDED(MFStartup(MF_VERSION, MFSTARTUP_NOSOCKET));

        //
        {
            CComPtr<IMFAttributes> encoder_attributes;

            MFCreateAttributes(&encoder_attributes, 2);

            hr = MFCreateSourceReaderFromMediaSource(m_device_source, encoder_attributes, &m_source_reader);
        }

        CComPtr<IMFMediaType> type;

        ATLENSURE_SUCCEEDED(MFCreateMediaType(&type));

        ATLENSURE_SUCCEEDED(type->SetGUID(MF_MT_MAJOR_TYPE, MFMediaType_Audio));

        ATLENSURE_SUCCEEDED(type->SetGUID(MF_MT_SUBTYPE, MFAudioFormat_PCM));
    }
private:
};

audio_utils.h
#pragma once

#include <Windows.h>
#include <cstdint>
#include <tuple>
#include <assert.h>
#include <mfapi.h>
#include <mfidl.h>
#include <atlbase.h>
#include <iostream>
#include <vector>

// libs
#pragma comment(lib, "mfplat.lib")
#pragma comment(lib, "mf.lib")
#pragma comment(lib, "evr.lib")
#pragma comment(lib, "mfuuid.lib")
#pragma comment(lib, "Winmm.lib")

struct audio_device_info
{
    wchar_t name[255];
    wchar_t endpoint_id[255];
};

HRESULT get_audio_devices_info(std::vector<audio_device_info>& audio_devices_information)
{
    HRESULT hr;

    hr = MFStartup(MF_VERSION, MFSTARTUP_NOSOCKET);

    uint32_t count;
    IMFActivate** devices;

    CComPtr<IMFAttributes> attr;

    hr = MFCreateAttributes(&attr, 1);

    hr = attr->SetGUID(MF_DEVSOURCE_ATTRIBUTE_SOURCE_TYPE, MF_DEVSOURCE_ATTRIBUTE_SOURCE_TYPE_AUDCAP_GUID);

    hr = MFEnumDeviceSources(attr, &devices, &count);

    printf("Detected %u devices:\n", count);

    for (uint32_t i = 0; i < count; i++)
    {
        audio_device_info audio_device {};

        uint32_t length;
        LPWSTR name;
        LPWSTR endpoint_id;

        hr = devices[i]->GetAllocatedString(MF_DEVSOURCE_ATTRIBUTE_FRIENDLY_NAME, &name, &length);

        hr = devices[i]->GetAllocatedString(MF_DEVSOURCE_ATTRIBUTE_SOURCE_TYPE_AUDCAP_ENDPOINT_ID, &endpoint_id, &length);

        wcscpy_s(audio_device.name, name);
        wcscpy_s(audio_device.endpoint_id, endpoint_id);

        {
            IMFMediaSource* video_device_source;
            CComPtr<IMFAttributes> attr;
            ATLENSURE_SUCCEEDED(MFCreateAttributes(&attr, 2));
            ATLENSURE_SUCCEEDED(attr->SetGUID(MF_DEVSOURCE_ATTRIBUTE_SOURCE_TYPE, MF_DEVSOURCE_ATTRIBUTE_SOURCE_TYPE_AUDCAP_GUID));
            ATLENSURE_SUCCEEDED(attr->SetString(MF_DEVSOURCE_ATTRIBUTE_SOURCE_TYPE_AUDCAP_ENDPOINT_ID, endpoint_id));
            ATLENSURE_SUCCEEDED(MFCreateDeviceSource(attr, &video_device_source));

            IMFPresentationDescriptor* pPD = nullptr;
            IMFStreamDescriptor* pSD = nullptr;
            IMFMediaTypeHandler* pHandler = nullptr;
            IMFMediaType* pType = nullptr;

            ATLENSURE_SUCCEEDED(video_device_source->CreatePresentationDescriptor(&pPD));

            BOOL fSelected;
            ATLENSURE_SUCCEEDED(pPD->GetStreamDescriptorByIndex(0, &fSelected, &pSD));

            ATLENSURE_SUCCEEDED(pSD->GetMediaTypeHandler(&pHandler));

            DWORD cTypes = 0;
            ATLENSURE_SUCCEEDED(pHandler->GetMediaTypeCount(&cTypes));

            for (DWORD i = 0; i < cTypes; i++)
            {
                ATLENSURE_SUCCEEDED(pHandler->GetMediaTypeByIndex(i, &pType));

                GUID Subtype;
                hr = pType->GetGUID(MF_MT_SUBTYPE, &Subtype);
                wchar_t SubtypeText[64];
                StringFromGUID2(Subtype, SubtypeText, static_cast<int>(std::size(SubtypeText)));
            }
        }

        audio_devices_information.push_back(audio_device);

        printf("%S = %S\n", name, endpoint_id);

        CoTaskMemFree(name);
        CoTaskMemFree(endpoint_id);

        devices[i]->Release();
    }

    CoTaskMemFree(devices);

    MFShutdown();

    return hr;
}

HRESULT get_device_source_from_audio_device_info(audio_device_info device_info, IMFMediaSource** video_device_source)
{
    HRESULT hr = S_OK;

    ATLENSURE_SUCCEEDED(MFStartup(MF_VERSION, MFSTARTUP_NOSOCKET));

    CComPtr<IMFAttributes> attr;
    ATLENSURE_SUCCEEDED(MFCreateAttributes(&attr, 2));

    ATLENSURE_SUCCEEDED(attr->SetGUID(MF_DEVSOURCE_ATTRIBUTE_SOURCE_TYPE, MF_DEVSOURCE_ATTRIBUTE_SOURCE_TYPE_AUDCAP_GUID));

    ATLENSURE_SUCCEEDED(attr->SetString(MF_DEVSOURCE_ATTRIBUTE_SOURCE_TYPE_AUDCAP_ENDPOINT_ID, device_info.endpoint_id));

    ATLENSURE_SUCCEEDED(MFCreateDeviceSource(attr, video_device_source));

    MFShutdown();

    return hr;
}

#ifndef DEBUG // works in VS
#define DebugPrint(x)
#else
#define DebugPrint(x) do { std::cout << x << std::endl; } while (0)
#endif

A: MFStartup and MFShutdown should only be called once for the duration of your presented code, for example, remove them everywhere and change main like this:
int main()
{
    MFStartup(MF_VERSION, MFSTARTUP_NOSOCKET);
    stub_function();
    MFShutdown();
}


text:
Q: Is the concept of a link inseparable from its html markup? I'm looking for a strategy for managing links within articles.  The body of the article is saved in a database and pulled during page assembly. What all should be saved in the database to easily define and manage links?
Some purists believe that markup should NEVER be stored in the database.  Some believe its ok in moderation.  But to me, the notion of a link is almost inseparable from its html markup.
Is there a better, more succinct way of representing a link in an article (in a database) than simply embedding "anchor text"?
One idea I've kicked around involves embedding just enough markup to semantically describe areas of interest, and in a different table, map those notions to actual URLs.  All encounters of a particular notion get wrapped with the link.

Here is an example of a
semantic
approach to link management.

A table then might associate the URL of the article and the key class of 'semantic-web' to a URL like http://en.wikipedia.org/wiki/Semantic_Web

Here is an example of a
semantic
approach to link management.

Things I like about this approach is that all my URLs are in one location in the database.  I could technically change or remove links without touching the body of the article. I have very good class names for CSS.
I don't like having another table to maintain, and another step/phase in render time.  It could slow down response time.
Are there any other strategies out there that provide superior link management?

A: There are a few attempts to do this that I have seen.
One way to do this is through URL redirects. You can implement a logic component on the server that will interpretate what the URL is requesting rather than a path to the content.
Another attempt is that the links orginally set to a reference value [which can be looked up in a database], and is requested at runtime/generation.
Regardless, you will have to reference the material that you wish to link to with some sort of identifier.

A: You  may want to look at templating (such as Smarty for PHP).
I agree that markup shouldn't normally be held in the database.
However, you might also consider implementing a "pointer" concept, where at each link, you break your storage of the page, add a pointer in the table to the link, then a pointer in the link table to the next segment of content for the page. (I have no idea how complicated that would be - just an idea.)
Or look at how various CMS tools handle the idea. Some just put everything in the database as one big block of text, while others rely on templating, and others may do something else entirely (like object-oriented environments such as Plone).


text:
Q: Trying to call API through Apex with custom security certificate but getting CalloutException I'm trying to use Apex to call some API endpoints to do some validation for my company. There are some specific properties of these APIs that make it a bit tricky:

*

*The APIs are hosted on self-deployed Kubernetes clusters, and have their own security certificates.

*These endpoints are not public right now and require a proxy to be running to hit them.

For other SDKs that we've validated, we've just had to specify the custom API endpoint and authenticate. Then, we could always do something like disabling SSL verification to get around the security issue.
Salesforce, as far as I can tell, does not allow you to do that. I've followed the instructions here to add the security certificate to my organization and the instructions here to set the certificate in my Apex code.
Beyond that, I've also made sure to add the API endpoint and proxy URL to the remote site settings.
With all that, I'm still getting the following error when trying to make an API call: System.CalloutException: Unable to tunnel through proxy. Proxy returns "HTTP/1.0 403 Forbidden"
Does anyone have any ideas what I might need to try next? I saw some things about whitelisting Salesforce IP addresses, so I'm asking around about that now. Other than that though, I'm at a loss on what to try next.


text:
Q: tkinter.filedialog calling twice cause crashing on macOS Here below is my code:
from tkinter import filedialog
path_1 = filedialog.askdirectory()
path_2 = filedialog.askdirectory()

I am trying to call filedialog.askdirectory() multiple times. I can run the above code in Windows without any problem. But when I do this in macOS, Python crashes once I call the function 2nd time (it is fine if just call once). The crash message is as follows:
Process finished with exit code 139 (interrupted by signal 11: SIGSEGV)

Actually, my original implementation is as below (since I found most people do like this):
import tkinter as tk
from tkinter import filedialog

root = tk.Tk()
root.withdraw()
path_1 = filedialog.askdirectory(parent=root)
path_2 = filedialog.askdirectory(parent=root)
root.destroy()

This implementation way does not cause any crashes in macOS. But there is a bug that, the root cannot be destroyed properly. The problem is as described in this question: tkinter gui hangups/freezes after destroy() on macOS. There will be an unresponsive window named 'Tk' left after root.destroy(). Therefore, I try to use filedialog.askdirectory() directly without root. Both the 2 ways above work fine in Windows, but not in macOS.
Here is some detail of my macOS env:

*

*Python 3.10.4

*tkinter 8.6

*macOS 12.3.1

*arm64 M1

How should I code to call filedialog.askdirectory() multi times on macOS, without trigger the above errors?

A: I have kind of solved the problem after many tries. Here is my code:
import tkinter as tk
from tkinter import filedialog

root = tk.Tk()
root.withdraw()
path_1 = filedialog.askdirectory()
path_2 = filedialog.askdirectory()

The above code does not generate any crashes or unresponsive windows on macOS. I found that there is no need to do root.destroy(). And, not passing root to filedialog.askdirectory() as parent argument, can prevent Tk window from showing behind the file dialog window. Hope this solution can help those who are dealing with the same problem as mine.
But still, I do not quite understand why I can call filedialog.askdirectory() directly on Windows, for multi times without any problem; but on macOS, I must first call tk.Tk() and withdraw() to prevent crashes. Please let me know if anyone knows the answer.


text:
Q: Is it possible for my GPS application to continue running in the background while the tablet is on standby? I have created an application that generates a tracklog of the Android devices location. A GPS coordinate is recorded at regular intervals and stored on the device for later download. Currently, when the phone goes on standby, the program stops recording points. Is there a method that would allow the application to continue documenting location while the unit is on standby? Thanks in advance.

A: According to android documentation, if your app targets API level 26 or higher, the system imposes restrictions on running background services when the app itself isn't in the foreground. Also for accessing location in the background you may need additional permissions
You can run a foreground service with showing an ongoing notification if you want to run a service which is always alive in the background. Or you can schedule tasks using WorkManager.

A: I found two solutions.
1.) Use Wakelock
public void wakeLock() {
         PowerManager powerManager = (PowerManager) getSystemService(POWER_SERVICE);
         PowerManager.WakeLock wakeLock = powerManager.newWakeLock(PowerManager.FULL_WAKE_LOCK, "MyApp::MyWakelockTag");
        wakeLock.acquire();
    }

with the following added to the manifest XML file,
<uses-permission android:name="android.permission.WAKE_LOCK"/>

or, 2.) use WindowManager to keep the device awake,
 public void noSleep() {
        if (bNoSleep == true){
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        } else if (bNoSleep != true){
            getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        }
}

I've chosen the latter as a user selectable feature accessible via checkbox in the main workspace. I've also set this to engage automatically when a tracklog is initiated with the user having the option to disable this and allow standby/sleep to occur. I did implement a wakelock, but had some issues with it that may be related to a custom ROM on some of my Android devices. This is why I went ultimately went w/the windowmanager solution.


text:
Q: Valid8 jquery plugin: dependent field validation? My client has required that I use a specific validation plugin (valid8), which seems to only do inline validation on focus. The documentation on the plugin is pretty weak, so I'm hoping someone else has experience with this particular plugin and they can help me out.
It's a contact form, where users must specify their preferred method of contact. If they specify email, then the email input field must be validated; if they specify phone, then the phone input field must be validated. I can selectively ADD the validation based on the radio selected, but I can't REMOVE validation if the user changes their contact preference before submitting the form.
Is there a way to remove valid8 validation from a field after it has been added using this plugin? I tried .unbind(valid8), but that doesn't work because unbind is for events, and valid8 is not an event. Do I have to manually unbind all events and remove the extra markup from the field?
Edit: http://jsfiddle.net/sjc8611/5d3CT/

A: I have not used this plugin but looking at the source it seems that information about validation for #element is stored in the arbitrary data settings, so you can try:
$('#element').data('settings', null);

And see what it does. It may generate errors though and if it does you can also remove the events associated it with, which are:
keyup
blur
click (for checkbox)

You can do it with just one command like this:
$('#element').unbind();

But this will remove ALL events for that element and again may cause problems, which is why I supplied the list above so you can remove them one by one if you need.
This is as much as I can say without ever using this, if it doesn't work you should post an example online (prefferably on jsFiddle) so we can have a look at it. If all else fails you can email the plugin author.

A: You could set the validation to a function that always returns true:
$("#element").valid8({
    jsFunctions: [{
        function: alwaysTrue, values: function() { return true; }
    }]
});


text:
Q: Problema en controlador laravel 5.8 Invalid argument supplied for foreach() Controlador
public function index()
    {
        $serie_eventos=Serie_eventos::all();
        $comisariosporE = array();
        foreach ($serie_eventos as $key => $value) {
            $ids = unserialize($value->comisarios);
            $temporal = [];
            foreach ($ids as $key2 => $value2) {
                $com = Comisarios::find($value2);
                $temporal[]= $com;
            }
            $comisariosporE[$value->id] = $temporal;
        }

        $equipamientoPorEvento = array();
        foreach ($serie_eventos as $key => $value) {
            $ids = unserialize($value->materiales);

            $temporal = [];
            foreach ($ids as $key2 => $value2) {
                $com = Equipamiento::find($value2);
                $temporal[]= $com;
            }
            $equipamientoPorEvento[$value->id] = $temporal;
        }
        return view('serie_eventos.index',compact('serie_eventos','comisariosporE','equipamientoPorEvento'));
    }

index view

                  Evento
                  Fecha
                  Duracion
                  Numero de participantes
                  Comisarios
                  Equipamiento
                  Opciones

                @foreach($serie_eventos as $key)

                  {{ $key->tipo }}
                  {{$key->fecha}}
                  {{ $key->horainicio }} - {{ $key->horafin }}
                  {{ $key->participantes }}

                  @foreach($comisariosporE[$key->id] as $comisario)
  {{ $comisario['nombre'] }}

@endforeach

                  @foreach($equipamientoPorEvento[$key->id] as $eq)
  {{ $eq->nombre }}

@endforeach

Y el error que me arroja es Invalid argument supplied for foreach()
El error esta en el foreach del controlador, precisamente arriba de las lineas que dicen foreach ($ids as $key2 => $value2){
Al parecer hay que crear una condición arriba de esta linea de codigo, un if con un is_array, pero probe y no funciono.
No encuentro el error todavia, no se que mas puede ser.
PD: Adjunte las partes mas importantes del codigo porque introducirlo todo es demasiado extenso.


text:
Q: Selecting columns & counting in a SQL query For each customer I need to list the CUS_CODE, the number of customers in each area (CUS_AREACODE) and the total balance (CUS_BALANCE) and group those records by the CUS_BALANCE.
This is what I have so far:
SELECT
    COUNT (CUS_AREACODE) AS CUSTOMERS_IN_AREA,
    CUS_CODE, CUS_BALANCE
FROM
    CUSTOMER
GROUP BY
    CUS_BALANCE;

I'm pretty new to SQL and i receive an error saying that

CUS_CODE isn't an aggregate function

and I'm not entirely sure what that means and why.

A: The rule of GROUP BY, same column list MUST be present in SELECT and GROUP BY clause. You are missing CUS_CODE in GROUP BY.
GROUP BY CUS_BALANCE, CUS_CODE;

instead of
GROUP BY CUS_BALANCE;


text:
Q: Does the constructor call have to be the first statement in the constructor? I have a class cShape to handle graphic images.  It takes the starting position in its constructor.  I would like the starting position to be random, so I have the following code
cBalloon(Context InContext, int w, int h) {
    // set up random postion
    Random randomGenerator = new Random();

    int sx=randomGenerator.nextInt(w);
    int sy=randomGenerator.nextInt(h);

    super( InContext,  sx,  sy,  0,0,  50,50,  "balloon", 50,50,0);
}

I get a error saying "Constructor class must be first in a constructor"
Is there a way to do this?

A: The super(...) must be a first statement in the constructor.
But, there is a workaround: create a static method
private static int getRandomtInt(int x) {
    Random randomGenerator = new Random();
    return randomGenerator.nextInt(x);
}

and call it in a super constructor:
cBalloon(Context InContext, int w, int h) {
    super( InContext,  getRandomInt(w),  getRandomInt(h),  0,0,  50,50,  "balloon", 50,50,0);
}

A: Yes, the super(..) should be the first statement in the constructor.
You basically have four options:
1) You can call directly to the constructor like this
cBalloon(Context InContext, int randx, int randY int w, int h, Random randomGenerator) {
         super(InContext, randomGenerator.nextInt(w), randomGenerator.nextInt(h), ...)
}

2) Or you can get the random variables BEFORE calling the constructor
cBalloon(Context InContext, int randx, int randY int w, int h){
      super(InContext, randx, randY, 0, 0, ...);
}

3) Create a static method that will generate the random number every time you call it. This will keep you constructor method very clean, which is good.
private static int getRandomInteger(final int x) {
    Random randomGenerator = new Random();
    return randomGenerator.nextInt(x);
}

cBalloon(Context InContext, int w, int h){
      super(InContext, getRandomInteger(w), getRandomInteger(h), 0, 0, ...);
}

4) Just generate the random numbers in the super class.
There is no need to declare those integer variables sx and sy like that.
Hope it helps.

A: You cannot call the super like that. The super function must be called first in the cBalloon constructor. So you would need to pass the random numbers directly to it.
Like so:
cBalloon(Context InContext, int randx, int randY int w, int h)
{
    super( InContext,  randX,  randY,  0,0,  50,50,  "balloon", 50,50,0);
}

A: super or this should be the first statement in the constructor. You can do it like this
super(InContext, new Random().nextInt(w), new Random().nextInt(h),
      0, 0, 50, 50, "balloon", 50, 50, 0)

OR Even this
class cBalloon{
Random randomGenerator=new Random();
cBalloon(Context InContext, int w, int h) {
    // set up random postion

    super( InContext,  randomGenerator.nextInt(w),  randomGenerator.nextInt(h),  0,0,  50,50,  "balloon", 50,50,0);
}

Hope this helps.

A: There are a number of workable pragmatic solutions here, but it bothered me that none are truly general for this class of task.  A general solution would work for some data source which was not truly random, ie, where it matters that you get both values from the same instance.  And it would be nice to avoid static variables, even temporary ones, for cleanliness and easy thread safety.
So here's my idea: have one constructor which invokes another, passing it a temporary instance of the data source Random(), which it will use to get both values.
public class cBalloon {

    public cBalloon(Context inContext, int w, int h) {
        this( inContext,  new Random(), w, h);
    }

    public cBalloon(Context inContext, Random randomGenerator, int w, int h) {
        super(inContext,
              randomGenerator.nextInt(w),
              randomGenerator.nextInt(h),
              0,0,  50,50,  "balloon", 50,50,0);
    }
}


text:
Q: Wifi very slow - ubuntu 16.04 - Centrino Advanced-N 6230 I have an HP ProBook 4431s.
After installing ubuntu 16.04 LTS, my WiFi is really slow so I have to use the LAN for now.
I tried the all the thread on Ubuntu where you select the realtek antenna after downloading Larry Finger's github repo.
My WiFi is still slow. I didn't see any improvements.
The output of ubuntu's wireless info is here:
https://paste.ubuntu.com/25350005/
I realized that my adapter was intel. After re-installing Ubuntu, the output is as follows:
https://paste.ubuntu.com/25353321/
FYI, I used to do dual boot between Windows 7 and ubuntu 12.04 LTS and everything was fine. This is due to the upgrade to 16.04 LTS.

A: Run in a terminal
sudo tee /etc/modprobe.d/iwlwifi-opt.conf <<< "options iwlwifi 11n_disable=8"

and reboot.

A: In your paste, we see several SSIDs named BELL101, including the one to which you are connected. I suspect that your wireless drops because it is attempting to roam to another instance of BELL101. If this is a router for which you have administrative access, I suggest that you rename it to, for example, BELL105 as it is a 5 gHz access point.
If you are unable to rename it, I suggest that you bind to the specific instance of BELL101 by MAC address, like this: Ubuntu connect drops. Worked for a while then started dropping again

A: I tried a combination of the above two solutions:
1) Changed the name of the wifi from something generic like BELL101 to VINEET101
2)

sudo tee /etc/modprobe.d/iwlwifi-opt.conf <<< "options iwlwifi 11n_disable=1"

it got my internet speed from 0.3 Mbps tp 21 Mbps. It still doesn't go to 80-90 Mbps like it usually does but it is at least something I can work with. If you have any further ideas about how to increase this value, please let me know.


text:
Q: Синтаксис REST API Каков синтаксис REST API? И с каким языком связано REST?

A: REST - это Representational State Transfer — "передача состояния представления". REST API не связан с конкретным языком.
Вообще, пуристы считают, что правильно говорить RESTful API и RESTful протокол.
А простыми словами говоря, REST - это способ приделать к программе, котрая что то делает, "ручки" (или рычаги, или кнопки - в общем, органы управления), "подёргать" за котрые можно при помощт HTTP - протокола.
При этом кроме методов GET и POST используется еще ряд методов, таких, напрмер, как DELETE. Имя HTTP-метода связано с выполняемой операцией.
Опять таки, REST - это не отдельный протокол, это расширение протокола HTTP. A REST API - это API, определенный припомощи протокола REST.
Посмотриет пример какого нибудь todo list REST API - по моему, станет понятнее.


text:
Q: Batch script that get hostname from list then pings hostname, if result then do stuff From: Batch ERRORLEVEL ping response
I found this pice  of  code
for /f %%i in ('ping racer ^| find /c "(0%% loss)"') do SET MATCHES=%%i
echo %MATCHES%

I am trying to replace "racer" with an variable I get from a textfile:
for /f %%x in (computers.txt)

trying to nest 2 for loops gives me erros
After this I want to do something like this (not tried this code yet):
    IF "%MATCHES%"=="0" (

shutdown /h /m \\%%x

) ELSE (

IF (

"%MATCHES%"!=="0"

)

echo "ping failed to %%x" >> failed01.txt

)

A: Try this:
@echo off
setlocal

for /f %%a in (computers.txt) do (
  Call :IsPingable %%a && shutdown /h /m \\%%a || echo Ping failed to %%a >> failed01.txt
)
exit /b

:IsPingable comp
ping -n 1 -w 3000 -4 -l 8 "%~1" | Find "TTL=">nul
exit /b


text:
Q: Removed remote. But remote branch still shows I've added a remote, so I could checkout a coworker's code.
$ git remote add coworker git@ourgitserver.local:...
$ git fetch coworker
$ git checkout coworker/theirbranch
$ git checkout -b mycopy

The code looked good. So I do some cleanup:
$ git checkout master
$ git remote remove coworker
$ git branch -D mycopy

But their remote branch still shows up:
$ git branch -a
remotes/coworker/theirbranch

I've done git fetch -p --all, git gc --prune=now and those did nothing.
I can't do git branch -D coworker/theirbranch because the remote doesn't exist. Neither can I git fetch -p coworker because that remote does not exist.
Any ideas?

A: The git remote remove coworker should have deleted the corresponding remote-tracking branches, and does in the quick tests I ran, so I am not sure what went wrong here.
To manually clean up, though, you may run git branch -d -r (note both flags) on each remaining remote-tracking branch:
git branch -d -r coworker/theirbranch


text:
Q: How to manually expire rails low cache by namespace We have:
Rails.cache.fetch("google.com/videos", expires_in: 12.hours) { # some request }
Rails.cache.fetch("google.com/images", expires_in: 12.hours) { # some request }
Rails.cache.fetch("stackoverflow.com/questions", expires_in: 12.hours) { # some request }

How can I get rails cache be expired by "google.com" key or "stackoverflow.com"?

A: If you are using the default cache store, i.e. the FileStore or the MemoryStore, deleting only a subset of keys should be possible with the delete_matched method, e.g.:
Rails.cache.delete_matched(/^google\.com/)

If you are using memcached, it is not possible and you would have to manually delete all keys exactly as used in the fetch calls. Or, simply not bother with expiration at all and use keys that change on every relevant change with the data they contain, see e.g. this blog post.


text:
Q: alter specific characters in pandas Background
I have the following df which contains tokenized Text and P_Name columns and is a modification of including word boundary in string modification to be more specific
P_Name = [list(['Steven', 'I','Jobs']),
          list(['A', 'Ma', 'Mary']),
          list(['U','Kar', 'Jacob'])]

Text =  [list(['Steven', 'I','Jobs', 'likes', 'apples','I', 'too']),
        list(['A','i', 'like', 'A', 'lot', 'of','sports','cares', 'A', 'Ma', 'Mary']),
        list(['the','U', 'Kar', 'Jacob', 'what', 'about', 'U', 'huh','?'])]

import pandas as pd
df = pd.DataFrame({'Text' : Text,
                  'P_ID': [1,2,3],
                  'P_Name' : P_Name,

                 })
df
   P_ID    P_Name            Text
0   1   [Steven, I, Jobs]   [Steven, I, Jobs, likes, apples, I, too]
1   2   [A, Ma, Mary]       [A, i, like, A, lot, of, sports, cares, A, Ma, Mary]
2   3   [U, Kar, Jacob]     [the, U, Kar, Jacob, what, about, U, huh, ?]

Goal
1) use the name in P_Name to block the corresponding text in the Text column by placing **block**
2) produce a new column New_Text
Tried
From including word boundary in string modification to be more specific
I have modified the code and tried the following
df['New_Text']=[pd.Series(x).replace(dict.fromkeys(y,'**block**') ).str.cat(sep=' ')for x , y in zip(df['Text'],df['P_Name'])]

Which gives close to what I want but not quite since some letters are being inappropriately labeled **block**  e.g I in row 0
 P_ID P_Name Text New_Text
    0             [**block**, **block**, **block**, likes, apples, **block**, too]
    1             [**block**, i, like, **block**, lot, of, sports, cares, **block**, **block**, **block**]
    2             [the, **block**, **block**, **block**, what, about, **block**, huh, ?]

Desired Output
P_ID P_Name Text New_Text
    0              [**block**, **block**, **block**, likes, apples, I, too]
    1              [A, i, like, A, lot, of, sports, cares, **block**, **block**, **block**]
    2              [the, **block**, **block**, **block**, what, about, U, huh, ?]

Question
How do I further modify
df['New_Text']=[pd.Series(x).replace(dict.fromkeys(y,'**block**') ).str.cat(sep=' ')for x , y in zip(df['Text'],df['P_Name'])]

or use new code to achieve my desired output?

A: You want each ordered occurrence of the P_Name sequence in the Text tokens. This can be achieved by iterating over the Text tokens & checking for equality on the entire P_Name tokens:
df["New_Text"] = df["Text"].apply(lambda tokens: tokens.copy())  # copy original tokens
for tokens, name in zip(df["New_Text"], df["P_Name"]):
    for i, token in enumerate(tokens):
        if tokens[i:i + len(name)] == name:
            tokens[i:i + len(name)] = ["**block**"] * len(tokens[i:i + len(name)])

Depending on your use case you might have the untokenised Text (& P_name) available. If so, then substring matching can be done instead, & then perform tokenisation after.


text:
Q: vscode move cursor to next highlighted word using an extension like es6 snippets, we get a block of code when we need to replace the highlighted words :
Example of block of code with highlighted words
My question is what is the shortcut to move to the next highlighted word ( item in the picture).
Thx in advance.

A: You can move the cursor to the next tabstop location of the code snippet with the Tab key.


text:
Q: The folders I deleted in android studio come back I don't know what file they are but i think they are related to android studio they come back when i delete accidentally i installed the .android folder directly in the directory i gave it another way from sdk manager but how do i solve this problem? I try to what ı know but i cant

*

*I try to change system environments path

*Restart my pc

UPDATE
The problem wasn't caused by android studio
UPDATE
Folder Content . All folders like that

A: It possible looks like the .git folder of a git repository or some kind other cache / object storage.
The easiest attempt to resolve this and to check if it's android studio causing this is to uninstall Android Studio. Remove all files. Remove the .android folder in your home directory. Remove (if present) the android sdk from %localappdata%\Android and the .AndroidStudio* folder from your user directory.
Then reinstall Android Studio
You can and should of course take backups from the settings if you want to.


text:
Q: SQL ROW_NUMBER gives error I need to order rows in MySQL and assign a number to each row according to that order. ORDER BY is working as intended but not ROW_NUMBER().
This works:
USE my_database;
SELECT
    id
    ,volume
    FROM my_table
    ORDER BY volume;

This does not work:
USE my_database;
SELECT
    id
    ,volume
    ,ROW_NUMBER() over(ORDER BY volume)
    FROM my_table
    ORDER BY volume;

I get this error message:

SELECT  id  ,volume  ,ROW_NUMBER() over(ORDER BY volume)  FROM my_table  ORDER BY volume    Error Code: 1064. You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '(ORDER BY volume)  FROM my_table  ORDER BY vol' at line 4  0.000 sec

What am I doing wrong and how do I make it work?
I also tried RANK() and DENSE_RANK() which gives the same problem.

A: There are no such things as ROW_NUMBER() or RANK() in MySQL. Try the following :
USE my_database;
SET @row_number = 0;
SELECT id
     , volume
     , @row_number := @row_number + 1 AS rank
FROM my_table
ORDER BY volume;

A: The function ROW_NUMBER() does not exist in MySQL.
However, you can replicate it, possibly: http://www.mysqltutorial.org/mysql-row_number/

The  row_number is a ranking function that returns a sequential number
  of a row, starting from 1 for the first row. We often want to use the
  row_number function to produce the specific reports we need.
  Unfortunately, MySQL does not provide  row_number like Microsoft SQL
  Server and Oracle. However, in MySQL, you can use session variables to
  emulate the  row_number function.

example:
SET @row_number = 0;

SELECT
    (@row_number:=@row_number + 1) AS num, firstName, lastName
FROM
    employees
LIMIT 5;

A: MySQL introduced the ROW_NUMBER() function since version 8.0.


text:
Q: FBReader on android 5.0 cannot read epub I am a  student,
This is my eclipse Project,on android 4.0 can use,but on android 5.0 have problem.
Epub cannot Import,I don't know what happened.
enter image description here

A: Follow below link  tutorial it contains good explanation
https://www.epubor.com/how-to-read-drm-epub-on-android-tablet.html


text:
Q: Compute some expectations involving beta and gamma distributions a) Let $X \sim {\text {Beta}}(a,b)$, with density $f(x) = \frac{x^{a-1}(1-x)^{b-1}} {B (a,b)}$. Find the expectation of $X \ln X$ and $\frac{1}{X+1}.$
b) Let $Y \sim {\text {Gamma}}(\alpha,\beta)$, with density $g(y) = {\frac {\beta ^{\alpha }}{\Gamma (\alpha )}}y^{\alpha \,-\,1}e^{-\beta y}$. Find the expectation of $Y \ln Y$ and $\frac{1}{Y+1}.$
c) Assume $X,Y$ are independent. Find $\Bbb E [\frac{1}{XY+1}]$ and $\Bbb E [\frac{1}{Y-XY+1}]$.
I reduced my previous question to the above much simpler questions. Any help with this question will help the previous question as well. Any help with any of above expectation calculations will be very much appreciated.

A: $\newcommand{\bbx}[1]{\,\bbox[15px,border:1px groove navy]{\displaystyle{#1}}\,}
 \newcommand{\braces}[1]{\left\lbrace\,{#1}\,\right\rbrace}
 \newcommand{\bracks}[1]{\left\lbrack\,{#1}\,\right\rbrack}
 \newcommand{\dd}{\mathrm{d}}
 \newcommand{\ds}[1]{\displaystyle{#1}}
 \newcommand{\expo}[1]{\,\mathrm{e}^{#1}\,}
 \newcommand{\ic}{\mathrm{i}}
 \newcommand{\mc}[1]{\mathcal{#1}}
 \newcommand{\mrm}[1]{\mathrm{#1}}
 \newcommand{\pars}[1]{\left(\,{#1}\,\right)}
 \newcommand{\partiald}[3][]{\frac{\partial^{#1} #2}{\partial #3^{#1}}}
 \newcommand{\root}[2][]{\,\sqrt[#1]{\,{#2}\,}\,}
 \newcommand{\totald}[3][]{\frac{\mathrm{d}^{#1} #2}{\mathrm{d} #3^{#1}}}
 \newcommand{\verts}[1]{\left\vert\,{#1}\,\right\vert}$
$\ds{\Large\left.a\right)}$
\begin{align}
&\bbox[13px,#ffd]{\int_{0}^{1}{x^{a - 1}\pars{1 - x}^{b - 1} \over \mrm{B}\pars{a,b}}\,x\ln\pars{x}\,\dd x} =
\left.{1 \over \mrm{B}\pars{a,b}}\,\partiald{}{\nu}
\int_{0}^{1}x^{a + \nu}\pars{1 - x}^{b - 1}\,\dd x\,\right\vert_{\ \nu\ =\ 0}
\\[5mm] = &\
\left.{1 \over \mrm{B}\pars{a,b}}\,\partiald{\mrm{B}\pars{a + \nu + 1,b}}{\nu}
\,\right\vert_{\ \nu\ =\ 0} =
\left.{1 \over \mrm{B}\pars{a,b}}\,\partiald{}{\nu}
{\Gamma\pars{a + \nu + 1}\Gamma\pars{b} \over \Gamma\pars{a + \nu + 1 + b}}
\,\right\vert_{\ \nu\ =\ 0}
\\[5mm] = &\
{\Gamma\pars{b} \over
\Gamma\pars{a}\Gamma\pars{b}/\Gamma\pars{a + b}}
\bracks{\Gamma\pars{1 + a}\,{H_{a} - H_{a + b} \over \Gamma\pars{1 + a + b}}}
\\[5mm] = &\
{\Gamma\pars{a + b} \over
\Gamma\pars{a}}\bracks{%
a\,\Gamma\pars{a}\,{H_{a} - H_{a + b} \over \pars{a + b}\Gamma\pars{a + b}}} =
\bbx{{a \over a + b}\pars{H_{a} - H_{a + b}}}
\end{align}

\begin{align}
&\bbox[13px,#ffd]{\int_{0}^{1}{x^{a - 1}\pars{1 - x}^{b - 1} \over \mrm{B}\pars{a,b}}
\,{1 \over x + 1}\,\dd x} =
{1 \over \mrm{B}\pars{a,b}}\int_{0}^{1}x^{a - 1}\pars{1 - x}^{b - 1}
\bracks{1 - \pars{-1}x}^{\,-1}\,\dd x
\\[5mm] = &\
{1 \over \mrm{B}\pars{a,b}}\bracks{%
\mrm{B}\pars{a,b}\,\mbox{}_{2}\mrm{F}_{1}\pars{1,a;a + b;-1}} =
\bbx{\mbox{}_{2}\mrm{F}_{1}\pars{1,a;a + b;-1}}\label{1}\tag{1}
\end{align}

\eqref{1} is evaluated as an 'Euler Type' expression for the Hypergeometric Function: It's given in
  this link.

$\ds{\Large\left.b\right)}$
\begin{align}
&\bbox[13px,#ffd]{\int_{0}^{\infty}{\beta^{\alpha} \over \Gamma\pars{\alpha}}
\,y^{\alpha - 1}\expo{-\beta y}y\ln\pars{y}\,\dd y} =
{\beta^{\alpha} \over \Gamma\pars{\alpha}}
\left.\partiald{}{\nu}\int_{0}^{\infty}y^{\alpha + \nu}\expo{-\beta y}\,\dd y
\,\right\vert_{\ \nu\ =\ 0}
\\[5mm] = &\
{\beta^{\alpha} \over \Gamma\pars{\alpha}}
\partiald{}{\nu}\bracks{{1 \over \beta^{\alpha + \nu + 1}}
\int_{0}^{\infty}y^{\alpha + \nu}\expo{-y}\,\dd y}_{\ \nu\ =\ 0} =
{\beta^{\alpha} \over \Gamma\pars{\alpha}}
\partiald{}{\nu}\bracks{{\Gamma\pars{\alpha + \nu + 1} \over
\beta^{\alpha + \nu + 1}}}_{\ \nu\ =\ 0}
\\[5mm] = &\
{\beta^{\alpha} \over \Gamma\pars{\alpha}}\braces{%
-\beta^\pars{-1 - \alpha}\,\Gamma\pars{1 + \alpha}\bracks{\ln\pars{\beta} - H_{\alpha} + \gamma}} =
\bbx{{\alpha \over \beta}\bracks{H_{\alpha} - \gamma - \ln\pars{\beta}}}
\end{align}

A: Have you tried a computer algebra system?
Part (a): For $X \sim \text{Beta}(a,b)$ with pdf $f(x)$:

Then here is the output generated by mathStatica / Mathematica to the first problem:

... where HarmonicNumber[n] denotes the $n^\text{th}$ harmonic number $H_n=\sum _{i=1}^n \frac{1}{i}$, and

where Hypergeometric2F1Regularized[a,b,c,z] denotes ${_2}F{_1}(a,b;c;z) / \Gamma(c)$, and Expect is a mathStatica function (of which I am one of the authors).

Part (b): For $Y \sim \text{Gamma}(\alpha,\beta)$ with pdf $g(y)$:

... you seek:

... where EulerGamma is Euler's constant (approx 0.577), and:

where ExpInteralE[$\alpha$, $\beta$ ] is the exponential integral function $\int _1^{\infty} \frac{1}{t^\alpha} e^{-\beta t} dt$

Part (c): Find $\Bbb E [\frac{1}{XY+1}]$ and $\Bbb E [\frac{1}{Y-XY+1}]$.
These two questions are essentially the same. To see this, note that if $X \sim \text{Beta}(a,b)$, then $(1-X) \sim \text{Beta}(b,a)$, and that $\Bbb E [\frac{1}{Y-XY+1}] = \Bbb E [\frac{1}{(1-X)Y+1}]$ which is thus also of form  $\Bbb E [\frac{1}{XY+1}]$ (just with the $X$ parameters swapped). So we only need to solve the first part.
Given independence, the joint pdf of $(X,Y)$, say $h(x,y) = f(x) g(y)$:

Then $\Bbb E [\frac{1}{XY+1}]$ is:

While this expression looks rather cumbersome, it appears to be correct, and works fine for non-integer parameter values. For instance, when ${a = 2.2, b = 3.3, \alpha = 4.1, \beta = 5.2}$, the above expression returns a value of 0.780101 for the expectation (which is consistent with Monte Carlo simulation).


text:
Q: Java one-time use wrapping class I'm using Data Access Layer/Object (DAL/DAO) pattern, and I am constructing a Request object to be sent to the back-end (note: I have no control over the back-end's design). The Request object looks something like this:
class DAORequest {

    private Integer field1;
    private String field2;
    private AttrList field3;
    ...
    private Long fieldn;

}

where AttrList class is:
class AttrList {

    private List<Attr> attributes; // this is the only field of AttrList class

}

(On the side note: I'm conforming to a JSON-format request that looks like this:
request {

    field1: value1,
    field2: value2,
    attrList: {
        attributes: [{}, {}, ..., {}]
    },
    ...
}

the Java object will be converted to GSON/JSON request)
I'm quite loathe to write another class (AttrList in my case) whose sole purpose is to wrap the actual content (and by consequence, would clutter my project space with un-reusable java files). Actually, there are many more RESTful endpoints in the back-end whose Requests are to be built this way. Is there anyway I can avoid writing AttrList and the like?


text:
Q: How to suppress the initial of citations? I am writing my dissertation and some citations are really wired. For example, some paper citations are shown as
T.Yang & Pan (2013) and T.Yang & Pan (2011) (those are two different papers by the same authors); Also most of the citations with more than two authors are shown as Tang et al. (1999) (this paper has four authors) but some of them show the first two authors' name as Goldfarb, Borror, et al. (2004) (This paper has four authors).
So I need to just show the last name of the authors as Yang & Pan (2013) even they might be different papers(required by school format) and only the first author's last name as Goldfarb et al. (2004) if there are more than two authors.
I have checked some questions here and seems like this one similar question. However, I have download the .bst file from APA website but didn't find the function mentioned in the solution and also not sure how to replace the .bst file. (I use WinEdit)/
Hope someone can give me some help on my question! Thanks!
My bibtex file as
@article{GBMA2004,
  title={Three-dimensional variance dispersion graphs for mixture-process experiments},
  author={Heidi B. Goldfarb and Connie M. Borror and Douglas C. Montgomery and Christine M. Anderson-Cook},
  journal={Journal of Quality Technology},
  volume={36},
  number={1},
  pages={109--124},
  year={2004},
  publisher={American Society for Quality}
}

@ARTICLE{YP2013,
AUTHOR={Tao Yang and Rong Pan},
year={2013},
title={A Novel Approach to Optimal {ALT} Planning with Interval Censoring},
journal={Reliability, IEEE Transaction on,},
volume={to appear on June Issue},
  number =       {},
  pages =        {},
  month =        {},
  note =         {},
  abstract =     {},
  keywords =     {},
  source =       {},
}

And my tex file as
\documentclass[oneside,12pt]{memoir}
\usepackage[framed,numbered,autolinebreaks,useliterate]{mcode}
\usepackage{apacite}
\usepackage{amssymb}
\usepackage{indentfirst}
\usepackage{algorithm2e}
\usepackage{natbib}
%\usepackage[cmex10]{amsmath}
\usepackage{amsmath}
\usepackage{amsfonts}
\usepackage{multirow}
\usepackage{amsthm}
\usepackage{setspace}
\newtheorem{thm}{Theorem}[chapter]
\newtheorem{proposition}{Proposition}[chapter]
\newtheorem{lem}[thm]{Lemma}
\newtheorem{definition}{Definition}[chapter]
\usepackage{caption}

\usepackage{mathptmx}
\DoubleSpacing
\usepackage{pwasu}
\usepackage{graphicx}
\usepackage{pwasu}
\usepackage{graphicx}

\def\listofsymbols{\input{memoir/symbols} \clearpage}
\def\addsymbol #1: #2#3{$#1$ \> \parbox{5.45in}{#2 \dotfill \pageref{#3}}\\}
\def\newnot#1{\label{#1}}

\chapter{INTRODUCTION}
\DoubleSpacing
\setlength{\parindent}{0.5in}
\section{Overview}
Reliability is defined as the ability of a system or component to perform its required functions under stated conditions for a specified period of time. An easier definition is: reliability is the quality over time (\citet{GBMA2004}). Nowadays, with the rapid development. And \citet{YP2013} ....
...
...
\newpage
\SingleSpace
\setlength{\beforechapskip}{-0.1in}
\renewcommand{\bibname}{REFERENCES}%\addcontentsline{toc}{chapter}{REFERENCES}
\bibliographystyle{apacite}
\bibliography{FinalReferences}
\clearpage
\addtocontents{toc}{%
 \protect\vspace{\lineskip}%
 \protect\noindent APPENDIX\protect\par
 \protect\vspace{-\lineskip}%
}
\renewcommand{\theequation}{A.\arabic{equation}}
\setcounter{equation}{0}

\end{document}

A: You only show part of your bibtex file, but by any chance do you have two entries such as:
@article{YP2013,
  author = {Tao Yang and Rong Pan},
...
@article{Yang1999,
  author = {Yang and ...},
...

In other words does the name sometimes appear with with and without the first name, or sometimes with the full name and sometimes with just the initial?  Editing you .bib file to make sure the names are all abbreviated consistently sometimes helps with that.

A: I wasn't sure how to do this strictly in LaTeX, but I wrote a Python program that would do this for you. It finds and removes any and all instances of white space followed by a single character and then a period. It also corrects for any comma duplication errors that could result.
Python Program (Make sure this and the file that's being modified are in the same folder)
Test File (Your examples and a couple I pulled off a paper I wrote recently)
Test With Fixes (The end results)
Hopefully this kind of thing isn't against Tex rules, and if rather than downloading you would like to have the straight hardcode posted here I can do that in a comment. Cheers!