text:
Q: divisibility of central binomial coefficients Every central binomial coefficient, starting with the one in row 2, is divisible by two. There are a few proofs of this already on this site, like
prove that $\frac{(2n)!}{(n!)^2}$ is even if $n$ is a positive integer
I looked at Pascal's triangle, and every other central binomial coefficient starting at the one in row 6, appears to be divisible by four. Is this true? Is there a nice way to prove this? (I attempted to use Pascal's identity, but didn't arrive to anything).
Side Note:
It also looks like every 4th central binomial coefficient, starting at row 14, is divisible by 8. Is it a pattern that doubling the previous "starting row" and adding two gives the next "starting row", and doubling the previous "gap" gives the new gap for the next power of two? I checked a few things: central binomial coefficient in row 30 is divisible by 16, the central coefficient in row 62 is divisible by 32, and the one in row 126 is divisible by 64.


text:
Q: Como ler  em arquivos HTML e imprimir como quebra de linha? Fiz um web scraper utilizando os módulos BeautifulSoup e requests, que pega a definição e exemplo de conceitos no Urban Dictionary. Este é código, utilizando a palavra "reparation" como exemplo.
word = 'reparation'
r = requests.get("http://www.urbandictionary.com/define.php?term={}".format(word))
soup = BeautifulSoup(r.content, features='html.parser')
definition = soup.find("div", attrs={"class": "meaning"}).text
example = soup.find("div", attrs={"class": "example"}).text

O programa retorna o exemplo do site como:

"Bob: Here is $50 for me hitting you.Charles: Thanks for the reparation."

Porém, há duas quebras de linha no site, deixando o exemplo como:

"Bob: Here is $50 for me hitting you.
Charles: Thanks for the reparation."

Como faço para incorporar essas quebras na string example?

A: Como text retorna o texto sem as tags, o
 também é removido.
Então o jeito seria substituir as tags
 antes de obter o text:
# obtém a tag (e não o text)
example = soup.find("div", attrs={"class": "example"})
# substitui os br que tem dentro da tag
for br in example.find_all("br"):
    br.replace_with("\n")

# agora sim pega o texto
print(example.text)

Com isso eu troco cada br por uma quebra de linha (\n), e a saída será:
Bob: Here is $50 for me hitting you.

Charles: Thanks for the reparation.

Ou, em vez de substituir a tag, podemos adicionar a quebra de linha nela:
for br in example.find_all("br"):
    br.append("\n") # usar append em vez de replace_with

print(example.text)

A diferença é que agora as tags br terão como conteúdo a quebra de linha (\n), e quando chamarmos text, ele removerá as tags mas manterá o \n.
Vale lembrar que tanto o MDN quanto o WHATWG definem que a tag br não tem conteúdo. Embora o WHATWG defina que na verdade o conteúdo do br é um "Nothing content model", que por sua vez só pode ter um inter-element whitespace (que por sua vez, é definido como um ou mais ASCII whitespaces, que no caso podem ser espaços, TAB's e quebras de linha - ou seja, o \n seria um conteúdo válido para a tag br, por isso tanto o append quanto o replace_with seriam soluções válidas).

redpajama_set_name: RedPajamaStackExchange


text:
Q: Windows 10 Start Menu Different Between Builds? The first image is from Windows 10 v1511 (Build 10586.218), and the "All apps" menu item is tucked into the lower left corner, out of sight & mind.

This image is from a Surface Pro 4 running v1607 (Build 14393.321). The All Apps menu is taking up a ton of real estate and not contributing anything to society. How can I move it down to the lower corner like in the green start menu above?


text:
Q: Getting Parse error in CSV LOAD DATA INFILE I am trying to upload a CSV file in Database with PHP script.
the query am writing for that is
mysql_query("LOAD DATA LOCAL INFILE  'data.csv' INTO TABLE  `raw_data` FIELDS TERMINATED BY  ',' ENCLOSED BY  '"' ESCAPED BY  '\\' LINES TERMINATED BY '\n' ");

The error i am getting while running this script is
Parse error: parse error in C:\wamp\www\price\godata.php on line 5

Can any1 tell me where i am doing wrong ?

A: By the looks of it, you are using a double quote " inside a string terminated by double quotes. You will need to escape the character, which you can do like this:
mysql_query("LOAD DATA LOCAL INFILE  'data.csv' INTO TABLE  `raw_data`
             FIELDS TERMINATED BY  ',' ENCLOSED BY  '\"' ESCAPED BY  '\\'
             LINES TERMINATED BY '\n' ");         // ^ PHP Thought your command
                                                  // ended at that point

A: Put escape \ character before " ie replace ENCLOSED BY  '"' by ENCLOSED BY  '\"'


text:
Q: PATCH in web API for Many to Many relationships using EF I'm trying to remove a tag from a list of tags using a PATCH request. But while saving changes to the db context I get the following error:.
This the the PATCH code.
[HttpPatch("{id:int}/{field}", Name = "UpdateNote")]
[ProducesResponseType(StatusCodes.Status204NoContent)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
public IActionResult UpdateNote(int id, string field, JsonPatchDocument<CreateNoteDTO> patchNoteDTO)
{
    if (id == 0 || patchNoteDTO == null)
        return BadRequest();
    var note = _db.Notes.AsNoTracking().FirstOrDefault(u => u.ID == id);
    if (note == null)
        return NotFound();

    CreateNoteDTO createNoteDTO = _mapper.Map<CreateNoteDTO>(note);
    if (field.Equals("tags"))
    {
        var tags = _db.Tags.Where(u => u.Notes.Any(x => x.ID == note.ID)).AsNoTracking().ToList();
        List<TagDTO> tagDTOs = new List<TagDTO>();
        if (tags.Count > 0)
        {
            foreach (var tag in tags)
            {
                TagDTO tagDTO = _mapper.Map<TagDTO>(tag);
                tagDTOs.Add(tagDTO);
            }
        }
        createNoteDTO.Tags = tagDTOs;
    }
    patchNoteDTO.ApplyTo(createNoteDTO, ModelState);

    if (!ModelState.IsValid)
        return BadRequest(ModelState);

    Note updateNote = _mapper.Map<Note>(createNoteDTO);
    updateNote.ID = id;
    updateNote.ChangedDate = DateTime.Now;
    _db.Update(updateNote);
    if (!field.ToLower().Equals("category"))
        _db.Entry(updateNote).Property(u => u.FKCategory).IsModified = false;
    _db.Entry(updateNote).Property(u => u.CreatedDate).IsModified = false;
    _db.SaveChanges();
    return NoContent();
}

My ApplicationDBContext looks like this:
public class ApplicationDbContext : DbContext
{
    public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options)
    {
    }
    public DbSet<Note> Notes { get; set; }
    public DbSet<Category> Categories { get; set; }
    public DbSet<Tag> Tags { get; set; }
    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        //Write Fluent API configurations here

        modelBuilder.Entity<Note>()
                    .HasOne(e => e.Category)
                    .WithMany(e => e.Notes)
                    .HasForeignKey(e => e.FKCategory)
                    .OnDelete(DeleteBehavior.Cascade);

        modelBuilder.Entity<Note>()
                .HasMany(n => n.Tags)
                .WithMany(t => t.Notes)
                .UsingEntity(j => j
                .ToTable("NoteTag")
                .HasData
                (
                    new { NotesID = 1, TagsTagID = 1 },
                    new { NotesID = 2, TagsTagID = 2 }
                ));

        modelBuilder.Entity<Category>().HasData
            (
            new Category
            {
                CategoryID = 1,
                CategoryName = "testCategory1",
                CreatedDate = DateTime.Now
            },
            new Category
            {
                CategoryID = 2,
                CategoryName = "testCategory2",
                CreatedDate = DateTime.Now
            }
            );
        modelBuilder.Entity<Tag>().HasData
            (
            new Tag
            {
                TagID = 1,
                TagName = "testTag1",
                CreatedDate = DateTime.Now
            },
            new Tag
            {
                TagID = 2,
                TagName = "testTag2",
                CreatedDate = DateTime.Now
            }
            );
        modelBuilder.Entity<Note>().HasData
            (
            new Note
            {
                ID = 1,
                Title = "testTitle1",
                Description = "testDescription1",
                FKCategory = 1,
                Deleted = false,
                CreatedDate = DateTime.Now,
                ChangedDate = DateTime.Now,
            },
            new Note
            {
                ID = 2,
                Title = "testTitle2",
                Description = "testDescription2",
                FKCategory = 2,
                Deleted = false,
                CreatedDate = DateTime.Now,
                ChangedDate = DateTime.Now,
            }
            );
    }
}

Any suggestions?
Thanks in advance.
Initially I tried without the following if condition:
CreateNoteDTO createNoteDTO = _mapper.Map<CreateNoteDTO>(note);
if (field.Equals("tags"))
{
    var tags = _db.Tags.Where(u => u.Notes.Any(x => x.ID == note.ID)).AsNoTracking().ToList();
    List<TagDTO> tagDTOs = new List<TagDTO>();
    if (tags.Count > 0)
    {
        foreach (var tag in tags)
        {
            TagDTO tagDTO = _mapper.Map<TagDTO>(tag);
            tagDTOs.Add(tagDTO);
        }
    }
    createNoteDTO.Tags = tagDTOs;
}

But I got a different error:

I wanted to remove a tag form the following object using a PATCH request:
Note Object


text:
Q: Wifi connection but no internet I have joined my home WiFi network and I don't get Internet through it anymore. Phones and other computers have no issues, others who were here haven't  changed anything or noticed any difference.
I was away from home for a week using various public and hotel WiFi networks, if that means anything. I used a public WiFi network 30 minutes before and had no issues.
I've looked through previous questions like this which had a lot of responses, and I still haven't solved it:
Full Wi-fi/ethernet signal but no internet
How do I troubleshoot my Wi-Fi connection when an exclamation mark appears?
I can log in to the router admin settings. Everything seems fine.
I have tried changing the IPv4 address manually, making sure nothing is using the same IP etc.
I have tried using 8.8.8.8 as the DNS server address.
In Terminal ifconfig en1 gives:
Flags=963<UP BROADCAST SMART RUNNING PROMISC SIMPLEX> mtu 1500
Options =60 <tso4, tso6>
Ether 4a:00:03:a0:13:90
Media: auto select <full-duplex>
Status: inactive

(Apologies if the syntax is off, I'm copying this on to my phone)
It is a MacBook Pro retina 13inch 2.9ghz i5, OSX 10.11.4
Any ideas are much appreciated!

A: Your wireless device appears to be in promiscuous mode.  Maybe you are doing a packet dump or sniffing packets?  If so, no worries.  If not, I would investigate this further, as it sometimes yet not always indicates a compromised system being used as a stepping stone in further network penetration.
First, a quick and dirty network device refresh can be effectuated by creating a new location in the System Preferences, under the network portion.  Look at the top, and under location, click edit locations.  Then click the plus button, and give the new location a name.
Then please select your home network, and re-enter the password.
Your problem might have been resolved.  If not, then please go back to the terminal and provide the output of these:
     ifconfig -a -v

     pfctl -v -si

     pfctl -v -sr

     ipconfig getpacket en1

     netstat -nvia -I en1

     netstat -nr

Hope that this helps.
F.


text:
Q: What is the difference between ANOVA and logistic regression using two groups? So just correct me where I go wrong, but my understanding of the differences between ANOVA and regression analysis is that ANOVA is comparing two independent groups while regression is used on one group with independent observations.
But then my question is:
Imagine we have two groups of patients, group A and group B. We have variable "x" that we want to investigate whether there exists a difference in between these two groups.
Now we could do an ANOVA but what would be the difference between doing this and simply making a binary variable with 0 denoting group A and 1 denoting group B and then running a regression with this variable as the dependent and "x" as the independent?
Thank you!

A: ANOVA and logistic regression have different aims. A bit loosely speaking, ANOVA uses a continuous response variable and predicts the value of that variable, while logistic regression uses a binary response variable and predicts the category. ANOVA then attempts to find the mean of the response variable, conditioned on the group membership.
You can use a classifier such as logistic regression to see how well you can separate your data. In that case, you would invert the problem: instead of predicting the continuous measurements from the group membership, predict the group membership from the continuous measurements. To get the p-value, look at the parameter on the continuous variable. While I am unfamiliar with Stata, R uses Wald confidence intervals by default, and I have been doing logistic regression parameter inference lately via likelihood ratio testing. A parameter significantly different from zero indicates that the variable gives insight into the group to which the observation belongs.
By the way, ANOVA is a linear regression. We have some posts about this fact. I will link one that I liked.
https://stats.stackexchange.com/a/76292/247274
EDIT I found another: https://stats.stackexchange.com/a/16956/247274. I will note that, when there are only two groups, this is identical to the equal-variance t-test. (Remember that R uses the unequal-variance Welch test by default, and other software may, too.) Allowing for some numerical imprecision on a computer, the F-stat from the method in this link and the square of the t-test's t-stat will be the same, and the resulting p-values will be the same.


text:
Q: Access network shares on diferent subnet I have two computers on my domain on different subnets, one in 10.100.176.x and other on 10.100.54.x. On the first one I can see the in explorer other network shares from 10.100.170.x to 10.100.178.x but although I can ping the second computer I can't see the shares and if I try to map anything I get error 53 network path not found. All the computers have the same configurations regarding network discovery and networking. Appreciate the help.

A: This sounds like a firewall/routing issue. You need to find out which port your particular network shares are running and make sure traffic from one subnet is allowed to the other on that particular port. The shortcut would be to allow any traffic bi-directionally between the two subnets on your firewall/router. The long way would be to find out which ports are needed for the particular network services that are sharing the files and to open that.
Also, there might be another reason why those subnets were created to segment the networks, and if there are security precautions that should be taken.
Hope this helps!
-Byron

A: Most likely a firewall issue, since you seem to have routing and DNS resolution working fine.
Windows file shares use SMB (TCP port 445); make sure this traffic is allowed between the two subnets.
Also check Windows Firewall on all involved machines.


text:
Q: Python lognorm.cdf vs. formula based implementation not matching Okay I am converting the scipy.stats.lognorm.cdf function over to a Cython function and using the formula here: http://www.cs.unitn.it/~taufer/SR/P-LN.pdf as 1/2 + 1/2* erf((ln(x)-mu)/sigma*sqrt(2). The results don't match, despite many other references to the same function online. EDIT: just fixed, only had to do np.log(mu) 2x ... Fixed code:
import numpy as np
from scipy.stats import lognorm
from scipy.special import erf

def lognormcdf(x, mu, sigma):
    return 0.5 + 0.5*erf((np.log(x)-np.log(mu))/(np.sqrt(2.0)*sigma))

mu = 3.85
sigma = 0.346
x = [-9.997137267734412802e-01,-9.984919506395958377e-01,-9.962951347331251428e-01,-9.931249370374434227e-01,-9.889843952429917540e-01,-9.838775407060570410e-01,-9.778093584869183008e-01,-9.707857757637063933e-01,-9.628136542558155542e-01,-9.539007829254917414e-01,-9.440558701362560257e-01,-9.332885350430795146e-01,-9.216092981453339883e-01,-9.090295709825296777e-01,-8.955616449707269888e-01,-8.812186793850184108e-01,-8.660146884971646752e-01,-8.499645278795913139e-01,-8.330838798884008245e-01,-8.153892383391762033e-01,-7.968978923903144995e-01,-7.776279096494954635e-01,-7.575981185197071532e-01,-7.368280898020207470e-01,-7.153381175730564312e-01,-6.931491993558019926e-01,-6.702830156031409636e-01,-6.467619085141292912e-01,-6.226088602037077591e-01,-5.978474702471787694e-01,-5.725019326213811599e-01,-5.465970120650941455e-01,-5.201580198817630230e-01,-4.932107892081909473e-01,-4.657816497733580086e-01,-4.378974021720314913e-01,-4.095852916783015440e-01,-3.808729816246299582e-01,-3.517885263724216949e-01,-3.223603439005291449e-01,-2.926171880384719759e-01,-2.625881203715034751e-01,-2.323024818449739570e-01,-2.017898640957360157e-01,-1.710800805386032686e-01,-1.402031372361139672e-01,-1.091892035800611088e-01,-7.806858281343663497e-02,-4.687168242159163445e-02,-1.562898442154308370e-02,1.562898442154308370e-02,4.687168242159163445e-02,7.806858281343663497e-02,1.091892035800611088e-01,1.402031372361139672e-01,1.710800805386032686e-01,.017898640957360157e-01,2.323024818449739570e-01,2.625881203715034751e-01,2.926171880384719759e-01,3.223603439005291449e-01,3.517885263724216949e-01,3.808729816246299582e-01,4.095852916783015440e-01,4.378974021720314913e-01,4.657816497733580086e-01,4.932107892081909473e-01,5.201580198817630230e-01,5.465970120650941455e-01,5.725019326213811599e-01,5.978474702471787694e-01,6.226088602037077591e-01,6.467619085141292912e-01,6.702830156031409636e-01,6.931491993558019926e-01,7.153381175730564312e-01,7.368280898020207470e-01,7.575981185197071532e-01,7.776279096494954635e-01,7.968978923903144995e-01,8.153892383391762033e-01,8.330838798884008245e-01,8.499645278795913139e-01,8.660146884971646752e-01,8.812186793850184108e-01,8.955616449707269888e-01,9.090295709825296777e-01,9.216092981453339883e-01,9.332885350430795146e-01,9.440558701362560257e-01,9.539007829254917414e-01,9.628136542558155542e-01,9.707857757637063933e-01,9.778093584869183008e-01,9.838775407060570410e-01,9.889843952429917540e-01,9.931249370374434227e-01,9.962951347331251428e-01,9.984919506395958377e-01,9.997137267734412802e-01]
mycdf = lognormcdf(x, np.log(mu), sigma)
scipycdf = lognorm.cdf(x, scale=np.log(mu), s=sigma)

# This line comparing the Scipy function and mine displays the results below
np.sum(np.nan_to_num(mycdf)-scipycdf)

Results:
1.2011928779531548e-15

A: The original post was edited to reflect the correct formula.
def lognormcdf(x, mu, sigma):
    return 0.5 + 0.5*erf((np.log(x)-np.log(mu))/(np.sqrt(2.0)*sigma))

Pass np.log(mu) in for mu and it works.


text:
Q: It is possible to define "styles" in tcolorbox listings? I am writing a document where I use tcolorbox to list code. I would like to have a couple of commands to list code from an external file, and one (or two) environment for inline snippets. What I have (and it's nicely working) is something along the way of this MWE:
\RequirePackage{filecontents}
\begin{filecontents}{test.c}
#include <stdio.h>

int main() {
    return 0;
}

\end{filecontents}

\documentclass{article}
\usepackage[listings, breakable, skins, fitting]{tcolorbox}

% from http://tex.stackexchange.com/a/163617/38080
\newtcbinputlisting[auto counter]{\putcodecomment}[2]{
    listing file={#1},
    title={Listing \thetcbcounter: #1}, fonttitle=\bfseries,
    listing and comment,
    comment={#2},
    %%% start of common things here
    breakable,
    width=0.9\linewidth,
    bicolor,
    lower separated=true,
    colback=red!5,
    colframe=red!75!black,
    listing options={
      language          = {[Visual]C++},           % Language
      basicstyle        = \ttfamily,             % Default format
      keywordstyle      = \color{blue},          % Keywordformat
      breaklines        = true,                  % Automatic line breaks
      breakatwhitespace = true,                  % Line breaks only at white spaces
      tabsize           = 4,                     % Number of spaces equal to a tab
      showspaces        = false,                 % Show spaces in the code
      showtabs          = false,                 % Show tabs in the code
      showstringspaces  = false,                 % Show spaces among strings
  },
}

\newtcblisting{justcode}[0]{
    listing only,
    breakable,
    width=0.9\linewidth,
    %%% start of common things here
    breakable,
    width=0.9\linewidth,
    bicolor,
    lower separated=true,
    colback=red!5,
    colframe=red!75!black,
    listing options={
      language          = {[Visual]C++},           % Language
      basicstyle        = \ttfamily,       % Default format
      keywordstyle      = \color{blue},          % Keywordformat
      breaklines        = true,                  % Automatic line breaks
      breakatwhitespace = true,                  % Line breaks only at white spaces
      tabsize           = 4,                     % Number of spaces equal to a tab
      showspaces        = false,                 % Show spaces in the code
      showtabs          = false,                 % Show tabs in the code
      showstringspaces  = false,                 % Show spaces among strings
  },
}

\begin{document}

\putcodecomment{test.c}{%
    No comment here
}

\begin{justcode}
    a = a + 1;
\end{justcode}

\end{document}

... which works, but as you can see, I had to use copy and paste to "repeat" the common part of the options of the boxes. Now, if I want to change the color of the background, I need to change it in two (really they are four) different place.
I tried to put all the common option in a \def\commonoptions{...} but it choked...
Is there a way to put the common part in common "style" so that I can organize it better? Something on the line of the tikz styles?

A: Just use \lstdefinestyle{foo}{ your options} and say listing options={style=foo}, this will save a lot of typing (or work).
You can change the listing options after setting the style:
listing options={style=foo,numbers=right}, for example.
Here's a modified version of the O.P. code
\RequirePackage{filecontents}
\begin{filecontents}{test.c}
#include <stdio.h>

int main() {
    return 0;
}

\end{filecontents}

\documentclass{article}
\usepackage[listings, breakable, skins, fitting]{tcolorbox}

\lstdefinestyle{rmano}{      language          = {[Visual]C++},           % Language
      basicstyle        = \ttfamily,             % Default format
      keywordstyle      = \color{blue},          % Keywordformat
      breaklines        = true,                  % Automatic line breaks
      breakatwhitespace = true,                  % Line breaks only at white spaces
      tabsize           = 4,                     % Number of spaces equal to a tab
      showspaces        = false,                 % Show spaces in the code
      showtabs          = false,                 % Show tabs in the code
      showstringspaces  = false,                 % Show spaces among strings
}

% from http://tex.stackexchange.com/a/163617/38080
\newtcbinputlisting[auto counter]{\putcodecomment}[2]{
    listing file={#1},
    title={Listing \thetcbcounter: #1}, fonttitle=\bfseries,
    listing and comment,
    comment={#2},
    %%% start of common things here
    breakable,
    width=0.9\linewidth,
    bicolor,
    lower separated=true,
    colback=red!5,
    colframe=red!75!black,
    listing options={style=rmano}
  }

\newtcblisting{justcode}[0]{
    listing only,
    breakable,
    width=0.9\linewidth,
    %%% start of common things here
    breakable,
    width=0.9\linewidth,
    bicolor,
    lower separated=true,
    colback=red!5,
    colframe=red!75!black,
    listing options={style={rmano},
  },
}

\begin{document}

\putcodecomment{test.c}{%
    No comment here
}

\begin{justcode}
    a = a + 1;
\end{justcode}

\end{document}

Edit
Here's a version that has common options for tcolorbox as well:
Use
\def\commonboxoptions{    breakable,
    width=0.9\linewidth,
    bicolor,
    lower separated=true,
    colback=red!5!,
    colframe=red!75!black,
}

and say code={\pgfkeysalsofrom{\commonboxoptions}} in the tcolorbox options (the listing boxes here!)
\RequirePackage{filecontents}
\begin{filecontents}{test.c}
#include <stdio.h>

int main() {
    return 0;
}

\end{filecontents}

\documentclass{article}
\usepackage[listings, breakable, skins, fitting]{tcolorbox}

\lstdefinestyle{rmano}{      language          = {[Visual]C++},           % Language
      basicstyle        = \ttfamily,             % Default format
      keywordstyle      = \color{blue},          % Keywordformat
      breaklines        = true,                  % Automatic line breaks
      breakatwhitespace = true,                  % Line breaks only at white spaces
      tabsize           = 4,                     % Number of spaces equal to a tab
      showspaces        = false,                 % Show spaces in the code
      showtabs          = false,                 % Show tabs in the code
      showstringspaces  = false,                 % Show spaces among strings
}

\def\commonboxoptions{    breakable,
    width=0.9\linewidth,
    bicolor,
    lower separated=true,
    colback=red!5!,
    colframe=red!75!black,
}

% from http://tex.stackexchange.com/a/163617/38080
\newtcbinputlisting[auto counter]{\putcodecomment}[2]{
    listing file={#1},
    title={Listing \thetcbcounter: #1}, fonttitle=\bfseries,
    listing and comment,
    comment={#2},
    %%% start of common things here
    code={\pgfkeysalsofrom{\commonboxoptions}},
    listing options={style=rmano}
  }

\newtcblisting{justcode}[0]{
    listing only,
    breakable,
    width=0.9\linewidth,
    %%% start of common things here
    code={\pgfkeysalsofrom{\commonboxoptions}},
    listing options={style={rmano},
  },
}

\begin{document}

\putcodecomment{test.c}{%
    No comment here
}

\begin{justcode}
    a = a + 1;
\end{justcode}

\end{document}


text:
Q: Как открыть новую вкладку перед уже открытой / JS Задача состоит в следующем...
window.open('https://google.com') // открываем таким образом вкладку в новом окне, она находится справа от существующего, необходимо чтоб вкладка открывалась слева, перед страницей в которой вызвался этот метод.


text:
Q: "Column count doesn't match value count at row 1" PKID Counts as Column even with AUTOINCREMENT? "Column count doesn't match value count at row 1"
{
code: 'ER_WRONG_VALUE_COUNT_ON_ROW',
errno: 1136,
sqlMessage: "Column count doesn't match value count at row 1",
sqlState: '21S01',
index: 0,
sql: "INSERT IGNORE INTO craig.cdata (pkid,country,region,site,area,category,id,repost_of,last_updated,title,neighborhood,url,lat,lon,address,misc,compensation) VALUES (pkid),('testcountry15'), ('testregion14'), ('testsite13'), ('testarea12'), ('testcategory11'), ('testid10'), ('repostoftest9'), ('lastupdatedtest8'), ('titletest7'), ('neighborhoodtest6'), ('urltest5'), ('lattest4'), ('lontest3'), ('addresstest2'), ('misctest2'), ('compensationtest1');"
}
controller: {"country":"testcountry15","region":"testregion14","site":"testsite13","area":"testarea12","category":"testcategory11","id":"testid10","repost_of":"repostoftest9","last_updated":"lastupdatedtest8","title":"titletest7","neighborhood":"neighborhoodtest6","url":"urltest5","lat":"lattest4","lon":"lontest3","address":"addresstest2","misc":"misctest2","compensation":"compensationtest1"}
DROP DATABASE IF EXISTS `craig`;
CREATE DATABASE `craig` DEFAULT CHARSET = utf8mb4 DEFAULT COLLATE = utf8mb4_unicode_ci;

USE `databasename`;

DROP TABLE IF EXISTS dbname.database1;
CREATE TABLE dbname.database1 (
            `pkid`          int unsigned NOT NULL AUTO_INCREMENT,
            `country`       varchar(200),
            `region`        varchar(200),
            `site`          varchar(200),
            `area`          varchar(200),
            `category`      varchar(200),
            `id`            varchar(200),
            `repost_of`     varchar(200),
            `last_updated`  varchar(200),
            `title`         varchar(200),
            `neighborhood`  varchar(200),
            `url`           varchar(200),
            `lat`           varchar(200),
            `lon`           varchar(200),
            `address`       varchar(200),
            `misc`          varchar(200),
            `compensation`  varchar(200),
            PRIMARY KEY (`pkid`)
) AUTO_INCREMENT=1;

let query = INSERT IGNORE INTO craig.cdata (country,region,site,area,category,id,repost_of,last_updated,title,neighborhood,url,lat,lon,address,misc,compensation) VALUES ('${pg.country}'), ('${pg.region}'), ('${pg.site}'), ('${pg.area}'), ('${pg.category}'), ('${pg.id}'), ('${pg.repost_of}'), ('${pg.last_updated}'), ('${pg.title}'), ('${pg.neighborhood}'), ('${pg.url}'), ('${pg.lat}'), ('${pg.lon}'), ('${pg.address}'), ('${pg.misc}'), ('${pg.compensation}');
^^^ SQL Statement. I know its not pretty, but its the best I could come up with learning on my own. I understand that the PKID is not included in this SQL statement which is probably producing the error "Column count doesn't match value count at row 1", I thought the whole point of having the PK AI NN ID is to increment to the next new id for any piece of data that is altered by the table, in this case INSERT IGNORE. I use this statement for another server which works the exact same way!
I don't think I am missing a comma, but I also might be crazy! Any help would be greatly appreciated. Thank you for your time. If you need any info, I will provide it promptly.

A: This way you are adding many rows with one column each.
Try .. VALUES ('${pg.country}', '${pg.region}', '${pg.site}'..., '${pg.compensation}')


text:
Q: ¿Como almacenar datos en un array y que no muestre los espacios nulos? Estoy intentando almacenar una "dirección" en un array con 150 espacios, esto se almacena en un documento txt y el problema es que al abrir el documento txt la dirección me muestra los espacios sobrantes.
El código es el siguiente:
struct cliente{
    char dni[9];
    char nombre[20];
    char apellidos[80];
    char direccion[150]
}clientes[max_clientes];

void aniadirCliente()
{

    if(clientes[n].dni[0]=='\0'){
        printf("\nIntroduce el nombre del archivo: \nNombre por defecto: clientes.txt\n\n");
        gets(nom_archivo);
        fflush(stdin);
        //Cuando abrimos el fichero le tenemos que poner rw para que podamos escribir y leer.
        archivo=fopen(nom_archivo,"rw");
        if ((archivo = fopen(nom_archivo, "rw")) == NULL) {
            fprintf(stderr, "\n\nEl archivo no existe.");
            system("cls"); //En windows limpia pantalla
        }else{
            int i;
            printf("\n\nArchivo cargado correctamente.");
            for(i=0; i<max_clientes;i++){
                //Los datos teneis que ponerlos con _ porque no coge los espacios. Ej: Pelegrin_Castillo
                fscanf(archivo,"\n %s %s %s %s",clientes[i].dni,clientes[i].nombre,clientes[i].apellidos,clientes[i].direccion);
            }
            for(i=0;i<max_clientes;i++){
                if(clientes[i].dni[0]=='\0'){
                    //Crear un nuevo cliente, lo mismo que antes los espacios con _
                    puts("DNI:");
                    scanf("%s", &clientes[i].dni);
                    fprintf(archivo, "%s", clientes[i].dni);

                    puts("Nombre:");
                    scanf("%s", &clientes[i].nombre);
                    fprintf(archivo, "%s", &clientes[i].nombre);

                    puts("Apellidos:");
                    scanf("%s", &clientes[i].apellidos);
                    fprintf(archivo, "%s", &clientes[i].apellidos);

                    puts("Direccion:");
                    scanf("%s", &clientes[i].direccion);
                    fprintf(archivo, "%s", &clientes[i].direccion);
                    break;
                    }
                }
            }

}
            fclose(archivo);
            system("cls");

}

A: Ésto te debería de funcionar. Cambia el modo de abrir el archivo de "rw" por "a+" entre otros cambios, como == por !=, suprimir la linea de abrir documento duplicada, etc... Había varios errores en tu código:
#include <stdio.h>
#define max_clientes 50

struct cliente{
    char dni[9];
    char nombre[20];
    char apellidos[80];
    char direccion[150]
}clientes[max_clientes];
FILE *archivo;

int main() {
    aniadirCliente();
    return 0;
}

void aniadirCliente()
{
    int i;
    char nom_archivo[50];

    printf("\nIntroduce el nombre del archivo: \nNombre por defecto: clientes.txt\n\n");
    gets(nom_archivo);
    fflush(stdin);

    //Cuando abrimos el fichero le tenemos que poner rw para que podamos escribir y leer.
    if ((archivo = fopen(nom_archivo, "a+")) != NULL) {

        for(i=0;i<max_clientes;i++){
                //Crear un nuevo cliente, lo mismo que antes los espacios con _
                puts("DNI:");
                scanf("%s", &clientes[i].dni);
                fprintf(archivo, "DNI: %s\n", &clientes[i].dni);

                puts("Nombre:");
                scanf("%s", &clientes[i].nombre);
                fprintf(archivo, "Nombre: %s\n", &clientes[i].nombre);

                puts("Apellidos:");
                scanf("%s", &clientes[i].apellidos);
                fprintf(archivo, "Apellidos: %s\n", &clientes[i].apellidos);

                puts("Direccion:");
                scanf("%s", &clientes[i].direccion);
                fprintf(archivo, "Direccion: %s\n", &clientes[i].direccion);
                break;
                }

    }
        fclose(archivo);
        system("cls");

}

Como está ahí puesto, no te imprimirá los espacios en blanco sobrantes que comentas.


text:
Q: Update Vue route param dynamically I have a multilingual Vue (Nuxt) app. Based I'm setting the selected language / locale in the URL, e.g. http://www.example.net/sv-SE/somepage.
The routes are registered with an optional iso code: /:iso_code([a-z]{2}-[A-Z]{2})?/somepage. This all works as intented.
Now to my question: I have a language dropdown where the user can set the desired language. Is there any way to update the route param iso_code above, without resorting to history.replaceState?
I've tried the router API, without success. The URL isn't updated, i.e. if the URL is http://www.example.net/sv-SE/somepage, sv-SE isn't replaced with en-US when running the code:
this.$router.replace({ path: this.$route.fullPath, params: { iso_code: 'en-US' } })

A: To push a route with the params object, you should use a named route:
const routes = [
  {
    path: '/:iso_code([a-z]{2}-[A-Z]{2})?/somepage',
    name: 'somepage',
    //...
  }
]
export default new VueRouter({ routes })

Then, you'd $router.push the route's name along with params:
App.vue:
<template>

    <router-link :to="{ name: 'somepage', params: { iso_code: 'sv-SE' }}">sv-SE</router-link>

    <button @click="$router.push({ name: 'somepage', params: { iso_code: 'es-SP' }})">es-SP</button>

</template>

demo of named route
Additionally, you could update the params of the current route by pushing only the params object (i.e., without a path or name). For example, assuming that path/name are already at the correct route to receive the iso_code parameter, you could $router.push({ params: { iso_code: 'es-SP' }}):
SomePage.vue:
<template>

{{ iso_code }}

    <button @click="$router.push({ params: { iso_code: 'es-SP' }})">es-SP</button>

</template>

demo of params update for current route

If you preferred not to use named routes, you'd have to push the fully resolved path (e.g., /sv-SE/somepage) and no params:
this.$router.push('/sv-SE/somepage')

The disadvantage in this case is you'd have to update this reference if you ever decide to change the path.


text:
Q: Removing dirs with lots of tiny files on Lustre I have a dir with a gigantic amount of very small files that I want to remove and simply removing the dir with rm -rf /path/to/the/dir is already taking multiple days.
It might sound strange that this is going slow, but the dir is not a dir on regular filesystem. It's a dir on a Lustre Filesystem of a cluster.
I'm running the rm command on node A of the cluster which has the Lustre mounted, but the backend of the Lustre are 2 ZFS filesystems, one on node B and one on node C so all the networktraffic might be the cause of rm going slow.
Does anyone know faster ways to remove the dir than my way ?

A: Several GNU commands, such as tar and rm are inefficient when operating on a large class of files on Lustre. For example, with millions of files, rm -rf * may take days, and have a considerable impact on Lustre for other users.
The reason lies in the time it takes to expand the wild card.
A better way to do this is to generate a list of files to be removed or tar-ed, and to act them one at a time, or in small sets.
A good way to review files before they are deleted is the following:
$ lfs find <dir> -t f > rmlist.txt
$ vi rmlist.txt
$ sed -e 's:^:/bin/rm :' rmlist.txt > rmlist.sh
$ sh rmlist.sh

# the directory structure will remain, but unless there are many directories, we can simply delete it:
$ rm -rf <dir>

Some of the useful references for Lustre IO:
1. https://www.nics.tennessee.edu/computing-resources/file-systems/io-lustre-tips
2. https://www.rc.colorado.edu/support/examples-and-tutorials/parallel-io-on-janus-lustre.html
Thanks!

A: Use munlink:
find -P $dir -type f -o -type l -print0 | xargs -0 munlink

... and remove the empty directories:
find -P $dir -depth -type d -empty -delete

I updated the find with more args.
Reference: https://support.pawsey.org.au/documentation/display/US/Deleting+Large+Numbers+of+Files+on+Lustre+Filesystems

A: Since I haven't got enough reputation so far I can't comment on @Atisom's solution, hence a new answer:
The find command shown in Atisom's solution is not working as find will match either -type f or -type l -print0
To make it work, add parentheses instead:
find -P $dir \( -type f -o -type l \) -print0 | xargs -0 munlink


text:
Q: Attribute the final output value of a directed graph proportionally to its vertices I have a business graph outlining user traffic behavior through an app. The edges are weighted as the amount of traffic it drives into each vertex. The final output vertices have $ values attached to them. How can I attribute backwards the value of each vertex via the proportional weights of the edges?
Image showing my situation
In the image linked above, the attribution to Notifications is simple because that is the input. Input equals output so it would be $1500 after summing up all of the infinite paths.
Please consider the Notification Center though. How can I calculate the proportion of the total $1500 in purchases that can be attributed to all paths containing it? There could be an infinite number of paths since a user theoretically could jump infinitely between vertices before their purchase. Is their a formula I can use for this? Thanks.


text:
Q: Google API Google Drive Node.js can´t upload file oAuth2 Hey I tried for over 6h now and nothing working. I came this far..
I created a successfull connection to my api with this default code from the google api pages. I also enabled advanced features Google Drive at my console google page. I successfull created the token and it´s now stored at C:\Users\Administrator.credentials
var fs = require('fs');
var readline = require('readline');
var google = require('googleapis');
var googleAuth = require('google-auth-library');

// If modifying these scopes, delete your previously saved credentials
// at ~/.credentials/drive-nodejs-quickstart.json
var SCOPES = ['https://www.googleapis.com/auth/drive.metadata.readonly'];
var TOKEN_DIR = (process.env.HOME || process.env.HOMEPATH ||
    process.env.USERPROFILE) + '/.credentials/';
var TOKEN_PATH = TOKEN_DIR + 'drive-nodejs-quickstart.json';

// Load client secrets from a local file.
fs.readFile('client_secret.json', function processClientSecrets(err, content) {
  if (err) {
    console.log('Error loading client secret file: ' + err);
    return;
  }
  // Authorize a client with the loaded credentials, then call the
  // Drive API.
  authorize(JSON.parse(content), listFiles);
});

/**
 * Create an OAuth2 client with the given credentials, and then execute the
 * given callback function.
 *
 * @param {Object} credentials The authorization client credentials.
 * @param {function} callback The callback to call with the authorized client.
 */
function authorize(credentials, callback) {
  var clientSecret = credentials.installed.client_secret;
  var clientId = credentials.installed.client_id;
  var redirectUrl = credentials.installed.redirect_uris[0];
  var auth = new googleAuth();
  var oauth2Client = new auth.OAuth2(clientId, clientSecret, redirectUrl);

  // Check if we have previously stored a token.
  fs.readFile(TOKEN_PATH, function(err, token) {
    if (err) {
      getNewToken(oauth2Client, callback);
    } else {
      oauth2Client.credentials = JSON.parse(token);
      callback(oauth2Client);
    }
  });
}

/**
 * Get and store new token after prompting for user authorization, and then
 * execute the given callback with the authorized OAuth2 client.
 *
 * @param {google.auth.OAuth2} oauth2Client The OAuth2 client to get token for.
 * @param {getEventsCallback} callback The callback to call with the authorized
 *     client.
 */
function getNewToken(oauth2Client, callback) {
  var authUrl = oauth2Client.generateAuthUrl({
    access_type: 'offline',
    scope: SCOPES
  });
  console.log('Authorize this app by visiting this url: ', authUrl);
  var rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
  });
  rl.question('Enter the code from that page here: ', function(code) {
    rl.close();
    oauth2Client.getToken(code, function(err, token) {
      if (err) {
        console.log('Error while trying to retrieve access token', err);
        return;
      }
      oauth2Client.credentials = token;
      storeToken(token);
      callback(oauth2Client);
    });
  });
}

/**
 * Store token to disk be used in later program executions.
 *
 * @param {Object} token The token to store to disk.
 */
function storeToken(token) {
  try {
    fs.mkdirSync(TOKEN_DIR);
  } catch (err) {
    if (err.code != 'EEXIST') {
      throw err;
    }
  }
  fs.writeFile(TOKEN_PATH, JSON.stringify(token));
  console.log('Token stored to ' + TOKEN_PATH);
}

/**
 * Lists the names and IDs of up to 10 files.
 *
 * @param {google.auth.OAuth2} auth An authorized OAuth2 client.
 */
function listFiles(auth) {
  var service = google.drive('v3');
  service.files.list({
    auth: auth,
    pageSize: 10,
    fields: "nextPageToken, files(id, name)"
  }, function(err, response) {
    if (err) {
      console.log('The API returned an error: ' + err);
      return;
    }
    var files = response.files;
    if (files.length == 0) {
      console.log('No files found.');
    } else {
      console.log('Files:');
      for (var i = 0; i < files.length; i++) {
        var file = files[i];
        console.log('%s (%s)', file.name, file.id);
      }
    }
  });
}

When I rerun this script I get
Files:
sample file.mp4 (123456789sampelcode)
projektname (123456789sampelcode)
Getting started (123456789sampelcode)

To the connection now worked with the token because I don´t need to do reenter something. I really don´t understand now how to upload a file. When i try to include my own upload function I can´t use it because I can´t combine it with the login process. I saw that
function listFiles(auth) {
}

Was default execuded after the login. So I thought I enter my code in this function it would work . So created this
function listFiles(auth) {
var drive = google.drive('v3');
var fileMetadata = {
  'name': 'photo.jpg'
};
var media = {
  mimeType: 'image/jpeg',
  body: fs.createReadStream('./photo.jpg')
};
drive.files.create({
   resource: fileMetadata,
   media: media,
   auth: auth,
   fields: 'id'
}, function(err, file) {
  if(err) {
    // Handle error
    console.log(err);
  } else {
    console.log('File Id: ', file.id);
  }
});

}

But nothing happen. My Terminal window is endless loading. No error no nothing.
Version 2 - This is my second version . also no log no nothing just endless loading. I turned of firewall so no way thats there a problem with the firewall or antivirus or somthing because in the default script I can see the files from my googledrive
const fs = require('fs');
const readline = require('readline');
const google = require('googleapis');
const googleAuth = require('google-auth-library');
const drive = google.drive('v3');

// If modifying these scopes, delete your previously saved credentials
// at ~/.credentials/drive-nodejs-quickstart.json
var SCOPES = ['https://www.googleapis.com/auth/drive'];
var TOKEN_DIR = (process.env.HOME || process.env.HOMEPATH ||
       process.env.USERPROFILE) + '/.credentials/';
var TOKEN_PATH = TOKEN_DIR + 'drive-nodejs-quickstart.json';

// Load client secrets from a local file.
fs.readFile('client_secret.json', function processClientSecrets(err, content) {
     if (err) {
       console.log('Error loading client secret file: ' + err);
       return;
     }
     // Authorize a client with the loaded credentials, then call the
     // Drive API.
     //authorize(JSON.parse(content), listFiles);
     authorize(JSON.parse(content), real_upload_files);
});

/*
    * Create an OAuth2 client with the given credentials, and then execute the
    * given callback function.
    *
    * @param {Object} credentials The authorization client credentials.
    * @param {function} callback The callback to call with the authorized client.
    */
function authorize(credentials, callback) {
     var clientSecret = credentials.installed.client_secret;
     var clientId = credentials.installed.client_id;
     var redirectUrl = credentials.installed.redirect_uris[0];
     var auth = new googleAuth();
     var oauth2Client = new auth.OAuth2(clientId, clientSecret, redirectUrl);

     // Check if we have previously stored a token.
     fs.readFile(TOKEN_PATH, function(err, token) {
       if (err) {
         getNewToken(oauth2Client, callback);
         //console.log('5')
       } else {
         oauth2Client.credentials = JSON.parse(token);
         callback(oauth2Client);
         // console.log('4')
       }
     });
} // function authorize(credentials, callback) {

function real_upload_files(auth) {

var fileMetadata = {
     'name': 'photo.jpg'
};
var media = {
     mimeType: 'image/jpeg',
     body: fs.createReadStream('./photo.jpg')
};
drive.files.create({
      resource: fileMetadata,
      media: media,
      auth: auth,
      fields: 'id'
}, function(err, file) {
     if(err) {
       // Handle error
       console.log(err);
     } else {
       console.log('File Id: ', file.id);
     }
});

} // function real_upload_files(auth) {

Also If I would change auth: auth     to    auth: oauth2Client  and change it also in the function then will be same result endless loading screen.
Can somebody explain me pls how to upload files or do other stuff with the oAuth2. I find as node.js newbie that there are to less sample codes to find for for node.js .. Please help me guys I strugggle so hard with this.. please help :D With dropbox it takes 10 min but there I easy used a API Key ..

A: I think that your script is no wrong. In my environment, your script works fine. So I propose following 2 modifications.
Modification points :

*

*What terminal do you use for this? It seems that from C:\Users\Administrator.credentials of your question, you use windows OS. If it's so, can you use cmd.exe for this? If you don't use windows. Please don't change the terminal.

*How about the use of readFile() for reading the file? readFile() can read whole data in the file to the memory. So I thought that the error might be avoided. But if the file size is large, I recommend to use createReadStream(). I confirmed that readFile() and createReadStream() can use to upload file to Google Drive using cmd.exe as a terminal with windows OS.

Modified script :
function real_upload_files(auth) {
    fs.readFile('./photo.jpg', function(err, content){
        var fileMetadata = {
            'name': 'photo.jpg',
        };
        var media = {
            mimeType: 'image/jpeg',
            body: new Buffer(content, 'binary'),
        };
        drive.files.create({
            resource: fileMetadata,
            media: media,
            auth: auth,
            fields: 'id',
        }, function(err, file) {
            if (err) {
                console.log(err);
            } else {
                console.log('File Id: ', file.id);
            }
        });
    });
}

I don't know whether these lead to the solution. I'm sorry.


text:
Q: I am validating data using Regex and I have the username and email working but the password is returning a value of null This is my code for this and I don't understand why it isn't working I used the same template as my email and username and they both work fine.
string Password = Request["Password"];

System.Text.RegularExpressions.Regex regex2 =
    new System.Text.RegularExpressions.Regex(@"^([^0-9]*)$");
// does the string follow the regex structure?
System.Text.RegularExpressions.Match match2 = regex2.Match(Password);
//if yes
if (match2.Success)
{

}
else
{
    passwordAlert = "password is not valid";
}

<form class="text-center" method="post">
    Email: <input type="text" name="email"/>
@emailAlert

    Username: <input type="text" name="username" />
@usernameAlert

    Password: <input type="password" name="Password" />
@passwordAlert

    <input type="submit" name="Submit" />

</form>

    string emailAlert = "";
    string usernameAlert = "";
    string passwordAlert = "";

    if(IsPost)
    {

    string email = Request["email"];

    System.Text.RegularExpressions.Regex regex = new System.Text.RegularExpressions.Regex(@"^([\w\.\-]+)@([\w\-]+)((\.(\w){2,3})+)$");
    // does the string follow the regex structure?
    System.Text.RegularExpressions.Match match = regex.Match(email);
    //if yes
    if (match.Success){

    } else {
        emailAlert = "email is not valid";
    }

    string username = Request["username"];

    System.Text.RegularExpressions.Regex regex1 = new System.Text.RegularExpressions.Regex(@"^[a-zA-Z0-9_@.-]*$");
    // does the string follow the regex structure?
    System.Text.RegularExpressions.Match match1 = regex1.Match(username);
    //if yes
    if (match1.Success)
    {

    }
    else
    {
        usernameAlert = "username is not valid";
    }

}

    string Password = Request.Form["Password"];

    System.Text.RegularExpressions.Regex regex2 = new System.Text.RegularExpressions.Regex(@"^([0-9],{6,})$");
    // does the string follow the regex structure?
    System.Text.RegularExpressions.Match match2 = regex2.Match(Password);
    //if yes
    if (match2.Success)
    {

    }
    else
    {
        passwordAlert = "password is not valid";
    }

}

<form runat="server" class="text-center" method="post">
      Email: <input type="text" name="email"/>
@emailAlert

      Username: <input type="text" name="username" />
@usernameAlert

      Password: <input Request.Form["Password"]; type="password" name="Password" />
@passwordAlert

      <input type="submit" name="Submit" />

</form>

I have added the full code now just in case there is a conflict before the point of error
thanks in advance

A: You need to change your regular expression from this
^([^0-9]*)$ to this ^([0-9]*)$
You also need to use to read password field
Request.Form["Password"];

In form tag add runat=Server


text:
Q: rm: cannot remove `/run/user/root/gvfs': Is a directory Whenever I type a command which is similar to sudo apt-get install or anything like this I get this kind of error:
$ sudo su
# exit
exit
rm: cannot remove `/run/user/root/gvfs': Is a directory

How can I resolve it?

A: Open your terminal (Ctrl+Alt+T) and run this:
sudo umount /run/user/root/gvfs


text:
Q: Return collection of one without "Trying to get property of non-object" error I have a SearchController where I check a search term against two tables, first for exact matches (followed by a redirect table to the relevant manufacturer page) and then for partial matches - four conditions in total. All of these conditions work except the last one, probably because it often needs to return just one result inside of a collection.
I need this to be the case as I would like to do $results->slug, $results->name, etc. throughout the view no matter which search condition is being triggered. Currently I'm able to do this to access the search results of all the conditions except the third one.
Search Controller class, where everything but the third condition is working as it should:
class SearchController extends Controller
{
        public function index() {
            if (request("search")) {

            # Works as expected
            $exact_terms = SearchTerm::with("manufacturer")->where('term', request("search"))->get();
            if($exact_terms->isNotEmpty()) {
                echo "Exact search term match!";
                $results = $exact_terms;

                foreach ($results as $result) {
                    $slug = $result->manufacturer->slug;
                }

                return redirect()->action([ManufacturerController::class, 'index'], ["manufacturer" => $slug]);
            }

            # Works as expected
            $exact_make = Manufacturer::where('slug', request("search"))->get();
            if($exact_make->isNotEmpty()) {
                echo "Exact manufacturer match!";
                $results = $exact_make;

                foreach ($results as $result) {
                    $slug = $result->slug;
                }
                return redirect()->action([ManufacturerController::class, 'index'], ["manufacturer" => $slug]);
            }

            # Doesn't work
            $search_terms = SearchTerm::with("manufacturer")->where('term', "like", '%' . request("search") . '%')->get()->unique("manufacturers");
            if($search_terms->isNotEmpty()) {
                echo "Search term match!";
                foreach ($search_terms as $search_term) {
                    $search_term = $search_term->manufacturer;
                }
                $results = collect($search_term);
            }

            # Works as expected
            $search_make = Manufacturer::where('slug', 'like', '%' . request("search") . '%')->get();
            if($search_make->isNotEmpty()) {
                echo "Manufacturer match!";
                $results = $search_make;
            }

        $results = isset($results) ? $results : collect();
        }

        return view("search", [
        "manufacturer" => $manufacturer,
        "results" => $results,
    ]);
    }
}

View file:
@if($results)

 {{ $results->count() }} {{ $results->count() == 1 ? "result" : "results" }} found for {{ request("search") }}

@foreach ($results as $result)

{{ $result->slug }}

@endforeach
@else

Sorry! We couldn't find any results for "{{ request("search") }}".

@endif

Result of a dd($results) when triggering the condition just before the foreach loop:
Illuminate\Support\Collection {#1406 ▼
#items: array:5 [▼
    "id" => 15
    "slug" => "ford"
    "name" => "Ford"
    "created_at" => "2022-01-28T19:53:28.000000Z"
    "updated_at" => "2022-01-28T19:53:28.000000Z"
]
#escapeWhenCastingToString: false
}

Result of a dd($result) when triggering the condition inside of the foreach loop (shows nothing from the array but the primary key):
15

A: You can't add a Model to a Collection via the constructor, it will end up pulling the attributes from it since Model is Arrayable (it will call toArray on it and get the attributes/appends/relationships as an array). You could call add on the Collection to add the Model.
$results = collect()->add($search_term);

Or you can pass an array to collect which it is expecting:
$results = collect([$search_term]);

On a side note, you are doing a lot of iterating to just get the last value from a Collection to use in all of these conditions. You could call last on the Collection to get the last value, or even restrict your query to return a single result instead of an entire result set since you are literally not using any of the result set except the last record.


text:
Q: Adding index on jsonb field fail when running migration I am using PostgreSQL with TypeORM. My Student entity has a jsonb field, defined like this:
@Entity('students')
export class Student {
  ...
  @Column('jsonb', { name: 'other_data', nullable: true })
  otherData: { nr?: string; hometown?: string } | null;
}

The students table was initially created without the column other_data but added later via the following migration:
await queryRunner.addColumns('students', [
      new TableColumn({
        name: 'other_data',
        type: 'jsonb',
        isNullable: true,
      }),
    ]);

The column adding was successful, I can see on psql console that \d students has the field with type jsonb.
The content of otherData is expected to be a json contains nr and hometown optional fields.
After database table is created, I try to run a migration to add index to the nr field of otherData (please bear in mind otherData is a jsonb type).
This is what I tried in TypeORM migration file:
public async up(queryRunner: QueryRunner): Promise<void> {
    await queryRunner.query(
      `CREATE INDEX "student_nr" ON "students" USING gin (other_data -> 'nr')`
    );

When I run the migration, I get error:
Migration "AddIndexOnOtherDataColumn1647948281597" has been failed, error: syntax error at or near "->"
query: ROLLBACK
Error during migration run:
QueryFailedError: syntax error at or near "->"
    at QueryFailedError.TypeORMError [as constructor] (/Users/john/myproj/src/error/TypeORMError.ts:7:9)
    at new QueryFailedError (/Users/john/myproj/src/error/QueryFailedError.ts:9:9)
    at PostgresQueryRunner.<anonymous> (/Users/john/myproj/src/driver/postgres/PostgresQueryRunner.ts:247:19)
    at step (/Users/john/myproj/node_modules/tslib/tslib.js:143:27)
    at Object.throw (/Users/john/myproj/node_modules/tslib/tslib.js:124:57)
    at rejected (/Users/john/myproj/node_modules/tslib/tslib.js:115:69)
    at processTicksAndRejections (node:internal/process/task_queues:96:5) {
  query: `CREATE INDEX "student_nr" ON "students" USING gin (other_data -> 'nr')`,
  parameters: undefined,
  driverError: error: syntax error at or near "->"

The noticeable part of the error message is parameters: undefined and error near "->". But I get stuck on why this error, where am I wrong?

A: I eventually solved the problem by adding one more () around other_data->'nr':
await queryRunner.query(
      `CREATE INDEX "student_nr" ON "students" USING gin ((other_data -> 'nr'))`
    );

But it would be nice if someone is experienced with it could verify whether I am right in fixing the issue & also would be nice to explain more on it. Thanks!


text:
Q: curl gives 400 error but works in postman? I am using codeigniter-3 ,inside controller i am hitting one external API it's giving 400 error but same curl request if i hit in postman it's working fine can you please help me did i miss anything ..?
CURL REQUEST in postman
curl --location --request POST 'http://armycalling.com/baligaz-api/api/userapi/login' \
--header 'x-api-key: ccccc' \
--header 'Authorization: Basic YWRtaW46YmFsaWdheiFAIyQ=' \
--header 'Content-Type: application/json' \
--header 'Cookie: ci_session=f3630b226e539f4aa079e980e23cc730609a1627' \
--data-raw '{
    "email" : "dummy@gmail.com",
    "password" : "dummy.srk"
}'

usercontroller.php
if(isset($_POST['login']))
        {
            //phpinfo();
            $url = 'http://localhost/login';
            $u_name = $this->input->post('username');
            $password= $this->input->post('password');
            $curl = curl_init($url);
            $data = [
                'email'=>$u_name,
                'password'=>$password
            ];
            curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data));
            curl_setopt($curl, CURLOPT_HTTPHEADER, array(
                        'x-api-key: ccccc',
                        'Authorization: Basic YWRtaW46YmFsaWdheiFAIyQ=',
                        'Content-Type: Application/json',
                        'Cookie: ci_session=6dc4b8f72e2953c590ff503bd47f52ecfa158c79'
            ));
            curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
            $result = curl_exec($curl);
            $httpcode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
            return print($httpcode);
            curl_close($curl);

A: Setting this request to use a cookie session and sending the username/password in a POST request yields a successful login.
function curl( $url=NULL, $options=NULL, $headers=false ){
    $vbh = fopen('php://temp', 'w+');
    session_write_close();

    /* Initialise curl request object - these should be OK as-is */
    $curl=curl_init();

    /* Define standard options */
    curl_setopt( $curl, CURLOPT_URL, trim( $url ) );
    curl_setopt( $curl, CURLOPT_AUTOREFERER, true );
    curl_setopt( $curl, CURLOPT_FOLLOWLOCATION, true );
    curl_setopt( $curl, CURLOPT_FAILONERROR, true );
    curl_setopt( $curl, CURLOPT_HEADER, false );
    curl_setopt( $curl, CURLINFO_HEADER_OUT, false );
    curl_setopt( $curl, CURLOPT_RETURNTRANSFER, true );
    curl_setopt( $curl, CURLOPT_BINARYTRANSFER, true );
    curl_setopt( $curl, CURLOPT_CONNECTTIMEOUT, 20 );
    curl_setopt( $curl, CURLOPT_TIMEOUT, 60 );
    curl_setopt( $curl, CURLOPT_USERAGENT, 'Mozilla/5.0' );
    curl_setopt( $curl, CURLOPT_MAXREDIRS, 10 );
    curl_setopt( $curl, CURLOPT_ENCODING, '' );

    /* enhanced debug */
    curl_setopt( $curl, CURLOPT_VERBOSE, true );
    curl_setopt( $curl, CURLOPT_NOPROGRESS, true );
    curl_setopt( $curl, CURLOPT_STDERR, $vbh );

    /* Assign runtime parameters as options to override defaults if needed. */
    if( isset( $options ) && is_array( $options ) ){
        foreach( $options as $param => $value ) curl_setopt( $curl, $param, $value );
    }

    /* send any headers with the request that are needed */
    if( isset( $headers ) && is_array( $headers ) ){
        curl_setopt( $curl, CURLOPT_HTTPHEADER, $headers );
    }

    /* Execute the request and store responses */
    $res=(object)array(
        'response'  =>  curl_exec( $curl ),
        'status'    =>  curl_getinfo( $curl, CURLINFO_RESPONSE_CODE ),
        'info'      =>  (object)curl_getinfo( $curl ),
        'errors'    =>  curl_error( $curl )
    );

    rewind( $vbh );
    $res->verbose=stream_get_contents( $vbh );
    fclose( $vbh );
    curl_close( $curl );

    return $res;
}

# create a temporary file somewhere to store cookie data.
# Using the system temp directory should mean automatic
# deletion of these files in time.
$cookiestore=tempnam( sys_get_temp_dir(), '_cookiejar_' );

$url='http://armycalling.com/baligaz-api/api/userapi/login';

$headers=array(
    'x-api-key: BALIGAZ@123',
    'Authorization: Basic YWRtaW46YmFsaWdheiFAIyQ='
);

$args=array(
    'email'     =>  'rasakumar.srk@gmail.com',
    'password'  =>  'rasakumar.srk'
);

/*
    Mark the request as a new Cookie session - subsequent requests
    would have different options without CURLOPT_COOKIESESSION
*/
$options=array(
    CURLOPT_COOKIESESSION   =>  true,
    CURLOPT_COOKIEFILE      =>  $cookiestore,
    CURLOPT_COOKIEJAR       =>  $cookiestore,
    CURLOPT_POST            =>  true,
    CURLOPT_POSTFIELDS      =>  $args
);

/*
    Make the request with specified config options
*/
$res=curl( $url, $options, $headers );

/*
    If the request is successful a 200 OK status code will be received
    so we can then proceed to work with the response data.

    If the request fails, using the returned info & verbose properties
    of the response will show useful debug info.
*/
if( $res->status==200 ){
    printf('<pre>%s</pre>',print_r( $res->response, true ) );
}

This yields:
{
  "status": true,
  "message": "User login successful.",
  "data": {
    "id": "22",
    "user_id": "baligaz_595689",
    "first_name": "Rasa",
    "last_name": "Kumar",
    "email": "rasakumar.srk@gmail.com",
    "password": "529f263ebb230b4709003bb0f7457f90",
    "phone": "73339190384",
    "profile_img": "http://armycalling.com/baligaz-api/profile_image/baligaz_595689_app_one.png",
    "role": "1",
    "station_id": "HP Petrols",
    "forgot_otp": "",
    "created": "2022-06-24 04:47:13",
    "created_by": null,
    "modified": "2022-06-30 23:38:15",
    "updated_by": "baligaz_595689",
    "login_completed": null,
    "status": "1"
  }
}


text:
Q: Test network problems in simulator launched by Appium XCUITest I have set of hardware devices in the test network(no internet connection) and have an iOS App that detects all the devices in the test network. Those devices can be seen in the App in iPhone or iPad after connecting to test network only.
I have developed a appium automation code in java and that launches the app in Simulators and displays the all hardware devices that are in test network. But whenever I run my code, Appium able to launch the App simulator but no hardware devices in the App are being displayed. Network settings showing 'NO wifi connection'. My Mac is connected to test network so simulator has to automatically connect to test network and show the hardware devices in the network.
Could any help me to get rid of this would be appreciated.
Code:
DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities.setCapability("deviceName", "iPhone 6 Plus");
capabilities.setCapability("automationName", "XCUITest");
capabilities.setCapability("browserName","");
capabilities.setCapability("platformName", "iOS");
capabilities.setCapability("platformVersion", "10.0");
File app = new File("/Users/Shiva/Desktop/*****IAP.app");
capabilities.setCapability("app", app.getAbsolutePath());
capabilities.setCapability("udid", deviceUDID());
capabilities.setCapability("sendKeyStrategy", "grouped");
capabilities.setCapability("realDeviceLogger", "/usr/local/lib/node_modules/deviceconsole/deviceconsole");
IOSDriver<MobileElement> driver = new IOSDriver<MobileElement>(new URL("http://127.0.0.1:4723/wd/hub"),capabilities);

Thanks in advance.


text:
Q: Cloning a package from github and use in spyder I would like to create a copy of a package on github that I can edit and use in spyder. I currently use the anaconda package manager  for my python packages.
Here are the steps that I have taken so far:

*

*fork repo

*clone repo onto my local directory

The package is called 'Nilearn'. I currently use anaconda and have installed nilearn via 'conda install nilearn'.
I would like to be able to use my own copy of nilearn inside spyder alongside nilearn. I have tried renamine the repo to nilearn_copy, but this doesn't appear to work.
If this is not possible or not the ideal solution, then please help suggest an alternative, I'm new to github and python.
Thanks a lot,
Joe

A: You need to open an IPython console, then run this command
In [1]: %cd /path/to/nilearn/parent

By this I mean that you to go with the %cd magic to the parent directory where nilearn is placed. After that you can run
In [2]: import nilearn

and that should import your local copy of nilearn.

Note: If you are planning to do changes to nilearn and want your changes to be picked up in the same console, you need to run these commands before the previous ones:
In [3]: %load_ext autoreload
In [4]: %autoreload 2


text:
Q: Spring 4 loading static resources I got a spring MVC application with a bunch of css and js files currently placed in the src/main/java/resources/assets directory.
I read through the Spring Docs and some Tutorials on how to load these files for my templates using the ResourceHandlerRegistry class. I especially thought that the code snippets from this Tutorial would perfectly fit my project structure.
But I get always a 404 on my resource files.
Here is the Application/Configuration class I'm currently running with:
@Configuration
@EnableAutoConfiguration
@ImportResource("/applicationContext.xml") // only used for jpa/hibernate
@EnableWebMvc
@ComponentScan(basePackages = "at.sustain.docutools.viewer.presentation")
public class Application extends WebMvcConfigurerAdapter {

    public static void main(String args[]) {
        SpringApplication.run(Application.class);
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/assets/**")
                .addResourceLocations("classpath:/assets/");
        registry.addResourceHandler("/css/**")
                .addResourceLocations("/css/");
        registry.addResourceHandler("/js/**")
                .addResourceLocations("/js/");

    }

}

And here a HEADer used in my HTML files (placed in resources/templates):
<head>
    <!-- local Stylesheet -->
    <link href="css/style.css" rel="stylesheet" />
    <!-- local Javascript files -->
    <script src="js/general.js"></script>
    <script src="js/xmlhttp.js"></script>
    <!-- local Javascript libraries -->
    <script src="js/lib/filter.js"></script>
    <script src="js/lib/jquery.fs.zoomer.js"></script>
    <script src="js/lib/jquery.validate.js"></script>
</head>

The html file is loaded correctly through my controller classes but when trying to hit e.g. my style.css file (http://localhost:8080/css/style.css) I get an 404 as already mentioned.
I can't seem to find any more resources who could provide me with more information on this subject for Spring 4. Do I miss some configuration files? Or aren't the resource handler registrations fitting my structure? I'm looking forward to your responses.

A: You say that your stylesheets and JavaScript files are under "/assets". I'm going to assume you have directories "/assets/css" and "/assets/js". Then, given the following resource handler definition:
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
  registry.addResourceHandler("/assets/**")
    .addResourceLocations("classpath:/assets/");
}

You would load these resources in your HTML like so:
<link href="/assets/css/style.css" rel="stylesheet" />
<script src="/assets/js/general.js"></script>


text:
Q: BigQuery Put Query Result into Day Partition Table BigQuery can save query result into specify table, but If target table has day partition, currently I use Python loop query one day data and save to table, is other faster way?
thanks!

A: There are two related feature requests that you can vote for and monitor progress - Update date-partitioned tables from results of a query and Partition on non-date field
Meantime, conceptually - the way you approach this - using loop - is correct and the only way as of now (August 2017)


text:
Q: JSF Primefaces: how to update selectOneMenu(in form1) from dialogBox in form 2? I want to update a selectOneMenu in form1 after submitting the commandbutton in form2. It is now only visible after a refresh of the page.
I have a selectOneMenu in form 1:
<h:form id="form1" rendered="#">

            <p:spacer height="30" />
            <h:selectOneMenu id="oneMenu" value="#{bean.value}">
                <f:selectItem itemLabel="Select Value" itemValue="" />
                <f:selectItems id="itemValues"
                    value="#{bean.allItems}" var="allItems"
                    itemValue="#{allItems}" itemLabel="#{allItems.name}" />
            </h:selectOneMenu>

and a DialogBOX in form2:
<h:form id="form2">
            <p:dialog header="Create new Item" widgetVar="newItem"
                resizable="false">

                <h:panelGrid columns="2" style="margin-bottom:10px">

                    <h:outputLabel for="item" value="Itemname:" />
                    <p:inputText id="itemname" value="#{bean.itemName}" />
                </h:panelGrid>

                <p:commandButton value="Submit"
                    actionListener="#{bean.newItem}"
                    update="form1:oneMenu" oncomplete="newItem.hide();"  />

            </p:dialog>

I've tried update="form1:oneMenu" but it doesn't work. I've also read this post
but it doesn't work either.
Thanks for help.

A: Make sure to use update=":form1:myPanel".
Example :
<h:form id="form1">
    <h:selectOneMenu id="oneMenu" value="#{bean.value}">
    ...
    </h:selectOneMenu>
</h:form>

<h:form id="form2">
    <p:dialog ..>
        ...
        <p:commandButton value="Submit" update=":form1:oneMenu" ..../>
    </p:dialog>
</h:form>

Otherwise
<h:form id="form1">
    <p:selectOneMenu id="oneMenu" value="#{bean.value}">
    ...
    </p:selectOneMenu>
</h:form>

<h:form id="form2">
    <p:dialog ..>
        ...
        <p:commandButton value="Submit" update=":form1:oneMenu" ..../>
    </p:dialog>
</h:form>

Update For Comment : Try that below. You can use h:selectOneMenu or p:selectOneMenu.
<h:form id="form1">
    <p:selectOneMenu style="width:195px;" required="true" id="cityMenu">
        <f:selectItems value="#{SelectOneMenuBean.cities}"/>
    </p:selectOneMenu>
    <p:commandButton oncomplete="newItem.show()" value="Show Dialog"/>
</h:form>
<h:form id="form2">
    <p:dialog header="Create new Item" widgetVar="newItem" resizable="false">
        <h:panelGrid columns="2" style="margin-bottom:10px">
            <h:outputLabel for="item" value="Itemname:" />
            <p:inputText id="itemname" value="#{SelectOneMenuBean.selectedValue}" />
        </h:panelGrid>

        <p:commandButton value="Submit" update=":form1:cityMenu" oncomplete="newItem.hide();"  />

    </p:dialog>
</h:form>

public class SelectOneMenuBean {
    private String selectedValue;

    public String getSelectedValue() {
        return selectedValue;
    }

    public void setSelectedValue(String selectedValue) {
        this.selectedValue = selectedValue;
    }

    public String[] getCities() {
        if(selectedValue != null && selectedValue.equals("AAA")) {
            return new String[] {"City_1 of AAA", "City_2 of AAA", "City_3 of AAA"};
        } else if(selectedValue != null && selectedValue.equals("BBB")) {
            return new String[] {"City_1 of BBB", "City_2 of BBB", "City_3 of BBB"};
        } else if(selectedValue != null && selectedValue.equals("CCC")) {
            return new String[] {"City_1 of CCC", "City_2 of CCC", "City_3 of CCC"};
        } else if(selectedValue != null && selectedValue.equals("DDD")) {
            return new String[] {"City_1 of DDD", "City_2 of DDD", "City_3 of DDD"};
        }
        return new String[] {"No City"};
    }
}

Note : If you input value AAA,BBB,CCC and DDD in dialog, the values of selectedOneMenu will be changed.


text:
Q: JQuery blinking image in cycle I have the blinking image. There is a jquery code:
function blink(){
        $("#light_3_1").animate({"opacity": 0}, 400 ).animate({"opacity": 1}, 400 );
    }
    $(document).ready(function(){
        setInterval(blink, 500);
    });

I want to make delay effect(10 seconds of blinking, then stop for some time, then again blinking and again stop...), but i can't find the way how to do it.

A: I heard you like intervals, so let's get an interval to control your interval so you can run an interval while you run an interval.
The following live demo has a "blink interval" running at 500ms, and a "pause interval" that controls the blink interval, running at 2000ms:

function blink() {
    $("#light_3_1").animate({
        "opacity": 0
    }, 400).animate({
        "opacity": 1
    }, 400);
}

var blinkInterval;
var pauseInterval;
var blinking = true;

$(document).ready(function () {
    blinkInterval = setInterval(blink, 500);
    pauseInterval = setInterval(toggleBlink, 2000);
});

function toggleBlink() {
    if (blinking) {
        clearInterval(blinkInterval);
        blinking = false;
    } else {
        blinkInterval = setInterval(blink, 500);
        blinking = true;
    }
}
#light_3_1 {
    width: 150px;
    height: 150px;
    background-color: blue;
}

JSFiddle Version: https://jsfiddle.net/kv18e1sL/1/

A: Since you want to stop after 10segs(10,000 ms) you just need to increment a variable to turn off the SetInterval.
Here I made a sample for you:
http://jsfiddle.net/leojavier/t83tb683/
However you should use CSS animation that way your animations are not going to impact your javascript thread.
$(document).ready(function(){
     var counter = 0;

    function blink(){
       $("#light_3_1").animate({"opacity": 0}, 400 ).animate({"opacity": 1}, 400 );
        counter++;
        if(counter > 9) {
            clearInterval(interval);
        }
    }
     var interval = setInterval(blink, 500);
});

Here is a version with CSS (RECOMMENDED): http://jsfiddle.net/leojavier/t83tb683/1/


text:
Q: how to save radio buttons value in mysql from laravel i have below code in my laravel blade:

    <input class="star star-5" id="star-5" type="radio" name="star"/>

    <input class="star star-4" id="star-4" type="radio" name="star"/>

    <input class="star star-3" id="star-3" type="radio" name="star"/>

    <input class="star star-2" id="star-2" type="radio" name="star"/>

    <input class="star star-1" id="star-1" type="radio" name="star"/>

when i use  dd($request->all())
it returned these line:
array:4 [▼
    "inputstar" => "11"
    "star" => "on"
    "products_id" => "84"
    "products_review" => "aaaaaa"
]

this code is for getting star rate
now , how to save radio buttons value in mysql from laravel code?

A: You are getting "on" because you haven't specified a value for your inputs. just add a value to each of your input fields and the form will return the given value for each input.

A: You can change your form as below:

@for($i = 5; $i >= 1; $i--)
  <input class="star star-{{$i}}" id="star-{{$i}}" type="radio" name="star" value="{{$i}}"/>

@endfor

Now, if you dd($request->all()); it should give you the value of star instead of the text on.


text:
Q: wget consistently failing over remote connection I am trying to download a large data set using wget which consistently fails.
For context, I am working from home and remote accessing my server using MobaXTerm. The server requires a proxy module to access the internet, for security reasons.
I am using
wget ftp2.collab.xyz.ac.uk/my_working_directory/file.txt.gpg --user=USER --password=PASSWORD

I receive back:
--2020-03-25 09:40:35--  ftp2.collab.xyz.ac.uk/my_working_directory/file.txt.gpg
Resolving proxy.uni.ac.uk (proxy.uni.ac.uk)... 10.95.131.12
Connecting to proxy.uni.ac.uk (proxy.uni.ac.uk)|10.95.131.12|:3128... connected.
Proxy request sent, awaiting response... 503 Service Unavailable
2020-03-25 09:41:35 ERROR 503: Service Unavailable.

I am able to use FileZilla to download to my machine using the same FTP address, user and password. However, this is inappropriate for this large dataset (100s of Gbs) as it would then require reupload to the work server.
Additionally, I cannot download tools to the remote server, such as lftp, due to restrictions.
Is there anything I can try to fix this?


text:
Q: FilePathResult serves file from Temp folder not the path provided Using PDFSharp, I have created and successfully saved a pdf file in a specific folder. Then I want to serve this file to the user on the browser upon request.
  return filePathResult = File(pdfFilePath,
                    MimeMapping.GetMimeMapping(pdfFilePath),
                    string.Format("{0}-data.pdf", userProfile.FullName));

The user gets open or save file prompt on the browser, but opening the file brings a pdf file that is created on the fly in the /AppData/Local/Temp/data.pdf, which has no content. I have done a lot of work around it, but so far I have not been able to force FilePathResult to serve the PDF file that I have created instead of creating a file in the temp folder and serving it to the user. How can I resolve this issue?


text:
Q: Auto Update Statistics threshold SQL Server 2016 since SQL Server 2016 the default auto statistics update threshold changed in that way that it uses a smaller threshold depending on the table size. In our application we periodically update statistics with fullscan. With this new behavior the auto update statistics runs after a smaller modification rate and uses only small sample rate. Until our maintenance job will update statistics again with fullscan next time, the auto statistics update runs and resets the 'fullscan' results. This could cause a performance problem in our application.
Is there any way to use the old behavior with auto statistics update without going back to a lower compatibility level?

A:
Until our maintenance job will update statistics again with fullscan
next time, the auto statistics update runs and resets the 'fullscan'
results

This is the side effect of updating statistics with fullscan on a weekly basis, it becomes more of a guessing game when your statistics are going to be automatically updated.
As mentioned in the comments and since you hopefully are on a patch level of SQL Server 2016 SP1 CU4 or above, setting the persisted sample rate higher can work for the tables that you are updating WITH FULLSCAN on a weekly basis.
You could try working with a lower sample rate than fullscan but still higher than the default sample rate for these tables to reduce the time it takes to update.
Another setting that can help due to your auto update statistics taking a longer time when a higher sample rate is used is to enable ASYNC_STAT_UPDATES. Enabling asynchronous stat updates makes your queries not wait for your statistic updates when enough changes have been made, causing them to use the old statistics which have a high sample rate.
The caveat is that the lowest level possible to enable asynchronous statistic updates is for your entire database. It would be wise to test this setting in development.
UPDATE STATISTICS dbo.tablename WITH SAMPLE 1 PERCENT, PERSIST_SAMPLE_PERCENT = ON;
UPDATE STATISTICS dbo.tablename WITH SAMPLE 5 PERCENT, PERSIST_SAMPLE_PERCENT = ON;
UPDATE STATISTICS dbo.tablename WITH FULLSCAN, PERSIST_SAMPLE_PERCENT = ON;

To enable asynchronous statistic updates:
ALTER DATABASE [DatabaseName] SET AUTO_UPDATE_STATISTICS_ASYNC ON WITH NO_WAIT;

Remember that when you truncate the table the sample rate is no longer persisted and when new indexes and their corresponding statistics are created that they will have the default sample rate.
Another idea would be to update your statistics more often for the tables that have more changes if your server has the resources to do so.


text:
Q: dynamicaly create "button" image with hover text I need to create a clickable image with dynamicaly getted text over it.
I already have the php that get the information needed for text but i'm having trouble creating the button(i'm really new to this kind of stuff).
This is an example of what I'd like to create:

The text "A020310" its a php answer and change all the time(saved in 'stringaPosizione', value of the button). A variable number of this image will be created and will be clicked to start some operation.
I have a javascript code that create button but they dont have image:
//Create an input type dynamically.
var element = document.createElement("input");

//Assign different attributes to the element.
element.setAttribute("type", "button");
element.setAttribute("class", "mybutt");
element.setAttribute("value", stringaPosizione);
element.setAttribute("name", idMappatura);
element.onclick = function() { runCommand(this) };

css:
.mybutt {
    background-image: url(/box.png);
    -moz-box-shadow:inset 0px -1px 20px 1px #ffffff;
    -webkit-box-shadow:inset 0px -1px 20px 1px #ffffff;
    box-shadow:inset 0px -1px 20px 1px #ffffff;
    background-color:transparent;
    -moz-border-radius:10px;
    -webkit-border-radius:10px;
    border-radius:10px;
    border:5px solid #dcdcdc;
    display:inline-block;
    color:#777777;
    font-family:arial;
    font-size:20px;
    font-weight:bold;
    padding:10px 40px;
    text-decoration:none;
    text-shadow:1px 3px 4px #ffffff;
}
.mybutt:active {
    position:relative;
    top:1px;
}

Do you have any suggestion?

A: Do you are appending the element on any object ? If not, you're just creating an element on the browser memory but not appending it to the dom tree.
Furthermore, you have to set the dimensions of your button to show the entire image.
Look at this fiddle and tell me if something is missing.


text:
Q: Is it possible to use regular expressions with pdfquery? Can we use regex to detect text within a pdf (using pdfquery or another tool)?
I know we can do this:
pdf = pdfquery.PDFQuery("tests/samples/IRS_1040A.pdf")
pdf.load()
label = pdf.pq('LTTextLineHorizontal:contains("Cash")')
left_corner = float(label.attr('x0'))
bottom_corner = float(label.attr('y0'))
cash = pdf.pq('LTTextLineHorizontal:in_bbox("%s, %s, %s, %s")' % \
        (left_corner, bottom_corner-30, \
        left_corner+150, bottom_corner)).text()
print cash
'179,000.00'

But we need something like this:
pdf = pdfquery.PDFQuery("tests/samples/IRS_1040A.pdf")
pdf.load()
label = pdf.pq('LTTextLineHorizontal:regex("\d{1,3}(?:,\d{3})*(?:\.\d{2})?")')
cash = str(label.attr('x0'))
print cash
'179,000.00'

A: This is not exactly a lookup for a regex, but it works to format/filter the possible extractions:
def regex_function(pattern, match):
    re_obj = re.search(pattern, match)
    if re_obj != None and len(re_obj.groups()) > 0:
        return re_obj.group(1)
    return None

pdf = pdfquery.PDFQuery("tests/samples/IRS_1040A.pdf")

pattern = ''
pdf.extract( [
('with_parent','LTPage[pageid=1]'),
('with_formatter', 'text'),
('year', 'LTTextLineHorizontal:contains("Form 1040A (")',
        lambda match: regex_function(SOME_PATTERN_HERE, match)))
 ])

I didn't test this next one, but it might work also:
def some_regex_function_feature():
    # here you could use some regex.
    return float(this.get('width',0)) * float(this.get('height',0)) > 40000

pdf.pq('LTPage[page_index="1"] *').filter(regex_function_filter_here)
[<LTTextBoxHorizontal>, <LTRect>, <LTRect>]


text:
Q: Decrease USB Detection Time in Linux? I'm creating a Linux based test rig for a USB device (not storage). Basically i've set it up using udev rules to automatically open a terminal and run a test script as soon as the USB device is plugged in, and this is all working fine.
However, there is about a 1 second lag between plugging the device in and the script running. Obviously not a problem normally, but when testing thousands of USB devices the time can add up fast.
Is there any way to improve to USB detection time?


text:
Q: Need a fast way to count and sum an iterable in a single pass Can any one help me? I'm trying to come up with a way to compute
>>> sum_widths = sum(col.width for col in cols if not col.hide)

and also count the number of items in this sum, without having to make two passes over cols.
It seems unbelievable but after scanning the std-lib (built-in functions, itertools, functools, etc), I couldn't even find a function which would count the number of members in an iterable.  I found the function itertools.count, which sounds like what I want, but It's really just a deceptively named range function.
After a little thought I came up with the following (which is so simple that the lack of a library function may be excusable, except for its obtuseness):
>>> visable_col_count = sum(col is col for col in cols if not col.hide)

However, using these two functions requires two passes of the iterable, which just rubs me the wrong way.
As an alternative, the following function does what I want:
>>> def count_and_sum(iter):
>>>     count = sum = 0
>>>     for item in iter:
>>>         count += 1
>>>         sum += item
>>>     return count, sum

The problem with this is that it takes 100 times as long (according to timeit) as the sum of a generator expression form.
If anybody can come up with a simple one-liner which does what I want, please let me know (using Python 3.3).
Edit 1
Lots of great ideas here, guys. Thanks to all who replied. It will take me a while to digest all these answers, but I will and I will try to pick one to check.
Edit 2
I repeated the timings on my two humble suggestions (count_and_sum function and 2 separate sum functions) and discovered that my original timing was way off, probably due to an auto-scheduled backup process running in the background.
I also timed most of the excellent suggestions given as answers here, all with the same model. Analysing these answers has been quite an education for me: new uses for deque, enumerate and reduce and first time for count and accumulate. Thanks to all!
Here are the results (from my slow netbook) using the software I'm developing for display:
┌───────────────────────────────────────────────────────┐
│                 Count and Sum Timing                  │
├──────────────────────────┬───────────┬────────────────┤
│          Method          │Time (usec)│Time (% of base)│
├──────────────────────────┼───────────┼────────────────┤
│count_and_sum (base)      │        7.2│            100%│
│Two sums                  │        7.5│            104%│
│deque enumerate accumulate│        7.3│            101%│
│max enumerate accumulate  │        7.3│            101%│
│reduce                    │        7.4│            103%│
│count sum                 │        7.3│            101%│
└──────────────────────────┴───────────┴────────────────┘

(I didn't time the complex and fold methods as being just too obscure, but thanks anyway.)
Since there's very little difference in timing among all these methods I decided to use the count_and_sum function (with an explicit for loop) as being the most readable, explicit and simple (Python Zen) and it also happens to be the fastest!
I wish I could accept one of these amazing answers as correct but they are all equally good though more or less obscure, so I'm just up-voting everybody and accepting my own answer as correct (count_and_sum function) since that's what I'm using.
What was that about "There should be one-- and preferably only one --obvious way to do it."?

A: You can keep count inside the sum with tricks similar to this
>>> from itertools import count
>>> cnt = count()
>>> sum((next(cnt), x)[1] for x in range(10) if x%2)
25
>>> next(cnt)
5

But it's probably going to be more readable to just use a for loop

A: I don't know about speed, but this is kind of pretty:
>>> from itertools import accumulate
>>> it = range(10)
>>> max(enumerate(accumulate(it), 1))
(10, 45)

A: You can use this:
from itertools import count

lst = range(10)
c = count(1)
tot = sum(next(c) and x for x in lst if x % 2)
n = next(c)-1
print(n, tot)

# 5 25

It's kind of a hack, but it works perfectly well.

A: I don't know what the Python syntax is off hand, but you could potentially use a fold.  Something like this:
(count, total) = fold((0, 0), lambda pair, x: (pair[0] + 1, pair[1] + x))

The idea is to use a seed of (0,0) and then at each step add 1 to the first component and the current number to the second component.
For comparison, you could implement sum as a fold as follows:
total = fold(0, lambda t, x: t + x)

A: 1_CR's complex number solution is cute but overly hacky. The reason it works is that a complex number is a 2-tuple, that sums elementwise. The same is true of numpy arrays and I think it's slightly cleaner to use those:
import numpy as np
z = [1, 2, 4, 5, 6]
y = sum(np.array([x, 1]) for x in z)
sum_z, count_z = y[0], y[1]
print sum_z, count_z
18 5

A: Something else to consider: If it is possible to determine a minimum possible count, we can let the efficient built-in sum do part of the work:
from itertools import islice

def count_and_sum(iterable):
    # insert favorite implementation here

def count_and_sum_with_min_count(iterable, min_count):
    iterator = iter(iterable)
    slice_sum = sum(islice(iterator, None, min_count))
    rest_count, rest_sum = count_and_sum(iterator)
    return min_count + rest_count, slice_sum + rest_sum

For example, using the deque method with a sequence of 10000000 items and min_count of 5000000, timing results are:
count_and_sum: 1.03
count_and_sum_with_min_count: 0.63

A: Thanks for all the great answers, but I decided to use my original count_and_sum function, called as follows:
>>> cc, cs = count_and_sum(c.width for c in cols if not c.hide)

As explained in the edits to my original question this turned out to be the fastest and most readable solution.

A: Adaption of DSM's answer. using deque(... maxlen=1) to save memory use.
import itertools
from collections import deque
deque(enumerate(itertools.accumulate(x), 1), maxlen=1)

timing code in ipython:
import itertools , random
from collections import deque

def count_and_sum(iter):
     count = sum = 0
     for item in iter:
         count += 1
         sum += item
     return count, sum

X = [random.randint(0, 10) for _ in range(10**7)]
%timeit count_and_sum(X)
%timeit deque(enumerate(itertools.accumulate(X), 1), maxlen=1)
%timeit (max(enumerate(itertools.accumulate(X), 1)))

results: now faster than OP's method
1 loops, best of 3: 1.08 s per loop
1 loops, best of 3: 659 ms per loop
1 loops, best of 3: 1.19 s per loop

A: Here's some timing data that might be of interest:
import timeit

setup = '''
import random, functools, itertools, collections

x = [random.randint(0, 10) for _ in range(10**5)]

def count_and_sum(it):
    c, s = 0, 0
    for i in it:
        c += 1
        s += i
    return c, s

def two_pass(it):
    return sum(i for i in it), sum(True for i in it)

def functional(it):
    return functools.reduce(lambda pair, x: (pair[0]+1, pair[1]+x), it, [0, 0])

def accumulator(it):
    return max(enumerate(itertools.accumulate(it), 1))

def complex(it):
    cpx = sum(x + 1j for x in it)
    return cpx.real, int(cpx.imag)

def dequed(it):
    return collections.deque(enumerate(itertools.accumulate(it), 1), maxlen=1)

'''

number = 100
for stmt in ['count_and_sum(x)',
             'two_pass(x)',
             'functional(x)',
             'accumulator(x)',
             'complex(x)',
             'dequed(x)']:
    print('{:.4}'.format(timeit.timeit(stmt=stmt, setup=setup, number=number)))

Result:
3.404 # OP's one-pass method
3.833 # OP's two-pass method
8.405 # Timothy Shields's fold method
3.892 # DSM's accumulate-based method
4.946 # 1_CR's complex-number method
2.002 # M4rtini's deque-based modification of DSM's method

Given these results, I'm not really sure how the OP is seeing a 100x slowdown with the one-pass method. Even if the data looks radically different from a list of random integers, that just shouldn't happen.
Also, M4rtini's solution looks like the clear winner.

To clarify, these results are in CPython 3.2.3. For a comparison to PyPy3, see James_pic's answer, which shows some serious gains from JIT compilation for some methods (also mentioned in a comment by M4rtini.

A: As a follow-up to senshin's answer, it's worth noting that the performance differences are largely due to quirks in CPython's implementation, that make some methods slower than others (for example, for loops are relatively slow in CPython). I thought it would be interesting to try the exact same test in PyPy (using PyPy3 2.1 beta), which has different performance characteristics. In PyPy the results are:
0.6227 # OP's one-pass method
0.8714 # OP's two-pass method
1.033 # Timothy Shields's fold method
6.354 # DSM's accumulate-based method
1.287 # 1_CR's complex-number method
3.857 # M4rtini's deque-based modification of DSM's method

In this case, the OP's one-pass method is fastest. This makes sense, as it's arguably the simplest (at least from a compiler's point of view) and PyPy can eliminate many of the overheads by inlining method calls, which CPython can't.
For comparison, CPython 3.3.2 on my machine give the following:
1.651 # OP's one-pass method
1.825 # OP's two-pass method
3.258 # Timothy Shields's fold method
1.684 # DSM's accumulate-based method
3.072 # 1_CR's complex-number method
1.191 # M4rtini's deque-based modification of DSM's method

A: How about this?
It seems to work.
from functools import reduce

class Column:
    def __init__(self, width, hide):
        self.width = width
        self.hide = hide

lst = [Column(10, False), Column(100, False), Column(1000, True), Column(10000, False)]

print(reduce(lambda acc, col: Column(col.width + acc.width, False) if not col.hide else acc, lst, Column(0, False)).width)

A: You might only need the sum & count today, but who knows what you'll need tomorrow!
Here's an easily extensible solution:
def fold_parallel(itr, **fs):
    res = {
        k: zero for k, (zero, f) in fs.items()
    }

    for x in itr:
        for k, (_, f) in fs.items():
            res[k] = f(res[k], x)

    return res

from operator import add

print(fold_parallel([1, 2, 3],
    count = (0, lambda a, b: a + 1),
    sum = (0, add),
))
# {'count': 3, 'sum': 6}

A: Using complex numbers
z = [1, 2, 4, 5, 6]
y = sum(x + 1j for x in z)
sum_z, count_z = y.real, int(y.imag)
print sum_z, count_z
18.0 5


text:
Q: How can I run a cancellable task to update UI component Using c# .NET, I'm trying to update a label in a form and reset it to empty after a few seconds, if no other update is done (in that case, the reset must be cancelled and delayed again).
I've found different solutions with cancellable tasks and updating UI after a delay, but not both combined.
This is a try, that fails when updating properties out of the UI thread:
    private CancellationTokenSource TokenClearUIMessage;

    private void SetUIMessage(string Message, string Detail, Color Color)
    {
        if (TokenClearUIMessage != null) TokenClearUIMessage.Cancel();

        TokenClearUIMessage = new CancellationTokenSource();
        Task.Delay(1000).ContinueWith(t => {
            LblMessage.Text = "-"; // <= THROWS EXCEPTION
            LblMessage.BackColor = Color.White;
        }, TokenClearUIMessage.Token);

        LblMessage.Text = Message;
        LblMessage.BackColor = Color;
        LblDetails.Text = Detail;
    }

How can I proceed?
Thank you.
Edit: Recommended solution was useful (How do I update the GUI from another thread?) but not completed I still missed the cancellation option but leaded me to the right solution.