text:
Q: Serialize list of objects in android and deserialize in WCF I have an ArrayList in android that I'm trying to convert to a Base64 String, then passing that to a wcf service though JSON and the wcf service inserts the string into a database. Then I need to be able to read that from the database and deserialize it in a .NET application.
This is how I am serializing the ArrayList in android:
    private String convertByteArrayToSave(byte[] b){
    if(b != null){
        return Base64.encodeToString(b,0,b.length,Base64.DEFAULT);
    }else{
        return "";
    }
}

private String convertListToStringToSave(ArrayList<myClasses.Shape> myList){
    ByteArrayOutputStream b = new ByteArrayOutputStream();
    ObjectOutputStream out;
    try {
        out = new ObjectOutputStream (b);
        out.writeObject(myList);
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    return convertByteArrayToSave(b.toByteArray());
}

Then in the WCF service I'm trying to take the Base64 string and deserialize it to the List(Of Shape) and serialize that to insert it into the database.
    Private Function ConvertAndroidByteToDotNet(ByVal s As String) As Byte()
    Dim result As Byte() = Nothing
    Dim b As Byte() = CType(System.Convert.FromBase64String(s), Byte())
    Dim msTest As New MemoryStream(b)
    msTest.Seek(0, SeekOrigin.Begin)
    msTest.Position = 0
    Dim formatter As New Runtime.Serialization.Formatters.Binary.BinaryFormatter()
    formatter.AssemblyFormat = Runtime.Serialization.Formatters.FormatterAssemblyStyle.Simple
    formatter.Binder = New BindChanger()
    Dim shapelist As List(Of ColbyDataTypes.Shape) = DirectCast(formatter.Deserialize(msTest), List(Of ColbyDataTypes.Shape))
    msTest.Close()

    Dim bin As New Runtime.Serialization.Formatters.Binary.BinaryFormatter()
    bin.AssemblyFormat = Runtime.Serialization.Formatters.FormatterAssemblyStyle.Simple
    bin.Serialize(msTest, shapelist)

    result = msTest.ToArray()

    Return result
End Function

The ultimate goal is to be able to be able to create a list of these shapes in the .NET app or android app and be able to read the list in the .NET app and android app no matter where it was created from. I'm able to it when you create the Shape from .NET and read it into android using WCF but creating it in android is where I'm stuck. I really appreciate any help, thanks.

A: I would choose JSON data format, and GSON to parse the objects in android side. It's very simple and lightweight to use. Check this consuming web service from android using JSON or this JSON parse , hope this help.


text:
Q: Compiling a C program without Main I have a simple C program I have to make (Which can't use a main function).
As such:
test.c
#include <stdio.h>

int getUserID(int id);

int getUserID(int id) {
    return 0;
}

Where my current function does nothing as of now:
However, I'm trying to compile this through a makefile, as such:
all:
    gcc test.c

Which didn't work because I didn't have a main so then I added the -c command within it.
all:
    gcc -c test.c

Which now compiles with make, but gives me an object file (but without a working executable), the executable I get when I try to run it: i.e ./test tells me permission denied
Any help would be greatly appreciated.

A: You cannot have a C++ or C program without a main (without evil, non-standard hacks at least). You can build a library without a main, but not a standalone executable.
For standalone applications, the main function is crucial because it defines where to start execution.

A: You can create an image where "main" is not the entry point.
Here is one such way (using gcc on a RHEL6 system):
$ cat sample.c
#include <stdio.h>
#include <unistd.h>

int notmain ( void ) {
        printf("hello, world\n");
        exit(0);
}
$ cc -ffreestanding -c sample.c
$ ld -enotmain -o sample sample.o -I/lib64/ld-linux-x86-64.so.2 -lc
$ ./sample
hello, world

And, BTW, this is not an "evil, non-standard hack" -- the C Standard defines two execution environments: (1) "hosted", which is the one most people are familiar with, and (2) "freestanding", which is typically some sort of embedded system (a toaster or whatnot).

A: You can separately compile this c file into an object file, but it will need to be linked with another object file containing the main function to become an executable program.
If you are not allowed to have a main function in this file, there must be another file you are expected to link with it.

redpajama_set_name: RedPajamaStackExchange


text:
Q: beautifulsoup creates an incomplete result? I want beautifulsoup to parse a page from lexico dictionary
what I want to parse is the content under this tag ul
screenshot of the tag
This (sorry for the wot) is the result that
url = 'https://www.lexico.com/definition/iron'
req = requests.get(url)
soup = BeautifulSoup(req.text, 'lxml')
semb = soup.find('ul', attrs={'class':'semb'})
print(semb)

should give(I think)
However, the code here gives this (sorry again)
It seems that bs stops parsing for some reason in the middle of the second li tag. It doesn't seem anything related to javascript to me, am I wrong? Thanks anyone.
Beautifulsoup version: 4.11.1
Python: 3.9.12

A: Since you want just the definitions, try the following, which will get all of the definitions under each grammar type (in the example page linked, it will get the noun and verb definitions)
import requests
from bs4 import BeautifulSoup

url = 'https://www.lexico.com/definition/iron'
req = requests.get(url)
soup = BeautifulSoup(req.text, 'lxml')  #I used html.parser as I didn't have lxml installed but either should work
definitions = soup.find_all("span", class_='ind one-click-content') # note the keyword is class_ because class is reserved.

# This gave us a list of all the <spans> containing the definitions.

for n, d in enumerate(definitions, start=1):
    print(f"{n}. {d.text}")

OUTPUT:
 1. A strong, hard magnetic silvery-grey metal, the chemical element of atomic number 26, much used as a material for construction and manufacturing, especially in the form of steel.
 2. Used figuratively as a symbol or type of firmness, strength, or resistance.
 3. A tool or implement now or originally made of iron.
 4. Metal supports for a malformed leg.
 5. Fetters or handcuffs.
 6. Stirrups.
 7. A handheld implement, typically an electrical one, with a heated flat steel base, used to smooth clothes, sheets, etc.
 8. A golf club with a metal head (typically with a numeral indicating the degree to which the head is angled in order to loft the ball)
 9. A shot made with an iron.
 10. A meteorite containing a high proportion of iron.
 11. Smooth (clothes, sheets, etc.) with an iron.
 12. Firmness or ruthlessness cloaked in outward gentleness.
 13. Have a range of options or courses of action available, or be involved in many activities or commitments at the same time.
 14. Have other options or courses of action available, or be involved in other activities or commitments at the same time.
 15. Having the feet or hands fettered.
 16. (of a sailing vessel) stalled head to wind and unable to come about or tack either way.
 17. Solve or settle difficulties or problems.

If you want to get the definitions for the different parts of grammar separately, that would be possible too.  Use find_all to get all  with class "semb" and then use find_all on each of those to get the spans as above, and also extract the labels for whichever section it is.


text:
Q: narrowing why server post from perl web app fails on ec2 Update: I corrected the below permission issue and I can read the log files dancer generates. There was a small code bug, fixed. So now the logs display nothing, but my POST request still just fails silently! :'(
Update 2 : I fixed it by just giving write permissions to /srv/www/domain.com/MyApp/logs
I have:

*

*An amazon-ec2 instance with the Amazon Linux AMI.

*It has apache2, running a perl dancer app on cgi as described here.

I have code doing OAuth with github API. Works perfect well on my machine but the final POST fails on amazon.
This may seem like a dev question, but I'm a beginner with linux sysadmin and I want clues as to how I should narrow my problem down.
This is my code:
my $browser                = LWP::UserAgent->new;
#alteast from the browser, seems like this POST never happens.
my $resp                   = $browser->post($github_post_url,
[
 client_id                  => $client_id,
 client_secret              => $client_secret,
 code                       => $code,
 state                      => $state
]);
die "error while fetching: ", $resp->status_line
unless $resp->is_success;

my %querystr = parse_query_str($resp->decoded_content);
my $acc = $querystr{access_token};

if($acc) {
        #code to retrive access token...
    redirect $github_auth_success;
    return;
}
    return redirect "/fail";#<<< THIS HAPPENS

The logs from here (tail /srv/www/domain.com/logs/error.log ) for this app say:

log directory /srv/www/domain.com/MyApp/bin/.. isn't writable/executable and can't chmod it at /usr/local/share/perl5/Dancer/Logger.pm line 16.

But my /bin directory IS writable! And executable for everyone!

*

*How do I figure what is really happening here? Do I look at some other log somewhere?

*Could amazon-ec2 be blocking the outgoing post? There doesn't seem to be any outbound rule I can set in the security groups?

A: ls -al /srv/www/domain.com/MyApp/
What are the permissions set to on the bin directory?
Whatever user is running your perl script needs to have read/write access to that log directory.
You can chmod the directory (literally 'change mode') like so chmod +600 /srv/www/domain.com/MyApp/bin
It's better to put your log directory somewhere expected like /var/log/MyApp but that's beside the point. 'var' is for 'variable data', like logs. ;-)


text:
Q: If web application and SQL Server are on different machines on intranet, can Windows anthentication still be used? If web application and SQL Server are on different machines(both running Windows) on intranet, can Windows anthentication still be used to access SQl Server or SQL authentication mode need to be used?

A: Yes, you can still use Windows Authentication. But how you do so depends on whether the web application forces Windows auth, or if it allow anonymous access and you've set the application itself to connect as a specific domain account.

A: The web application server will be able to use Integrated Security (Windows Authentication) to access the SQL server if they are both part of the same Active Directory.  If they're not, you'll need to use mixed mode.


text:
Q: How to pass the unquoted name of a variable (and not its value) into a function dynamically? I wish to write a function to analyze several identical variables in several datasets
I built the function below but it does not work well. I am not sure how to pass a name in a function dynamically. Could someone help?
There are 10 identical variables (testvar1, testvar2,..., testvar10, etc...)
in 15 different datasets (mydata1, mydata2,...mydata15, etc...)
library(readxl)

to_analyze <- function (data="mydata1", var = testvar1) {

  #reading my file in
  excelfile <- paste(`data`, "xlsx", sep = ".")
  dataset_name <- read_excel(excelfile)

  #populating the testvar1, testvar2,...
  dataset_name$var_interest <-  dataset_name$var #this does not work
  #I was hoping it would give dataset_name$var_interest <- dataset_name$testvar1

  #creating a smaller dataset
  eco <- dataset_name %>%
    select(id, var_interest) #I want var_interest to be testvar1 (not the value but the name)

  ##doing some analysis on that dataset
}

#creating another function for all the datasets (15 total)

fct_all <- function(x){
  for(i in 1:15){
    iq <- as.double(i)
    dsn <- paste("mydata", deparse(iq), sep="")
    to_analyze(data=dsn, var = x)
  }
}

#applying the function for all the variables

all_var <- c(testvar1, testvar2, testvar3)
fct_all(all_var)```

A: You can use equivalently data$var1 or data[['var1']]. Which means that with the second form, as you provide the variable name as a string, you can easily replace the string by a dynamical variable name :
var <- 'var1'
dataset_name$var_interest <- dataset_name[[var]]

Note that dplyr is very clever and does accept string or symbols. Which means you can further simplify your function with one of the following forms :
library(dplyr)

# Using select then rename with the var given as a string
to_analyze <- function (data = "mydata1", var = "testvar1") {
  eco <- paste(data, "xlsx", sep = ".") %>%
    read_excel() %>%
    select(id, var) %>%
    rename(var_intereset = var)
  ...
}

For the sake of interest, you could also use quasiquotation, but given that you'll eventually wrap your variables into a vector, I guess it's not that useful. Would be something of the form :
library(dplyr)

to_analyze <- function (data = "mydata1", var = quo(testvar1)){
  quo_var <- enquo(var)
  eco <- paste(data, "xlsx", sep = ".") %>%
    read_excel() %>%
    select(id, !!quo_var) %>%
    rename(var_intereset = !!quo_var)
  ...
}

This form allows you to call your variable with the raw variable name rather than a string : to_analyse(data = "mydata1", var = testvar1). But as said before, probably not the most useful in your case.

A: Thank you @Romain. Your code worked well. I just changed the single quote to backticks
var <- `var`

to_analyze <- function (data = "mydata1", var = "testvar1") {
  eco <- paste(data, "xlsx", sep = ".") %>%
    read_excel() %>%
    select(id, var) %>%
    rename(var_intereset = var)
  ...
}


text:
Q: Removing objects from array based on two properties I have an array that contains custom objects that look like this:
{
    field: fieldName,
    dataType: usuallyAString,
    title: titleForLocalization,
    environmentLabel: environmentName
}

There are a couple of other properties on the object, but the only ones that I actually care about are field and environmentLabel. I need to filter out any objects that have identical field and environmentLabel but don't care about any other properties. The array can have objects that share field or environmentLabel, just not both.
Ideally I'd like to use Array.filter but have yet to figure out how to do it based on two properties. Also, I am limited to es5.

A: Create another object that contains all the combinations of properties you want to test. Use filter() and test whether the pair already exists in the object. If not, add the properties to the other object and return true.
var seen = {};
newArray = array.filter(function(obj) {
    if (seen[obj.field]) {
        if (seen[obj.field].includes(obj.environmentLabel) {
            return false;
        } else {
            seen[obj.field].push(obj.environmentLabel);
        }
    } else {
        seen[obj.field] = [obj.environmentLabel];
    }
    return true;
});

A:

const data = [{
    field: 1,
    dataType: "usuallyAString",
    title: "titleForLocalization",
    environmentLabel: 1
},
{
    field: 1,
    dataType: "usuallyAString",
    title: "titleForLocalization",
    environmentLabel: 1
},
{
    field: 2,
    dataType: "usuallyAString",
    title: "titleForLocalization",
    environmentLabel: 2
}]

var result = _.uniqWith(data, function(arrVal, othVal) {
  return arrVal.field=== othVal.field && arrVal.environmentLabel=== othVal.environmentLabel;
});

console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>

If you are able to use lodash, you can do:
var result = _.uniqWith(data, function(arrVal, othVal) {
  return arrVal.field=== othVal.field && arrVal.environmentLabel=== othVal.environmentLabel;
});

console.log(result)


text:
Q: IntelliJ Community Edition - How to import an Eclipse project? There seems to be no eclipse support in the IntelliJ Community Edition. Do you know a smart way to import an eclipse project into IntelliJ Community Edition?
See also http://blogs.jetbrains.com/idea/2009/10/intellij-idea-open-sourced/

A: Please see the IntelliJ IDEA Editions Comparison. Eclipse project interoperability is listed as available for both editions. It's not available in the first preview release because of the bug in our build subsystem. The updated build with Eclipse import support will be published later today. Sorry for the inconvenience.

A: Use Maven, stop relying on IDEs.

A: You can do it with the paid edition without any problem.  You'll see the option to do so when you first open IntelliJ.  If it's not there, perhaps they left it out of the community edition.


text:
Q: Content of some windows degrade over time I have the following setup:

*

*Motherboard: AS Rock

*CPU: Ryzen 9 3900X

*GPU: NVIDIA GeForce GTX 1650

*Memory: 32Gb

*SSD 1Tb Samsung 970 EVO Plus

*OS: Windows 11 Pro

*Display: Samsung C49RG9xSS

*Resolution: 5120 x 1440

I have a problem with some of the windows degrading over time (blurring). Below is an example:

I've tried resetting all NVIDIA settings to the default.
Switch on/off:

*

*Scaling

*HDR

*G-Sync

*Hardware Accelerated GPU Scheduling

Nothing seems to change anything. Help appreciated.
Apps in which this is happening are:

*

*WhatApp

*Loxone (example images)


text:
Q: Overriding ActiveRecord Column Methods with a Mixin I'm trying to make it so that I can configure some columns to always convert to a different timezone based on user settings. I'd like the config to be like:
class MyClass
  include TimeZonify
  tz_column :col1, :col2
end

My mixin is obviously incorrect but it looks something like this:
module TimeZonify
  def self.included(base)
    base.extend(ClassMethods)
  end

  module ClassMethods

    def tz_column(*columns)
      columns.each do |column|
        instance_eval do   # <-- obviously this block does not get executed
          <<-CODE
            def #{column}
              super.in_time_zone("Lima")
            end
          CODE
        end
      end
    end

  end

end

So now, when I call MyClass.new.col1, it will no longer be in UTC, but instead in whatever timezone the user has in their profile.

A: If you are using Rails, then time zone support must work out of the box. And you can have different time zone for each user.

I would not recommend to override the date/time method accessors because then you will also need to override the setter.
If you will not, following will result in invalid result every time it is executed (for example, on update).
original = it.effective_at
it.effective_at = it.effective_at # it +TimeZone
it.effective_at = it.effective_at # it +TimeZone
original == it.effective_at # => false - every assignment actually changes the time by +TimeZone

But if you need a shortcut for display purposes, instead I would recommend to use an extension to this method:
it.effective_at_local
which can be implemented with the mixin:
module TimeZonify
  def self.included(base)
    base.extend(ClassMethods)
  end

  module ClassMethods

    def tz_column(*columns)
      columns.each do |column|
        instance_eval do
          <<-CODE
            def #{column}_local
              #{column}.in_time_zone("Lima")
            end
          CODE
        end
      end
    end

  end

end

BTW, on the related note you can use TimeZone.


text:
Q: Get (1, 2, 3, 4, 2, 3, 4, 3, 4, 4) from (1, 2, 3, 4) in R I have vector
z1 <- c(1, 2, 3, 4)

and want to get from it another vector
z2 <- c(1, 2, 3, 4,
           2, 3, 4,
              3, 4,
                 4)

I've tried different variants of rep() function, but get only this
z3 <- rep(z1, times=seq(length(z1), 1))

z3 <- c(1, 1, 1, 1,
           2, 2, 2,
              3, 3,
                 4)

Also z2 get be done with for() loops
temp <- z1
res <- c()

for (i in 1:length(z1)){

    res <- c(res, temp)
    temp <- temp[-1]

}

res <- c(1, 2, 3, 4,
            2, 3, 4,
               3, 4,
                  4)

But is there any ways to transform z1 to z2 with one string built-in functions like rep()?

A: You can try sapply + unlist + tail like below
> unlist(sapply(-seq_along(z1), tail, x = c(NA, z1)))
 [1] 1 2 3 4 2 3 4 3 4 4

A: c(z1, unlist(lapply(1:length(z1), function(x) z1[-c(1:x)])))
[1] 1 2 3 4 2 3 4 3 4 4

A: Edit: updating post to account for an ordered solution
Populate a matrix by repeating every value the maximum number of times. Then take the lower triangle of the matrix. Note: using length(z1) in this case so that the values are note required to be integers, use max(z1) instead if that value would make sense.
z2 <- matrix(data = rep(z1, times = length(z1)), ncol = length(z1), byrow = FALSE)
z2

Resulting matrix
     [,1] [,2] [,3] [,4]
[1,]    1    1    1    1
[2,]    2    2    2    2
[3,]    3    3    3    3
[4,]    4    4    4    4

Subset the matrix using lower.tri to extract the lower triangle and the diagonal
z2 <- z2[lower.tri(z2, diag = TRUE)]
print(z2)

Result
[1] 1 2 3 4 2 3 4 3 4 4

Previous partial solution (for an unordered solution)
Use lapply to iterate through the vector, with each iteration, repeat each element the desired number of times using rep, and then unlist the result to turn it into a vector
 z1 <- c(1, 2, 3, 4)
 z2 <- unlist(lapply(z1, function(x) rep(x, times = x)))
 print(z2)

Result
 [1] 1 2 2 3 3 3 4 4 4 4

A: Base R using eval parse:
z1 <- c(1, 2, 3, 4)
max_num <- max(z1)
unlist(lapply(paste(z1, max_num, sep = ":"), function(x){
      eval(parse(text=x))
    }
  )
)


text:
Q: How to prove $4\mid n$? How to prove that $4\mid n$ ?
We know
$$\frac{x_1}{x_2}+\frac{x_2}{x_3}+\cdots+\frac{x_{n-1}}{x_n}+\frac{x_n}{x_1}=0.$$
and $x_1,x_2,\cdots,x_n$ is $1$ or $-1$.

A: Hint: what happens when you change the sign of just one of the $x_i$?

A: All the $x_i/x_j$'s in the sum is 1 or -1. Therefore you need an even number of them to make the sum 0, since every time you have a 1 you must have another -1 to cancel it out and vice versa. Multiplying toghether all the $x_i/x_j$'s, you get 1. So an even number of $x_i/x_j$'s equal -1. Then since there are as many $x_i/x_j$'s equal to 1 as $x_i/x_j$'s equal to -1, $n$ is twice that even number, hence divisible by 4.

A: Prove using induction that $|x_i|=|x_j|\neq0, \ \ \forall  \ i,j\Longrightarrow\frac{x_1}{x_2}+\frac{x_2}{x_3}+\cdots+\frac{x_{n-1}}{x_n}+\frac{x_n}{x_1}\equiv n \pmod 4:$
$$\frac{x_1}{x_2}+\frac{x_2}{x_3}+\cdots+\frac{x_{n-1}}{x_n}+\frac{x_n}{x_1}=\\
\frac{x_1}{x_2}+\frac{x_2}{x_3}+\cdots+\frac{x_{n-1}}{x_1}+\left(\frac{x_{n-1}}{x_n}+\frac{x_n-x_{n-1}}{x_1} \right)\equiv \\ \equiv n-1 +\frac{x_{n-1}}{x_n}+\frac{x_n-x_{n-1}}{x_1} \pmod 4\equiv \\ (\text{cases }x_{n-1}=\pm x_n)\equiv n \pmod 4.$$

A: Let $x_i = (-1)^{a_i}$, where $a_i \in \{0, 1\}$. We are given:
$$\sum_{\text{cyclic}} (-1)^{a_i + a_{i+1}} = 0$$
Note that $(-1)^{x} = 1-2x$ for $x \in \{ 0,1\}$. Hence we always have
$$\sum_{\text{cyclic}} (-1)^{a_i + a_{i+1}}  = n - 2 \sum_{\text{cyc}} ((a_i + a_{i+1}) \mod 2)$$
Thus
$$n = 2 \sum_{\text{cyc}} ((a_i + a_{i+1}) \mod 2)$$
Since $\sum_{\text{cyc}} ((a_i + a_{i+1}) \mod 2) = 2\sum a_i = 0 \mod 2$, we deduce that $n$ is divisible by $4$. We also find that in general, $\sum \frac{x_i}{x_{i+1}} \equiv n \mod 4$.


text:
Q: Rendering Shiny ggplot chart output after gather() I am trying to build a ggplot output for Shiny.
I gathered my initial data frame with gather() into tidy format.
               variable             value
1                Region            Africa
2                Region            Europe
3                Region           Europe
4                Region     Latin America
13              Country             Sudan
14              Country            Russia
15              Country    United Kingdom
16              Country              Peru
17              Country          Malaysia
35              Client              Bank
36              Client              Bank2
37              PG                  PG 1
38              PG                  PG 2
54                Status              High
55                Status            Signed
56                Status               Low

Now I am trying to create a simple chart, where change of variable should lead to changes of plot.
 # UI code

 ui <- fluidPage(theme = shinytheme("united"),
            sidebarLayout(
              sidebarPanel(
                           selectInput("dataInput", "Choose to filter by:",
                                       choices = c("Region",
                                                   "Country",
                                                   "Client",
                                                   "PG",
                                                   "Status"),
                                       selected = "Choose to display by")
              ),

              mainPanel(

                # Output
                tabsetPanel(type = "tabs",
                            # tabPanel("Map", leafletOutput(outputId = 'map', height = 850)),
                            tabPanel("Plot",  plotOutput("plot", height = 850)))
                )
              )
            )

My server looks like this
 server <- function(input, output) {

 # 1. Select among columns
 selectedData <- reactive({

 data_pg_df1[!is.na(data_pg_df1$variable) & data_pg_df1$variable == input$dataInput, ]
 })

 # Output
 output$plot <- renderPlot({
ggplot(data_pg_df1, aes(selectedData)) + geom_bar()
 })

 }
 shinyApp(ui = ui, server = server)

I receive an error
Don't know how to automatically pick scale for object of type reactiveExpr/reactive. Defaulting to continuous.
Warning: Error in : Column x must be a 1d atomic vector or a list
Tried to resolve, but failed.
Is my approach for ggplot correct? Or I need also add "value" column to data input.  I do not think so, because I want to select based on "variable" only.
What am I missing?
My desired output looks like this. I have it with the eval(), but would like to do in a tidy way, described above.
output$plot <- renderPlot({
  eval(parse(text = paste0("ggplot(data_pg_df, aes(x=",input$dataInput,")) + geom_bar()"  )))
})

A: Your problem lies in how you retrieve object from reactive.
You can try something like:
output$plot <- renderPlot({
data <- selectedData()
ggplot(data_pg_df1, aes(data)) + geom_bar()
})

See here for reactive helps and here for SO related question.
Careful also with ggplot2 syntax...


text:
Q: QListView with CustomWIdget using QStyledItemDelegate I'm trying to create a QListView with QStyledItemDelegate to show data more organizing way.
I gone through this site, and its all in C++, and I have no idea about it, guessing from the syntax and calls which has been used in the post, I tried my way to achieve it, but I had not luck. Can someone please help me out with this?
import sys, os

from PyQt4 import QtGui, QtCore

class ListView(QtGui.QListView):
    def __init__(self, parent=None):
        super(ListView, self).__init__(parent)

        self._model = None
        self._data = [
                        [
                        'Header: King Arthur',
                        'Project: TBN',
                        'Asset: arthur',
                        'Task name: Design doc',
                        'Start Date: Today',
                        'End Date: Next Monday'
                        ]
                    ]
        self.set_model()
        item_delegate = ItemDelegate()
        self.setItemDelegate(item_delegate)
        self.openPersistentEditor(self._model.createIndex(0, 0))

    def set_model(self):
        self._model = ListModel(self._data, parent=self)
        self.setModel(self._model)

class ListModel(QtCore.QAbstractItemModel):
    def __init__(self, data=[], parent=None):
        super(ListModel, self).__init__(parent)
        self._data = data

    def rowCount(self, *arg):
        return 1

    def columnCount(self, *arg):
        return len(self._data)

    def data(self, index, role):
        row = index.row()
        column = index.column()

        if role == QtCore.Qt.DisplayRole:
            return QtCore.QVariant(' | '.join(self._data[column]))

        return QtCore.QVariant()

    def index(self, row, column, parent):
        return self.createIndex(row, column)

    def parent(self, index):
        item = index.internalPointer()
        if item:
            return item.getParent()
        else:
            item = self.createIndex(index.row(), index.column()).internalPointer()
            if item:
                return item.getParent()

        return QtCore.QModelIndex()

class ItemDelegate(QtGui.QStyledItemDelegate):
    def createEditor(self, parent, option, index):
        item_data = str(index.data().toString())
        editor = Widget(item_data.split('|'), parent=parent)
        return editor

    def updateEditorGeometry(self, editor, option, index):
        editor.setGeometry(option.rect)

class Widget(QtGui.QWidget):
    def __init__(self, widget_data=[], parent=None):
        super(Widget, self).__init__(parent)

        vbox = QtGui.QVBoxLayout(self)
        key_font = QtGui.QFont()
        key_font.setWeight(QtGui.QFont.Bold)
        val_font = QtGui.QFont()
        val_font.setWeight(QtGui.QFont.Normal)

        for each_data in widget_data:
            hbox = QtGui.QHBoxLayout()
            key, value = each_data.split(':')
            key_text = QtGui.QLabel(self)
            val_text = QtGui.QLabel(self)

            key_text.setToolTip('Key: %s' % key)
            val_text.setToolTip('Value: %s' % value)

            key_text.setText(key)
            val_text.setText(value)

            key_text.setFont(key_font)
            val_text.setFont(val_font)

            hbox.addWidget(key_text)
            hbox.addWidget(val_text)
            # vbox.addLayout(hbox)

if __name__ == '__main__':
    qapp = QtGui.QApplication([])
    app = ListView()
    app.show()
    sys.exit(qapp.exec_())

A: Unless you have a compelling reason to use the View/Model pattern, in most cases it's going to be easier to use the Widget/Item pattern -- QListWidget and QListWidgetItem.
The QItemDelegate and QStyledItemDelegate are designed to be subclassed.  You then define methods that are responsible for handling events, sizing, and painting the views/widgets.
class MyWidget(QtGui.QWidget):

    def __init__(self, parent):
        super(MyWidget, self).__init__(parent)
        self.listwidget = QtGui.QListWidget(self)
        self.delegate = MyDelegate(self, self.listwidget)
        self.listwidget.setItemDelegate(self.delegate)

        datas = [
            {'Header': 'Blah', 'Project': 'TBN'},
            {'Header': 'Other', 'Project': 'Something'},
        ]
        for data in datas:
            MyItem(self.listwidget, data)

class MyItem(QtGui.QListWidgetItem):

    def __init__(self, parent, data):
        super(MyItem, self).__init__(parent)
        self._data = data

class MyDelegate(QtGui.QStyledItemDelegate):

    def __init__(self, parent, listwidget):
        super(MyDelegate, self).__init__(parent)
        self.listwidget = listwidget

    def sizeHint(self, option, index):
         if index:
             item = self.listwidget.itemFromIndex(index)
             print item._data
             # Do fontmetrics stuff from C++ article you linked
             # using the text in the data dictionary.

    def paint(self, painter, option, index):
        # same thing, get the item using the index
        # get the data from the item
        # paint the data however you want.

A: class ItemDelegate(QtGui.QStyledItemDelegate):
    def createEditor(self, parent, option, index):
        item_data = str(index.data().toString())
        editor = Widget(item_data.split('|'), parent=parent)
        return editor

    def updateEditorGeometry(self, editor, option, index):
        editor.setGeometry(option.rect)

    def paint(self, painter, option, index):
        painter.save()
        index.model().setData(index, option.rect.width(), Qt.UserRole+1)

fixed this issue


text:
Q: How to use multi devise model for rails_admin I have two devise models, user and admin, When user and admin login through login form, then will redirect to /admin
I have read the rails_admin wiki, but it seems just about configuration about single devise model, Can I define multi warden scope like following:
RailsAdmin.config do |config|
  config.authenticate_with do
    warden.authenticate! scope: [:user,:admin]
  end
  config.current_user_method(&:current_user)
  config.current_admin_method(&:current_admin)
end

A: You can add more than one devise model. Here is an example (with a checksum authentication):
# initilizer/devise.rb
Devise.setup do |config|
  config.warden do |manager|
    manager.strategies.add :admin, Admin::ChecksumAuthenticatable
  end
end

You class Admin::ChecksumAuthenticatable (for example) needs to inherit from ::Devise::Strategies::Base. Then define all methods you want and overwrite authenticate! method:
def authenticate!
  admin = Admin.from_checksum_for_auth!(checksum)
  # from_checksum_for_auth! is defined on Admin model and check checksum validity
  success! admin
end


text:
Q: Exporting a mySQL database out of Microsoft Webmatrix I am trying to deploy a WordPress site that was created on localhost with Microsoft Webmatrix, to a server that runs PHPmyadmin. I can copy the files over, however I'm having trouble with the mySQL database. As far as I can tell I need to export the database from Webmatrix and then import it with PHPmyadmin on the server.
I can see the mySQL database when I'm editing the site in Webmatrix, but I can't see how to export it. The instructions that I've read say to click migrate, however that button is greyed out for me. I tried to create a new database and ended up with a .sdf file (that I can migrate) however it is empty and I can't copy my actual database over to it as far as I can see. I'm running out of things to try. Any help appreciated.


text:
Q: Height issue with Facebook Embed Post I am using the FB Post Embed. On initial load the posts are shown up. But if I add a new post and then call an ajax postback, after postback all the posts are not shown.I checked the documentation it mentioned to call FB.XFBML.parse() method, i called that but it still didn't work. While looking into the the code I saw that the height and width of the span that FB returns back and iframe inside the span is set to 0 and overflow hidden. The fb:post code is shown up here:

A: I was able to resolve this issue. The issue was that I have kept the inside my container div tag using $("#container").prepend("");. The container div tag was getting emptied and refilled using $("#container").empty();, that's why the height width were getting 0. I updated the code to keep the fb-root outside of the container using $("#container").parent().prepend("");


text:
Q: In pandas, what would be the idiomatic way to select multiple columns based on different patterns? I'm trying to replicate some of R4DS's dplyr exercises using Python's pandas, with the nycflights13.flights dataset. What I want to do is select, from that dataset:

*

*Columns through year to day (inclusive);

*All columns that end with "delay";

*The distance and air_time columns

In the book, Hadley uses the following syntax:
library("tidyverse")
library("nycflights13")

flights_sml <- select(flights,
   year:day,
   ends_with("delay"),
   distance,
   air_time
)

In pandas, I came up with the following "solution":
import pandas as pd
from nycflights13 import flights

flights_sml = pd.concat([
    flights.loc[:, 'year':'day'],
    flights.loc[:, flights.columns.str.endswith("delay")],
    flights.distance,
    flights.air_time,
], axis=1)

Another possible implementation:
flights_sml = flights.filter(regex='year|day|month|delay$|^distance$|^air_time$', axis=1)

But I'm sure this is not the idiomatic way to write such DF-operation. I digged around, but haven't found something that fits in this situation from pandas API.

A: You are correct. This will create multiple dataframes/series and then concatenate them together, resulting in a lot of extra work. Instead, you can create a list of the columns you want to use and then simply select those.
For example (keeping the same column order):
cols = ['year', 'month', 'day'] + [col for col in flights.columns if col.endswith('delay')] + ['distance', 'air_time']
flights_sml = flights[cols]

A: According to the dataset's columns info, we can utilize str.contains
df.loc[:, df.columns.str.contains('year|month|day|delay|distance|air_time')]

   year  month  day  dep_delay  arr_delay  air_time  distance
0  2013      1    1        2.0       11.0     227.0      1400
1  2013      1    1        4.0       20.0     227.0      1416
2  2013      1    1        2.0       33.0     160.0      1089
3  2013      1    1       -1.0      -18.0     183.0      1576
4  2013      1    1       -6.0      -25.0     116.0       762

A: One option is with select_columns from pyjanitor:
# pip install pyjanitor
import pandas as pd
import janitor
from nycflights13 import flights

flights_sml = flights.select_columns(
                          slice('year', 'day'),
                          '*delay',
                          'distance',
                          'air_time'
                       )

flights_sml.head()
   year  month  day  dep_delay  arr_delay  distance  air_time
0  2013      1    1        2.0       11.0      1400     227.0
1  2013      1    1        4.0       20.0      1416     227.0
2  2013      1    1        2.0       33.0      1089     160.0
3  2013      1    1       -1.0      -18.0      1576     183.0
4  2013      1    1       -6.0      -25.0       762     116.0


text:
Q: Create multipart file upload from Uint8ClampedArray via fetch I crafted a binary file in the Browser in JavaScript as Uint8ClampedArray and now need to upload it to a webserver as if it was chosen from a file-picker.
I tried this:
var data = new Uint8ClampedArray(32);
data[0] = 0x42;
data[1] = 0x4D;
postdata = new FormData();
postdata.append('data', new Blob(data), 'test.txt');
fetch('http://localhost/',{
    method: 'POST',
    body: postdata
});

But it creates this request:
POST / HTTP/1.1
content-length: 230
content-type: multipart/form-data; boundary=----WebKitFormBoundaryfsPRCG3QGnD2bWZS

------WebKitFormBoundaryfsPRCG3QGnD2bWZS
Content-Disposition: form-data; name="data"; filename="test.txt"
Content-Type: application/octet-stream

6677000000000000000000000000000000
------WebKitFormBoundaryfsPRCG3QGnD2bWZS--

And thus this Textfile :(
6677000000000000000000000000000000

How do I create a valid binary Blob()?
Thx!

A: try this way,
var data = new Uint8ClampedArray(32);
data[0] = 0x42;
data[1] = 0x4D;
postdata = new FormData();

// Blob constructor takes an Array. so you need provide `[data]` not `data`
postdata.append('data', new Blob([data], {type: "text/plain"}), 'test.txt');

fetch('http://localhost/',{
    method: 'POST',
    body: postdata
});


text:
Q: java ProcessBuilder doesn't work right with Imagemagick on windows I'm using im4java to call imagemagick from a grails app.  The command line I'm trying to get it to use is
convert "c:\ZonesG\web-app\spresources\summarypage_images\00\09\18\myimage.jpg" -resize 100x100 "c:\ZonesG\web-app\spresources\summarypage_images\00\09\18\myimage_thumbnail100.jpg"
or
convert c:\ZonesG\web-app\spresources\summarypage_images\00\09\18\myimage.jpg -resize 100x100 c:\ZonesG\web-app\spresources\summarypage_images\00\09\18\myimage_thumbnail100.jpg
The args passed to ProcessBuilder look correct.  There are 5 separate Strings as follows.
convert
c:\ZonesG\web-app\spresources\summarypage_images\00\09\18\myimage.jpg
-resize
100x100
c:\ZonesG\web-app\spresources\summarypage_images\00\09\18\myimage_thumbnail100.jpg
I get an error that the -resize parameter is not valid when I run it through processbuilder. That makes it seem as if it is calling the convert function, but something has happened to the parameters so that it no longer recognizes them.  It's not the hypens in the directories.  I tried it to different directories and it still doesn't work.
When I run it from the command line it works perfectly.
I've tried adding double quotes around the two file names.  Again it works great in the command window but doesn't work from the java code.
Any Ideas?

A: Thanks for your comment Jonathan,
Meanwhile, I discovered what was happening.

*

*The order of the args mattered more when calling from the ProcessBuilder.  I changed it so that the resize and geometry are first and the input image file is next.  That made it work.

A: I had this error too. It is actually because it is running a program from Microsoft in Windows called "convert". To get im4java to run the correct you need to make an environment variable. Eg: IM4JAVA_TOOLPATH=C:\Program Files (x86)\ImageMagick-6.6.4-Q16\


text:
Q: Vue cant watch object property setted inside for loop I would like to set a object property inside a for-loop, and watch for those changes, but somehow Vue simply doesn't listen to all changes on the watch prop.
Here is my test code to simplify my issue (https://jsfiddle.net/hn2wepc9/).
If you click on the button, it should log 5 lines in the console (because of the loop method), but it only logs 1. I don't understand why Vue simply doesnt listen to all changes when I use Vue.set() inside a for loop and try to watch these changes.
<div id="app">
  <button @click="loop">Button</button>
</div>

new Vue({
  el: '#app',
  data: () => {
    return {
          obj: {
            name: 'John Doe'
        }
     }
  },
  methods: {
    loop() {
      for (let i = 0; i < 5; i++) {
        Vue.set(this.obj, 'name', 'Dohn Joe ' + i);
      }
    }
  },
  watch: {
    obj: {
      deep: true,
      handler(newVal, oldVal) {
        window.console.log(newVal.name + ' - ' + new Date().toLocaleString());
      }
    }
  }
});

A: By default, watchers are run asynchronously (in the next macro tick) as a performance optimization. I think the motivation is watchers are assumed to only care about the most recent change.
You can configure the watcher to be synchronous by setting the sync flag (one of several undocumented watch flags):
watch: {
  obj: {
    sync: true
  }
}

updated fiddle

For reference, in Vue 3, the flag is called flush with pre, post, and sync as possible values. See Effect flush timing.


text:
Q: Translate ruby to python I'm rewriting some code from Ruby to Python. The code is for a Perceptron, listed in section 8.2.6 of Clever Algorithms: Nature-Inspired Programming Recipes. I've never used Ruby before and I don't understand this part:
def test_weights(weights, domain, num_inputs)
  correct = 0
  domain.each do |pattern|
    input_vector = Array.new(num_inputs) {|k| pattern[k].to_f}
    output = get_output(weights, input_vector)
    correct += 1 if output.round == pattern.last
  end
  return correct
end

Some explanation: num_inputs is an integer (2 in my case), and domain is a list of arrays: [[1,0,1], [0,0,0], etc.]
I don't understand this line:
input_vector = Array.new(num_inputs) {|k| pattern[k].to_f}

It creates an array with 2 values, every values |k| stores pattern[k].to_f, but what is pattern[k].to_f?

A: Try this:
input_vector = [float(pattern[i]) for i in range(num_inputs)]

A: pattern[k].to_f

converts pattern[k] to a float.

A: I'm not a Ruby expert, but I think it would be something like this in Python:
def test_weights(weights, domain, num_inputs):
    correct = 0
    for pattern in domain:
        output = get_output(weights, pattern[:num_inputs])
        if round(output) == pattern[-1]:
            correct += 1
    return correct

There is plenty of scope for optimising this: if num_inputs is always one less then the length of the lists in domain then you may not need that parameter at all.
Be careful about doing line by line translations from one language to another: that tends not to give good results no matter what languages are involved.
Edit: since you said you don't think you need to convert to float you can just slice the required number of elements from the domain value. I've updated my code accordingly.


text:
Q: Sobolev topology on essentially compactly supported Sobolev-"functions" The locally convex space of essentially compactly-supported $p$-integrable "functions" $\operatorname{L}_{\mathrm{comp}}^p(\mathbb{R}^d,\mathbb{R})$ is defined as the set
$$
\bigcup_{n \in \mathbb{N}} \left\{
f \in L^p(\mathbb{R}^d,\mathbb{R}):\, \operatorname{ess-supp}(f)\subseteq [-n,n]^d
\right\},
$$
topologized with the injective limit topology in the category of LCSs with continuous linear maps as morphisms, where the colimit is taken over the injective system $$\left\{L^p(\mathbb{R}^d,\mathbb{R}):\, \operatorname{ess-supp}(f)\subseteq [-n,n]^d\right\}_{n \in \mathbb{N}}.$$
Fix a $k \in \mathbb{N}$, $1\leq p<\infty$ and let $W^{k,p}_{\mathrm{comp}}(\mathbb{R}^d):=W^{k,p}(\mathbb{R}^d) \cap \operatorname{L}_{\mathrm{comp}}^p$.  How are the subspace topologies on $W^{k,p}_{\mathrm{comp}}(\mathbb{R}^d)$ comparable?  Is the subspace topology induced by restricting the subspace topology on $L^p_{\mathrm{comp}}(\mathbb{R}^d,\mathbb{R})$ to $W^{k,p}_{\mathrm{comp}}(\mathbb{R}^d)$ at-least as fine than the one obtained by restricting the Sobolev topology $W^{k,p}$ to $W^{k,p}_{\mathrm{comp}}(\mathbb{R}^d)$?

A: To make my comment an answer: No. To see this, fix a cube $K$ and look at $L^p_K=\{f\in L^p: \text{ ess-supp}(f) \subseteq K\}$. On this space, the $L^p_{comp}$-topology coincides with the $L^p$-topology (this follows from the stricness of the inductive limit) and the $W^{k,p}$-topology is strictly finer on this subspace.


text:
Q: Can one set up a write-through cache with aufs? Say I have a system with two filesystems; one fast, small and unreliable (ie: ec2 ephemeral disk) and one slow, big and reliable (ie: ebs). Can I union mount the two filesystems so that the fast, unreliable FS acts as a write-through cache in front of the slow, reliable FS?

A: You could try brsync. It's just like rsync but between branches.
With a bit of integration with inotify (ex.: if you don't write for 1 minute, launch brsync) or crontab and eventually with some kind of transaction/snapshotting management,
you could get something fast and reliable (take in mind that you could lose some datas if something go down before sync ends).


text:
Q: "error: cannot find symbol HashMap" Trying to create (or rather learn) a HashMap in below fashion :
public class Demo{

     public static void main(String args[]){
        System.out.println("============Starting Hashmap============");

        //hashmap portion
        HashMap<String, Integer> myMap = new HashMap<String, Integer>();

        System.out.println("============Ending Hashmap============");
     }
}

I am using an online complier and have searched a lot, i found that my way of declaration is correct but something else is popping up the errorBelow is the error
Demo.java:8: error: cannot find symbol
                HashMap<String, Integer> myMap = new HashMap<String, Integer>();
                ^
   symbol:   class HashMap
   location: class Demo

   Demo.java:8: error: cannot find symbol
                HashMap<String, Integer> myMap = new HashMap<String, Integer>();
                                                     ^
      symbol:   class HashMap
      location: class Demo

2 errors

What i need help in : m just trying to get the basic of creating a hashmap and inserting some key and value in it, but above error stopped me in very first step.....any help in solving this is appreciated!! :)

A: You need to import the HashMap into the class
import java.util.HashMap;

public class Demo{

      public static void main(String args[]){
        System.out.println("============Starting Hashmap============");

        //hashmap portion
        HashMap<String, Integer> myMap = new HashMap<String, Integer>();

        System.out.println("============Ending Hashmap============");
     }
}

A: you need to import the HashMap to avoid the compile error
import java.util.HashMap;

A: java.util.HashMap<Character, Integer> map = new java.util.HashMap<>();
Use this if you can't import java.util.HashMap;


text:
Q: Using np.einsum to multiply and add two arrays I have two numpy arrays p and s:
p = np.ones((32, 64, 4, 1, 1))
s = np.ones((32, 1, 4, 512, 512))

and I want to do this operation:
x = p * s
x = np.sum(x, axis = 2)

This code describes exactly what I want to do, I want to multiply the arrays and sum them on the axis 2, but this solution has a serious problem, the p * s operation generates an array of shape (32, 64, 4, 512, 512) which takes up a generous amount of memory, and it is not really necessary, because in the next step I use np.sum in axis 2, so the ideal solution would be to multiply and add at the same time directly to the result (32, 64, 512, 512) array. I think it is possible to use np.einsum for this, but I would like some help with that.

A: Indeed, using np.einsum will be much much faster:
p = np.ones((32, 64, 4, 1, 1))
s = np.ones((32, 1, 4, 512, 512))
x = np.einsum('abcde,abcde->abde',p,s)


text:
Q: FB like button doesn't appear I am trying ot get an FB like button on my website. I have the following code for it. But the like button doesn't show.
<fb:like href="https:\dev3.ticketalternative.com/Events/21558.aspx" send="false" width="200" height="55" show_faces="false" fb-xfbml-state="rendered" class=" fb_edge_widget_with_comment fb_iframe_widget">

</fb:like>

A: Seems like you are using the XFBML version. You need this in your body:

and

in your html tag.


text:
Q: something with one openflow controller and two openvswitch I create a network like below
   host1:floodlight controller

                |

         L2 physical switch

                |

           /           \

host2:ovs1                host3:ovs2

every host has one network device
host1:  eno1(192.168.100.101)
host2:  config openvswitch br1(192.168.100.102) with eno1
host3:  config openvswitch br1(192.168.100.103) with eno1
floodlight running on host1: listen on 0.0.0.0:6653
When I don't set the ovs controller on host2 and host3, host2/host3 can ping host1 and host2 can ping host3
when I do set ovs controller on host2(/host3) and not set on host3(/host2), host2/host3 can ping host1 and host2 can ping host3
when I do set ovs controller on host2 and host3, host2 can ping host3, but host2/host3 can not ping host1
After checking the tcpdump on host2/host3, found that the icmp data packet alreay send and recv on eno1:
tcpdump -i eno1 icmp

....192.168.100.102 > 192.168.100.101....

....192.168.100.101 > 192.168.100.102....

....192.168.100.102 > 192.168.100.101....

....192.168.100.101 > 192.168.100.102....

Also found that the icmp data packet alreay send and not recv on br1
tcpdump -i br1 icmp

....192.168.100.102 > 192.168.100.101....

....192.168.100.102 > 192.168.100.101....

why?? my config have some error?


text:
Q: 2 x @NotNull == too much? The BytesUtil.bytesEqual parameters use both the Jetbrains @NotNull and the OpenHFT @NotNull annotation the same parameter:
public static boolean bytesEqual(
        @org.jetbrains.annotations.NotNull @NotNull RandomDataInput a, long offset,
        @org.jetbrains.annotations.NotNull @NotNull RandomDataInput second, long secondOffset, long len)
        throws BufferUnderflowException {

which appears redundant -- is there any reason for using both? The two annotations are (currently) defined as:
package net.openhft.chronicle.core.annotation;

@Documented
@Retention(CLASS)
@Target({METHOD, FIELD, PARAMETER, LOCAL_VARIABLE})
public @interface NotNull {
}

and
package org.jetbrains.annotations;

@Documented
@Retention(CLASS)
@Target({METHOD, FIELD, PARAMETER, LOCAL_VARIABLE})
public @interface NotNull {
  String value() default "";
}

so Jetbrains @NotNull provides a default empty string value otherwise the two annotations are the same...so why specify both?

A: The problem we had with IntelliJ's annotation is that when byte code instrumentation is enabled, it add a check which throws an IllegalArgumentException. However, when the code is released or run in another context it instead triggers a NullPointerException.
For this reason, we added our own annotation across much of the code base so there would be code analysis checking in IntelliJ without the extra runtime check being added.
Most likely we should only use our annotation everywhere to make the exception thrown deterministic.


text:
Q: setup zlib to generate gzipped data I have a question about using zlib library for compressing data.
I want to setup zlib (namely deflateInit function) in such a way that the compressed data is binary equal to the data generated by command: gzip -9. Is this possible?
Thank you in advance

A: You cannot get exactly the same output as gzip.  You can however get output that is compatible with gzip, so that gzip will be able to decompress it.  You need to use deflateInit2().

A: windowsBits argument's default value is 15.
Adding 16 to it will be 31.
15 | 16 returns 31.
z_stream strm;
unsigned char* in = DATA TO COMPRESS;

strm.zalloc = Z_NULL;
strm.zfree = Z_NULL;
strm.opaque = Z_NULL;
strm.next_in = in;

int windowsBits = 15;
int GZIP_ENCODING = 16;

deflateInit2 (&strm, Z_DEFAULT_COMPRESSION, Z_DEFLATED,
              windowsBits | GZIP_ENCODING,
              8,
              Z_DEFAULT_STRATEGY));

http://www.lemoda.net/c/zlib-open-write/index.html


text:
Q: Access Control: Database (Fortify) public void removerSolicitacao(Long codigoSolicitacao)
throws IntegrationException {
beginMethod(LOGGER, "removerSolicitacao(codigoSolicitacao)");
    String delete = null;

    try {
        Connection connection = null;
        PreparedStatement preparedStatement = null;

        try {
            connection = this.getConnection();

            delete = "DELETE FROM DBPROD.SOLTC_DISPZ_ARQ WHERE CSOLTC_DISPZ_ARQ = ? ";

            preparedStatement = connection.prepareStatement(delete);
            preparedStatement.setLong(1, codigoSolicitacao.longValue());

            preparedStatement.executeUpdate();

        } catch (SQLException sqle) {
            LOGGER.fatal(sqle);
            throw new IntegrationException(sqle.getMessage());

        } finally {
            //closeStatement(preparedStatement); original
            if(preparedStatement!=null) {
                closeStatement(preparedStatement);
            }
            closeConnection(connection);
        }
    } finally {
        endMethod(LOGGER, "removerSolicitacao(codigoSolicitacao)");
    }
}


text:
Q: Sum of product of squared binomial coefficients Similar to the sum of product of binomial coefficients:

*

*What happens when I square the binomial coefficients $?$. Is there a nice closed formula for that $?$.

*More precisely, I'm interested in the special case where the $k_{i}$ are all equal to the sum of all $x_{i}$ ( to use the notation of the question linked above ), which I'll call $m$ ( not necessarily equal to $n$ here ).

So what I'm looking for is making the following sum tractable:
$$
S_{n,m} =
\sum_{x_{1} + \cdots + x_{n}\ =\ m}\,\,\,\,\,
\prod_{i = 1}^{n}\binom{m}{x_{i}}^{2}
$$
My goal is to show that $S_{n,m}\cdot n^{-2m}$ decreases as the number of summands, $n$, grows. I've tried expanding $n^{2m}$:
\begin{align}
n^{2m} & =
\sum_{y_{1} + \cdots + y_{n}\ =\ 2m}
\,\,\binom{2m}{y_{1},\ldots,y_{n}}
\\[5mm] & =
\sum_{y_{1} + \cdots + y_{n}\ =\ 2m}
\,\,\,\,
\prod_{i = 1}^{w}
\binom{\sum_{j = 1}^{i}y_{j}}{y_{i}}
\end{align}
but I didn't get anywhere with that. I'd be grateful for any pointers on how to approach this.

A:
We consider the generating function
  \begin{align*}
S_m(x)=\sum_{j=0}^m\binom{m}{j}^2x^j\qquad\qquad m\geq 0
\end{align*}
  Note $S_{n,m}$ is the coefficient of $x^m$ of $\left(S_m(x)\right)^n$.
  \begin{align*}
S_{n,m}=\sum_{{x_1+\ldots+x_n=m}\atop{x_j\geq 0}}\prod_{i=1}^{n}{\binom{m}{x_i}^2}
=[x^m]\left(S_m(x)\right)^n
\end{align*}

We can represent $S_m(x)$ in terms of Legendre polynomials $P_m(x)$. From the representation
\begin{align*}
P_m(x)=\frac{1}{2^m}\sum_{j=0}^m\binom{m}{j}^2(x-1)^{m-j}(x+1)^j
\end{align*}
we obtain
\begin{align*}
P_m\left(\frac{x+1}{x-1}\right)
&=\frac{1}{2^m}\sum_{j=0}^m\binom{m}{j}^2\left(\frac{x+1}{x-1}-1\right)^{m-j}\left(\frac{x+1}{x-1}+1\right)^j\\
&=\frac{1}{2^m}\sum_{j=0}^m\binom{m}{j}^2\frac{2^{m-j}}{(x-1)^{m-j}}\cdot
\frac{(2x)^j}{(x-1)^j}\\
&=\frac{1}{(x-1)^m}\sum_{j=0}^m\binom{m}{j}^2x^j\tag{1}
\end{align*}

Multiplication of (1) with $(x-1)^m$ gives
  \begin{align*}
S_m(x)=(x-1)^mP_m\left(\frac{x+1}{x-1}\right)\qquad\qquad  m\geq 0
\end{align*}
  and we finally conclude
  \begin{align*}
S_{n,m}&=[x^m]\left(S_m(x)\right)^n\\
&=[x^m](x-1)^{mn}P_m\left(\frac{x+1}{x-1}\right)^n\qquad\qquad n\geq 1,m\geq 0
\end{align*}

Example: $S_{3,1}$ to $S_{3,3}$
At first wie calculate $S_{3,1}$ to $S_{3,3}$ according to the OPs definition of $S_{n,m}$. The we look at the coefficients of the corresponding transformed Legendre polynomials.
\begin{align*}
S_{3,1}&=\sum_{{x_1+x_2+x_3=1}\atop{x_j\geq 0}}\prod_{i=1}^3\binom{1}{x_i}^2
=\frac{3!}{2!1!}\binom{1}{0}^2\binom{1}{0}^2\binom{1}{1}^2\\
&=\color{blue}{3}\\
S_{3,2}&=\sum_{{x_1+x_2+x_3=2}\atop{x_j\geq 0}}\prod_{i=1}^3\binom{2}{x_i}^2\\
&=\frac{3!}{2!1!}\binom{2}{0}^2\binom{2}{0}^2\binom{2}{2}^2
+\frac{3!}{1!2!}\binom{2}{0}^2\binom{2}{1}^2\binom{2}{1}^2\\
&=3+48\\
&=\color{blue}{51}\\
S_{3,3}&=\sum_{{x_1+x_2+x_3=3}\atop{x_j\geq 0}}\prod_{i=1}^3\binom{3}{x_i}^2\\
&=\frac{3!}{2!1!}\binom{3}{0}^2\binom{3}{0}^2\binom{3}{3}^2
+\frac{3!}{1!1!1!}\binom{3}{0}^2\binom{3}{1}^2\binom{3}{2}^2\\
&\qquad+\frac{3!}{3!}\binom{3}{1}^2\binom{3}{1}^2\binom{3}{1}^2\\
&=3+486+729\\
&=\color{blue}{1218}
\end{align*}
On the other hand we obtain with some help of Wolfram Alpha
\begin{align*}
S_1(x)&=(x-1)P_1\left(\frac{x+1}{x-1}\right)\\
&=1+x\\
S_1^2(x)&=1+2x+x^2\\
S_1^3(x)&=1+\color{blue}{3}x+3x^2+x^3\\
\\
S_2(x)&=(x-1)^2P_2\left(\frac{x+1}{x-1}\right)\\
&=1+4x+x^2\\
S_2^2(x)&=1+8x+18x^2+8x^3+x^4\\
S_2^3(x)&=1+12x+\color{blue}{51}x^2+88x^3+51x^4+12x^5+x^6\\
\\
S_3(x)&=(x-1)^3P_3\left(\frac{x+1}{x-1}\right)\\
&=1+9x+9x^2+x^3\\
S_3^2(x)&=1+18x+99x^2+164x^3+99x^4+18x^5+x^6\\
S_3^3(x)&=1+27x+270x^2+\color{blue}{1218}x^3+2484x^4+2484x^5+1218x^6+270x^7+27x^8+x^9
\end{align*}
with corresponding coefficients marked in $\color{blue}{\text{blue}}$.


text:
Q: Phpstorm как в файле изменить отступы? Смотрите, есть настройки для каждого типа файлов, допустим, html. Я указал там отступы табуляции 2, чтоб поуже было.
Но в некоторых файлах остались отступы 4. Т.е. очень широкий код получается, а я люблю пользоваться автоформатированием.
Вот и как в этих файлах принудительно изменить отступы? на 2. Настройки уже изменены. Но на некоторые файлы не влияет.

A: Вам нужно переформатировать код Code|Reformat Code. Более детально в официальной документации

A: *

*Ctrl+Alt+S (File→Settings)

*Editor→Code Style→HTML (название вашего языка)

*Необходимо изменить Tab size, Ident, Continuation ident — я ставлю все 2.

*Если пользуетесь пробелами, а не табами необходимо снять галочку Use tab character (я снял).

*В окне редактирования файла нажать Ctrl+Alt+L (Code→Reformat Code)

A:

*Если всё равно после Ctrl+Alt+L (Code→Reformat Code) ставит пробелы, попробуйте снять галочку с Enable EditorConfig support (File→Settings→Editor→Code Style)

A: Снять галку Editor->Code Style->Enable EditorConfig support
или отредактировать .editorconfig в корне проекта.
https://www.jetbrains.com/help/phpstorm/configuring-code-style.html#


text:
Q: How to Get and filter Data attribute of all parents in a nested list, till a target (div) of html element? I've a nested (UL->LI->UL-LI..) list. On any clicked node, I'm using ParentsUntil() to find all the parents till a certain ancestor element.
In each nested element's data attribute (data-weight:), there is number that represent weight.
I want to sum/aggregate total weight till the parent. These numbers (Areas) are in the data-area field of each item.

I

II

A

B

1

2

3

C

III

    $( "li.item-2" )
       .parentsUntil( $( "ul.level-1" ), ".yes" );

In the list above,

*

*How can I get the an array/list of them items from the clicked item
to the parent item with their data-weight [key,value]? for e.g. $VarArrayCargoVessel

*And as I traverse up, How can I sum/total weights (data-weight-total) of each/nested list and populate\fill-in the data-weight-total? I have zero's right now, because I dont know how to insert/write into a array value

A: Look into the following jQuery methods, they are all you need:

*

*each (link),

*attr (link),

*find (link) / children (link)

For example, at page load, you want to find each node that has a data-weight-total attribute, go through all its (immediate or all) children that have a data-weight attribute, get the sum of them and assign it to the node's data-weight-total property. If you want only immediate children, you would use .children(), or for all you would use .find():
$( document ).ready(function(){ // DOM ready

    $('[data-weight-total]').each(function(){

        var total = 0;

        $(this).find('[data-weight]').each(function(){
            total = total + parseInt($(this).attr('data-weight'));
        });

        $(this).attr('data-weight-total',total);

    });
})

This would calculate and assign data-weight-total values to all nodes that have such an attribute, as soon as the document is loaded. Let me know if you need explanations for any of what's going on in the function.

A:

$("li").click(function(event){
  event.stopPropagation();
  var list = $(this).closest("ul");
  var children = list.children();
  var values = [];
  for(var i = 0; i < children.length; i++){
    values.push(parseInt((children[i].getAttribute("data-weight") !== null) ? children[i].getAttribute("data-weight") : "0"));
  }
  var sum = 0;
  for(var j = 0; j < values.length; j++){
    sum += values[j];
  }
  $("#summed").html(sum);
});
li{
  cursor: pointer;
  }

I

II

A

B

1

2

3

C

III

Okay, let's get through this step by step. The first thing we do is creating a click event for each "li" item. If a li item is clicked, we execute our function ("function(event)").
The first line stops the event from propagating up. jQuery would go up to the very first "ul" item otherwise and execute the code for each "ul" element. We would receive the first list all the time.
http://api.jquery.com/event.stopPropagation/
We then get the closest "ul" element and store this in the variable "list". We don't want the list itself, that's why we store its children ("li" elements) in the variable "children".
We loop then through each children and store the "data-weight" attribute (method "getAttribute") in the array "values". Note that we only store the attribute if it's actually exists. If not, we just store "0".
https://developer.mozilla.org/en-US/docs/Web/API/Element/getAttribute
We then create a variable "sum" which stores our summed up attributes. To do so we loop through the array and add the value (+= values[j]) to the sum variable.
The last step writes the sum variable in the html of the div with the id #summed (check the html section).
Further reading:
https://developer.mozilla.org/en-US/docs/Web/API/Element/getAttribute
http://api.jquery.com/closest/
http://api.jquery.com/click/
http://api.jquery.com/event.stopPropagation/
http://api.jquery.com/children/
http://www.sitepoint.com/shorthand-javascript-techniques/
http://api.jquery.com/html/

Version 2:

$("li").click(function(event){
  event.stopPropagation();
  var list = $(this).find("ul").first();
  console.log(list);
  var children = list.children();
  var values = [];
  for(var i = 0; i < children.length; i++){
    values.push(parseInt((children[i].getAttribute("data-weight") !== null) ? children[i].getAttribute("data-weight") : "0"));
  }
  var sum = 0;
  for(var j = 0; j < values.length; j++){
    sum += values[j];
  }
  $("#summed").html(sum);
});
li{
  cursor: pointer;
  }

I

II

A

B

1

2

3

C

III

Note the third line in the answer. I've changed it to:
var list = $(this).find("ul").first();

Version 3:

$("li").click(function(event){
  event.stopPropagation();
  var children = $(this).find("ul").first().children();
  if(children.length === 0){
    children = $(this);
  }
  console.log(children);
  var values = [];
  for(var i = 0; i < children.length; i++){
    values.push(parseFloat((children[i].getAttribute("data-weight") !== null) ? children[i].getAttribute("data-weight") : "0"));
  }
  var sum = 0;
  for(var j = 0; j < values.length; j++){
    sum += values[j];
  }
  $("#summed").html(sum);
});
li{
  cursor: pointer;
  }

I

II

A

B

1

2

3

C

III


text:
Q: javax.jcr.version.VersionException: Cannot set property. Node is checked in I am trying to upload an image in DAM and workflow (OOTB) gets stuck. following is the error I am getting.
12.07.2018 09:58:27.712 *ERROR* [JobHandler: /etc/workflow/instances/server1/2018-07-11_2/update_asset_923:/content/../../../../../../icon-1.png/jcr:content/renditions/original] com.day.cq.dam.core.impl.AssetImpl addRendition: cannot add new rendition [cq5dam.thumbnail.48.48.png] for asset [/content/dam/____________________________]:
com.adobe.granite.asset.api.AssetException: javax.jcr.version.VersionException: Cannot set property. Node is checked in.
    at com.adobe.granite.asset.core.impl.DefaultRenditionHandler.setRendition(DefaultRenditionHandler.java:79)
    at com.adobe.granite.asset.core.impl.AssetImpl.setRendition(AssetImpl.java:131)
    at com.day.cq.dam.core.impl.AssetImpl.addRendition(AssetImpl.java:490)
    at com.day.cq.dam.core.impl.AssetImpl.addRendition(AssetImpl.java:484)
    at com.day.cq.dam.core.impl.RenditionMakerImpl$PlanBasedTemplate.apply(RenditionMakerImpl.java:129)
    at com.day.cq.dam.core.impl.RenditionMakerImpl.generateRenditions(RenditionMakerImpl.java:184)
    at com.day.cq.dam.core.process.CreateThumbnailProcess.execute(CreateThumbnailProcess.java:121)
    at com.day.cq.workflow.compatibility.CQWorkflowProcessRunner.execute(CQWorkflowProcessRunner.java:93)
    at com.adobe.granite.workflow.core.job.HandlerBase.executeProcess(HandlerBase.java:215)
    at com.adobe.granite.workflow.core.job.JobHandler.process(JobHandler.java:143)
    at org.apache.sling.event.impl.jobs.queues.JobQueueImpl.startJob(JobQueueImpl.java:395)
    at org.apache.sling.event.impl.jobs.queues.JobQueueImpl.access$100(JobQueueImpl.java:66)
    at org.apache.sling.event.impl.jobs.queues.JobQueueImpl$1.run(JobQueueImpl.java:238)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1152)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:622)
    at java.lang.Thread.run(Thread.java:745)
Caused by: javax.jcr.version.VersionException: Cannot set property. Node is checked in.
    at org.apache.jackrabbit.oak.jcr.session.NodeImpl$35.checkPreconditions(NodeImpl.java:1330)
    at org.apache.jackrabbit.oak.jcr.delegate.SessionDelegate.prePerform(SessionDelegate.java:606)

After image upload I can see the property set on the asset node is

What can be the possible cause of this.

A: This is a known product bug affecting AEM 6.0, 6.1 and 6.2.
From official documentation

This is a known product bug CQ-4215298.  When a user creates a version
  or publishes ("activates") a page that is locked by another user, then
  it causes the page to go into an inconsistent state.

Resolution

This issue is fixed in AEM6.3 and AEM6.2 SP1 Cumulative Fix Pack 8.
With or without the fix pack applied, you would have to fix the broken
  pages.  To fix the pages, follow the steps below:
Go to /crx/explorer/index.jsp and log in as admin user. Open Content
  Explorer. Browse to the jcr: content subnode of the broken page.  For
  example: /content/geometrixx/en/services/jcr:content Go to Versions =>
  CheckOut. Go to /sites.html UI and browse to the page and open it for
  editing. Unlock the page by clicking the lock icon on the top left.


text:
Q: How to update my bios in Windows XP I have this BIOS no

INTEL MQ96510J.86A.0816.2006.0716.2308

Can anyone please tell me where I can find the update bios image and how can I update that. I don't have any floppy drive on my computer.

A: There's a bit of a lack of research here, and a certain lack of information - since i managed to google up an answer within a few minutes, but some specifics are lacking.
Firstly, there's a whole class of motherboards that use this chipset, and bios - unfortunately i cannot direct link - but go here and search for MQ96510J.86A, you will find the utility to update your bios from windows and alternate bios recovery utilities. Pick the one for your specific motherboard (though i suspect they're all the same download) and you should be good.

A: The latest version of your BIOS is 1761. That page has links to the BIOS file as well as a DOS and Windows update tools. You can use the Windows program to flash the BIOS, but even if there were only a DOS verison, you could still use that by making a bootable, DOS flash drive and setting your BIOS to boot from that.


text:
Q: Woocommerce global percentage discount on simple products if customer is logged in I'm looking for advice on what's wrong with the following function.
My goal in this example is to apply a 50% off discount to all WooCommerce simple products, as long as the user is logged in.
function tier_pricing_logic() {

    if ( is_user_logged_in() ) {

        function assign_tier_pricing( $price, $product ) {
            $price = $price * 0.5; // Set all prices for simple products to 50% off.
        }
        return $price;

        add_filter('woocommerce_product_get_price', 'assign_tier_pricing', 90, 2 );
        add_filter('woocommerce_product_get_regular_price', 'assign_tier_pricing', 90, 2 );
    }

}
add_action( 'init', 'tier_pricing_logic' );

This function has no effect on the prices, am I approaching this all wrong?

A: Here you don't need the init hook and your IF statement needs to be inside the hooked function, so try that instead (for simple products):
add_filter('woocommerce_product_get_price', 'assign_tier_pricing', 90, 2 );
add_filter('woocommerce_product_get_regular_price', 'assign_tier_pricing', 90, 2 );
function assign_tier_pricing( $price, $product ) {
    if ( is_user_logged_in() && $product->is_type('simple') ) {
        $price *= 0.5; // Set all prices for simple products to 50% off.
    }
    return $price;
}


text:
Q: Web USB API not working properly when calling USB device microphone I'm trying to trigger Microphone using Web USB API on Chrome, the below is my HTML code:
<!DOCTYPE html>
<html>
    <head>
        <title>index.html</title>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
        <script src="./lib/webusb.js" ></script>
    </head>
    <body>

        <button id="btn">CLick me</button>
    </body>
</html>

and my js file:
  $(function() {
      console.log("ready!");
      $("#btn").click(function()
      {
          myFunction();
      });
  });

  function myFunction()
  {

    let device;
    try
    {
        device = navigator.usb.requestDevice
        ({ filters: [{vendorId: 0x0451, providerId:0x2036}]});
        console.log('Clicked');
        navigator.usb.getDevices()
        .then(devices => {
            console.log("devices: " + devices);
    });
    }
    catch (error)
    {
        debugger;
        console.log(error.message);
    };
    if (device !== undefined) {
    }
}

I found the providerId and vendorId from Device Manager:

I was expecting a microphone permission allowance pop-up window but only get the below result, which shows No Compatible devices found. So how to achieve it?


text:
Q: Positioning issue using jQuery Cycle I've built a slideshow using the jquery Cycle plugin, each image spans the width of the page (liquid layout) and has an accompanying caption. I need the caption to sit over the image and hence I'm using position: absolute in my CSS. However, as per some blog posts and Stack answers I've read, Cycle overides CSS positioning, and the caption is pushed below the image. I've used !important in my CSS but that doesn't work either.
Here is my Jquery:
$(document).ready(function(){
    $(".slideshow").cycle({
        fx: 'scrollRight',
        next: '#right-arrow',
        timeout: 0,})
    $(".slideshow").cycle({
        fx: 'scrollLeft',
        next: '#left-arrow',
        timeout: 0,})
    })

and my HTML. Note that I've included the caption in a separate DIV element than the image. Putting it in the same DIV was making the caption a separate slide in the show.

    {% for photo in gallery %}

    {% endfor %}

    {% for photo in gallery %}

{{ photo.caption }}

    {% endfor %}

and finally my CSS:
#copy-container {
        position: absolute;
        top: 350px;
        width: 7%;
        right: 3%;
        z-index: 10;
        background-color: red;}

Here is what is showing up using Chrome Inspect Elements:
Computed Styles:
    display: block;
    height: 54px;
    overflow-x: hidden;
    overflow-y: hidden;
    position: relative;
    width: 101px;

Styles:
    :active :hover
    :focus  :visited
    element.style {
    position: relative;
    width: 101px;
    height: 54px;
    overflow: hidden;
    }

Matched CSS Rules
    user agent stylesheetdiv {
    display: block;
    }
    Inherited from body
    body {
    font: arial;
    }

HTML from Chrome Dev tools...

client:American Express

WOOOHOOOO

client:Selfridges

nbew image

A: I'll note first that, especially when you're first learning new things, it's best to give every bit of information you have.  It's easier for those with more experience to help you if they can see the whole picture.
This is pulling from koala_dev's answer.  After figuring out what your requirements are I put together a fiddle: http://jsfiddle.net/rCsHG/
A couple of things to note:

*

*You have to get rid of those id attributes, as already mentioned

*You need to wrap your entire slideshow (which is actually 2 slideshows) in a wrapper.  You can then position:relative the main wrapper, and position:absolute the slideshows.

*You should have separate classes for each slideshow; I know it was working for you, but it's just good practice.
So, your HTML will look like this:

    {% for photo in gallery %}

    {% endfor %}

    {% for photo in gallery %}

{{ photo.caption }}

    {% endfor %}

Then CSS:
.slideshow-wrapper {
  position: relative;
}
.slideshow-img, .slideshow-caption {
  position: absolute;
  width: 100%;
}
.slideshow-caption {
  top: 0;
}

And, finally, JavaScript:
$(document).ready(function(){
var _timeout = 100; // when using the same value in multiple places, consider storing it in a variable for easy modification
$(".slideshow-img").cycle({
    fx: 'scrollRight',
    // add back in your prev/next
    timeout: _timeout,})
$(".slideshow-caption").cycle({
    fx: 'scrollLeft',
    // add back in your prev/next
    timeout: _timeout,})
})

A: You should have everything inside one container but use a div for each slide, also you need to use classes instead of ids since ids should be unique in a HTML page

    {% for photo in gallery %}

{{ photo.caption }}

    {% endfor %}

The position your caption using CSS
.slide{
    position: relative;
}

.caption{
    position: absolute;
    top: 350px;
    width: 7%;
    right: 3%;
    background-color: red;
}


text:
Q: Como organizar enum em um projeto Ionic 3 Possuo um grupo de mensagens estáticas para validação de campos de formulário. Essas mensagens estão presentes por toda a aplicação e por isso gostaria de usar alguma maneira de torná-las dinâmicas e organizadas dentro da estrutura.
Hoje eu tenho o grupo organizado dentro do meu .ts dessa maneira por exemplo:
login.ts
  validation_messages = {
'email': [
  { type: 'required', message: 'O email precisa ser preenchido' },
],
'password': [
  { type: 'required', message: 'A senha precisa ser preenchida' },
  { type: 'minlength', message: 'O campo de senha precisa ter no mínimo 8 digitos' },
  { type: 'maxlength', message: 'O campo de senha precisa ter no máximo 16 digitos' },
]};

login.html
<form novalidate [formGroup]="formLogin">

      <ion-item>
        Email
        <ion-input type="email" placeholder="Digite seu email" [(ngModel)]="userModel.email" formControlName="email"></ion-input>
      </ion-item>

      <ng-container *ngFor="let validation of validation_messages.email">

          {{validation.message}}

      </ng-container>

      <ion-item>
        Password
        <ion-input type="password" placeholder="Digite sua senha" [(ngModel)]="userModel.password" formControlName="password"></ion-input>
      </ion-item>

      <ng-container *ngFor="let validation of validation_messages.password">

          {{validation.message}}

      </ng-container>

        <button class="btn btn-primary btn-lg active" (click)="doLogin()" [disabled]="!formLogin.valid">Entrar</button>

    </form>

Existe alguma forma de organizar essas mensagens estáticas com ENUM, ou existe algum outro caminho com "pipe, component" ?

A: Consegui resolver da seguinte forma:
Criei uma estrutura como essa :
MeuProjeto pastas
├── /meuprojeto
└── /node_modules
└── /src
    └── /app
    └── /assets
    └── /components
    └── /directives
    └── /enums
    └── /environments
    └── /model
    └── /pages
    └── /pipes
    └── /providers

Na pasta 'enums' eu criei um arquivo para gerenciar as mensagens :
.src/enums/validationMessages.ts
export enum Email {
required = <string>'O email precisa ser preenchido'}

E na minha view eu importei o enum desejado e usei da seguinte forma:
./src/pages/home.ts
import { Component } from '@angular/core';
/* Enums */
import { Email } from '../../../enums/validationMessages';

@IonicPage()
@Component({
  selector: 'page-home',
  templateUrl: 'home.html',
})
export class HomePage {
constructor(){
  console.log(Email.required);
}
ionViewDidLoad() {}


text:
Q: ViewModel is not updated after ajax call in Knockout I'm trying to make a simple grid system with knockout for my project. But I can not update the my viewmodel properly
here is my JS;
$(function () {
    function AppViewModel(initialData) {
        var self = this;
        self.prices = ko.observableArray(initialData.Data);
        self.TotalCount = ko.observable(initialData.TotalCount);
        self.Page = new PageViewModel(initialData);
        self.GoTo = function (d) {
            $.getJSON("/prices/GetByFilterViaJSON?limit=3&page=" + d, function (data) {
                self.Page = new PageViewModel(data);
                self.prices(data.Data);
            });
        };
    };

    function PageViewModel(listData) {
        var self = this;
        ko.mapping.fromJS(listData.Page, {}, self);
    }

    $.getJSON("/prices/GetByFilterViaJSON?limit=3", function (data) {
        ko.applyBindings(new AppViewModel(data));
    });
});

and HTML

            Prices

                                    No.

                                    Tier

edit

deny

When I click to paging numbers (GoTo function in viewModel), self.Page is not updated thus page number class is always same. That is  What I can't success.
You think what am I doing wrong?

A: Knockout does not know about your new PageViewModel when you do this in your GoTo method:
  self.Page = new PageViewModel(data);

The UI is bound against the previous PageViewModel and does not know about this new one.  You would likely want to make self.Page an observable and populate it with the current PageViewModel.  So, then your GoTo method would do:
self.Page(new PageViewModel(data))`.

You would initially define it like:
self.Page = ko.observable(new PageViewModel(initialData));

In your UI, you would then need to either do with: Page around your section or access the values like Page().CurrentPage.


text:
Q: Unhide/Hide a sheet which uses hidden sheet I am having a recorded macro on a excel sheet.
I have a button on another sheet to run this macro.
When I run the macro it says the following error.
1642493829920.png
I want to add two lines. First to unhide the sheet where the macro is running and second hide it automatically.


text:
Q: Read Serial Port After Writing using Node.js My node.js script uses the serialport npm package to read and write to COM5 port, which is connected to an RS-232 device. This device only writes to the serial port when it receives a command sent by the PC connected to it.
How can I read what is returned by the RS-232 device after writing to it?
var SerialPort = require('serialport');
var port = new SerialPort('COM5', {
    parser: SerialPort.parsers.readline('\r')
}, function() {
    port.write('#01RD\r', function(err) {
        if(err)
            console.log('Write error')
        else {
            // HOW TO READ RESPONSE FROM DEVICE?
        }
    });
    port.write('#01VER\r', function(err) {
        if(err)
            console.log('Write error')
        else {
            // HOW TO READ RESPONSE FROM DEVICE?
        }
    });
});

A: I think this is a better way to do it. By function calling,
first create your function of reading and writing:
var serialport = require("serialport");
var SerialPort = serialport.SerialPort;

var sp = new SerialPort("/dev/ttyACM0", {
  baudrate: 9600,
  parser: serialport.parsers.readline("\n")
});

function write() //for writing
{
    sp.on('data', function (data)
    {
        sp.write("Write your data here");
    });
}

function read () // for reading
{
    sp.on('data', function(data)
    {
        console.log(data);
    });
}

sp.on('open', function()
{
    // execute your functions
    write();
    read();
});


text:
Q: Xorg crashing when touching system tray A few weeks ago I've updated Ubuntu on my ThinkPad T470 (equipped with a touchscreen) from 17.04 to 17.10. I'm not a huge fan of GNOME so I installed unity again and everything seemed to be working fine.
Except there's a strange issue with Xorg crashing when I touch icons in the system tray (I'm not yet sure if any particular icon is responsible for that or it's the system tray in general).
I've never experienced anything like this in 17.04. The issue doesn't seem to be tied to one particular touchscreen - I recently got an external touch display, touching the tray icons on it also crashes X11.
There's one thing I noticed though - there's an old issue with Unity multitouch gestures ceasing to work after some time when Google Chrome is started and I am affected by it (I experienced this with 17.04 too). I can touch tray icons as much as I want before this problem will kick in and everything will be fine. As soon as the gestures will stop working, it will take just one touch to kill X.
Here's how a typical stacktrace looks like:
[ 21295.825] (EE) Backtrace:
[ 21295.825] (EE) 0: /usr/lib/xorg/Xorg (xorg_backtrace+0x4d) [0x555e637b937d]
[ 21295.825] (EE) 1: /usr/lib/xorg/Xorg (0x555e63601000+0x1bc119) [0x555e637bd119]
[ 21295.825] (EE) 2: /lib/x86_64-linux-gnu/libpthread.so.0 (0x7f4f9d679000+0x13150) [0x7f4f9d68c150]
[ 21295.826] (EE) 3: /lib/x86_64-linux-gnu/libc.so.6 (gsignal+0xcb) [0x7f4f9d2d00bb]
[ 21295.826] (EE) 4: /lib/x86_64-linux-gnu/libc.so.6 (abort+0x16d) [0x7f4f9d2d1f5d]
[ 21295.826] (EE) 5: /lib/x86_64-linux-gnu/libc.so.6 (0x7f4f9d299000+0x8128d) [0x7f4f9d31a28d]
[ 21295.826] (EE) 6: /lib/x86_64-linux-gnu/libc.so.6 (0x7f4f9d299000+0x8864a) [0x7f4f9d32164a]
[ 21295.826] (EE) 7: /lib/x86_64-linux-gnu/libc.so.6 (0x7f4f9d299000+0x8a73e) [0x7f4f9d32373e]
[ 21295.826] (EE) 8: /lib/x86_64-linux-gnu/libc.so.6 (cfree+0x6e) [0x7f4f9d32844e]
[ 21295.826] (EE) 9: /usr/lib/xorg/Xorg (0x555e63601000+0x5f7bf) [0x555e636607bf]
[ 21295.827] (EE) 10: /usr/lib/xorg/Xorg (0x555e63601000+0x803b6) [0x555e636813b6]
[ 21295.827] (EE) 11: /usr/lib/xorg/Xorg (UnmapWindow+0x19b) [0x555e636842ab]
[ 21295.827] (EE) 12: /usr/lib/xorg/Xorg (0x555e63601000+0x4cffa) [0x555e6364dffa]
[ 21295.827] (EE) 13: /usr/lib/xorg/Xorg (0x555e63601000+0x52e28) [0x555e63653e28]
[ 21295.827] (EE) 14: /usr/lib/xorg/Xorg (0x555e63601000+0x56e70) [0x555e63657e70]
[ 21295.827] (EE) 15: /lib/x86_64-linux-gnu/libc.so.6 (__libc_start_main+0xf1) [0x7f4f9d2ba1c1]
[ 21295.827] (EE) 16: /usr/lib/xorg/Xorg (_start+0x2a) [0x555e63641b2a]
[ 21295.827] (EE)
[ 21295.828] (EE)
Fatal server error:
[ 21295.828] (EE) Caught signal 6 (Aborted). Server aborting

I'll be glad for any tips how to solve this issue or how to debug it (it's gonna be my first time digging into X).


text:
Q: Convert rdf to xml I need to convert RDF files in XML, through a process in C#. Is this possible?

What I need is a process or command that can convert one or more Oracle report (. Rdf) to XML, for example:
We start example.rdf and need a process that transforms example.rdf in an XML file (example.xml) containing the same information as the rdf file.
I searched and found rwconverter.exe Oracle http://download.oracle.com/docs/html/B10314_01/pbr_cla.htm#634712. I've also been seeing rdf2xml http://www.semwebtech.org/rdf2xml/, but not if it's the right way.
Thank you so much

A: Your question is unclear but I'll give you a quick example using the open source API dotNetRDF that I'm a developer on to just convert between RDF serializations.  If this was not what you meant then you need to expand your question to explain what you want to do as others have already commented.
Simplest way to convert between one RDF serialization and another:
Graph g = new Graph();
g.LoadFromFile("input.ttl");
g.SaveToFile("output.rdf");

The above example would take in input.ttl and attempt to read it as Turtle (does auto-format detection based on file extension) and then attempt to save it as RDF/XML (again does auto-format detection based on file extension).
If your file extensions were not standard you can specify the reader and writer explicitly e.g.
Graph g = new Graph();
g.LoadFromFile("input.temp", new RdfJsonParser());
g.SaveToFile("output.temp", new NTriplesWriter());

That example will read the input file as RDF/JSON and output is as NTriples.
If you are only wanting to do conversion and have large input data to convert there are more memory efficient ways of doing this as the above examples require loading the entire input into memory first.  If the input is too big you may hit an OutOfMemoryException in trying to run the above (if your file is several hundred megabytes then the above method is likely to run into this problem).
If you're interested in seeing the alternative conversion method please comment and I can add examples of leveraging the pure streaming conversion APIs but the code is a bit less obvious than these examples.


text:
Q: Wordpress Disable Plugin on Specific Pages/Posts Does anyone know a really effective method for disabling a plugin (that is active) on a specific page? There are some plugins that are not really needed in some pages of the website and they have lot of CSS and JavaScript files that are slowing the loading speed of the website and sometimes might conflict with other files.
I know that I can mess with the plugin's code etc. but it's not really effective.
Any ideas?
Thanks in advance!

A: I know it's old but this thread was exactly what I needed.
The only caveat to numediaweb's answer is that remove action requires the same priority as the add action
Hooks in the plugin
add_action('wp_print_styles', 'easy_fancybox_enqueue_styles', 999);
add_action('wp_enqueue_scripts', 'easy_fancybox_enqueue_scripts', 999);
add_action('wp_head', 'easy_fancybox', 999);

Code to remove hooks
function remove_easy_fancybox() {

     global $post;
     $ids = array(12,34,55);
     if(in_array($post->ID,$ids)):
          remove_action('wp_print_styles', 'easy_fancybox_enqueue_styles', 999);
          remove_action('wp_enqueue_scripts', 'easy_fancybox_enqueue_scripts',999);
          remove_action('wp_head', 'easy_fancybox', 999);

          wp_dequeue_script( 'jquery.fancybox' );
          wp_dequeue_script( 'jquery.easing' );
          wp_dequeue_script( 'jquery.mousewheel' );
          wp_dequeue_script( 'jquery.metadata' );
     endif;
}

add_action('wp_head', 'remove_easy_fancybox', 1);

From http://codex.wordpress.org/Function_Reference/remove_action

Important: To remove a hook, the $function_to_remove and $priority arguments must match when the hook was added. This goes for both
  filters and actions. No warning will be given on removal failure.

I've included my if statement to only run the action on specific post ids, thought it might be helpful.

A: First check, if the plugin you want to remove doesn't have an option menu where you set pages to exclude.
Second is, look for your plugin action hooks for ex:
add_action('wp_head', 'easy_fancybox', 999);

This is an example from easy fancybox plugin that hooks to wordpress header. To remove it, I placed this function in your functions.php and before any instance of wp_head(); is called:
function remove_easy_fancybox() {

     remove_action('wp_head', 'easy_fancybox_enqueue_styles');
     remove_action('wp_head', 'easy_fancybox_enqueue_scripts');
     remove_action('wp_head', 'easy_fancybox');

     wp_dequeue_script( 'jquery.fancybox' );
     wp_dequeue_script( 'jquery.easing' );
     wp_dequeue_script( 'jquery.mousewheel' );
     wp_dequeue_script( 'jquery.metadata' );
}

add_action('wp_head', 'remove_easy_fancybox', 1);

A: you can now use the free plugin Freesoul Deactivate Plugins to deactivate specific plugins on specific pages, posts, custom posts and archives, the settings page is really simple

A: Here is the idea.
 add_filter( 'option_active_plugins', 'lg_disable_cart66_plugin' );

 function lg_disable_cart66_plugin($plugins){

      if(strpos($_SERVER['REQUEST_URI'], '/store/') === FALSE && !is_admin() ) {
         $key = array_search( 'cart66/cart66.php' , $plugins );
         if ( false !== $key ) unset( $plugins[$key] );
      }

     return $plugins;
 }

p.s. Some people say you might need to put this in mu-plugins folder.


text:
Q: What is meant by a smooth structure with respect to a function? Suppose $M$ is a smooth manifold. Up until now (which I learned from Lee's book Introduction to Smooth Manifolds) I have taken a smooth structure on $M$ to be a maximal smooth atlas. That is, a collection of charts $\{(U_\alpha, \phi_\alpha)\}$ such that the transition maps $\phi_\alpha \circ \phi_\beta^{-1}$ is smooth for all $\alpha$ and $\beta$, and also such that this collection of charts is contained in no other collection.
However, further along in the book he mentions smooth structures with respect to certain functions. For example, in the section regarding immersed submanifolds, Lee says

An immersed submanifold $M$ is a subset $S \subset M$ endowed with a topology with respect to which it is a topological manifold, and a smooth structure with respect to which the inclusion map $S \hookrightarrow M$ is a smooth immersion.

I am having trouble understanding what is meant by the last half of the above definition. How do we have a smooth structure with respect to a function? If we denote the inclusion map by $i$, does this amount to requiring $\phi \circ i \circ \psi^{-1}$ be smooth where $\phi$ belongs to some chart in $M$ and $\psi$ belongs to some chart in $S$?

A:
How do we have a smooth structure with respect to a function?

It's the other way around; $S$ is endowed with a smooth structure (so that is is a smooth manifold in and of itself) and with respect to this smooth structure the inclusion map (which is a priori a continuous map) $\iota: S\to M, s\mapsto s$ is a smooth function. The point is that there are subtleties regarding what a "submanifold" ought to mean, and in this case an immersed smooth submanifold need not inherit a smooth structure from the ambient manifold (globally speaking). The standard example is a line with irrational slope in $2$-torus, see my answer at Dynamics on the torus.
The general theme is that because there are subtleties with the definition of a submanifold as a "subset of a manifold which is a manifold in and of itself", one emphasizes the parameterization of the submanifold.

If we denote the inclusion map by $i$, does this amount to requiring $\phi \circ i \circ \psi^{-1}$ be smooth where $\phi$ belongs to some chart in $M$ and $\psi$ belongs to some chart in $S$?

Yes, but what makes the definition confusing is that $\psi$ need not be related to $\phi$ in general. In the case of the irrational line immersed in the torus, $\psi$ takes a one-dimensional open subset to an open interval, whereas $\phi\circ \iota$ will have the image of an open subset densely foliated by line segments (because the irrational line (as a topological subspace) is dense in the torus).
It might be a useful exercise to compare and contrast a comparison between

*

*"topological subspace",

*"(injectively) immersed smooth submanifold",

*"embedded smooth submanifold",

*"properly embedded smooth submanifold",

*"embedded topological submanifold", and

*"properly embedded topological submanifold";

all these phrases are defined in the book you are citing.


text:
Q: Aspect before call to org.apache.commons.logging.Log.warn what I'd like to do, is have an aspect which listens to a call to org.apache.commons.logging.Log.warn and does something after the call.
Is that possible?
I created an aspect like this, but it doesn't ever get called when I do a LOG.warn:
@Pointcut("execution(* org.apache.commons.logging.Log.warn.*.*(..))")
public void warn() {}

@Around("warn()")
public void collect(JoinPoint joinPoint) throws Throwable {
  System.out.println("debug - 1"); // I have a breakpoint here that never gets hit
}

Test class:
private static final Log LOG = LogFactory.getLog(TestCollectMessagesAspect.class);

public String testCall(String param) {
    LOG.warn("this is a test");
    return param;
}

Thanks

A: This is a typical pitfall for AspectJ beginners: You are trying to intercept method execution(), but in order to achieve this you need to weave your aspect into the target code, i.e. into Commons Logging in this case. In order to do that you would have to do binary weaving and create a woven version of the 3rd party JAR.
While this is possible, there is a simpler solution, provided you control the calling code and are only interested in warnings created by your own code, not by other 3rd party libs or so. If so, just switch from execution() to call() pointcuts. This will weave the callers rather than the callee.


text:
Q: Swift 4: When a user clicks on a UiButton how do I grab the string that is selected in a UICollectionView? Question: I am trying to know which town someone selected when they clicked on a UIButton. When the user clicks on the UIButton I want to be able to know the "name" of which townName the user selected. How can I do this? I was able to pass the indexPath.row successfully but I am not sure how to pass the name of the town the user selected. This is my code below. Would love any help on this!
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath) as! TownCell
    let name = townName[indexPath.row].name
    let regionId = townName[indexPath.row].region_code

    cell.townLabel.text = "\(name), \(regionId)"

    cell.button.tag = indexPath.row
    print(townName[indexPath.row].name)
    print(townName[indexPath.row].region_code)
    return cell
}

    lazy var button: UIButton = {
        let button = UIButton(type: .system)
        button.backgroundColor = greenCTAColor
        button.layer.cornerRadius = 15
        button.setTitle("select", for: .normal)
        button.setTitle("selected", for: .selected)
        button.setTitleColor(.white, for: .normal)
        button.setTitleColor(.white, for: .selected)
        button.tintColor = .clear
        button.titleLabel?.font = UIFont(name: "ProximaNova-Semibold", size: 16)
        button.addTarget(self, action: #selector(selectedAction), for: .touchUpInside)
        return button
    }()

    @objc func selectedAction(sender: AnyObject) {
        let currentCellNumber = sender.tag
        if let button = sender as? UIButton {
            if button.isSelected {
                button.isSelected = false
                button.backgroundColor = greenCTAColor
                print("User unselected cell number: \(currentCellNumber!)")
            } else {
                button.isSelected = true
                button.backgroundColor = blueCTAColor
                print("User selected cell number: \(currentCellNumber!)")
            }
        }
    }

A: Just get the town from the townName array based on the button tag you set in collection view, and is your action method is calling? if its calling below will work
@objc func selectedAction(sender: UIButton) {
        let currentCellNumber = sender.tag
        if button.isSelected {
            button.isSelected = false
            button.backgroundColor = greenCTAColor
            print("User unselected cell number: \(currentCellNumber!)")
        } else {
            button.isSelected = true
            button.backgroundColor = blueCTAColor
            print("User selected cell number: \(currentCellNumber!)")
        }

        let town = townName[currentCellNumber]
        print(town.name)
    }

In cellForItemAt
add action to the button for that cell
cell.button.addTarget(self, action: #selector(selectedAction), for: .touchUpInside)

I always create button and action in the collectionViewCell class and than use delegate patten to pass around data. but as you have created action in the same controller above will work, as action is set to self it will call  selectedAction.