text:
Q: How to insert value into tkinter entry without curly brackets or additional symbols? So my issue is I'm creating a form and currently I need entries into the tk.Entry to be able to be saved and loaded. I have it to the point where it works, however any entries with multiple words are treated as tuples and when loaded appear as {what's this for?} in the entry box and when saved again it becomes {{what's this for?}} etc.
I've considered using the print command to get the tuple to a string value, but I'm not sure how to do that in this instance.
p.s. If anyone who could tell me how to replace text added when loaded instead of adding, that would be great.
def ldload():
    f=open(ldcreds, 'r')
    content = f.readlines()
    l = [x.strip() for x in content]
    ldsplitlists = [i.split(", ") for i in l]
    Characterentx, Playerentx = ldsplitlists
    Characterent.insert(0, Characterentx)
    Playerent.insert(0, Playerentx)

and here is how I save it if it will help
def ldsave():
with open(ldcreds, 'w') as f:
        f.write(Characterent.get())
        f.write('\n')
        f.write(Playerent.get())
        f.write('\n')

yes I do close it, I just left out most of the variables.
I appreciate all your help, let me know if I am missing something

A: I solved the curly braces around entries when inserting data into a listboxes by just looping over the tuple ( a tuple was returned in my case from a SQL cursor.fetchall() ) and then selecting the index number for the listbox insert.  That stripped the curly braces from displaying in the listbox.
for columns in feedback:
    captured_columns_list.insert(END, columns[0])

A: Here is an example of a simple program that will take in 3 fields and save them to a file called test_text in your main directory.
That same file can be used to load to each field through the use of some if statements when the load button is pressed.
This should be a good example to assist you with your problem.
import tkinter as tk

class App(tk.Frame):

    def __init__(self, parent, *args, **kwargs):
        tk.Frame.__init__(self, parent, *args, **kwargs)

        self.master = parent
        self.save_btn = tk.Button(self.master, text = "Save fields", command= self.ldsave)
        self.save_btn.grid(row=0, column=0)
        load_btn = tk.Button(self.master, text = "Load fields", command= self.ldload)
        load_btn.grid(row=0, column=1)

        label1 = tk.Label(self.master, text = "First Name: ")
        label1.grid(row=1, column=0)
        self.entry1 = tk.Entry(self.master)
        self.entry1.grid(row=1, column=1)

        label2 = tk.Label(self.master, text = "Last Name: ")
        label2.grid(row=2, column=0)
        self.entry2 = tk.Entry(self.master)
        self.entry2.grid(row=2, column=1)

        label3 = tk.Label(self.master, text = "Age: ")
        label3.grid(row=3, column=0)
        self.entry3 = tk.Entry(self.master)
        self.entry3.grid(row=3, column=1)

    def ldsave(self):
        list_of_entries = [self.entry1.get(), self.entry2.get(), self.entry3.get()]
        with open("./test_text", 'w') as f:
            for item in list_of_entries:
                f.write("{}\n".format(item))

    def ldload(self):
        try:
            with open("./test_text", 'r') as f:
                content = f.readlines()
                content = [x.strip() for x in content]
                for i in range(3):
                    if i == 0:
                        self.entry1.delete(0,tk.END)
                        self.entry1.insert(0,content[i])
                    if i == 1:
                        self.entry2.delete(0,tk.END)
                        self.entry2.insert(0,content[i])
                    if i == 2:
                        self.entry3.delete(0,tk.END)
                        self.entry3.insert(0,content[i])
        except:
            print("File test_text does not exist")

if __name__ == "__main__":
    root = tk.Tk()
    my_app = App(root)
    tk.mainloop()


text:
Q: Not able to access instance after Sitecore setup as Azure App Service from marketplace I have setup Sitecore 8.2 Update 3 as Azure App Service using Marketplace.
The setup completed and i got urls for cm and cd like
xxxxxx-cd.azurewebsites.net and
xxxxxx-cm.azurewebsites.net
But when I access these URLs I get this screen.
Also xxxxxx-cm.azurewebsites.net/sitecore gives page not found.
Am I missing anything?

A: According to your screen, the Azure App Service has been created, but there is nothing inside it. Seem like something went wrong and deployment script didn't deploy Sitecore's file to App Service. You can verify it using App Service Editor tool.
The reason why deployment went wrong could be this known issue: https://kb.sitecore.net/articles/755670.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Angular - How to set default values for optional input properties I wonder what is the "Angular/Typescript way" to set up default values for optional properties in Angular component? I am having troubles when values passed to optional properties are null or undefined.
Currently I am having something like this:
export class FooComponent implements OnInit {
  @Input() foo = 'foo';
  @Input() bar = 0;
  @Input() baz?: string;
}

If you declare default value, you dont have to specify type since it is type of assigned value and property is optional by default. This is the case of bar and foo properties.
Alternatively you can use ? to mark that this property is optional but you cant declare its default value. This is the case of baz property.
Now let us see what happens when you pass different values to those properties.
<app-foo-component
  [foo]
  [bar]="null"
  [baz]="undefined"
>
</app-foo-component>

if I console log these properties, this is what I got:
foo will be correctly 'foo'
bar will be null
baz will be undefined
Is there a elegant way to also set default values when passed values are null/undefined or do I need some checking in OnInit like this?
OnInit() {
  this.bar = this.bar || 0;
}

It feels like there is some way to do this. To me, optional property means that value could be missing, null or unset but when I want to set default value, it only works when property is missing or empty. It still set value as null or undefined in these cases and that seems to be confusing.

A:
Here is the PROPER best solution for this. (ANGULAR 7,8, 9)

Addressing solution: To set a default value for @Input variable. If no value passed to that input variable then It will take the default value.
Example:
I have an object interface named car:
export interface car {
  isCar?: boolean;
  wheels?: number;
  engine?: string;
  engineType?: string;
}

You made a component named app-car where you need to pass the properties of car with @input decorator of angular. But you want that isCar and Wheels properties must have a default value (ie.. isCar: true, wheels: 4)
You can set a default to that object as per below code:
export class CarComponent implements OnInit {
  private _defaultCar: car = {
    // default isCar is true
    isCar: true,
    // default wheels  will be 4
    wheels: 4
  };

  @Input() newCar: car = {};

  constructor() {}

  ngOnInit(): void {

   // this will concate both the objects and the object declared later (ie.. ...this.newCar )
   // will overwrite the default value. ONLY AND ONLY IF DEFAULT VALUE IS PRESENT

    this.newCar = { ...this._defaultCar, ...this.newCar };
   //  console.log(this.newCar);
  }
}

For more detailed article refer this.
Refer Destructuring assignment from here

A: You could define bar as a getter/setter property, and make sure that the default value is applied in the setter when necessary:
private _bar = 0;

@Input() get bar() {
  return this._bar;
}
set bar(value) {
  this._bar = value || 0;
}

See this stackblitz for a demo.

A: I have same problem when having some nested child components.
Finally this worked for me:
  @Input()
  public foo;
  get fooWithDefault() {
    return this.foo ?? 'any default value';
  }

then i used fooWithDefault property in template instead of foo.


text:
Q: Join 2 many-to-many tables and get 3 adjacent boolean columns Let's say there are three tables A, B and C where
Table A is:
╔═══════╗
║ col_1 ║
╠═══════╣
║ a     ║
║ b     ║
║ c     ║
╚═══════╝

Table B is:
╔═══════╗
║ col_2 ║
╠═══════╣
║ o     ║
║ p     ║
║ q     ║
╚═══════╝

Table C is:
╔═══════╗
║ c_col ║
╠═══════╣
║ x     ║
║ y     ║
║ z     ║
╚═══════╝

Let's say there is a many-to-many relationship between table A and table C via a mapping table A_to_C shown below:
╔═══════╦═══════╗
║ col_1 ║ c_col ║
╠═══════╬═══════╣
║ a     ║ x     ║
║ a     ║ y     ║
║ b     ║ y     ║
║ b     ║ z     ║
║ c     ║ x     ║
╚═══════╩═══════╝

Also there is a many-to-many relationship between table B and table C via a mapping table B_to_C shown below:
╔═══════╦═══════╗
║ col_2 ║ c_col ║
╠═══════╬═══════╣
║ o     ║ y     ║
║ o     ║ z     ║
║ p     ║ x     ║
║ q     ║ x     ║
║ q     ║ y     ║
╚═══════╩═══════╝

For value 'b' in col_1 and value 'q' in col_2 I need to get the result as:
╔═══════╦═══════╦════════╗
║ c_col ║ col_1 ║ col_2  ║
╠═══════╬═══════╬════════╣
║ x     ║ NULL  ║ q      ║
║ y     ║ b     ║ q      ║
║ z     ║ b     ║ NULL   ║
╚═══════╩═══════╩════════╝

which can later be transformed into:
╔═══════╦═══════╦═══════╗
║ c_col ║ col_1 ║ col_2 ║
╠═══════╬═══════╬═══════╣
║ x     ║ False ║ True  ║
║ y     ║ True  ║ True  ║
║ z     ║ True  ║ False ║
╚═══════╩═══════╩═══════╝

I asked a similar question here but in this case
due to many to many relationships with duplicate column values I am not able to achieve the above result without duplicate columns using the solution in the above link.

A: You can use the following query:
select c.c_col, ac.col_1 is not null, bc.col_2 is not null
from C c
left join (select * from A_to_C where col_1 = 'b') ac on c.c_col = ac.c_col
left join (select * from B_to_C where col_2 = 'b') bc on c.c_col = bc.c_col
where (ac.col_1, bc.col2) = ('b', 'q')

A: You don't need the two LEFT JOINS and the IS NOT NULL; EXISTS() already yields a boolean:

SELECT C.c_col
        , EXISTS( SELECT *
                FROM A_to_C ac
                WHERE ac.c_col = C.c_col AND ac.col_1 = 'b'
                ) AS col_1
        , EXISTS( SELECT *
                FROM B_to_C bc
                WHERE bc.c_col = C.c_col AND bc.col_2 = 'q'
                ) AS col_2
FROM C
        ;

A: You can generate this result with a series of LEFT JOINs, placing your col_1 and col_2 filters in the JOIN conditions:
SELECT C.c_col, ac.col_1, bc.col_2
FROM C
LEFT JOIN A_to_C ac ON ac.c_col = C.c_col AND ac.col_1 = 'b'
LEFT JOIN B_to_C bc ON bc.c_col = C.c_col AND bc.col_2 = 'q'

Output:
c_col   col_1   col_2
x       (null)  q
y       b       q
z       b       (null)

Demo on SQLFiddle
Those values can then be converted into booleans by testing they are not NULL:
SELECT C.c_col, ac.col_1 IS NOT NULL AS col_1, bc.col_2 IS NOT NULL AS col_2
FROM C
LEFT JOIN A_to_C ac ON ac.c_col = C.c_col AND ac.col_1 = 'b'
LEFT JOIN B_to_C bc ON bc.c_col = C.c_col AND bc.col_2 = 'q'

Output:
c_col   col_1   col_2
x       false   true
y       true    true
z       true    false

Demo on SQLFiddle


text:
Q: I'm fetching some data from an api and when I'm logging the fetched data on the console it get's logged again and again Here's the function that's fetching the data from api:

import axios from "axios";

const url = "https://covid19.mathdro.id/api";

export const fetchData = async () => {
  try {
    const {
      data: { confirmed, recovered, deaths, lastUpdate },
    } = await axios.get(url);
    return { confirmed, recovered, deaths, lastUpdate };
  } catch (error) {}
};

I'm using this function in App.js and passing the response to cards component via props, here's the code:

import { fetchData } from "./api";

function App() {
  const [data, setData] = useState({});
  useEffect(() => {
    async function getData() {
      const response = await fetchData();
      setData({ data: response });
    }
    getData();
  });

  return (
    <div className={styles.container}>
      <Cards data={data} />

finally I'm logging the received props on console using this code but it gets logged again and again on console:

const Cards = (props) => {
  console.log(props);

here's the screen shot of the console for your reference:screen shot

A: useEffect gets executed everytime the component rerenders. Pass an empty array as an argument to useEffect to prevent that.
useEffect(() => {
  async function getData() {
      const response = await fetchData();
      setData({ data: response });
    }
    getData();
}, []);

A: You must pass an empty list of dependencies in useEffect (run only once on mount):
useEffect(() => {
    async function getData() {
        const response = await fetchData();
        setData({ data: response });
    }
    getData();
}, []);

otherwise it will run on every render


text:
Q: Paste character from a column to another column of the same row I've got a dataframe that looks like this:
name  value  position
tex21 0.2    r45
tex21 0.5    r45
ca14  0.9    r67
ca14  0.1    r67

For every position I want to paste the corresponding row name next to its string. Like this:
name  value  position
tex21 0.2    tex21.r45
tex21 0.5    tex21.r45
ca14  0.9    ca14.r67
ca14  0.1    ca14.r67

How can I do this?

A: Try this paste code overwrting column position data:
df$position<-paste(df$name,df$position,sep=".")

Input
df<-data.frame(name=c('text21','text21','cal14','cal14'),
                value=c(0.2,0.5,0.9,0.1),
                position=c('r45','r45','r67','r67'))

Output
df$position<-paste(df$name,df$position,sep=".")
df
    name value   position
1 text21   0.2 text21.r45
2 text21   0.5 text21.r45
3  cal14   0.9  cal14.r67
4  cal14   0.1  cal14.r67

A: Try this:
library(dplyr)

df <- data.frame(name = c("tex21", "tex21", "ca14", "ca14"),
                 value = c(0.2, 0.5, 0.9, 0.1),
                 position = c("r45", "r45", "r67", "r67")
)

df2 <- df %>% mutate(position = paste(name,position,sep="."))
df2

   name value  position
1 tex21   0.2 tex21.r45
2 tex21   0.5 tex21.r45
3  ca14   0.9  ca14.r67
4  ca14   0.1  ca14.r67

A: Use this Code:
library(dplyr)

df <- df %>%
+ mutate(Position = paste(name, position, sep = "."))
> df
   name value position  Position
1 tex21   0.2      r45 tex21.r45
2 tex21   0.5      r45 tex21.r45
3  ca14   0.9      r67  ca14.r67
4  ca14   0.1      r67  ca14.r67


text:
Q: sudo yum remove php linux in aws When I was trying to upgrade PHP version in amazon web server I got this kind of error. I'm trying to up upgrade PHP version 5.6 to 7.0 in amazon web server and I am using to putty to upgrade.
[root@cpanel ec2-user]# sudo yum remove PHP

Loaded plugins: priorities, universal-hooks, update-motd, upgrade-helper
No Match for argument: PHP
No Packages marked for removal

A: we should give proper package name.First check which version of php installed.
rpm -qa php*
check the package installed and remove it.
yum remove rh-php56
or
rpm -Uvh --nodeps php-<version>.rpm


text:
Q: A question on sequences using squeeze theorem. $a_n=(1+\frac{1}{n})^n$ ,
$b_n=\sum_{k=0}^n \frac{1}{k!}$.
Given that  $\lim_{n\to \infty}b_n=e$.
(i) Show that $b_n-\frac{3}{2n} < a_n < b_n$ for all positive integer $n$.
(ii) Using Squeeze theorem deduce that $\lim_{n\to \infty}a_n=e$.
(i) I have proved the R.H.S of the inequality as follows.
$$\begin{align}
\left(1+\frac1n \right)^n &=\sum_{k=0}^n \binom{n}{k}\frac{1}{n^k}\\\\
&=\sum_{k=0}^n \frac{n(n-1)(n-2)\cdots (n-k+1)}{n^k}\frac{1}{k!}\\\\
&=\sum_{k=0}^n \left(\left(1-\frac{1}{n}\right)\left(1-\frac{2}{n}\right)\left(1-\frac{3}{n}\right)\cdots \left(1-\frac{k-1}{n}\right)\right)\frac{1}{k!}\\\\
&\le \sum_{k=0}^n\frac{1}{k!}\\\\
\end{align}$$
I am unable to get the L.H.S of the inequality using algebraic method.
(ii) From the inequality i got the answer easily by applying squeeze therem.
It is easy to prove $\lim_{n\to \infty}b_n-\frac{3}{2n}=\lim_{n\to \infty}b_n=e$, hence by squeeze theorem the result $\lim_{n\to \infty}a_n=e$
Please Help me to get the L.H.S of the inequality.


text:
Q: How to display multiple items using puts? I have written a Travel App with Tour Items and  I'm trying to display the order at the end.
When I use puts @order_items I get {"SevendaySurfSportTour"=>2} for two tours.
I would like it to display
2 SevendaySurfSportTour at the end. But I don't know how, any help would be good?
class TourOrder
    def initialize
        @order_items = Hash.new(0)
    end
    def add_item(name, quantity)
        @order_items[name] += quantity
    end
    def get_items
        return @order_items
    end

    def display
        puts "Thank you for coming!"
        puts @order_items
    end
end

A: @order_items is a hash and what has printed out if the string representation of such a hash. When you want to format the output differently, then you have to implement that on your own – for example like this:
def display
  puts "Thank you for coming!"

  @order_items.each do |name, quantity|
    puts "#{quantity} #{name}"
  end
end

A: Below code works for you
class TourOrder
  def initialize
    @order_items = Hash.new(0)
  end

  def add_item(name, quantity)
    @order_items[name] += quantity
  end

  def get_items
    @order_items
  end

  def display
    puts "Thank you for coming!"
    puts items
  end

  def items
    @order_items.collect{ |k, v| "#{v} #{k}"}
  end
end

t = TourOrder.new
t.add_item('SevendaySurfSportTour', 2)
t.add_item('Foo', 4)
t.add_item('Bar', 1)
t.display
=> Thank you for coming!
   2 SevendaySurfSportTour
   4 Foo
   1 Bar


text:
Q: Can't unwrap Optional.None with AutoreleasingUnsafePointer Upon running NSAppleScript.executeAndReturnError with an Applescript command that should fail and return an error, I get a Can't unwrap Optional.None error for errorDict.
var errorDict: NSDictionary? = nil
var scriptObject:NSAppleScript = NSAppleScript(source: command)
var execute:NSAppleEventDescriptor = scriptObject.executeAndReturnError(&errorDict)

I understand that the error is due to unwrapping a nil optional variable, though executeAndReturnError must take an optional variable. How could I fix this?

A: This error is most likely occurring while trying to initialize the NSAppleScript object, not your NSDictionary? object. NSAppleScript(source:) is a failable initializer, meaning it could return nil if an error occurs compiling your script. Your code should look something like this:
if let scriptObject = NSAppleScript(source: command) {
    var errorDict: NSDictionary? = nil
    let execute = scriptObject.executeAndReturnError(&errorDict)
    if errorDict != nil {
        // script execution failed, handle error
    }
} else {
   // script failed to compile, handle error
}

Sulthan's answer makes a good point, but as of Swift 1.2, executeAndReturnError(errorInfo:) no longer returns an Optional type even though it could return a nil (see this radar). The proper way to handle the execution failing is by checking the errorInfo dictionary for errors.


text:
Q: Read command output into array and parsing array to convert into .csv I essentially execute a command and have to iterate over it one file at a time. The output is read into an array. I want to do this only one time: 1. for efficiency and 2. the directory structure is constantly changing with new files being added hourly.
#Get file list
file_list=(`ls -lrt *.bin | awk '{print $9}'`)

#Get file output
output=$(for i in "${file_list[@]}"; do script.bash $i; done)

Now with the way $output is written, all data resides in a single element $output[0]. To extract and read this array line by line we can simply use read line which seems to work great.
# Read $output line by line to search for specific keywords and here
# is where my problem lies
while read -r line
do
        var1=$(echo "${line}" | grep keyword1)
        var2=$(echo "${line}" | grep keyword2)
        echo "$var1,$var2"
done <<< $output

Unfortunately the above is not working how I want it and the result within the terminal prints blank lines and that is because well, var1 and var2 don't have a match. I'm really just trying to search the line for a specific keyword, parse it, store it in a variable and then finally print it in comma delimited format.
Desired Output:
Line1: $var1,$var2
Line2: $var1,$var2

Output for a single .bin file. These are the values I'm grepping for each line.
UD  :   JJ533
ID :   117
Ver :   8973
Time:   15545

A: First of all ,I know this is not the exact solution you looking for, and also lookup for keywords is missing. I still not sure what you like to achieve, it might because of my English.
I only hope this code might help you to achieve your goal.
# Awk not required here if you not use long listing -l
file_list=$(ls -rt *.bin)

let "x=1"
for filename in ${file_list[@]}; do

        echo '--- file #'"${x}"' ---'
        let "y=1"

        # as awk give output: "var1 var2", read can put them into different variable.
        while read col1 col2;do

                # col1 contain first column (ID UD Ver Time)
                # col2 contain the value
                echo "Line${y}: ${col1},${col2}"
                let y++

        # cat is used instead of script.bash as only its output is provided.
        # awk cut down any space and remove : separator from each line.
        done <<< "$(cat "${filename}" | awk -F ":" '{gsub(/ /,"");print $1 " " $2}')"

        let x++
done

Files:
f1.bin <-- newer
UD  :   JJ533
ID :   117
Ver :   8973
Time:   15545

f2.bin <-- older
UD  :   ZZ533
ID :   118
Ver :   9324
Time:   15548

Output:
--- file #1 ---
Line1: UD,ZZ533
Line2: ID,118
Line3: Ver,9324
Line4: Time,15548
--- file #2 ---
Line1: UD,JJ533
Line2: ID,117
Line3: Ver,8973
Line4: Time,15545

A: This is much cleaner if you stick to Awk. Replace /.*/ with any /regex/ you want to match, otherwise it prints all lines in each file.
 awk -F ' *: *' '
    FNR==1{print "\n---", "file", ++f ":", FILENAME, "---"}
    /.*/{print "Line" FNR ":", $1 "," $2}
' *.bin

Outputs:

--- file 1: f1.bin ---
Line1: UD,JJ533
Line2: ID,117
Line3: Ver,8973
Line4: Time,15545

--- file 2: f2.bin ---
Line1: UD,ZZ533
Line2: ID,118
Line3: Ver,9324
Line4: Time,15548

etc.


text:
Q: Histogram in Matplotlib with input file I wish to make a Histogram in Matplotlib from an input file containing the raw data (.txt). I am facing issues in referring to the input file. I guess it should be a rather small program. Any Matplotlib gurus, any help ?
I am not asking for the code, some inputs should put me on the right way !

A: i would recommend using 'loadtxt' which is actually in the NumPy library. There are related functions in Matplotlib (csv2rec) but Matplotlib is actually standardizing on loadtxt.
Here's how it works:
from matplotlib import pyplot as PLT

with open('name_of_your_file.csv') as f:
  v = NP.loadtxt(f, delimiter=",", dtype='float', comments="#", skiprows=1, usecols=None)

'v', the object returned from 'loadtxt', is an n x m NumPy array.
'loadtxt' accepts either a file or a file descriptor. The instance above has most of the method signature.
'skiprows' is an integer that specifies the number of rows counting from the top that you want to skip; it's common to set it to "1" to skip the header row; 'usecols' begins at '0' and is a list reciting the columns you want to include ('None' is the default, and means 'include all'). The other parameters work as expected.
To plot a histogram from this data:
from matplotlib import pyplot as PLT

v_hist = NP.ravel(v)   # 'flatten' v
fig = PLT.figure()
ax1 = fig.add_subplot(111)

n, bins, patches = ax1.hist(v_hist, bins=50, normed=1, facecolor='green')
PLT.show()

A: You can't directly tell matplotlib to make a histogram from an input file - you'll need to open the file yourself and get the data from it. How you'd do that depends on the format of the file - if it's just a file with a number on each line, you can just go through each line, strip() spaces and newlines, and use float() to convert it to a number.


text:
Q: Multithread proccesing events from epoll_wait with coroutines I have such io context class:
    class IOContext
    {
    public:
        explicit IOContext(uint32_t eventPoolCount);
        ~IOContext();

        IOContext(IOContext&) = delete;
        IOContext& operator=(IOContext&) = delete;
        IOContext(IOContext&&) = delete;
        IOContext& operator=(IOContext&&) = delete;

        void processAwaitingEvents(int timeout);

        void scheduleOperation(std::derived_from<IOOperation> auto& operation)
        {
            // ok?
            if(0 == epoll_ctl(this->epollFD, EPOLL_CTL_ADD, operation.fd, &operation.settings))
                return;

            if(errno == EEXIST)
                // re-init event
                if(0 == epoll_ctl(this->epollFD, EPOLL_CTL_MOD, operation.fd, &operation.settings))
                    return;

            throw std::system_error{errno, std::system_category(), strerror(errno)};
        }

    private:
        tinycoro::Generator<IOOperation::CoroHandle> yieldAwaitingEvents(int timeout);

        std::unique_ptr<epoll_event[]> eventsList;
        const uint32_t eventPoolCount;
        int epollFD = -1;
    };

    //.
    //. //constructor, destructor
    //.
    void IOContext::processAwaitingEvents(int timeout)
    {
        for(auto& event : this->yieldAwaitingEvents(timeout))
        {
            event.resume();
        }
    }

    tinycoro::Generator<IOOperation::CoroHandle> IOContext::yieldAwaitingEvents(int timeout)
    {
        int eventCount = epoll_wait(this->epollFD, eventsList.get(), this->eventPoolCount, timeout);
        if(eventCount == -1)
        {
            throw std::system_error{errno, std::system_category(), strerror(errno)};
        }

        for(int i = 0; i < eventCount; ++i)
        {
            co_yield std::coroutine_handle<IOOperation>::from_address(eventsList[i].data.ptr);
        }
    }

and I want to enable multi-threaded processing for io events (IOOperation is the base class, which contains fd), so when some events are ready, first from N thread will get them and process them.
So, I think that i could move eventsList to cpp as thread_local variable, like this:
    //.
    //. //constructor, destructor
    //.
    void IOContext::processAwaitingEvents(int timeout)
    {
        for(auto& event : this->yieldAwaitingEvents(timeout))
        {
            event.resume();
        }
    }

    tinycoro::Generator<IOOperation::CoroHandle> IOContext::yieldAwaitingEvents(int timeout)
    {
        thread_local std::unique_ptr<epoll_event[]> eventsList = std::make_unique<epoll_event[]>(this->eventPollCount);
        int eventCount = epoll_wait(this->epollFD, eventsList.get(), this->eventPoolCount, timeout);
        if(eventCount == -1)
        {
            throw std::system_error{errno, std::system_category(), strerror(errno)};
        }

        for(int i = 0; i < eventCount; ++i)
        {
            co_yield std::coroutine_handle<IOOperation>::from_address(eventsList[i].data.ptr);
        }
    }

But I'm not sure it's good idea, ie if this solution is safe (I do some tests, everything was OK, but despite this, I have doubts).
I could make yieldAwaitingEvents as a public function, but I don't think that giving raw coroutine handle is good idea...
Thanks!
EDIT:
I change a little bit code - initializing of thread_local variable was moved to yieldAwaitingEvents function


text:
Q: Monotonized Submodular Function with the Same Polymatroid I am doing Exercise 8.10 (Submodular function minimization) of Introduction to Linear Optimization by Bertsimas and Tsitsiklis and may have found a mistake in (b).

Exercise 8.10* (Submodular function minimization) We are given a finite set $N=\{1,...,n\}$, and a function $f(S)$ defined for all subsets $S$ of $N$. We assume that $f(S)$ is submodular, that is
$$
f(S)+f(T)\ge f(S\cap T)+f(S\cup T),\quad\forall\,S,T\subset N.
$$
In this exercise, we show how to use the equivalence of separation and optimization to solve the problem of minimizing $f(S)$ over all $S\subset N$.
(a) Suppose first that $f(S)$ is submodular and nondecreasing, i.e. $f(S)\le f(T)$ if $S\subset T$, and $f(\emptyset)=0$. Consider the polyhedron
$$
P(f)=\left\{\mathbf{x\ge 0}:\sum_{j\in S}x_j\le f(S),\ \forall\,S\subset N\right\},
$$
...
(b) Consider a submodular. but not necessarily nondecreasing, set function $f(S)$. Let
$$
f_{\text{mon}}(S)=\min\{f(T)\mid S\subset T\subset N\}-\min\{f(T)\mid T\subset N\}.
$$
Prove that $f_{\text{mon}}(S)$ is submodular and nondecreasing, and that $P(f)=P(f_{\text{mon}})$.

The part I am having doubts about is $P(f)=P(f_{\text{mon}})$. Clearly $P(f)\supset P(f_{\text{mon}})$. But I do not think $P(f)\subset P(f_{\text{mon}})$. For example, let $N=\{1\}$ and let $f(S)=1$ for all $S\subset N$. Then $f_{\text{mon}}(S)=0$ for all $S\subset N$. In this case,
$$
P(f)=[0,1]\neq\{0\}=P(f_{\text{mon}}).
$$
However, if I use $\tilde{f}_{\text{mon}}=\min\{f(T)\mid S\subset T\subset N\}$ (that is, without the constant term $\min\{f(T)\mid T\subset N\}$), then I can show that $P(f)=P(\tilde{f}_{\text{mon}})$.
Did I miss something? Or is this question wrong?


text:
Q: Declare long list of variables quickly using Javascript without arrays? I know you can use arrays but is there a way to declare multiple variables quickly - lets say up to 50 using a loop and an integer at the end of each variable going up by one every time.
<!DOCTYPE html>

JavaScript Variables

A:
I know you can use arrays

Yes. And you absolutely should use arrays for that purpose. It is what are designed for.

is there a way to declare mutiple variable quickly

Only if you create global variables. Globals are awful.
window["price" + i] = somevalue;

A: If you don't want to use an array and if eval still is considered an evil even for this simple operation, you can go for an object. Lets say you create an object with all the variables you need as properties and done by loop.
var myVars = {};

for (var i = 0; i < 50 i++) {
   myVars['price' + i] = 0;
}


text:
Q: Running django + apache in localhost windows i wanna try using apache as a server for django, i already add a code in the bottom httpd.conf like this
WSGIScriptAlias / /D:/CodeTesting/Django/project1/project1/wsgi.py
WSGIPythonHome /C:/Users/Fatoni/Envs/django
WSGIPythonPath /D:/CodeTesting/Django/project1

<Directory /D:/CodeTesting/Django/project1/project1>
   <Files wsgi.py>
      Require all granted
   </Files>
</Directory>

note: i have changed documentroot apache into d:/ and i am using virtualenv in development, i am also using apache through xampp.
did i make a mistake in that configuration, what kind of thing that i should do to run django in apache locally?
it showing error like this after i added that code
10:06:05  [Apache]  Status change detected: running
10:06:07  [Apache]  Status change detected: stopped
10:06:07  [Apache]  Error: Apache shutdown unexpectedly.
10:06:07  [Apache]  This may be due to a blocked port, missing dependencies,
10:06:07  [Apache]  improper privileges, a crash, or a shutdown by another method.
10:06:07  [Apache]  Press the Logs button to view error logs and check
10:06:07  [Apache]  the Windows Event Viewer for more clues
10:06:07  [Apache]  If you need more help, copy and post this
10:06:07  [Apache]  entire log window on the forums


text:
Q: Very basic persistence or data storage for a Python script I have a script which processes a list of URLs. The script may be called at any time with a fresh list of URLs. I want to avoid processing an URL which has already been processed at any time in the past.
At this point, all I want to match are URLs, which are really long strings, against all previously processed URLs, to ensure uniqueness.
My question is, how does an SQL query matching a text URL against a MySQL database of only URLs (say 40000 long text URLs) compare, against my other idea of hashing the URLs and saving the hashes using, say, Python's shelve module?
shelf[hash(url)] = 1

Is shelve usable for a dictionary with 40000 string keys? What about with 40000 numerical keys with binary values? Any gotchas with choosing shelve over MySQL for this simple requirement?
Or, if I use a DB, is there a huge benefit to store URL hashes in my MySQL DB instead of string URLs?

A: Store the URLs in a set, which assures O(1) for finding items, and shelve it. At this amount of URLs, storing and restoring will take very little time and memory:
import shelve

# Write URLS to shelve
urls= ['http://www.airmagnet.com/', 'http://www.alcatel-lucent.com/',
       'http://www.ami.com/', 'http://www.apcc.com/', 'http://www.stk.com/',
       'http://www.apani.com/', 'http://www.apple.com/',
       'http://www.arcoide.com/', 'http://www.areca.com.tw/',
       'http://www.argus-systems.com/', 'http://www.ariba.com/',
       'http://www.asus.com.tw/']

s=set(urls)                        # Store URLs as set - Search is O(1)
sh=shelve.open('/tmp/shelve.tmp')  # Dump set (as one unit) to shelve file
sh['urls']=s
sh.close()

sh=shelve.open('/tmp/shelve.tmp')  # Retrieve set from file
s=sh['urls']
print 'http://www.apple.com/' in s # True
print 'http://matan.name/'    in s # False

This approach is quite fast:
import random
import string
import shelve
import datetime

urls=[''.join(random.choice(string.ascii_uppercase + string.digits) for x in range(50))
          for i in range(40000)]
s=set(urls)
start=datetime.datetime.now()
sh=shelve.open('/tmp/test.shelve')
sh['urls']=urls
end=datetime.datetime.now()
print end-start

A: Using a shelve is in general a bad idea for large amounts of data. A database is better suited with you have lots of data.
Options are:

*

*ZODB (Python Object Database)

*any RDBMS

*noSQL world (like MongoDB which is easy approachable and very fast)

A: Hashing is a good idea. To search strings in data bases they use indexes. Since one can define a comparison operation on strings it's possible to build an index which is search tree and process each query with logarithmic complexity


text:
Q: How to map DataFrame values from strings to float in Python I have a data frame I am trying to do predictions on house-prices based on the data such as square footage or if it has central air.
I need to convert string values to numbers in order to model it.
For example the values in the CentralAir column are 'N' or 'Y' which I want to be 0 and 1 respectively.
# pull data into target (y) and predictors (X) using other standard predictors;
train_y2 = df_train.SalePrice

#convert strings to float so we can use predictors like the neighborhood and building type
central_air_mapping = {'N':0, 'Y':1}
df_train['CentralAir'] = df_train.map(central_air_mapping)

predictor_cols2 = ['CentralAir']

# Create training predictors data
train_X2 = df_train[predictor_cols2]

my_model2 = RandomForestRegressor()
my_model2.fit(train_X2, train_y2)

Then it returns
AttributeError: 'DataFrame' object has no attribute 'map'

A: def ToNum(c):
    if c == "Y":
        return 1
    else:
        return 0

df_train["CentralAir"] = df_train["CentralAir"].apply(ToNum)

A: .map() is defined for Series, not DataFrames. This is why you are getting an error.
central_air_mapping = {'N':0, 'Y':1}
df_train['CentralAir'] = df_train['CentralAir'].map(central_air_mapping)
                                      ^^^^
                                 this was missing


text:
Q: In regard to the overriding methods, is the code using two derived classes legal? For example:
public class example {
    public class A {
            public void speak() {
                    System.out.println("Hello!");
            }
  }

    public class B extends A {
            public void response() {
                    System.out.println("How are you?");
            }
  }

    public class C extends A {
            public void responseTwo() {
                    System.out.println("Good!");
  }
}

A test1 = new A(); // it's legal.
A test2 = new B(); // it's also legal.
B test3 = new C(); // not legal. Why is that?

A: Unless there's some information you haven't shared that should be fine since B and C have distinct names. They may have the same fields or not; it doesn't matter.

A: I think you mean in the same source file. The answer is NO.
(Compiler will warn you with the following message : The public type B must be defined in its own file or The public type C must be defined in its own file)
You can define inner classes though, as below :
public class A {
    //blah blah blah

    public class B extends A {
        //blah blah blah
    }

    public class C extends A {
        //blah blah blah
    }

}

A: The declaration of that classes are RIGHT. You cannot declare more than one public class in a file, but you can declare public classes inside other class. But you can only use them in your class in which they are declared.
This is illegal because B and C are diferents classes. See:
A test1 = new A(); // it's legal.

A test2 = new B(); // it's also legal.

B test3 = new C(); // not legal. Why is that?**

You are assigning an object of type C to a variable of type B. They are "brothers" not parent/child classes.
You can do:
A test = new C();

Your classes hierachy are like this:
    A
----|----
|       |
B       C

A: All of these classes should have their own "file"
Is you are using Eclipse it's basically making a new class.
Unless there is any information that you haven't shared with us.
You can't just put multiple classes in the same "file" (class file)
You need to create separate class files for each class you wish to have in your program.

A: What do you mean by "same program"?
You can create multiple classes within same FILE with .java extension, but only one class will be allowed to be public, for example:
public class A {

}

class B extends A{

}

class C extends B{

}

and filename should be the one with public modifier in this case it will be A.java


text:
Q: base64 decode string - emacs different than jvm? With the base64-encoded string JVBERi0xLjENCiXi48/TDQoxIDAgb2JqDQo8PCAN I am getting difference results from emacs than from the clojure code below.
Can anyone explain to me why?
The elisp below gives the correct output, giving me ultimately a valid pdf document (when i past the entire string).  I am sure my emacs buffer is set to utf-8:
(base64-decode-string "JVBERi0xLjENCiXi48/TDQoxIDAgb2JqDQo8PCAN")

"%PDF-1.1
 %âãÏÓ
 1 0 obj
 <<

Here is the same output with the chars in decimal (i think):
  "%PDF-1.1
  %\342\343\317\323
  1

The clojure below gives incorrect output, rendering the pdf document invalid when i give the entire string:
(import 'java.util.Base64 )

(defn decode  [to-decode]
  (let [
        byts           (.getBytes to-decode "UTF-8")
        decoded        (.decode (java.util.Base64/getDecoder) byts)
        ]
    (String. decoded "UTF-8")))

(decode "JVBERi0xLjENCiXi48/TDQoxIDAgb2JqDQo8PCAN")

"%PDF-1.1
%����
1 0 obj
<<

Same output, chars in decimal (i think).  I couldn't even copy/paste this, i had to type it in.  This is what it looks like when i opened the PDF in text-mode for the first three columns:
 "%PDF-1.1
  %\357\277\275\357\277\275\357\277\275\357\277\275
  1"

Edit  Taking emacs out of the equation:
If i write the encoded string to a file called encoded.txt and pipe it through the linux program base64 --decode i get valid output and a good pdf also:
This is clojure:
(defn decode  [to-decode]
  (let [byts        (.getBytes to-decode "ASCII")
        decoded     (.decode (java.util.Base64/getDecoder) byts)
        flip-negatives  #(if (neg? %) (char (+ 255 %)) (char %))
        ]
    (String. (char-array (map flip-negatives decoded)) )))

(spit "./output/decoded.pdf" (decode "JVBERi0xLjENCiXi48/TDQoxIDAgb2JqDQo8PCAN"))

(spit "./output/encoded.txt" "JVBERi0xLjENCiXi48/TDQoxIDAgb2JqDQo8PCAN")

Then this at the shell:
➜  output git:(master) ✗ cat encoded.txt| base64 --decode > decoded2.pdf
➜  output git:(master) ✗ diff decoded.pdf decoded2.pdf
2c2
< %áâÎÒ
---
> %����
➜  output git:(master) ✗

update - this seems to work
Alan Thompson's answer below put me on the correct track, but geez what a pain to get there.
Here's the idea of what works:
(def iso-latin-1-charset (java.nio.charset.Charset/forName "ISO-8859-1" ))

(as-> some-giant-string-i-hate-at-this-point $
  (.getBytes $)
  (String. $   iso-latin-1-charset)
  (base64/decode $ "ISO-8859-1")
  (spit "./output/a-pdf-that-actually-works.pdf" $ :encoding "ISO-8859-1" ))

A: Returning the results as a string, I get:
(b64/decode-str "JVBERi0xLjENCiXi48/TDQoxIDAgb2JqDQo8PCAN")
  => "%PDF-1.1\r\n%����\r\n1 0 obj\r\n<< \r"

and as a vector of ints:
(mapv int (b64/decode-str "JVBERi0xLjENCiXi48/TDQoxIDAgb2JqDQo8PCAN"))

  => [37 80 68 70 45 49 46 49 13 10 37 65533 65533 65533 65533 13 10 49 32 48
      32 111 98 106 13 10 60 60 32 13]

Since both the beginning and end of the string look OK, I suspect the B64 string might be malformed?

Update
I went to http://www.base64decode.org and got the result
"Malformed input... :("

Update #2
The root of the problem is that the source characters are not UTF-8 encoded.  Rather, they are ISO-8859-1 (aka ISO-LATIN-1) encoded.  See this code:
  (defn decode-bytes
    "Decodes a byte array from base64, returning a new byte array."
    [code-bytes]
    (.decode (java.util.Base64/getDecoder) code-bytes))

  (def iso-latin-1-charset (java.nio.charset.Charset/forName "ISO-8859-1" )) ; aka ISO-LATIN-1

  (let [b64-str         "JVBERi0xLjENCiXi48/TDQoxIDAgb2JqDQo8PCAN"
        bytes-default   (vec (.getBytes b64-str))
        bytes-8859      (vec (.getBytes b64-str iso-latin-1-charset))

        src-byte-array  (decode-bytes (byte-array bytes-default))
        src-bytes       (vec src-byte-array)
        src-str-8859    (String. src-byte-array iso-latin-1-charset)
        ]...  ))

with result:
iso-latin-1-charset => <#sun.nio.cs.ISO_8859_1 #object[sun.nio.cs.ISO_8859_1 0x3edbd6e8 "ISO-8859-1"]>

bytes-default  => [74 86 66 69 82 105 48 120 76 106 69 78 67 105 88 105 52 56 47 84 68 81 111 120 73 68 65 103 98 50 74 113 68 81 111 56 80 67 65 78]
bytes-8859     => [74 86 66 69 82 105 48 120 76 106 69 78 67 105 88 105 52 56 47 84 68 81 111 120 73 68 65 103 98 50 74 113 68 81 111 56 80 67 65 78]

(= bytes-default bytes-8859) => true

src-bytes      => [37 80 68 70 45 49 46 49 13 10 37 -30 -29 -49 -45 13 10 49 32 48 32 111 98 106 13 10 60 60 32 13]
src-str-8859   => "%PDF-1.1\r\n%âãÏÓ\r\n1 0 obj\r\n<< \r"

So the java.lang.String constructor will work correctly with a byte[] input, even when the high bit is set (making them look like "negative" values), as long as you tell the constructor the correct java.nio.charset.Charset to use for interpreting the values.
Interesting that the object type is sun.nio.cs.ISO_8859_1.

Update #3
See the SO question below for a list of libraries that can (usually) autodetect the encoding of a byte stream (e.g. UTF-8, ISO-8859-1, ...)
What is the most accurate encoding detector?

A: I think you need to verify the actual bytes that are produced in both scenarios. I would save both decoded results in a file and then compare them using for example xxd command line tool to get the hex display of the bytes in the files.
I suspect your emacs and clojure application uses different font causing the same non-ASCII bytes to be rendered differently, e.g. the same byte value is rendered as â in emacs and � in clojure output.
I would also check if elisp indeed creates the resulting string using UTF-8. base64-decode-string mentions unibytes and I am not sure it's really UTF-8. Unibyte sounds like encoding characters using always one byte per character whereas UTF-8 uses one to four bytes per character.

A: Update
@glts made a correct point in his comment to the question. If we go to http://www.utilities-online.info/base64/ (for example), and we try to decode the original string, we get a third, different result:
%PDF-1.1
%⣏Ӎ
1 0 obj
<<

However, if we try to encode the data the OP posted, we get a different Base64 string: JVBERi0xLjEKICXDosOjw4/DkwogMSAwIG9iagogPDwg, which if we run using the original decode implementation as written by the OP we get the same output:
(decode "JVBERi0xLjEKICXDosOjw4/DkwogMSAwIG9iagogPDwg")
"%PDF-1.1\n %âãÏÓ\n 1 0 obj\n << "

No need to make any conversions. I guess you should check out the encoder.
Original answer
This problem is due to java's Byte being signed.. So much fun!
When you convert it to string, it truncates all negative values to 65533, which is plain wrong:
(map long (decode "JVBERi0xLjENCiXi48/TDQoxIDAgb2JqDQo8PCAN"))

;; (37 80 68 70 45 49 46 49 13 10 37 65533 65533 65533 65533 13 10 49 32 48 32 111 98 106 13 10 60 60 32 13)

lets see what happens:
(defn decode  [to-decode]
  (let [byts           (.getBytes to-decode "UTF-8")
        decoded        (.decode (java.util.Base64/getDecoder) byts)]
    decoded))

(into [] (decode "JVBERi0xLjENCiXi48/TDQoxIDAgb2JqDQo8PCAN"))

;; [37 80 68 70 45 49 46 49 13 10 37 -30 -29 -49 -45 13 10 49 32 48 32 111 98 106 13 10 60 60 32 13]

See the negatives? lets try to fix that:
 (into [] (char-array (map #(if (neg? %) (char (+ 255 %)) (char %))(decode "JVBERi0xLjENCiXi48/TDQoxIDAgb2JqDQo8PCAN"))))

;; [\% \P \D \F \- \1 \. \1 \return \newline \% \á \â \Î \Ò \return \newline \1 \space \0 \space \o \b \j \return \newline \< \< \space \return]

And if we turn this into a string, we get what emacs gave us:
(String. (char-array (map #(if (neg? %) (char (+ 255 %)) (char %)) (decode "JVBERi0xLjENCiXi48/TDQoxIDAgb2JqDQo8PCAN"))))
;; "%PDF-1.1\r\n%áâÎÒ\r\n1 0 obj\r\n<< \r"


text:
Q: Парсинг строки в дату android ошибка Есть дата и время:
Thu, 14 Mar 2019 14:00:56 GMT

Есть код для перевода в дату:
String str_date = response.headers().get("Date");
Date localTime = null;
try {
localTime = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss Z", Locale.getDefault()).parse(str_date);
System.out.println("TimeStamp is " + localTime.getTime());
} catch (java.text.ParseException e) {
e.printStackTrace();
}

и как ни странно есть ошибка:
System.err: java.text.ParseException: Unparseable date: "Thu, 14 Mar 2019 14:00:56 GMT"

хотя все правильно расписано. В чем может быть проблема?

A: Проблема в локализации, поставьте Locale.ENGLISH
new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss Z", Locale.ENGLISH).parse(str_date);


text:
Q: How to scale a second set of observations to the first set in a non-parametric way? Imagine we have a vector of continuous transformations from a process [u_1, u_2, ..., u_n] for a set of inputs [p_1, p_2, ..., p_n], i.e. f(p_i) = u_i. We next develop another set of inputs [q_1, q_2, ..., q_m] where m not necessarily equals n and get observations [v_1, v_2, ..., v_m]. Problem is that the process f is somewhat stochastic i.e. the hidden states of f may change in some unpredictable way. Ergo, two different calls on the same input may result in two somewhat different vector of results. An easy way to think of this is that f computes a deterministic result but adds some random noise to that result before returning it. Is there a good non-parametric way to then scale the second set of output to make it comparable to the first?
One naïve approach would to be concatenate the first and second input and run the second call so that the transformations on both p and q are on the same scale and results are comparable. But imagine if I was doing this in a loop, and the function call was expensive, then I would have to figure out a good selection of inputs from earlier iterations to ensure that transformation results from my current iteration was comparable to previous iterations?


text:
Q: Retina tiled background for Launch Screen.nib I'm trying out the new funky Launch Screen.xib (storyboard) instead of using launcher images in my iOS app.
On my first page I have a tiled background image called bodybg@2x.png which I put on the background of that first page via code:
self.view.backgroundColor = [UIColor colorWithPatternImage: [UIImage imageNamed:@"bodybg.png"]];

So I could do with having the same background on the Launch Screen. Presumably there's no way to execute code when the Launch Screen.xib is loaded, so how do I go about putting a tiled, retina background on a Launch Screen.xib?

A: *

*Add the image to an asset catalog.

*Choose Editor > Show Slicing.

*Change slicing configurations as the following (100x100 image is used here):

(This tells Xcode that there are no fixed parts and the entire image should be tiled).

*Add UIImageView to your launch screen and use the previous image. Set the mode to Scale to Fill and the image will be tiled to fill the image view.


text:
Q: How do check for key value pair over multiple arrays and filter with javascript? I'm trying to filter data by key value pairs. I need to be able to check if a key value pair exists across multiple arrays.
I have some working code to count the number of objects containing a key value pair but run into problems when there are more that one array.

var data = [{
    LastName: "Johnson",
    Id: 2222,
    specialties: [{
        Specialty: "Cardiology",
        BoardCertified: true,
        IsPrimary: true
      },
      {
        Specialty: "Pediatrics",
        BoardCertified: true,
        IsPrimary: true
      }
    ],
  },

  {
    LastName: "Hamilton",
    Id: 2332,
    specialties: [{
      Specialty: "Pediatrics",
      BoardCertified: true,
      IsPrimary: true
    }, ],
  }
]

var specialty = "Pediatrics";

var filtered = data.filter(function(item) {
  return item.specialties[0].Specialty == specialty;
});

console.log(filtered.length);

This counts the items with a key value pair of "Specialty: "Pediatrics"".
Right now this will only return "1" but I want it to return "2".
Is this possible?
return item.specialties.Specialty == specialty;     //does not work

A: If you are sure it will only appear once in each grouping, you can modify your filtering function:
var filtered = data.filter(function(item){
     return item.specialties.some(item => item.Specialty === specialty);
)};

Or with two arrow functions:
var filtered = data.filter(item =>
      item.specialties.some(item =>
         item.Specialty === specialty)
   )


text:
Q: How to stop dhcp discover messages after dhcp release? I configured a wrong interface as dhcp and did a ifdown and ifup on that interface. DHCP client keeps sending DHCP discover messages and I had to wait for a while for it stop. ctl+z or ctl+c didn't really work.
Is there a way to stop that instead of waiting for a long time.
Thanx in advance.

A: You can find the PID of the DHCP Client with pgrep. Read man pgrep. You can kill (send a signal to) by name with pkill. man pkill.


text:
Q: Angular 2: ngFor in descention order I have a component with an array of items.
Every time the user clicks a button, a new item added to this array.
This array is shown in a ngFor loop this way:
    <li *ngFor="let log of Logs" class="list-group-item" [innerHTML]="log"

Now, new logs are shown at the bottom of the list. What I'm trying is making the new logs shown at the top of the list.
How it can be done with angular 2?

A: You could create a custom pipe for this:
@Pipe({
  name: 'reverse'
})
export class ReversePipe {
  transform(arr) {
    var copy = arr.slice();
    return copy.reverse();
  }
}

(note that I create a copy of the array not to update the source array)
and use it this way:
<li *ngFor="let log of Logs | reverse"
    class="list-group-item" [innerHTML]="log"

Don't forget to add this pipe into the pipes attribute of the component where you use it.


text:
Q: Looking for a story about the end of life on earth I am looking for a story I read in an anthology. In the story, the stars started to disappear and strange creatures appeared and collected all of the butterflies on earth.  Eventually, the sun went out.

A: This is John Varley's "In Fading Suns and Dying Moons", published in 2003, and collected in his anthology "The John Varley Reader" as well as some other publications.
In the story, aliens had seeded the development of the Solar System, and had returned four billion years later to see how it turned out. A line of aliens appeared on the west coasts of all land masses and moved east, collecting all the butterflies. An entomologist is conscripted by the US army to find out why.
It turns out that they're collecting them because:

"Butterflies are the most beautiful thing on your planet, aren't they?"

and

"We are building...a place. Our leader wishes it to be a very special place. Therefore we are making it of these very special creatures."

At the same time as they were doing this, the aliens were also harvesting creatures from other planets:

 "... Deep in the atmospheres of your four gas giants, Jupiter, Saturn, Uranus and Neptune, beautiful beings have evolved that...our leader treasures. On Mercury, creatures of quicksilver inhabit deep caves near the poles. These are being gathered as well. And there are lifeforms we admire that thrive on very cold planets."

 The protagonist assumes that they're referring to Pluto, but later finds out that they mean to extinguish the sun and cultivate them on Earth.


text:
Q: Best way to populate a dropdown sitewide that is I am using  CakePHP 1.3 and a layout which includes a dropdown of organizations a user has access to administer, so I'm trying to populate that dropdown with organizations that contain the userid that is logged in, but I want to populate it before the user sees anything so they can use it in the header. The dropdown needs to appear on every page once logged in. I tried adding  the query to pull these organizations in the appcontroller, but userid was not yet available to use in before filter. Where or how should I do this? Should it be in session or is there a better construct to use? Element?

A: In my app it's no problem to use the user_id from within the beforeRender (if you are using the Auth-Component).
You can use it with $this->Auth->user('id').
I would do it like this: Check in the AppController if the user is logged in. If he is, pull your wanted information from the database (or whereever you get your information from) and store it in a variable called $dropdown for example.
If the user is not logged in, $dropdown will be false.
You now make this variable available to the view with $this->set(compact('dropdown'))
Now in your layout (this is important to you have it on every page) you can easily do a check if $dropdown is false or not. If not, you can work with your variable and show the user your wanted dropdown.


text:
Q: Problem with a double integral Why is the following integral not evaluated by Mathematica (ver. 11.3, Windows 10)
Integrate[1, {x, 2 - Sqrt[2], 1}, {y,
  1/2 - 1/2 Sqrt[(-4 + 8 x - 4 x^3 + x^4)/((-2 + x)^2 x^2)],
  1/2 + 1/2 Sqrt[(-4 + 8 x - 4 x^3 + x^4)/((-2 + x)^2 x^2)]}]

Edit: This is actually a double integral $\int_{2-\sqrt{2}}^{1} dx \int_{ \frac{1}{2} - \frac{1}{2} \sqrt{(-4 + 8 x - 4 x^3 + x^4)/((-2 + x)^2 x^2)}}^{ \frac{1}{2} + \frac{1}{2} \sqrt{(-4 + 8 x - 4 x^3 + x^4)/((-2 + x)^2 x^2)}} dy$.

A: I am confused as to what integral you want to be solved.
You need to write the integral function in a form like
(*integrand*)
eq = 1;
(*limits*)
limits = {x, 2 - Sqrt[2], 1};

result = Integrate[eq, limits]

So, I don't understand your question - are you trying to integrate it twice?
eq = 1;
limits = {y,
   1/2 - 1/2 Sqrt[(-4 + 8 x - 4 x^3 + x^4)/((-2 + x)^2 x^2)],
   1/2 + 1/2 Sqrt[(-4 + 8 x - 4 x^3 + x^4)/((-2 + x)^2 x^2)]};
result1 = Integrate[eq, limits]
limits2 = {x, 2 - Sqrt[2], 1};
NIntegrate[result1, limits2]

A: As an alternative to @Tomi's solution, define a two-dimensional region:
R = ImplicitRegion[x*(x-2)*(x*y*(x-2)*(y-1)+1)+1 <= 0 &&
                   2 - Sqrt[2] <= x <= 1,
                   {x, y}];

Numerical integration over regions is straightforward:
NIntegrate[1, Element[{x, y}, R]]
(*    0.339303    *)

You can of course also use your original parametrization of the region:
R0 = ImplicitRegion[2 - Sqrt[2] <= x <= 1 &&
       1/2 - 1/2 Sqrt[(-4 + 8 x - 4 x^3 + x^4)/((-2 + x)^2 x^2)] <= y <=
       1/2 + 1/2 Sqrt[(-4 + 8 x - 4 x^3 + x^4)/((-2 + x)^2 x^2)],
       {x, y}];
NIntegrate[1, Element[{x, y}, R0]]
(*    0.339303    *)


text:
Q: Assembly Test Instruction I want to know what does this operation mean?
Test EDX, 200

I have DWORD value in EDX like:
1A1B1C00

When I do test EDX, 200
and then a JE, jump is taken. Why? EDX is not equal to 200.
I want to know more about Test EDX, 200 meaning.

A: A test performs an AND without modifying the operands (it only modifies some flags, like ZF et al). A je simply tests ZF (the zero flag) and jumps if set.
So Test EDX, 200 will AND the value in EDX with 0x200 and set ZF to 1 if the result of that AND was 0.  In your case that will give us:
0x1A1B1C00 AND 0x00000200 -> 0x00000000

Since 0x0200 is 0000 0010 0000 0000 in binary, the intent of the instruction Test EDX, 200 is to test the value in EDX and see if the 9th bit (9  places from the right counting from 0) is a 0 or 1, and take the jump if it is a zero.

A: To find out what an assembly instruction does, I recommend using Google. In Google you can just write the name of the instruction, in this case test, and something like intel instruction (for Intel instructions):
Google: test intel instruction
From the results of the Google search linked above you'll also find out that some servers have separate pages for different x86 assembly instructions named according to the name of the instruction:
http://web.itu.edu.tr/kesgin/mul06/intel/instr/test.html
As it says on the webpage linked above:
TEST - Test For Bit Pattern

    Usage:  TEST    dest,src
    Modifies flags: CF OF PF SF ZF (AF undefined)

    Performs a logical AND of the two operands updating the flags
    register without saving the result.

To find out what some other instruction does, for example cmpxchg, all you need to do is to replace the name of the instruction in the address, so it would be:
http://web.itu.edu.tr/kesgin/mul06/intel/instr/cmpxchg.html
Finally, the ultimate source of information regarding Intel assembly are the Intel Software Developer Manuals, and they are very useful and freely available as pdf:
Intel® 64 and IA-32 Architectures Software Developer Manuals
Combined Volume Set of Intel® 64 and IA-32 Architectures Software Developer's Manuals


text: Q: Combining images in opencv I am working on a project to generate a collage in OpenCv for an art project. I first select random frames from a video and then use facial recognition to identify a person in an image, if there is one I extrude the foreground and save the image as just foreground with the background blacked out. I now want to generate these 'stickers' into a larger collage and was wondering about the best way to combine such images and remove the black. Any suggestions or links would be amazing.


text:
Q: per-file dependencies in ant I have a set of input files, each of which is processed to generate an output file.  In one case it's hibernate xml files as input, and java files as output, but that isn't the only case I have to deal with.
In make, I would have set up a rule to tell it how to generate a .java file from an .hbm.xml file (modulo the .hbm.xml specifying a different class name to generate), and modifying a single .hbm.xml files would trigger the build of a single .java file.
How do I express the dependencies in ant so it will only build the out of date .java files and not all of them just because one .hbm.xml changed?
I'm looking at apply and up-to-date, but not seeing a solution yet...

A: Have you looked at ant-contrib outofdate task?
The example at the end of the doc looks like something you could use:
  <outofdate property="manual.outofdate"
             outputsources="grammer.sources">
    <sourcefiles>
      <fileset dir="${src.grammer}" includes="**/*.y"/>
    </sourcefiles>
    <mapper type="glob" dir="${src.grammer}" from="*.y" to="${gen.grammer}/*.c"/>
    <mapper type="glob" dir="${src.grammer}" from="*.y" to="${gen.grammer}/*.h"/>
    <sequential>
      <shellscript shell="bash">
        cd ${gen.grammer}
        for g in ${grammer.sources}
        do
            gengrammer $g
        done
      </shellscript>
    </sequential>
  </outofdate>

Also note that you might use ant-contrib "for" task in the body of the outofdate task.
To initialize ant-contrib do this:
<property name="ant-contrib.jar" location="..."/>
<taskdef
  resource="net/sf/antcontrib/antlib.xml"
  uri="http://ant-contrib.sourceforge.net"
>
  <classpath>
    <pathelement location="${ant-contrib.jar}"/>
  </classpath>
</taskdef>


text:
Q: Running "apply" command on a very large data frame I have a tibble in R that has dimension of 15,000,000 x 140. Size-wise it's about 6 gb.
I want to check if any of columns 11-40 for a given row start in a specific list. I want to get out a vector of 1 & 0's that is then 15,000,000 long.
I can do this using the following:
subResult <- apply(rawData[,11:40], c(1,2), function(x){substring(x,1,3) %in% c("295", "296", "297", "298", "299")})

result <- apply(subResult, 1, sum)

Problem is that this is way too slow -- it would take over 1 day to do just for the first line.
Is there any way to do this faster -- perhaps directly through dplyr or data.table?
Thank you!
Here's a sampling of the data trimmed to just columns 11-40.
!> head(rawData)
 # A tibble: 6 x 30
   X1    X2    X3    X4    X5    X6    X7    X8    X9    X10   X11   X12   X13
   <chr> <chr> <chr> <chr> <chr> <chr> <chr> <chr> <chr> <chr> <chr> <chr> <chr>
 1 39402 39451 3fv3i 19593 fk20 14p4  59304  329fj2 NA    NA    NA    NA    NA
 2 39422 f203ff vmio2  vo2493  19149 59833 13404 394034 43920  349304   59302 1934 34834
 3 3432f32 fe493  43943 H2344 53049  V602  3124  K148 K13  NA    NA    NA    NA
 # ... with 17 more variables: X14 <chr>, X15 <chr>, X16 <chr>, X17 <chr>,
 #   X18 <chr>, X19 <chr>, X20 <chr>, X21 <chr>, X22 <chr>, X23 <chr>,
 #   X24 <chr>, X25 <chr>, X26 <chr>, X27 <chr>, X28 <chr>, X29 <chr>, X30 <chr>

A: My comments:

*

*apply converts your data to a matrix

*a data frame is above all a list, not a matrix

*substring() is a vectorized function (%in% too)

So, I would do:
sapply(rawData[11:40], function(var) {
  substring(var, 1, 3) %in% c("295", "296", "297", "298", "299")
})

and then use rowSums() instead of apply(subResult, 1, sum).

A: Based on the description, this can be done either with tidyverse
library(tidyverse)
rawData %>%
   select(11:40) %>% #select the columns
   #convert to logical columns
   mutate_all(funs(substring(.,1,3) %in% c("295", "296", "297", "298", "299"))) %>%
   reduce('+') %>% #get the rowwise sum
   mutate(rawData, newcol = .) # assign a new column to the original data

Or with data.table by converting the 'data.frame' to 'data.table' (setDT(rawData)), specify the columns of interest in .SDcols, loop through the columns, convert it to logical by using the OP's condition, Reduce by taking the sum of each row and assign (:=) to 'newcol'
library(data.table)
setDT(rawData)[, newCol := Reduce('+', lapply(.SD, function(x)
      substring(x, 1, 3) %chin% c("295", "296", "297", "298", "299"))),
     .SDcols = 11:40]

A: Try to use Rcpp package.
Here is a simple C++ program which takes two string vectors, and checks if 3 characters of elements in first are equal to the second one. So it will output logical matrix of size length(first vector) x length(second vector).
#include <Rcpp.h>
using namespace Rcpp;

// [[Rcpp::export]]
LogicalMatrix IndicatorMatrix(std::vector<std::string> target, std::vector<std::string> tocheck) {

  int nrows = target.size();
  int ncols = tocheck.size();

  LogicalMatrix ind(nrows, ncols);

  for(int r=0; r<nrows; r++) {
    for(int c=0; c<ncols; c++) {

      bool found = target[r].substr(0,3) == tocheck[c];
      ind(r,c) = found;

    }
  }

  return ind;

}

After that you can source this program into R and use your IndicatorMatrix function as if it would be a R function object.
library(Rcpp)
sourceCpp("C:/Users/Desktop/indicatorMatrix.cpp")

rep("123456", 15000000) -> x
df <- data.frame(x,x,x,x,x,x,x,x, stringsAsFactors=FALSE)
y <- c("123", "124", "345", "231", "675", "344", "222")

t1 <- Sys.time()
out <- lapply(1:length(df), function(col) {

  res <- IndicatorMatrix(unlist(df[,col]), y)
  res

})
t2 <- Sys.time()
t2-t1

Program searched for 8 3-character strings in 8 column data frame with 15 milions of rows in about 100 seconds. So this could be right direction for you.


text:
Q: Why there is no Syncing Mechanism for Editing posts? It happened many times that I submit an Edit Suggestion and immediately after that I see the post has already been edited by another guy (usually higher-rep) and my edit has been rejected by either Community or reviewers.
Why there is no mechanism to prevent simultaneous edits and avoid unfair rejection?
This is my first attempt to edit the post:

As you can see it got rejected by community because another user submitted an edit. And immediately after that I wanted to re-edit my edit which turned to this (Actually it rolled back all the edits):

A: Because that higher privileged user is... well... higher privileged.
His edit privileged will not be locked out just because any (potentially anonymous) user is suggesting an edit to the post.
Also, we don't know which edit is better, nor we know whether he started editing, and didn't finish or left the tab open.
The idea is good, but you can't cleanly implement it without introducing a whole set of problems.


text:
Q: python pandas add new calculated column by evaluating expressions(combination of other columns) I am new to pandas, data-frames  i am struggling at a point where i
need to add a new column to my data frame which is something like
combination of other columns on the basis of arithmetic operations
something like..
Dataframe columns:
col1 , col2 col3.. etc

Functions:
sum()
count()
distinct()
min()
etc..

Operators: like + - * / etc..

now user can drag and drop anything from above 3(functions, columns
and operators) which might make expression like..

sum(col1) + min(col2) * 10 + 2    or something like this...

So my question how can i calculate it on pandas dataframe which forms
(calculated) a new column in dataframe.
Please help me, how can i implement this feature where i can give
permission to user to choose any combination of column and operation
or combination of operation on a single column which i call as
calculated column

A: I dont know why my question marked as -1 but i finally find out the answer,
just i need to modify the expression being created via drag and drop and user this function from python's eval() which nicely works with pandas data-frames
df.eval(col1.sum() + col2.min() * 10 + 2)

and it works fine for any expression, hope it helps anyone similar.


text:
Q: include boost in CMake I try to include the current version of the Boost library into my cmake file. But I 'm struggle with the full include. I have already included the boost::filesystem library. So I hope this is not a big change in the code.
Here my Cmake include that works for me:
#include boost
#===========================================================================
set(Boost_INCLUDE_DIR "/Volumes/Code/boost_1_79_0")
set(Boost_LIBRARY_DIR "/Volumes/Code/boost_1_79_0/stage/lib")

find_package(Boost
    1.79.0 REQUIRED
    COMPONENTS
        filesystem
    )

if(NOT Boost_FOUND)
    message(FATAL_ERROR "Boost Not found")
else()
    message(STATUS "Boost version ${Boost_VERSION} found")
endif()

include_directories(include)
include_directories(${Boost_INCLUDE_DIR})
target_link_libraries(${EXECUTABLE}
PUBLIC
    Boost::filesystem)
#===========================================================================

Then I tried that and it failed:
#include boost
#===========================================================================
set(Boost_INCLUDE_DIR "/Volumes/Code/boost_1_79_0")
set(Boost_LIBRARY_DIR "/Volumes/Code/boost_1_79_0/stage/lib")

find_package(Boost
    1.79.0 REQUIRED
    COMPONENTS
        filesystem
        optional
    )

if(NOT Boost_FOUND)
    message(FATAL_ERROR "Boost Not found")
else()
    message(STATUS "Boost version ${Boost_VERSION} found")
endif()

include_directories(include)
include_directories(${Boost_INCLUDE_DIR})
target_link_libraries(${EXECUTABLE}
PUBLIC
    Boost::filesystem
    Boost::optional)
#===========================================================================

Does anyone know a way to integrate all Boost Libraries without listing them or sees my mistake?
If someone has suggestions for improvements, feel free to teaching me.

A:
set(Boost_INCLUDE_DIR "/Volumes/Code/boost_1_79_0")
set(Boost_LIBRARY_DIR "/Volumes/Code/boost_1_79_0/stage/lib")

That's not how you should use CMake: your solution just hardcodes paths, and the whole idea of CMake is that you can take a CMake project and build it on a different machine, where paths and necessary flags are different.
So, delete that altogether. You want to have
set(BOOST_REQUIRED_COMPONENTS
    filesystem
    optional
)
set(BOOST_MIN_VERSION 1.79.0) # or whatever you need!
# Here you can either append or set a root to look into
# In general, **don't do that**! Your boost build and installation
# should come with the correct CMake configure scripts to automate this!
# If you set it here, the people trying to build your code on a different
# machine **WILL** hate you.
# set(BOOST_ROOT "/Volumes/Code/boost_1_79_0")
find_package(
    Boost ${BOOST_MIN_VERSION} REQUIRED
    COMPONENTS ${BOOST_REQUIRED_COMPONENTS}
)
target_link_libraries(${EXECUTABLE} PUBLIC
    Boost::filesystem
    Boost::optional
)
target_include_directories(${EXECUTABLE} PRIVATE include)

You whole setting include_directories(${Boost_INCLUDE_DIR}) is redundant (and a bad idea); target_link_libraries( ... Boost::...) does that automatically.

Does anyone know a way to integrate all Boost Libraries without listing them or sees my mistake?

You don't do that, or your linking takes forever, you produce, under circumstances, gigantic object files and executables, and all for the advantage of not having to write down each Boost component as you use them, in a single place!
So, you could use the ALL meta-compoent (which was introduced by Boost 1.73), but I'd strongly encourage you not to do that.


text:
Q: How does Linux kernel find dirty page to flush? Since the pages are stored in address_space within each inode, how does the background page cache flush thread know all dirty pages?

A: They're all in one place:
struct bdi_writeback {
        struct backing_dev_info *bdi;   /* our parent bdi */
        unsigned int nr;

        unsigned long last_old_flush;   /* last old data flush */
        unsigned long last_active;      /* last time bdi thread was active */

        struct task_struct *task;       /* writeback thread */
        struct timer_list wakeup_timer; /* used for delayed bdi thread wakeup */
        struct list_head b_dirty;       /* dirty inodes */
        struct list_head b_io;          /* parked for writeback */
        struct list_head b_more_io;     /* parked for more writeback */
        spinlock_t list_lock;           /* protects the b_* lists */
};

b_dirty is the list you're looking for.
For some information on how the flushing happens, take a look in here. The code is kind of complex though. To summarize (alot), consider that in the default configuration data written to disk will sit in memory until either a) they're more than 30 seconds old, or b) the dirty pages have consumed more than 10% of the active, working memory.

A: On the x86 platform the OS must inspect its page table entries to find the pages that are dirty. There's a special, dirty, bit in them that's set by the CPU automatically during memory writes. There must be some code that scans the PTEs for dirty=1.


text:
Q: Use await only for 20 seconds I am waiting for my promise to resolve in an async function using await but I want to wait for only 20 sec. If no response comes in that time (neither positive nor negative from the promise), I want to continue and display 'timeout'. How can I do this?

A: You can use Promise.race:
const promise1 = func();
const promise2 = new Promise((res, rej) => setTimeout(rej, 20000));

try {
   await Promise.race([promise1, promise2]);
} catch (e) {
   // time out or func failed
}


text:
Q: What is the mathematical expression for the Higgs boson coupling constant? I have been searching around and cannot get an expression for the Higg's coupling constant.
By 'coupling constant', I mean for the strong force $$\alpha_S=\frac{{g_S}^2}{4 \pi \hbar c}\approx 0.1\tag{1}$$
and for the weak force
$$\alpha_W=\frac{{g_W}^2}{4 \pi \hbar c}\approx 0.034\tag{2}$$
and for the EM force
$$\alpha_{EM}=\frac{{e}^2}{4 \pi \epsilon_0\hbar c}\approx 0.0073$$
Where in $(1)$ and $(2)$, $g_S$ and $g_W$ is the vertex strength in the Feynman $\mathrm{diagram^{\chi}}$:

Does a similar expression exist for the Higgs boson?

$\chi$ - Image from ICL dept. of physics.

A: The Higgs boson does not have a separate coupling to the rest of the particles in the table of elementary particles.  The magnitude of the coupling is a combination of the weak and the electromagnetic coupling constant, depending on the reaction measured . There are efforts to quantify this from experimental data.

We estimate the expected precision at a multi-TeV muon collider for measuring the Higgs boson couplings with electroweak gauge bosons, HVV and HHVV (V=W±,Z), as well as the trilinear Higgs self-coupling HHH.

A: This article notes that particles can exert a force on one another via the Higgs field and assigns a dimensionless coupling constant (of the same form as the examples given):
\begin{equation}
\alpha_{Higgs} = \left ( \frac{mc^2}{4 \pi v} \right )^2
\end{equation}
where $v$ is the vacuum expectation value of the Higgs field. Note that this force extremely short range due to the mass of the Higgs boson.
In the standard model, the Yukawa couplings of each of the fermions to the Higgs field are independent inputs. Therefore, the value of the expression above will depend on the particle you consider.


text:
Q: How do I create a List from another List filtered by an object's property in Java? I have an object CalendarEvent
public class CalendarEvent {

    LocalDate startDate;
    String clientName;
    Worker worker;
}

And I need to find all the objects that have the same startDate. I tried using Maps but they filter by unique keys so it doesn't work for repeated dates

A: If you have all of those objects in some type of collection called events...
    Map<LocalDate, List<CalendarEvent>> mapped = events.stream()
        .collect(Collectors.groupingBy(event -> event.startDate));

This will return a map where the keys are the unique start dates and the values are lists of CalenderEvents that have that start date.


text:
Q: My WorkManager isn't running in foreground or background This is the code I am using to setup the work task in my main activity:
    val apiFetchBuilder = PeriodicWorkRequestBuilder<APIWorker>(timeValue, TimeUnit.MINUTES) // timeValue = 1 for testing
    val apiFetchWorker = apiFetchBuilder.build()
    val instance = WorkManager.getInstance(this)
    instance.enqueueUniquePeriodicWork(Constants.background_work, ExistingPeriodicWorkPolicy.KEEP, apiFetchWorker)

and then my work manager is setup as follows:
class APIWorker(context: Context, workerParams: WorkerParameters): Worker(context, workerParams){

override fun doWork(): Result {
    Log.d("WorkManager", "doWork: ")
    //Do API Work here
    return Result.success()
}

The logcat isn't registering this call at all no matter how long I wait or how many times I open the main activity to enqueue the work manager


text:
Q: Apache httpd auth fails with Bcrypt I'm using .htaccess and .htpasswd to authenticate users, but authentication fails every time for some reason. I have passwords in htpasswd hashed with Bcrypt (PHP's password_hash function).
Everything works perfect when using in production server (CentOS 7 with Apache), but it fails every time when I'm trying to authenticate in development server (MacOS Sierra 10.12 with Zend Server).
Do you have any idea what would cause the problem? Is there some configuration where the Bcrypt hash isn't turned on, or something?

A: Depending on the authentication type (e.g. basic), the appropriate mod_auth_* modules must be loaded. To see which modules are loaded in your Apache, try on the command line
apachectl -M

or maybe
apache2ctl -M

Compare the loaded modules from production and development server and adjust accordingly. To see just the authentication modules, try
apachectl -M | grep auth


text:
Q: net::ERR_INCOMPLETE_CHUNKED_ENCODING 200 (OK) I am new in networking and I try to write my first http server on C. However i faced a problem. When i try to send image by chunks i recive an error GET http://localhost/img.jpg net::ERR_INCOMPLETE_CHUNKED_ENCODING 200 (OK), whith html it works fine.
void answerOnGet(int socketCopy, char *fileName)
{
struct stat sbuf;
char filePath[SIZE];
determinateFilePath(fileName, filePath);

stat(filePath, &sbuf);

char responseHeader[2*SIZE];
char fileType[SIZE];

if (strstr(fileName, ".html") || !strcmp(fileName, "/"))
{
    strcpy(fileType, "text/html");
}
else if (strstr(fileName, ".jpg"))
{
    strcpy(fileType, "image/jpg");
}
else if(strstr(fileName, ".ico"))
{
    strcpy(fileType, "image/ico");
}
else
{
    fprintf(stderr, "Type error\n");
    exit(1);
}

FILE *fd = fopen(filePath, "rb");

if(fd == NULL)
{
    perror("Opening error");
    exit(1);
}

snprintf(responseHeader, sizeof(responseHeader),
    "HTTP/1.1 200 OK\r\n"
    "Transfer-Encoding: chunked\r\n"
    "Content-type: %s\r\n\r\n", fileType
);

if(write(socketCopy, responseHeader, strlen(responseHeader)) < 0)
{
    perror("Write error");
    exit(1);
}

long unsigned sizeOfChunk = 0;

if(sbuf.st_size > SIZE)
{
    sizeOfChunk = sbuf.st_size/50;
}
else
{
    sizeOfChunk = sbuf.st_size;
}

char *buf = malloc(sizeof(char) * (sizeOfChunk + 2));

printf("Size of chunk = %ld\n", sizeOfChunk);

char amountOfBytes[SIZE];
while(fread(buf, sizeof(char), sizeOfChunk, fd) == (sizeOfChunk))
{

    sprintf(amountOfBytes, "%lX\r\n", sizeOfChunk);

    puts("\nStart to write");
    if(write(socketCopy, amountOfBytes, strlen(amountOfBytes)) < 0)
    {
        perror("Write bytes error");
        exit(1);
    }

    strcat(buf, "\r\n");

    if(write(socketCopy, buf, strlen(buf)) < 0)
    {
        perror("Write error");
        exit(1);
    }
    puts("\nEnd of write");

    bzero(buf, sizeOfChunk);
    bzero(amountOfBytes, strlen(amountOfBytes));
}

puts("Send zero chunk");

if(write(socketCopy, "0\r\n\r\n", strlen("0\r\n\r\n")) < 0)
{
    perror("Write zero chunk error");
    exit(1);
}

fclose(fd);
free(buf);

}

A: Your mistake is most likely
if(write(socketCopy, buf, strlen(buf)) < 0)

What does strlen(buf) do? It counts the number of bytes up to the first 0 byte.
Is that the correct number of bytes to write? Only if there's a 0 byte at the end and none before that.
Is there? Well, no. Files can have 0 bytes in the middle and fread does not put one at the end.
Instead of strlen(buf) you should use sizeOfChunk.
Other bugs:

*

*As @rveerd pointed out, it's possible that you call write and the kernel only writes part of the data. If that happens, you still have to call it again to write the rest of the data. This may happen multiple times so you need a loop. I suggest making a function actually_write which does the loop, then you can call actually_write(socketCopy, buf, sizeOfChunk)

*Your program doesn't send some of the bytes at the end sometimes. If the file is, for example, 1001 bytes long, then you do 20-byte chunks, and after the last full chunk there is still one byte, and fread returns 1 but you don't send the extra byte.


text:
Q: Spring JPA: How to run multi sql query in one round? In spring if we define method in repository like this:findByName(String name), we could call this method to retrieve data back. What I want is that, could I have some ways to call 2 or more methods like I say above, and spring sends query to database in just one round instead of 2rounds? I would like to optimize performance in the case that I am certain that some sql queries will be sent togother
update: one round means in one connection we send multi sql queries. The object is to avoid more than one round trip time when there is more than 1 sql query is about to send.
e.g., query 1 is select * from table where xx=bb
query 2 is selext * from another_table where zz=cc
in trivial way, we may send 2 queries like this:
1. send query 1 by   calling repository's findbyxx method
2. send query 2 by   calling repository's findbyzz method
in above case, query 2 will be sent after query 1's response came back. This is a waste IMHW. I am seeking a way to send these 2 queries at once and got answer at once.

A: If you want to keep the database connection between these two queries, you must set up a transaction manager for your JPA Configuration:
<bean id="txManager" class="org.springframework.orm.jpa.JpaTransactionManager">
   <property name="entityManagerFactory" ref="yourEntityManagerFactory" />
</bean>
<tx:annotation-driven transaction-manager="txManager" />

This will imply that when you annotate a @Service's method with @Transaction (or the whole class), the same session/connection will be kept between your queries.
For more info: https://www.baeldung.com/transaction-configuration-with-jpa-and-spring


text:
Q: Bootstrap navbar collapse and visible part I am creating a theme with Bootstrap and I would like my top menu to have:
about, home, contact etc., and another icon for messages. (you can check this image)
But when the page is viewed on mobile I would like the menu to collapse as in this image
But only the messages icon to be still visible.
Currently it is not, any ideas how I can do that?

A: Wrap the image icon with .visible-xs class example:
<img class="visible-xs" src="...">

Here is the link for more information:
Responsive utilities


text:
Q: null pointer exception in captcha I am implementing the captcha code in my form but I am getting a null pointer exception the method getImage().
I have two captcha codes in the project one is working fine but the other one is showing the following error. I don't know why it is not taking the captcha as a parameter.
I am providing the logcat and the mainactivity.java below.
Logcat
FATAL EXCEPTION: main

Process: com.mws.tms_application, PID: 6983
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.mws.tms_application/com.mws.tms_application.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.graphics.Bitmap com.mws.tms_application.TextCaptcha.getImage()' on a null object reference
     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2817)
     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2892)
     at android.app.ActivityThread.-wrap11(Unknown Source:0)
     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1593)
     at android.os.Handler.dispatchMessage(Handler.java:105)
     at android.os.Looper.loop(Looper.java:164)
     at android.app.ActivityThread.main(ActivityThread.java:6540)
     at java.lang.reflect.Method.invoke(Native Method)
     at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
  Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.graphics.Bitmap com.mws.tms_application.TextCaptcha.getImage()' on a null object reference
     at com.mws.tms_application.MainActivity.onCreate(MainActivity.java:41)
     at android.app.Activity.performCreate(Activity.java:6980)
     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1213)
     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2770)
     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2892)
     at android.app.ActivityThread.-wrap11(Unknown Source:0)
     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1593)
     at android.os.Handler.dispatchMessage(Handler.java:105)
     at android.os.Looper.loop(Looper.java:164)
     at android.app.ActivityThread.main(ActivityThread.java:6540)
     at java.lang.reflect.Method.invoke(Native Method)
     at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)

main activity.java
package com.mws.tms_application;

import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {
     TextView Registerlink;
     Button Submit_btn ,Reset_btn,Link_btn;
     EditText Username,Usermob,UserAddress,Usermailid,Userpass,Usercapt;
     ActionBar actionBar;
     ImageView imageView1;
     TextCaptcha textCaptcha1;
     //#2eb82e
     @Override
     protected void onCreate(Bundle savedInstanceState) {
          super.onCreate(savedInstanceState);
          setContentView(R.layout.activity_main);
          Intent intent = getIntent();
          Registerlink = (TextView) findViewById(R.id.loginlink);
          Submit_btn=(Button)findViewById(R.id.Submit_btn);
          Reset_btn=(Button)findViewById(R.id.Main_Reset_btn);
          Username=(EditText)findViewById(R.id.username_edtext);
          Usermob=(EditText)findViewById(R.id.usermob_no_edtext);
          UserAddress=(EditText)findViewById(R.id.userAddresss_edtext);
          Usermailid=(EditText)findViewById(R.id.usermailid_edtext);
          Userpass=(EditText)findViewById(R.id.userpass_edtext);
          Usercapt=(EditText)findViewById(R.id.usercapt_edtext);
          Link_btn=(Button)findViewById(R.id.Link_btn);
          imageView1=(ImageView)findViewById(R.id.register_capt_imageview);
          imageView1.setImageBitmap(textCaptcha1.getImage());
          actionBar=getSupportActionBar();
          actionBar.show();
          actionBar.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#2eb82e")));

          MainLogic();
     }

     private void MainLogic()
     {    Link_btn.setOnClickListener(new View.OnClickListener() {
          @Override
          public void onClick(View v) {
               Intent i=new Intent(MainActivity.this,Home_Navigation_Activity.class);
               startActivity(i);
          }
     });
          Submit_btn.setOnClickListener(new View.OnClickListener() {
               @Override
               public void onClick(View v) {
                    isValidData();
               }
          });
          Reset_btn.setOnClickListener(new View.OnClickListener() {
               @Override
               public void onClick(View v) {
               claredata();
               }
          });
          Registerlink.setOnClickListener(new View.OnClickListener() {
               @Override
               public void onClick(View v) {
                    Intent i=new Intent(MainActivity.this,Login_Activity.class);
                    startActivity(i);
               }
          });
     }
     /* Userid,Username,usermob,userAddress,usermailid,userpass,usercapt;*/

     public  boolean isValidData()
     {
        String id,name,mobile,address,email,password,captch;

          name=Username.getText().toString();
          mobile=Usermob.getText().toString();
          address=UserAddress.getText().toString();
          email=Usermailid.getText().toString();
          password=Userpass.getText().toString();
          /*captch=Usercapt.getText().toString();*/
          if (!name.equals("")&&!mobile.equals("")&&mobile.length()>=10&&mobile.length()<=13&&!address.equals("")&&!email.equals("")&&!password.equals(""))
          {
               if (validEmail((email)))
               {
                    return true;
               }
               else
               {
                    AlertDialog.Builder alt=new AlertDialog.Builder(MainActivity.this);
                    alt.setMessage("Invalid Email_Id");
                    alt.setCancelable(true);
                    alt.setPositiveButton("ok", new DialogInterface.OnClickListener() {
                         @Override
                         public void onClick(DialogInterface dialog, int which) {
                              dialog.dismiss();
                         }
                    });
                    AlertDialog alertDialog=alt.create();
                    alertDialog.show();
                    return false;
               }

          }
          else
          {
          AlertDialog.Builder alt=new AlertDialog.Builder(MainActivity.this);
               alt.setMessage("Please fill all details");
               alt.setCancelable(true);
               alt.setPositiveButton("ok", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                         dialog.dismiss();
                    }
               });
               AlertDialog alertDialog=alt.create();
               alertDialog.show();
          }
        return false;
     }
     public boolean claredata()
     {
          Username.setText("");
          Usermob.setText("");
          UserAddress.setText("");
          Usermailid.setText("");
          Userpass.setText("");
          /*captch=Usercapt.getText().toString();*/
          return false;
     }
     private boolean validEmail(String email) {
          final String emailPattern = "[a-zA-Z0-9._-]+@[a-z]+\\.+[a-z]+";
          if (email.trim().matches(emailPattern))
          {
               return true;
          }
          return false;

     }

}

A: It is coming from
imageView1.setImageBitmap(textCaptcha1.getImage());

you are using textCaptcha1 but you have not initialized it anywhere


text:
Q: Show $1 + z_{\alpha/2}/\sqrt{n} \approx \chi^2_{\alpha/2} (2n)/(2n)$ I have the following problem,

Show $1 + z_{\alpha/2}/\sqrt{n} \approx \chi^2_{\alpha/2} (2n)/(2n)$

where $z_{\alpha/2}$ is $\alpha/2$ upper quantile of $N(0,1)$, and $\chi^2_{\alpha/2}(2n)$ is $\alpha/2$ upper quantile of $\chi^2(2n)$ where $2n$ denotes the degree of freedom.

Try
By CLT, we have $\frac{X - 2n}{\sqrt{4n}} \to N(0,1)$, where $X \sim \chi^2(2n)$ since $\chi^2(2n) \equiv \sum_i^n Z_i$ where $Z_i \overset{iid}{\sim} \Gamma(1,2)$. But I cannot proceed.

A: It seems I found it.
By CLT $\frac{\chi^2_{\alpha/2} (2n) - 2n}{\sqrt{4n}} \approx z_{\alpha/2}$.
By rearranging, $z_{\alpha/2} \approx \sqrt{n}(\chi^2_{\alpha/2} (2n) - 2n)/(2n)$.
thus  we have $1 + z_{\alpha/2}/\sqrt{n} \approx \chi^2_{\alpha/2}(2n)$


text:
Q: Why does the qtip tooltip appear on other buttons that do not share the same id? So, I want to show tooltips for specific buttons and not for other buttons.
Here's my code with an example where I want to show tooltip with the word "TAB" on hover for the TAB button. However, if I hover over other buttons like FOO and BAR, it shows TAB too. I'm not sure what would be causing this? Is it because they share the same class even though I put a particular ID for TAB?
js function:
    $('#TabBtn').mouseover(function () {
        BrowserSide.Objects.ToolTip("#TabBtn", "Tab");
    }).mouseout(function () {
        $("#TabBtn").qtip('destroy', true);
    });

Where Tooltip is:
ToolTip:function(elementId,toolTipContent){

    $(elementId).parent().mouseover(function (event) {

        $(this).qtip({
            overwrite: false,
            content: toolTipContent,
            once: false,
            show: {
                event: event.type,
                delay: 500,
                ready: true,
            },
            position: {

                my: 'top center',
                at: 'top center',
                target: 'mouse',
                adjust: {
                    x: 0,
                    y: -35,
                    mouse: true  // Can be omitted (e.g. default behaviour)
                }
            },
            style: {
                classes: "qtip-tooltip-for-ellipse"
            }
        }, event);
  });
}

Html code:
<button id="TabBtn" class='newUI-toolbar-button-with-icon' style="margin:10px 8px 5px 8px; width:40px !important; height:30px !important">Tab</button>
<button class='newUI-toolbar-button-with-icon' style="margin:10px 8px 5px 8px; width:40px !important; height:30px !important">Foo</button>
<button class='newUI-toolbar-button-with-icon' style="margin:10px 8px 5px 8px; width:40px !important; height:30px !important">Bar</button>

A: You are adding a new .mouseover handler to the button's parent each time you mouseover the button. Is there a reason for this?
It should be enough if you do just:
$('#TabBtn').mouseover(function (event) {
    BrowserSide.Objects.ToolTip("#TabBtn", "Tab", event);
})

function(elementId,toolTipContent, event){
        $(this).qtip({
            overwrite: false,
            content: toolTipContent,
            once: false,
            show: {
                event: event.type,
                delay: 500,
                ready: true,
            },
            position: {

                my: 'top center',
                at: 'top center',
                target: 'mouse',
                adjust: {
                    x: 0,
                    y: -35,
                    mouse: true  // Can be omitted (e.g. default behaviour)
                }
            },
            style: {
                classes: "qtip-tooltip-for-ellipse"
            }
        }, event);
}

A: Default qTip
Let's go over the default qtip functionality.
$('#btn').qtip({
    content: "Mouseover in a qtip"
});

This creates a qtip that appears everytime the user mouses over the button. It does this without having to specify a mouseover handler. (demo)
qTip's Target
The qtip appears on whatever selection is to the left of the .qtip(). So
// when parent of button is moused over
$(elementId).parent().mouseover(function (event) {
    // add a qtip to $(this)
    $(this).qtip({

In that function, this is the window object. So you are adding a qtip to the global window object but only creating and destroying it when you mouseover the parent of a button. Needless to say, there isn't a good reason to do this.
Standard qTip usage
Unless you have some edge case for manually showing and hiding of qtips, don't. Instead utilize qTip's built in event handling and customize it with options or callbacks.
I'd recommend:

*

*1 qtip per button

*create the qtip only once

*create the qtip when the page loads (or the widget initializes, etc)

*use the show and hide options to control visibility

So, from your code, I imagine you want something like:
var ToolTip = function (element, toolTipContent) { // Adds one qtip to one element.
    $(element).qtip({
        content: toolTipContent,
        show: {
            event: "mouseenter",
            delay: 500,
            //ready: true, //don't do this
        },
        position: {
            target: 'mouse', //qtip will follow the mouse
            my: 'top center',
            at: 'top center',
            adjust: {
               x: 0,
               y: 15,
            }
        },
        style: {
            classes: "qtip-tooltip-for-ellipse"
        }
    });
};

ToolTip("#TabBtn", "Tab"); // This should be run only once at page load

Fiddle


text:
Q: I cant make my new thread to function im really new to android and i need my app to send my current coordinates to my webapp , to achieve this i made a new thread, but the thread isn't doing anything. the magic is supost to happen in the SendQueryString() function.
My code is :
     @Override
     public void onLocationChanged(Location location) {
     // Draw the marker, if destination location is not set
     latitude = location.getLatitude();
     longitude = location.getLongitude();
     if (mMarkerPoints.size() < 2) {

     mLatitude = location.getLatitude();
     mLongitude = location.getLongitude();
     LatLng point = new LatLng(mLatitude, mLongitude);

     mGoogleMap.moveCamera(CameraUpdateFactory.newLatLng(point));
     mGoogleMap.animateCamera(CameraUpdateFactory.zoomTo(18));

     drawMarker(point);
     }
     String Text = "My current Latitude = " + latitude + " Longitude = "
     + longitude;
     Thread trd = new Thread(new Runnable() {
            @Override
            public void run() {
                try {

                    SendQueryString();
                } catch (Throwable e) {
                    e.printStackTrace();
                }
            }
        });
        trd.start();

     }

    public void SendQueryString() {
                String url = "http://sistemamedicointegrado.azurewebsites.net/Home/Ubicacion?latitud="
                        + latitude + "&longitud=" + longitude + "&id=4";

                try {
                    HttpClient Client = new DefaultHttpClient();
                    HttpGet httpget = new HttpGet(url);
                    Client.execute(httpget);

                } catch (Exception ex) {

                }
            }

    @Override
    public void onProviderDisabled(String provider) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onProviderEnabled(String provider) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {

    }

    }

A: Displaying Toast in a Thread won't work. Ui can be updated only on the ui thread.
You have
  SendQueryString();

in Threads run method
Then in SendQueryString() you display
  Toast.makeText(getApplicationContext(), "YESS",
                        Toast.LENGTH_SHORT).show();

which is wrong.
Instead of Thread you can use Asynctask where you can override onPreExecute, onPostExecute and onProgressUpdate and update ui. You can do your background work in doInBackground.

A: To show toast inside thread means you have to use runonUIThread
runOnUiThread(new Runnable() {
                 public void run() {
                 Toast.makeText(ActivityName.this,"YESS",Toast.LENGTH_LONG).show();
            }
        });

Otherwise use handler to set message and communicate to the main UI thread.for Example
Inside thread use this code

h.sendEmptyMessage(0);

and then  call this handleMessage method

Handler h = new Handler() {
  public void handleMessage(Message msg){
    if(msg.what == 0){
      Toast.makeText(Activityname, "HelloWorld!", Toast.LENGTH_SHORT).show();
    }
  }
};