text:
Q: Mousepad tap does not work on debian stable lxde I have an Acer Aspire One KAV60 running debian 7.0 stable with lxde as the window manager.
I can't get the mousepad to register a click when I tap it.
I've tried installing gpointing-device-settings, which works for some settings like using 2 fingers to scroll, but does nothing when I turn mousepad taps on or off.
Any help would be much appreciated.

A: I had exactly the same problem with a fresh install of Wheezy on my Asus eee 901GO - I googled the problem and the answer was the next page listed after this! It's quite simple by all accounts - as superuser (at least I was) type the following command in a terminal:
synclient TapButton1=1

Worked first time for me.

A: Building on responses from Larry and user193782, I found that this worked for LXDE on Debian stable (wheezy):
$ su
$ cd /etc/X11/Xsession.d
$ vi 99-synclient

The file 99-synclient should contain:
#! /bin/sh
synclient TapButton1=1

Then make the 99-synclient executable:
$ chmod 555 99-synclient

A: Please try these steps:

*

*Open Root Terminal(Menu>Accessories>Root Terminal)

*Enter the Administrative password

*Type the following commands:
mkdir /etc/X11/xorg.conf.d
leafpad /etc/X11/xorg.conf.d/synaptics.conf

*Copy the following script
Section "InputClass"
Identifier      "Touchpad"
MatchIsTouchpad "yes"
Driver          "synaptics"
Option          "MinSpeed"              "0.5"
Option          "MaxSpeed"              "1.0"
Option          "AccelFactor"           "0.075"
Option          "TapButton1"            "1"
Option          "TapButton2"            "2"
Option          "TapButton3"            "3"
Option          "VertTwoFingerScroll"   "1"
Option          "HorizTwoFingerScroll"  "1"
Option          "VertEdgeScroll"        "1"
Option          "CoastingSpeed"         "8"
Option          "CornerCoasting"        "1"
Option          "CircularScrolling"     "1"
Option          "CircScrollTrigger"     "7"
Option          "EdgeMotionUseAlways"   "1"
Option          "LBCornerButton"        "8"
Option          "RBCornerButton"        "9"
EndSection

*Then paste it to the synaptics.conf file

*Click File and Save

*Logoff and login again.....

A: Same issue here with wheezy and GNOME 3! synclient works for the current session and none of the advise I found in the net worked for me to make it permanent.
Here's how I finally did it:
dconf-editor, under org/gnome/settings-daemon/peripherals/touchpad there's a tap-to-click checkbox.
Wish this helps.


text:
Q: Access Neo4j server with Ubuntu OS over the Internet(Public IP address)? My Neo4j version is 3.2.2 Enterprise edition. The server I am using is VM Ubuntu 16.0 Server on Microsoft Azure. I want to access it over the public address. For the time being I turned off the firewall on Ubuntu. I also configured, Neo4j network configuration which is found on /etc/neo4j/neo4j.conf to be accessible outside the local network.
The problem is, I am unable to access it with public IP address. Keeps saying time is out.
I tried to use Neo4j enterprise template on Microsoft Azure but the following error which is posted on this link Neo4j on Microsoft Azure Deployment template validation failed? keeps showing up?

A: Can you access neo4j from your Azure VM?
According to your description, it seems a NSG settings issue.
As we know, those ports should be opened up in our firewall settings and Azure NSG settings:

It seems you have turn off your ubuntu firewall, so we just add those ports to Azure NSG inbound rules, like this:

We can add NSG inbound rules via Azure portal, more information about set NSG inbound rules, please refer to this link below.
https://learn.microsoft.com/en-us/azure/virtual-network/virtual-networks-create-nsg-arm-pportal
By the way, we can use this template to deploy neo4j cluster in Azure, more information about it, please refer to this answer.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Переход между формами c++ Есть 2 формы (MyForm и MyForm 1) , нужно что бы после нажатия на кнопку (перейти) открывалась вторая форма.
if (Login == RL && Password == RP)
    {

        MyForm1->Show();
        MessageBox::Show("Login and Password is right!", "Your AUTH");

    }
    else
    {
        MessageBox::Show("Login or Password is WRONG!", "Your AUTH");
    }

}

Проблема в том, что когда я добавляю в код MyForm1->Show(); , то мне выдается ошибка (требуется идентификатор)
Начал недавно изучать плюсы, ответа не нашел пока.

A: Решил задачу путем добавления в MyForm.cpp строки #include "MyForm1.h" и заменив MyForm1->Show(); на :
MyForm1^ frm = gcnew MyForm1;
frm->Show(this);


text:
Q: Is it a City, Province, State or a District? And How to Properly Translate my Address? I'm applying for a the US Diversity Visa Lottery and there is something in the instructions (PDF) that is making me so confused, and I'm so paranoid about it, so bear with me.
I live in Egypt, in Cairo.
Now I'm required to enter the city where I was born in the DV Lottery form and mentioned above ("City of birth only. Do not enter District/ County/ Province/ State"). I believe I was born in Cairo, but what is really Cairo?
Now because I live in Egypt, I never really understood the concept of what a state, county, district nor province really mean. All I know is that Egypt is a country, but is it a state?
And I know that Cairo is called the City of Cairo and it is also one of Egypt's  twenty-seven governorates, so what category does Cairo fall into regarding from an American perspective? Is it really a city, a district, a county, or a province of Egypt? And what's even the difference between those?
Furthermore Cairo is divided divided into forty-one administrative divisions, called qism in Arabic. I live in one of those administrative areas, called
Ain Shams (literally meaning Sun's Eye if you'r curious). This is even more confusing to me because I do not know what those administrative areas should be called as they are parts of Cairo, and I grew up knowing that these areas are just neighborhoods if I would translate how it is said in Arabic.
So same question: What is Ain Shams, a district, a county, or a province of Cairo? and what should I write in the DV lottery field that asks for the "City of Birth"? Should I write Cairo or Ain Shams?
What makes me more confused is there is another field in the mailing address section that asks for the City/ town, What should be my town? will it be the same as my city?
and another field asking for the District/County/ Province/ State, What should I write in this field?
Finally, my address. How should I translate my address in terms of eligibility if reviewed by someone potentially American.
My Address as in my ID would be translated a so,
first: Street number
Second: My street name
third: the neighborhood I live in
fourth: mentioning the neighborhood either (eastern or western)
So my address would be
20 Ahmed Hamdy St. Eastern Ain Shams, Cairo
Is this eligible? or should I write it
No 20 Ahmed Hamdy St. Eastern of Ain Shams (district/ county/ province whatever you tell me it is) + my apartment number.
If I made you confused sorry, Here are two links from wikipedia about the topics
check them:
Cairo Governorate
Governorates of Egypt

A: Americans would consider Cairo a city.  It is the capital and largest city of Egypt.  Any of those other terms are intermediate between a city and the entire country.  Egypt may not have that kind of a division, Wikipedia says that Cairo has a population of 9,500,000.  The metropolitan area, which generally means the city and suburbs, has a population of 20,439,541.
A metropolitan area is not a unified government.  The main city has its own local government, and nearby smaller cities and towns have their own governments.  One way of picturing a metropolitan area is the territory covered by broadcast television stations, because usually over-the-air signals can travel maybe 80 km (50 miles), and do not stop for city and town borders.
Reading the Wikipedia article, I see that Cairo is also a governorate.  Governors in the US are the executive leaders of states, so that Cairo is, no doubt due to its size and importance, also (in US terms) its own state.  This fact does not take away from the fact that it also counts as a city, which is what those instructions ask you to list.  This is similar to Washington, DC, which is the city of Washington, which is in and equivalent to the District of Columbia, which is a special territory similar to a state (but not part of any other state).  This is a unique situation among cities in the US, but not in the world.  Canberra, Australia, is in, and contains nearly all of the population of, the Australian Capital Territory.
I feel you're probably overthinking the question.  You probably consider your city of birth to be Cairo, and Americans do, too.


text:
Q: Calculate if time period is contained within a start and end time I have a problem where I am trying to calculate in Excel if any part of a  provided work duty time period is contained within a user defined period which specifies the night working hours e.g. 2330-0559 or 0000-0630.
If I provide a work duty time I want and any part of the duty is within the specified period it needs to be identified.  E.g. 2230-0630 duty time is within both examples above.
I can tried a few different solutions and still not got the right way solve it.
Maybe someone can help.  I also know that 24:00 in excel is used for midnight at the end of the day and 00:00 is used for midnight starting the day as excel works from 0-1 as part of the day.

=OR(MOD(A5,1)>$E$2,MOD(A5,1)<$F$2)

A: I would work with the number of minutes as decimal and with it make a valid range from "Duty start time" and "Duty end time".
Check if you can make any sense out of this:

Here the example:
https://drive.google.com/file/d/1O1B76srlY8sYQHsV_TiZVzi-7B_18eSj/view?usp=sharing

Update: Sorry for the lack of explanation. Here I try my best to clarify how I did it.
Conversion
First of all I try to convert any time into minutes, so 00:00 is 0 minutes, 01:00 is 60 minutes, 24:00 (excel shows 00:00) is 1440 minutes, 25:00 (excel shows 01:00) is 1500 minutes.
That conversion I do with CONVERT(E2,"day", "mn"), which does convert from day to minutes.
Range Normalization and inclusion
Now every range has to be normalized, that means the "End" has to be always bigger than "Start". For 00:00 to 06:00 this works fine, but for 22:00 to 06:00 it needs to be tweaked. So if "Start" is bigger than "End" then I add 1440 mins (24 hours) to "End". That I do with IF(A6>B6, 1440,0).
You then need to see if any "Duty range" contains the "Night range". That normally is done with the formula if (DutyEnd > NightStart AND DuttyStart < NightEnd) then TRUE.
Challenge 1
That was the main concept. But then if you try to compare a range like 00:00-06:00 contained in 24:00-06-00 it does not work. And that is because the converted minutes are 0-360 and 1440-1830, they don't contain each other.
In E3 to fix this I cut down 1440 with modulo (MOD()), then MOD(1440, 1440) = 0. So even if you use values like 25:00 or 52:00, they will be cut down to the smallest amount of minutes. E.g. 25:00 (1500 mins) = 1:00 = 60 mins, 52:00 (3120 mins) = 4:00 = 240 mins
Challenge 2
We have yet another challenge, the possible comparisons are as follows:

*

*00:00-06:00 contained in 00:00-06:00 which in minutes is 0-390 contained in 0-390

*00:00-06:00 contained in 22:00-06:00 which in  minutes is 0-390 contained in 1320-1830

*22:00-06:00 contained in 00:00-06:00 which in minutes is 1320-1830 contained in 0-390

These last two will not match. So that is why in the "Contains" column (E.g.: E6) I compare against the "Night criteria" - 1400 and + 1400.
Hope it is a bit clear. Let me know otherwise..

A: Well, I think I'm missing something but let's see if this works for you. To make this work:

*

*All hours must be typed in hh:mm format

*Night Criteria End must be on a different day. This means it must be over 00:00 or formulas won't work. If you type something
  like start criteria=22:00 and night criteria= 23:50, both times
  would be in the same day, so formulas won't work

*This formulas only work in periods less than 24 hours. If anytime the different between criterias is over 24 hours, formulas won't work
  properly.

Now, I replied your data like this:

The trick here is dealing with times without dates. Dates in Excel are înteger numbers and decimal parts are the hours/minutes/seconds. So to compare properly hours like this, you need to add an integer part.
Let me explain. In Excel, 18:00 would be 0,75. And 06:00 would be 0,25. If you try to get the difference between both times, you will get -0,5. In decimal it makes sense, but when trying to convert to time, it makes no sense for Excel. So, as I said before, the trick here is adding integers (in this case, because 06:00 is lower than 18:00, we would add +1), so Excel would make 1,25 - 0,75 = 0,5. And Excel can convert 0,5 to hours, and it will return exactly 12 hours, the right result.
So knowing this, the trick in formulas for your data is comparing ends with starts and add 1 or 2 to compare then properly with your criteria. That way Excel can figure out if a time is later or sooner than a criteria.
All my formulas are these ones:

*

*LENGHT: =IF(B5<A5;B5+1-A5;B5-A5)

*CROSS MIDNIGHT: =IF(Y(B5<A5;B5<>0);TRUE;FALSE)

*START BETWEEN CRITERIA: =IF(AND(IF(A5<$E$2;A5+2;1+A5)>=1+$E$2;IF(A5<$E$2;A5+2;1+A5)<=$F$2+2);TRUE;FALSE)

*END BETWEEN CRITERIA: =IF(AND(IF(B5<$E$2;B5+2;1+B5)>=1+$E$2;SI(B5<$E$2;B5+2;1+B5)<=$F$2+2);TRUE;FALSE)

*ANY PART:=IF(OR(E5=TRUE;F5=TRUE;AND(A5<$E$2;A5+C5>1+$F$2));TRUE;FALSE)
Anyways, I uploaded a file to my Gdrive, in case it may be helpful to download and check the formulas.
This is the best I got. Probably there is a better way, but I hope this can help you, or at least, you can adapt it to your needs.
https://drive.google.com/open?id=1nrZKfyUhED_y6iiPRSUwRf7GhJlBYt-O

A:
UNDERSTANDING DATE AND TIME IN EXCEL
Dates in excel are stored as INTEGERS.  They represent the days since 1900/01/1 with that date being 1.
Time is stored as a decimal which represents a fraction of a day.  24 hours is 1, 0.5 is 12 noon. etc.
In other words, everything to the left of the decimal is date and everything to the right is time.
JUST USING TIME AND CROSSING MIDNIGHT
This is problematic from the view point that early morning times are less than the late times of the previous day.  The fact of the matter is that they are larger.  In our heads we do the mental math of knowing the are the following day but we ignore the date aspect.
A quick way to rectify this is to add the date to your time.  Life will become much easier with the math.  You may however not want to add full dates to start and end times.  WITH THE ASSUMPTION that start and end times are not more than 24 hours the simple work around is is to add 1 to the end time when the end time is less than the start time.  This means its the next day.
It the example date you provided, column C was insert to CORRECT the end time.  It did the check of end less than start if so add one using the following formula:
=B6+(B6<=A6)

The part in brackets is a logic check.  It either evaluates to TRUE or FALSE.  When excel runs a boolean (TRUE or FALSE) through a math operator (not a function like sum) it will convert TRUE to 1 and FALSE to 0.
LENGTH
Straight forward math of C minus A since C is always after you start and is the larger of the two numbers.
=C6-A6

CROSSING MIDNIGHT
Need to be a little careful in your definition of crossing midnight when a start time or end time is exactly midnight.  Technically speaking you did not cross it if you start or stop on it.  The difference is really < versus <= or > versus >=.  I will leave that to you to sort out.  For the math I used:
=AND(A6<1,C6>=1)

Though I did not use this column for anything else
START CHECK
=OR(A6>$F$2,A6<$G$2)

END CHECK
=OR(B6>$F$2,B6<$G$2)

ANY TIME CHECK
I broke this into three columns.  It can be combined into one but wanted to show the working parts.  The first check is to see if the start time is before the night start and that the shift end time was after the night start time.  The second check was similar for the the fisrt except you want to know if the start time is before the night end time and the shift end time is after the night end time.  For the OR case you want to check to see if ANY of columns F through I are true:
COLUMN H
=AND(A6<=$F$2,C6>$F$2)

COLUMN I
=AND(A6<$G$2+1,C6>$G$2+1)

Note the +1 for night end time.  This is to reflect that the end time is actually on the following day.
COLUMN J
=OR(F6,G6,H6,I6)
or
=(F6+G6+H6+I6)>=1

Place the above formulas in row 6 and copy down as needed


text:
Q: SQL queries related to join There are three tables -
employee (emp_id, emp_name)
department (emp_id, emp_dept)
salary (emp_id, emp_sal)

I have to find out maximum salary from each department.
Need following columns in output  -
emp_id, emp_name, emp_sal, emp_dept

Note -
emp_id is primary key.
In output, emp_sal should be the maximum salary of the department.

A: Try the below query:
   select max(emp_salary), emp_dept  from department d join salary s on d.emp_id = s.emp_id group by emp_dept

A: I have put sample data with the query below. I have tested this in SQL Server
create table #dept(emp_id int, emp_dept varchar(30))
create table #emp(emp_id int, emp_name varchar(30))
create table #salary(emp_id int, salary int)

insert into #dept values(1,'HR'), (2,'HR'), (3,'Finance')
insert into #emp values (1, 'Venkat'), (2,'raman'), (3, 'Murugan')
insert into #salary values(1, 5000), (2, 10000), (3, 20000)

select emp_dept, emp_id, emp_name
from
(
select d.emp_dept,d.emp_id, e.emp_name, Row_Number() over (partition by d.emp_dept order by s.salary desc) as rnk
from #Dept AS d
LEFT JOIN #Salary AS s
ON d.emp_id = s.emp_id
LEFT JOIN #emp AS e
ON d.emp_id = e.emp_id
) as t
where rnk = 1

A: Always try to fetch some data first using simple query and then just make it filter one by one as you want data from that query, so you get a clear idea. Also try below query.
SELECT emp_id, emp_name, emp_dept, max(emp_sal) from (SELECT emp_id, emp_name, emp_dept, emp_sal from salary inner join department on salary.emp_id = department.emp_id inner join employee on salary.emp_id = employee.emp_id ) group by emp_dept

Also see this link.
SELECT rows with MAX(Column value), DISTINCT by another column


text:
Q: Getting rid of the bar on the left How do I change my desktop so it looks like this again   I haven't used Ubuntu in awhile and found it annoying having this massive bar on the left taking up my screen space.
I liked Ubuntu because it was slim and simple. Anyway Its not the theme I'm after its the placement and functionality of the bars.

A: In order to install the Gnome Classic Desktop as you see in the picture:

*

*Open Software Center

*Edit -> Software Sources

*Make sure the check box with (universe) is checked.

*Close the dialog and let it update if it needs to

*Search the Software Center for gnome-session-fallback and install it

*Log out, hit the Ubuntu logo next to your username and select "Gnome Classic".

*After login you'll be at the original Gnome desktop.

A: The left side bar is part of Ubuntu Unity interface. It can't be removed, unless you switch to another desktop environment. You should probably use older Ubuntu version like Ubuntu 10.04 LTS if you don't like the `Unity interface.
The other options are:

*

*Use one of the different Ubuntu flavours, such as Kubuntu, Xubuntu or Lubuntu. You can install their desktops on top of Ubuntu, and then choose your preference at the login screen.

*Use a different distribution, such as Linux Mint.
Courtesy

A: The Unity launcher bar can be set to auto-hide. Just go to system settings, appearance, behaviour tab, auto-hide the launcher = On


text:
Q: What is the best way to store big amounts of data, and then write it to file in Java? We have a Java method that retrieves some columns from a large database table, operates on them, and then reformat each row as CSV. These rows should be written to a single file, which the next system will pick up. (I guess appending a file is time consuming.). We are writing to AWS S3, if that matters.
I don't really know how I should approach this. I could use a List or ArrayList, and add each row to it, and then write the entire object to file I guess, or maybe I need to loop the object and append the file... But I don't know how to do this in the most efficient way in Java, even after some googling.
So, what is the best way to store big amounts of data, and then write it to file in Java?


text:
Q: Confusion on Time.toMillis(boolean) My Time objects toString() returns 19700101T000000America/New_York(4,0,0,0,18000)
The fields are as below:
allDay - false
gmtOff - 0
hour - 0
isDst - -1
Min - 0
Month - 0
MonthDay - 1
Second - 0
TimeZone - America/New_York
Year - 0
YearDay - 1970

But when I am using Time.toMillis(false), its always returns a value larger than 0. As the time represents 1970, 1st Jan, I want the value 0 to be returned. Even the second field of object is also having 0 in it. But still a different value.
How do I solve this?

A: This is because the time zone you have chosen is America/New_York.
The time zone should be GMT for it to return 0 value.
The toMillis method will return the number of milliseconds since epoch. Epoch is 1 January 1970 00:00:00 UTC(GMT).


text:
Q: Error Handling in DWR I am working on a Java web-application which uses DWR in a number of places. I am adding a new DWR component, which must not propogate any errors back to the end-user. Currently, if there's a server-side error, this is displayed in a pop-up to the user, which I want to prevent. So there are two parts to this:
1) according http://directwebremoting.org/dwr/documentation/browser/errors.html, errors-handling is configured via the:
dwr.engine.setErrorHandler(handler);
call, but I can't find this in our code-base. Does this mean the existing popup is just the DWR default behaviour?
2) If I supress the existing message with a call to
dwr.engine.setErrorHandler(handler);

where handler does nothing, does this just affect the only the pages where I make this call, or will I have wiped out the default-handler for other pages (which I want to keep)
Thanks

A: To answer my own question, I've overriden this and it works correctly so

*

*it does seem to be DWR default behaviour

*setting the handler only changes the behaviour for the current page


text:
Q: Set labels in a custom cell to names from an array using a separate controller I have a view controller with a table. The view controller has a button that segues to another controller with 4 textfields. There is a name textfield and three others where numbers can be inputed. When a user presses add, an array is appended and the view controller is dismissed while updating the table in the previous view controller. The user is then presented a table with a new cell added. The cell has 4 labels.
I am trying to figure out how to set each label in a cell to the 4 textfields that are in the view controller that created the new cell. Here is a picture of the view controller with a cell created:

Here is the view controller when the plus button is pressed that creates the cell by updating the array:

I would like to be able to set the far left label to represent the name that is added to the array every time. The first time a person clicks the plus button, the textfields view controller will pop up and the the user can put the name in the textfield. When the add button is pressed the label on the left would show the name in the controller that appended the array. The next name that is added through the view controller will be in the cell below the previous name entered and so forth. I need to get the array to show the text properly. I originally wanted the cells to have textfields that the user could put the info in there but the cells data wasn't sending to firebase database properly.
Here is the code for the first view controller:
import UIKit
import Firebase

class ConsiderationsTestViewController: UIViewController, UITextFieldDelegate {

@IBOutlet weak var tableView: UITableView!

static var numberOfPeople: [String] = []

var AddPersonCell = "AddPersonCell"

@IBOutlet weak var CompanyImage: UIImageView!

@IBOutlet weak var companyNameTextFieldConsiderations: UITextField!

@IBOutlet weak var companyDescriptionTextFieldConsiderations: UITextField!

@IBOutlet weak var startDateTextFieldConsiderations: UITextField!

@IBOutlet weak var endDateTextFieldConsiderations: UITextField!

let datePickerS = UIDatePicker()
let datePickerE = UIDatePicker()

    var database: Database!
    var storage: Storage!
    var selectedImage: UIImage?

    var ref:DatabaseReference?
    var databaseHandle:DatabaseHandle = 0

    let dbref = Database.database().reference()
    let uid = Auth.auth().currentUser?.uid

    override func viewDidLoad() {
        super.viewDidLoad()

        tableView.delegate = self
        tableView.dataSource = self

        self.companyNameTextFieldConsiderations.delegate = self
        self.companyDescriptionTextFieldConsiderations.delegate = self

        // Set the Firebase reference
        ref = Database.database().reference()

        let tapGesture = UITapGestureRecognizer(target: self, action: #selector(ConsiderationsTestViewController.handleSelectCompanyImageView))
         CompanyImage.addGestureRecognizer(tapGesture)
         CompanyImage.isUserInteractionEnabled = true

        self.navigationController!.navigationBar.isTranslucent = false

        navigationItem.backBarButtonItem = UIBarButtonItem(
        title: "", style: .plain, target: nil, action: nil)

        createDatePickerForStart()

        createDatePickerForEnd()

        NotificationCenter.default.addObserver(self, selector: #selector(loadList), name: NSNotification.Name(rawValue: "load"), object: nil)
    }

  @objc func loadList(){
    //load data here
    self.tableView.reloadData()
}

    @objc func handleSelectCompanyImageView() {

        let pickerController = UIImagePickerController()
        pickerController.delegate = self
        pickerController.allowsEditing = true
        present(pickerController, animated: true, completion: nil)
                    }

    @IBAction func AddPersonTapped(_ sender: Any) {

       }

    @IBAction func sendButtonTapped(_ sender: Any) {

    let companyNameC = companyNameTextFieldConsiderations.text!.trimmingCharacters(in: .whitespacesAndNewlines)
    let companyDescriptionC = companyDescriptionTextFieldConsiderations.text!.trimmingCharacters(in: .whitespacesAndNewlines)

    let today = Date()
    let formatter1 = DateFormatter()
    formatter1.dateFormat = "MMM d y"
    print(formatter1.string(from: today))
    let todaysDate = formatter1.string(from: today)

    let storageRef = Storage.storage().reference(forURL: "STORAGE URL HERE")
    let imageName = companyNameTextFieldConsiderations.text!
    let storageCompanyRef = storageRef.child("Company_Image_Considerations").child("\(todaysDate)").child(imageName)
    let companyDescriptionTextFieldText = companyDescriptionTextFieldConsiderations.text
    let dateToStart = startDateTextFieldConsiderations.text
    let dateToDecide = endDateTextFieldConsiderations.text
    let companyRef = Database.database().reference().child("Considerations").child("\(todaysDate)").child(imageName)

    let considerationInfluencerRef = Database.database().reference().child("Considerations").child("\(todaysDate)").child(imageName).child("Users")

     //let values = ["Feed_Quantity": "feedTFC", "Story_Quantity": "storyTFC", "Compensation": "compensationTFC"]

        guard let imageSelected = self.CompanyImage.image else {
            print ("Avatar is nil")
            return
                }

                var dict: Dictionary<String, Any> = [
                    "Company Image": "",
                    "Company Description": companyDescriptionTextFieldText!,
                    "Start Date": dateToStart!,
                    "Decision Date": dateToDecide! ]

        guard let imageData = imageSelected.jpegData(compressionQuality: 0.5) else {
            return
                }

                let metadata = StorageMetadata()
                metadata.contentType = "image/jpeg"
                storageCompanyRef.putData(imageData, metadata: metadata, completion:
                { (StorageMetadata, error) in
                if (error != nil) {
                return
                    }

                storageCompanyRef.downloadURL { (url, error) in
                if let metadateImage = url?.absoluteString {
                dict["Company Image"] = metadateImage

                companyRef.updateChildValues(dict, withCompletionBlock:  {
                (error, ref) in
                if error == nil {
                print("Done")
                return
                    }
                  }
                )
               }
             }

                                   storageRef.updateMetadata(metadata) { metadata, error in
                                    if error != nil {
                                    //Uh-oh, an error occurred!
                                    } else {
                                    // Updated metadata for 'images/forest.jpg' is returned
                                }
                            }
                        })

      //        considerationInfluencerRef.updateChildValues(values as [AnyHashable : Any]) { (error, ref) in
      //        if error != nil {
      //        print(error ?? "")
      //        return
      //                           }

      self.navigationController?.popViewController(animated: true)
      //           }
       }

    func createDatePickerForStart() {
    // center text in field
    startDateTextFieldConsiderations.textAlignment = .center

    // toolbar
    let toolbar = UIToolbar()
    toolbar.sizeToFit()

    // barbutton
    let doneButton = UIBarButtonItem(barButtonSystemItem: .done, target: nil, action: #selector(donePressedStart))
    toolbar.setItems([doneButton], animated: true)

    // assign toolbar to textfield

    startDateTextFieldConsiderations.inputAccessoryView = toolbar

    // assign datePicker to text field
    startDateTextFieldConsiderations.inputView = datePickerS

    // date picker mode
    datePickerS.datePickerMode = .date

     }

    func createDatePickerForEnd() {
    // center text in field
    endDateTextFieldConsiderations.textAlignment = .center

    // toolbar
    let toolbar = UIToolbar()
    toolbar.sizeToFit()

    // barbutton
    let doneButton = UIBarButtonItem(barButtonSystemItem: .done, target: nil, action: #selector(donePressedEnd))
    toolbar.setItems([doneButton], animated: true)

    // assign toolbar to textfield
    endDateTextFieldConsiderations.inputAccessoryView = toolbar

    // assign datePicker to text field
    endDateTextFieldConsiderations.inputView = datePickerE

    // date picker mode
    datePickerE.datePickerMode = .dateAndTime
       }

    @objc func donePressedStart() {
    // formatter
    let formatter = DateFormatter()
    formatter.dateStyle = .medium
    formatter.timeStyle = .none

    startDateTextFieldConsiderations.text = formatter.string(from: datePickerS.date)
    self.view.endEditing(true)
     }

    @objc func donePressedEnd() {
    // formatter
    let formatter = DateFormatter()
    formatter.dateStyle = .medium
    formatter.timeStyle = .medium

    endDateTextFieldConsiderations.text = formatter.string(from: datePickerE.date)
    self.view.endEditing(true)
            }

    @IBAction func testTapped(_ sender: Any) {
    print(ConsiderationsTestViewController.numberOfPeople)
           }
        }

    extension ConsiderationsTestViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
               func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
                   //print("did Finish Picking Media")
                   if let image = info[UIImagePickerController.InfoKey(rawValue: "UIImagePickerControllerEditedImage")] as? UIImage{
                       selectedImage = image
                       CompanyImage.image = image
                   }
                   dismiss(animated: true, completion: nil)
               }
           }

      extension ConsiderationsTestViewController: UITableViewDelegate, UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return ConsiderationsTestViewController.numberOfPeople.count
         }

    func numberOfSections(in tableView: UITableView) -> Int {
    return 1
         }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCell(withIdentifier: AddPersonCell, for: indexPath) as! ConsiderationsCell

    return cell
       }

     }

Here is the code for the second view controller:
import UIKit
import Firebase

class DropDownCellViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, UISearchBarDelegate, UITextFieldDelegate {

var numberOfPeople = [String]()

var users = [User]()

var userName = [String]()

var filteredNames: [String]!

let dropDownCell = "dropDownCell"

var emptyField = [String]()

override func viewDidLoad() {
super.viewDidLoad()

updateDataArray()

tableView.register(UserCell.self, forCellReuseIdentifier: dropDownCell)

filteredNames = userName

    tableView.delegate = self
    tableView.dataSource = self
    nameTextField.delegate = self

    tableView.isHidden = true

       // Manage tableView visibility via TouchDown in textField
nameTextField.addTarget(self, action: #selector(textFieldActive), for: UIControl.Event.touchDown)
   }

@IBOutlet weak var nameTextField: NoCopyPasteUITextField!

@IBOutlet weak var tableView: UITableView!

@IBOutlet weak var gridTextField: UITextField!

@IBOutlet weak var storyTextField: UITextField!

@IBOutlet weak var compensationTextField: UITextField!

@IBAction func textFieldChanged(_ sender: AnyObject) {
    tableView.isHidden = true
}

@IBAction func cancelButtonTapped(_ sender: Any) {
    self.navigationController?.popViewController(animated: true)
}

@IBAction func addButtonTapped(_ sender: Any) {

    ConsiderationsTestViewController.numberOfPeople.append("\(nameTextField.text!)")

    self.navigationController?.popViewController(animated: true)

    print(ConsiderationsTestViewController.numberOfPeople)

    DispatchQueue.main.async {
       NotificationCenter.default.post(name: NSNotification.Name(rawValue: "load"), object: nil)
            }
    }

  let searchController = UISearchController(searchResultsController: nil)

  override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    }

  override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?)
    {
      guard let touch:UITouch = touches.first else
      {
          return;
      }
      if touch.view != tableView
      {
          nameTextField.endEditing(true)
          tableView.isHidden = true
      }
    }

   @objc func textFieldActive() {
       tableView.isHidden = !tableView.isHidden
   }

  // MARK: UITextFieldDelegate
   func textFieldDidEndEditing(_ textField: UITextField) {
       // TODO: Your app can do something when textField finishes editing
       print("The textField ended editing. Do something based on app requirements.")
   }

   func textFieldShouldReturn(_ textField: UITextField) -> Bool {
       textField.resignFirstResponder()
       return true
   }

  func numberOfSections(in tableView: UITableView) -> Int {
      // #warning Incomplete implementation, return the number of sections
    return 1
   }

  func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    // #warning Incomplete implementation, return the number of rows

    return filteredNames.count
    }

  func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCell(withIdentifier: dropDownCell, for: indexPath) as!
    UserCell

    let user = users[indexPath.row]
    cell.textLabel?.text = user.name

    if let profileImageUrl = user.profileImageUrl {

    cell.profileImageView.loadImageUsingCacheWithUrlString(urlString: profileImageUrl)

    }
    return cell
}

func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 72
}

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    // Row selected, so set textField to relevant value, hide tableView
           // endEditing can trigger some other action according to requirements
           nameTextField.text = userName[indexPath.row]
           tableView.isHidden = true
           nameTextField.endEditing(true)
       }

//Mark: Search Bar Config
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {

    filteredNames = []

    if searchText == "" {
        filteredNames = userName

    }
    else {
        for names in userName {

            if names.lowercased().contains(searchText.lowercased()) {

                filteredNames.append(names)
            }
        }
    }
    self.tableView.reloadData()
}

func updateDataArray() {

    Database.database().reference().child("users").observe(.childAdded, with: { (snapshot) in

        if let dictionary = snapshot.value as? [String: AnyObject] {

            let user = User()
            //self.setValuesForKeys(dictionary)
            user.name = dictionary["name"] as? String
            user.email = dictionary["email"] as? String
            user.facebookUrl = dictionary["facebookUrl"] as? String
            user.instagramUrl = dictionary["instagramUrl"] as? String
            user.linkedInUrl = dictionary["linkedInUrl"] as? String
            user.profileImageUrl = dictionary["profileImageUrl"] as? String
            user.twitterUrl = dictionary["twitterUrl"] as? String
            user.id = dictionary["id"] as? String
            user.userType = dictionary["userType"] as? String

            self.users.append(user)
            self.userName.append(user.name!)
            self.filteredNames.append(user.name!)

            DispatchQueue.main.async {
            self.tableView.reloadData()
            }
        }

    }, withCancel: nil)

  }
 }

I am trying to append the label with a function that is called in the addButton function called renameLabel. Here is the func rename label code:
func renameLabel() {
let cell = ConsiderationsTestViewController.init().tableView.dequeueReusableCell(withIdentifier: AddPersonCell) as! ConsiderationsCell

cell.nameLabelC.text = ("\(ConsiderationsTestViewController.numberOfPeople)")
}

I am now getting the error:
Thread 1: Fatal error: Unexpectedly found nil while implicitly unwrapping an Optional value

Any help would be awesome!

A: First of all create a protocol above second VC.
protocol UpdatingArrayDelegate: class {
    func updateArray(newArray: [String])
}

And inside the second VC create:
var updatingArrayDelegate: UpdatingArrayDelegate!

Then before pushing to the second VC, set the delegate to self:
@objc func pushToSecondVCButtonTapped() {
    let destVC = secondVC()
    updatingArrayDelegate = self
    self.navigationController?.pushViewController(destVC, animated: true)
    // if you don't have self.navigationController use:
    // present(destVC(), animated: true, completion: nil)
}

Now when finishing the edit on secondVC when pressing your addButton do the following:
@objc func doneButtonTapped() {
    updatingArrayDelegate?.updateArray(newArray: myNewArrayCreatedOnThisSecondVC)
    self.navigationController?.popViewController(animated: true)
}

Then add the delegate function on first
extension FirstVC: UpdatingArrayDelegate {
    func updateArray(newArray: [String]) {
        print("updateArray")
        let myCell = myTableView.cellForRow(at: IndexPath(row: x, section: y)) as! MyCell
        myCell.textLabel1.text = newArray[0]
        myCell.textLabel2.text = newArray[1]
        myCell.textLabel3.text = newArray[2]
        myCell.textLabel4.text = newArray[3]
    }
}

You can think about delegate like this:
The boss (secondVC) gives a the worker (firstVC) a protocol of what to do. The Worker reads the protocol and is doing the work with his function given in the protocol. Before the worker runs to the boss, he must be sure that he can do the next task (written on the protocol he is going to have.)


text:
Q: Segmentation fault when trying to sort linked list Every time I try to run this program,I keep getting segmentation fault.When I try to sort all the numbers in the linked list from smallest to greatest,I found that it is somewhere in the while loop -
while(marker_ptr->link()->link()!= NULL)
{
  minum = prev->link();
  temp=minum->link();
  prev->set_link(temp);
  minum->set_link(head_ptr);
  head_ptr=minum;
  marker_ptr=minum->link();
previouse_minimum(head_ptr);
    }

i have no idea what is wrong with it
this is most of the code so you can get some context where i am using it
node(
    const value_type& init_data = value_type( ),
    node* init_link = NULL
)
{ data_field = init_data; link_field = init_link; }

// Member functions to set the data and link fields:
    void set_data(const value_type& new_data) { data_field = new_data; }
    void set_link(node* new_link)             { link_field = new_link; }

// Constant member function to retrieve the data:
value_type data( ) const { return data_field; }

// Constant member functions to retreive the link:
    node* link( ) const          { return link_field; }

private:
value_type data_field;
node* link_field;
};

node* previouse_minimum(node*& head_ptr){
    node* cursor;
    node* minimum;
    node* prev;
    minimum=head_ptr;

    for(cursor=head_ptr; cursor != NULL; cursor=cursor->link())
      if(cursor->data() < minimum->data())
         minimum=cursor;

    cursor = head_ptr;
    prev = cursor;
   while(cursor->link() != minimum)
    {
      cursor = cursor->link();
      prev = cursor;

    }
    cout << prev->link()->data() << endl;
    return prev;

}

void sort(node*& head_ptr, node*& marker_ptr)
{
   node* print_ptr;
   node* prev = previouse_minimum(head_ptr);
   node* temp=NULL;
   node* minum;
   marker_ptr = head_ptr;

   while(marker_ptr->link()->link()!= NULL)
    {
      minum = prev->link();
      temp=minum->link();
      prev->set_link(temp);
      minum->set_link(head_ptr);
      head_ptr=minum;
      marker_ptr=minum->link();
      previouse_minimum(head_ptr);
    }
   for(print_ptr = head_ptr; print_ptr !=NULL; print_ptr = print_ptr->link())
   cout <<  print_ptr->data() << " ";

   cout << endl;

   }


text:
Q: How can I retrieve the values from window of class "ThunderRT6ListBox" using user32.dll in c# I am trying to retrieve information from extern desktop aplication in Windows.
I know how extract the text from Textboxes (class "Edit") but I don't know how extract the values from controls with class name "ThunderRT6ListBox" and "ThunderRT6ComboBox". How can I do that?
I have this code to extract the text from the textbox:
public static class ModApi
{
    [DllImport("user32.dll", EntryPoint = "FindWindowA", CharSet = CharSet.Ansi, SetLastError = true, ExactSpelling = true)]
    public static extern IntPtr FindWindow(string lpClassName, string lpWindowName);

    [DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)]
    public static extern int GetClassName(IntPtr hWnd, StringBuilder lpClassName, int nMaxCount);

    [DllImport("user32.dll", EntryPoint = "SendMessageTimeout", SetLastError = true, CharSet = CharSet.Auto)]
    public static extern uint SendMessageTimeoutText(IntPtr hWnd, int Msg, int countOfChars, StringBuilder text, uint flags, uint uTImeoutj, uint result);

    [DllImport("user32.dll", CharSet = CharSet.Ansi, SetLastError = true, ExactSpelling = true)]
    static internal extern bool EnumChildWindows(IntPtr hWndParent, funcCallBackChild funcCallBack, IntPtr lParam);

    [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = false)]
    static extern IntPtr SendMessage(IntPtr hWnd, uint Msg, IntPtr wParam, StringBuilder lParam);
    const int LB_GETCOUNT = 0x018B;
    const int LB_GETTEXT = 0x0189;

    public static string GetText(IntPtr hwnd)
    {
        var text = new StringBuilder(1024);
        if (SendMessageTimeoutText(hwnd, 0xd, 1024, text, 0x2, 1000, 0) != 0)
        {
            return text.ToString();
        }

        return "";
    }
}

public foo()
{
     IntPtr value = new IntPtr(0x019C086A); //ID locate using Spy++
     String caption = ModApi.GetText(value);
}

UPDATE 1:
The way to read from ListBox:
    public static List<string> GetListBoxContents(IntPtr listBoxHwnd)
    {
        int cnt = (int)SendMessage(listBoxHwnd, LB_GETCOUNT, IntPtr.Zero, null);
        List<string> listBoxContent = new List<string>();
        for (int i = 0; i < cnt; i++)
        {
            StringBuilder sb = new StringBuilder(256);
            IntPtr getText = SendMessage(listBoxHwnd, LB_GETTEXT, (IntPtr)i, sb);
            listBoxContent.Add(sb.ToString());
        }
        return listBoxContent;
    }

UPDATE 2:
The way to read from ComboBox:
    public static List<string> GetComboBoxContents(IntPtr cbBoxHwnd)
    {
        int cnt = (int)SendMessage(cbBoxHwnd, CB_GETCOUNT, IntPtr.Zero, null);
        List<string> listBoxContent = new List<string>();
        for (int i = 0; i < cnt; i++)
        {
            //int txtLength = SendMessage(cbBoxHwnd, CB_GETLBTEXTLEN, i, 0);
            StringBuilder sb = new StringBuilder(256);
            IntPtr getText = SendMessage(cbBoxHwnd, CB_GETLBTEXT, (IntPtr)i, sb);
            listBoxContent.Add(sb.ToString());
        }
        return listBoxContent;
    }

A: You're dealing with a VB6 application from eons ago. "Thunder" was the internal name for the VB product/project (trivial side note).
You're closer than you realize. If you have the HWND to the control, and I think you do:

*

*Call SendMessage with that HWND and the message LB_GETCOUNT to get the number of items in the list.

*For each index, call SendMessage with LB_GETTEXTLEN and the current item index to get the length of the text, then allocate a buffer accordingly.

*Call SendMessage again, this time using LB_GETTEXT message, same item index (zero-based), and the reference to your buffer, and that should get you each item's text.

You might consider one more declaration/alias to SendMessage that just returns an int, which should make some of these calls simpler.
If I get a chance, I will clean this up a bit later with a more specific code example (or at least pseudocode), but I get the impression you're very much on the right track already and may only need this basic description to get the rest of the way.
Good luck!


text:
Q: How to draw a line dynamically between two circles I have drawn two circles with the below code, i have to draw a line between these two circles but the tricky point when i start to draw a line from the first circle there should be availability of second circle then only it should draw otherwise it shouldn't draw line and vice versa. if i click outside of  circle then also  it shouldn't draw line
in my below code or fiddle check it i can a draw a line my condition is not working
   var line;

var svg = d3.select("body").append("svg")
    .attr("width", 600)
    .attr("height", 400).on("mousedown", mousedown).on("mouseup", mouseup);

function mousedown() {
    var m = d3.mouse(this);
    line = vis.append("line")
        .attr("x1", m[0])
        .attr("y1", m[1])
        .attr("x2", m[0])
        .attr("y2", m[1]);

    svg.on("mousemove", mousemove);
}

function mousemove() {
    var m = d3.mouse(this);
    line.attr("x2", m[0])
        .attr("y2", m[1]);
}

function mouseup() {
    svg.on("mousemove", null);
}

var inputs = [
{ "x" : 200, "y" : 150,  r : 50},
{ "x" : 300,  "y" : 250,  r : 50},
]

         svg.selectAll("circle").data(inputs).enter().append("circle")

         .attr("r", function(d, i){ return d.r })
         .attr("cx", function(d, i){ return d.x })
         .attr("cy", function(d, i){ return d.y })
         .attr("stroke", "red")
         .attr("fill", "white")

Here is my fiddle : https://jsfiddle.net/34j6pkn9/1/

A: maybe this will help you but its far from a good solution, but it work

Note :
  circle drawing its bit ridiculus for me, it draw rect, imagine you
  draw rect first then you draw a circle inside of it that its why, it
  have bug on each angle of it that look like circle but difinetly its
  a reactangle,
i think it can be solve by some calculation,but sorry i didnt know any of
  that

var line;
var mx =0
var my =0
var inputs = [
{ "x" : 200, "y" : 150,  r : 50},
{ "x" : 300,  "y" : 250,  r : 50},
]
var vis = d3.select("body").append("svg")
    .attr("width", 600)
    .attr("height", 400)
    .on("mouseup", mouseup);

function mousedown() {
    var m = d3.mouse(this);

    line = vis.append("line")
        .attr("x1", m[0])
        .attr("y1", m[1])
        .attr("x2", m[0])
        .attr("y2", m[1]);
     mx = m[0]
     my = m[1]
    vis.on("mousemove", mousemove);
}

function mousemove() {
    var m = d3.mouse(this);
    line.attr("x2", m[0])
        .attr("y2", m[1]);
}

function mouseup() {
 var m = d3.mouse(this);
  //console.log(mx-m[0],my-m[1])
 inputs.forEach(function(d,i){
 if(m[0]<(d.x+d.r)&& m[0]>(d.x-d.r)&&m[1] <(d.y+d.r)&& m[1]>(d.y-d.r)){
  if(mx<(d.x+d.r)&& mx>(d.x-d.r)&&my <(d.y+d.r)&& my>(d.y-d.r)){

 }else{
  vis.on("mousemove", null);
 }

  }
 })

}

         vis.selectAll("circle").data(inputs).enter().append("circle")

         .attr("r", function(d, i){ return d.r })
         .attr("cx", function(d, i){ return d.x })
         .attr("cy", function(d, i){ return d.y })
         .attr("stroke", "red")
         .attr("fill", "white")
         .on("mousedown", mousedown).on("mouseup", mouseup);
svg {
    border: 1px solid red;
}

line {
    stroke: steelblue;
    stroke-width: 2px;
    stroke-linecap: round;
}
<html>
<head>
  <meta charset="utf-8">
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.2.3/d3.min.js"></script>

  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head><body>
</body>

A: There will be a line after every circle (except the first one). Each line will connect the centers of every two consecutive circles.
You've the first circle which you are appending in your svg now, but how will you find the previous circle? You can, simply, find previousElementSibling of the first circle. But, there is catch here, notice there is line after every circle. So, be sure to check the name of the previousElementSibling if it's "line", find previousElementSibling once more.

// At this point, you've just appended the circle in
// 'svg' based on where the mouse is etc.

// Now, find the previous circle.
const parentNode = document.querySelector("svg");
// 'thisCircle' is the one you're appending in svg now.
const thisCircle = parentNode.lastElementChild;

// Previous sibling of this circle.
const previousSibling = thisCircle.previousElementSibling;
// If this is the first circle drawn, then do nothing- return
if (!previousSibling) {
  return;
}

// Check if previous sibling is indeed 'circle' and not 'line'
const nodeNameOfPreviousSiblig = previousSibling.nodeName;
let previousCircle = previousSibling;
// If the previous node is 'line' go one more step upwards- it must be a circle. Since pattern => 1 circle, 1 line.
if (nodeNameOfPreviousSiblig == 'line') {
  previousCircle = previousSibling.previousElementSibling;
}

// center of the previous circle.
const xCoordOPrevCircleCenter = previousCircle.getAttribute("cx");
const yCoordOPrevCircleCenter = previousCircle.getAttribute("cy");

Now, finally, append the line connecting these two consecutive circles centers:

svg.append('line')
  .attr('x1', xCoordOThisCircleCenter)
  .attr('y1', yCoordOThisCircleCenter)
  .attr('x2', xCoordOPrevCircleCenter)
  .attr('y2', yCoordOPrevCircleCenter)


text:
Q: Creating a new dataframe with averages from another dataframe with multiple conditions in R I have fish count data and am trying to create a new dataframe using averages of the measurements based on conditions of two different columns. here is my data:
df <- structure(list(SITE = structure(c(1L, 1L, 1L, 2L, 2L, 2L, 3L,
3L, 3L, 1L, 1L, 1L, 2L, 2L, 2L, 3L, 3L, 3L, 1L, 1L, 1L, 2L, 2L,
2L, 3L, 3L, 3L, 1L, 1L, 1L, 2L, 2L, 2L, 3L, 3L, 3L, 1L, 1L, 1L,
2L, 2L, 2L, 3L, 3L, 3L), .Label = c("1", "2", "3"), class = "factor"),
    ZONE = structure(c(5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 1L,
    1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 4L, 4L, 4L, 4L, 4L, 4L, 4L,
    4L, 4L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 2L, 2L, 2L, 2L,
    2L, 2L, 2L, 2L, 2L), .Label = c("CREST", "INNER_FLAT", "MID_FLAT",
    "OUTER_FLAT", "SLOPE"), class = "factor"), C_TOTAL = c(44L,
    7L, 20L, 14L, 0L, 4L, 2L, 3L, 1L, 8L, 28L, 24L, 31L, 12L,
    33L, 6L, 16L, 33L, 75L, 21L, 60L, 81L, 37L, 89L, 21L, 35L,
    71L, 5L, 2L, 0L, 0L, 10L, 23L, 0L, 5L, 11L, 3L, 1L, 5L, 0L,
    0L, 8L, 7L, 6L, 42L), C_M2 = c(0.210465706, 0.029861994,
    0.090324177, 0.066599319, 0, 0.022092452, 0.011750593, 0.015245519,
    0.004710433, 0.033111594, 0.155094195, 0.110576495, 0.193659068,
    0.059152822, 0.192379108, 0.047800772, 0.08917095, 0.141336411,
    0.402538785, 0.130438337, 0.315206235, 0.460746849, 0.278643938,
    0.467754275, 0.192830321, 0.119928472, 0.411502497, 0.015370489,
    0.005150184, 0, 0, 0.034651441, 0.067824733, 0, 0.009805851,
    0.034844309, 0.010614352, 0.004131048, 0.01850898, 0, 0,
    0.029195413, 0.021409016, 0.030498145, 0.172406074), TRANS_A = c(209.0601875,
    234.411677, 221.4246571, 210.2123593, 226.6158348, 181.0573136,
    170.2041767, 196.7791332, 212.294701, 241.6072127, 180.5354478,
    217.0443184, 160.0751279, 202.8643689, 171.536298, 125.5209863,
    179.4306337, 233.485481, 186.3174499, 160.9956132, 190.3515643,
    175.801528, 132.7859497, 190.2708425, 108.9040348, 291.8406241,
    172.5384427, 325.2986863, 388.3356059, 303.1957479, 261.1574528,
    288.5882879, 339.1093313, 239.1118021, 509.89965, 315.6899993,
    282.6362022, 242.0693453, 270.1391425, 294.8864591, 321.2013381,
    274.0156514, 326.9650539, 196.7332763, 243.6109069), SCARID_T = c(35L,
    4L, 4L, 13L, 0L, 4L, 2L, 0L, 1L, 4L, 20L, 12L, 17L, 5L, 20L,
    6L, 6L, 18L, 63L, 11L, 41L, 75L, 34L, 89L, 14L, 33L, 68L,
    0L, 0L, 0L, 0L, 10L, 22L, 0L, 0L, 10L, 0L, 0L, 1L, 0L, 0L,
    6L, 0L, 4L, 42L), ACAN_T = c(4L, 0L, 11L, 0L, 0L, 0L, 0L,
    0L, 0L, 0L, 8L, 5L, 0L, 0L, 0L, 0L, 3L, 2L, 7L, 8L, 8L, 1L,
    1L, 0L, 0L, 1L, 0L, 0L, 0L, 0L, 0L, 0L, 1L, 0L, 5L, 0L, 0L,
    0L, 1L, 0L, 0L, 2L, 0L, 0L, 0L), SIG_T = c(5L, 3L, 5L, 1L,
    0L, 0L, 0L, 3L, 0L, 4L, 0L, 7L, 14L, 7L, 13L, 0L, 7L, 13L,
    5L, 2L, 11L, 5L, 2L, 0L, 7L, 1L, 3L, 5L, 2L, 0L, 0L, 0L,
    0L, 0L, 0L, 1L, 3L, 1L, 3L, 0L, 0L, 0L, 7L, 2L, 0L)), row.names = c(NA,
-45L), class = "data.frame")

I want to average all the measurements by each zone, but also according to site. So I want anew data frame where each site has one measurement for each zone.
Can anyone help me? Thanks!

A: library(dplyr)
df %>%
    group_by(SITE, ZONE) %>%
    summarise(
        across(where(is.numeric), mean)
    )
# A tibble: 15 x 8
# Groups:   SITE [3]
   SITE  ZONE       C_TOTAL    C_M2 TRANS_A SCARID_T ACAN_T  SIG_T
   <fct> <fct>        <dbl>   <dbl>   <dbl>    <dbl>  <dbl>  <dbl>
 1 1     CREST        20    0.0996     213.   12      4.33   3.67
 2 1     INNER_FLAT    3    0.0111     265.    0.333  0.333  2.33
 3 1     MID_FLAT      2.33 0.00684    339.    0      0      2.33
 4 1     OUTER_FLAT   52    0.283      179.   38.3    7.67   6
 5 1     SLOPE        23.7  0.110      222.   14.3    5      4.33
 6 2     CREST        25.3  0.148      178.   14      0     11.3
 7 2     INNER_FLAT    2.67 0.00973    297.    2      0.667  0
 8 2     MID_FLAT     11    0.0342     296.   10.7    0.333  0
 9 2     OUTER_FLAT   69    0.402      166.   66      0.667  2.33
10 2     SLOPE         6    0.0296     206.    5.67   0      0.333
11 3     CREST        18.3  0.0928     179.   10      1.67   6.67
12 3     INNER_FLAT   18.3  0.0748     256.   15.3    0      3
13 3     MID_FLAT      5.33 0.0149     355.    3.33   1.67   0.333
14 3     OUTER_FLAT   42.3  0.241      191.   38.3    0.333  3.67
15 3     SLOPE         2    0.0106     193.    1      0      1


text:
Q: How to use GRIDFSBuckets with KMongo coroutine client I am trying to use GRIDFSBuckets in ktor to upload files. I am using KMongo coroutine extension to create my MongoDB client. When calling GRIDFSBucket.create(). Its parameters need a MongoDatabase and bucketName. This is fine but KMongo coroutines creates a CoroutineDatabase not a MongoDatabase that is needed. Is there anyway around this?

A: You can get a MongoDatabase instance from CoroutineDatabase by calling CoroutineDatabase.database. In your case that would be db.database


text:
Q: Организация вывода фраз из бд на html страницу по рейтингу и случайно Уважаемые профессионалы.
Как правильно изменить (дописать) код чтобы получился вывод из БД на html страницу:

*

*По рейтингу

*Случайный вывод

-
F3::route('GET /',
function () {
    F3::set('html_title','Название');
    include  $_SERVER['DOCUMENT_ROOT'].'/perecc/rating/rating.php';
    //$article=mysql_query('SELECT * FROM article ORDER by id DESC limit 5');

    $rep_page=100;
    $num_pages=ceil(paginator()/$rep_page);
    for($i=1;$i<=$num_pages;$i++){
    $pages[$i][0]=$i;
    }

    F3::set('paginator',$pages);
    $query="SELECT * FROM article ORDER by id DESC limit $rep_page";
    $article=mysql_query($query) or die ("Error");

    $query2="SELECT content FROM article";
    $randmas=mysql_query($query2);
    for ($randmasdata=array();$row=mysql_fetch_assoc($randmas);$randmasdata[]=$row);
    for ($data=array();$row=mysql_fetch_assoc($article);$data[]=$row);
    $rnd=rand(1, count($randmasdata)-1);
    $random[0]=$randmasdata[$rnd];

    F3::set('content','blog_home.html');
    for ($i=0;$i<count($data);$i++)
    {
    $data[$i]['rat']=callrating($data[$i]['id'], "thumb", ' ');
    }

    F3::set('random',$random);
    F3::set('list',$data);
    echo Template::serve('layout.html');
}
);

Перенесено из комментария.
Может как-то так?
<?php

@mysql_connect("localhost", "root", "");
mysql_select_db("kakaeto_bd");
@mysql_query("SET NAMES 'utf8'");

$col = 1; // Сколько всего выводить записей

$sql = "SELECT * FROM anekdots ORDER BY RAND() LIMIT " . $col;
$res = mysql_query($sql);

for ($i = 0; $i < $col; $i++) {
    $row    = mysql_fetch_array($res);
    $text   = $row['text'];
    $author = $row['author'];
    echo $text . " [ Автор:<b>" . $author . "</b> ]";
}

?>


text:
Q: Bool to string in C#? I run my C# application which is big so I just included a part of the code
My code:
allowGift = Convert.ToInt32(dRow[14]) == 1;
allowInventoryStack = Convert.ToInt32(dRow[15]) == 1;
interactionType = InterractionTypes.GetTypeFromString((string)dRow[16]); //Line of error

And the error of stack trace

System.InvalidCastException: Unable to cast object of typpe 'System.Boolean' to type 'System.String'

A: Instead of this:
(string)dRow[16]

Try ToString:
dRow[16].ToString()

Or Convert.ToString :
Convert.ToString(dRow[16])

A: Change this line:
interactionType = InterractionTypes.GetTypeFromString((string)dRow[16]); //Line of error

to this:
interactionType = InterractionTypes.GetTypeFromString(dRow[16].ToString()); //Line of error

A: A bool cannot be directly cast to a string it needs to be converted.  You can just use the Converter class as you've done elsewhere in the code
InterractionTypes.GetTypeFromString(Convert.ToString(dRow[16]));

A: Instead of (string)dRow[16] Use dRow[16].ToString()


text:
Q: How to connect Backblaze B2 with Cloudflare and Flutter app? I built a Flutter app. The main part of the app is uploading user videos. Until now I had connected Firebase cloud storage to my app.  However, for cost reasons I wanted to use Backblaze as storage and Cloudflare as CDN.  The question I have is: I need to provide a URL in Cloudflare, the problem with this is a Flutter app which is not a domain like a website after all.  I don't quite understand how to solve this?  App is written in Flutter most of the backend is Firebase. I want to use the free plan from Cloudflare.
If any questions please let me know.

A: I work at Backblaze. I'm not an expert on Flutter or Firebase, but I did a little investigation to see if this is possible.
Firebase is more than just a storage platform. It is managing your user's accounts, and issuing ID tokens. When a user logs in, your app gets a short-lived token to use in interacting with Firebase on behalf of that user.
If you want to use a different storage platform, you will have to write your own backend. This is why...
Writing directly from your app to Backblaze B2 would mean that your app's binary contained the Backblaze credentials. An attacker could extract them from the binary and have the same access to your B2 buckets as your app has. "Apps can't keep secrets".
A custom backend can contain Backblaze B2 credentials without revealing them to an attacker.
This article explains how your backend can verify and decode Firebase ID tokens before acting on the users behalf.


text:
Q: Android - Exclude some url path to open the apps from deeplinking I want to exclude some url path to prevent it open the apps, so it should behave something like this:

But I can't figure out how to set the intent-filter correctly or what I should be setting:

 <intent-filter>
       <action android:name="android.intent.action.VIEW" />

       <category android:name="android.intent.category.DEFAULT" />
       <category android:name="android.intent.category.BROWSABLE" />

       <data
             android:scheme="https"
             android:host="www.example.com"/>
 </intent-filter>


text:
Q: allow variadic unknowns in function arguments I want to create a small helper function that will allow me to stop repeating this code 100s of times:
SELECT
    jsonb_strip_nulls(
        jsonb_build_object(
            'hello', 'world',
            'value', 5,
            'error', null
        )
    );
-- returns {"hello": "world","value":5}

However, when I try to wrap this in a function I get errors because the string literals are technically unknowns:
CREATE OR REPLACE FUNCTION jsonb_build_nullless_object(VARIADIC anyarray) RETURNS jsonb AS $$
    SELECT
        jsonb_strip_nulls(
            jsonb_build_object(
                VARIADIC $1
            )
        )
$$ LANGUAGE sql IMMUTABLE;

SELECT jsonb_build_nullless_object(
    'hello', 'world',
    'value', 5,
    'error', null
);
-- ERROR:  invalid input syntax for integer: "hello" has type unknown

Since the plain jsonb_build_object handles un-explicitly-typed string literals just fine, I assume there is a function decorator that would allow me to do the same?

A: There is no reason to use the pseudo-type anyarray as the arguments always are texts:
CREATE OR REPLACE FUNCTION jsonb_build_nullless_object(VARIADIC text[])
...

Db<>fiddle.
Note that arguments on odd positions are texts, so the whole array of arguments has to be text[]. SQL functions cannot have arguments of type "any" in contrast to some built-in functions like jsonb_build_object(VARIADIC "any").


text:
Q: App android can not Play video with video in USB OTG I make app android to interact with USB OTG, I can read info all file in USB OTG, but i can not play video in USB OTG, but i can play video in SD. help me. Thanks All
my code:
 fun openVideo(path: String){
    val viewIntent = Intent(Intent.ACTION_VIEW)
    val file = File(path)

    viewIntent.setDataAndType(
        FileProvider.getUriForFile(
            context,
            BuildConfig.APPLICATION_ID + ".provider",
            file
        ), "video/*"
    )
    viewIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
    context?.startActivity(Intent.createChooser(viewIntent, null))
}


text:
Q: Generation of Unique ID Can some help with how to generate a unique 6 digit URN in R,as I don't know how to do this please.
Below are the rule for the URN

*

*It needs to be alphanumeric,start with letter and maybe end with   letter (e.g AA34YB)

*Use only upper case alphabets

*Do not use the alphabets O or I (this is the alphabet after H and before J)

*Use only    digits from 1- 9. Exclude 0

*First  two digit should be letter,then followed by 2 digit number and end with 2 digit letter,e.g "AA22DD","EE34TY","ER67YU"

*All records must contain number as shown in rule 5

*IT MUST BE 6 DIGIT PLEASE

I would love to generate upto 4 million unique records please.Any R code suggestion is highly welcome.I am not an expert in R,actually new to R
Thanks very much

A: You can use expand.grid to generate Unique ID's.
n <- 10
t1 <- LETTERS[!LETTERS %in% c("O", "I")]
t2 <- 1:9
#t1 <- rawToChar(as.raw(c(65:72,74:78,80:90)), multiple = TRUE) #Alternativ
#t2 <- rawToChar(as.raw(49:57), multiple = TRUE)
apply(expand.grid(t1, t1, t2, t2, t1, t1)[seq(n),], 1, paste, collapse = "")
#       1        2        3        4        5        6        7        8
#"AA11AA" "BA11AA" "CA11AA" "DA11AA" "EA11AA" "FA11AA" "GA11AA" "HA11AA"
#       9       10
#"JA11AA" "KA11AA"

set.seed(1) #Sample randomly
apply(expand.grid(t1, t1, t2, t2, t1, t1)[sample(length(t1)^4*length(t2)^2, n),]
  , 1, paste, collapse = "")
#10938497 17633234 12201267 18120554 21612295 21509711 13901861  6841049
#"SL15UK" "BG59TR" "CU65XL" "BH54ES" "GJ13HV" "YF31FV" "EE79KN" "SV66CG"
#23945701 10770210
#"NK23KX" "TG68QK"

In case it needs to much memory look @Joseph-Crispell's answer.

A: here is a function that will generate ordered unique IDs:
generateIDs <- function(n, existing=NULL){

  # Initialise a counter to produce IDs
  counter <- 0

  # Create a arrays of letters and digits
  letters <- LETTERS[LETTERS %in% c("O", "I") == FALSE]
  digits <- 1:9

  # Initialise an array to store the IDs created
  ids <- c()

  # iterate through the letters
  for(first in letters){

    # iterate through the letters
    for(second in letters){

      # iterate through the digits
      for(third in digits){

        # iterate through the digits
        for(fourth in digits){

          # iterate through the letters
          for(fifth in letters){

            # iterate through the letters
            for(sixth in letters){

              # Create the unique code
              code <- paste0(first, second, third, fourth, fifth, sixth)

              # Check if already exists
              if(code %in% existing == FALSE){

                # Iterate the counter
                counter <- counter + 1

                # Store the ID
                ids[counter] <- code
                existing[length(existing) + 1] <- code

                # Check if created enough IDs
                if(counter == n){
                  return(ids)
                }

                # Note progress
                if(counter %% 10000 == 0){
                  cat("\rCreated", counter, "ids!")
                }
              }
            }
          }
        }
      }
    }
  }
}

That is a horrific number of nested for loops but it avoids the inefficient random generation of IDs. You can test it using the following code:
generateIDs(10)

"AA11AA" "AA11AB" "AA11AC" "AA11AD" "AA11AE" "AA11AF" "AA11AG" "AA11AH" "AA11AJ" "AA11AK"

Note that ideally you should run this function once. Theoretically, this function could create up to 26873856 unique IDs but it doesn't scale well!
See @GKi's answer for a much better solution! :-)


text:
Q: CSS grid doesn't work in Chrome but works in other browsers It works in Firefox, Edge and Safari but not Chrome.
https://giovanniroverso.com/p_gal.php, for example, has a grid gallery near the bottom of the page which does not display in Chrome and I can't figure out why.
Help, please?
Thanks

A: I changed max-height: 100%; to height-100%. THAT SOLVES IT!
Thanks again Micahel_B!


text:
Q: Is it Possible to Cache Method Invocations on Symfony2 Some methods on my web application are quite resource consuming and could be cached. They aren't dependent on global variables, temporal data or such, they are exclusively dependent on the parameters used on invocation.
Is there a simple way to cache those invocations? It would be cool to have them annotated with something like @Cacheable, giving some TTL and cache name.
Side note: those methods are implemented on services declared on services.yml.

A: I've found a bundle that works exactly like you describe (the annotation is really called @Cacheable). I'm having difficulties getting it to work and posted an issue on their github.
But maybe you have more success (and if you do, please let me know).
See https://github.com/phpro/annotated-cache for how it should work.
And https://github.com/phpro/annotated-cache-bundle for its symfony bundle and its configs


text:
Q: How do I get file url after put file to amazon s3 in Go? File is uploaded successfully, and I want to return file url after uploading.
_, err := s3.New(s).PutObject(&s3.PutObjectInput{
    Bucket:               aws.String("bucket"),
    Key:                  aws.String(tempFileName),
    ACL:                  aws.String("public-read"), // could be private if you want it to be access by only authorized users
    Body:                 bytes.NewReader(buffer),
    ContentLength:        aws.Int64(int64(size)),
    ContentType:          aws.String(http.DetectContentType(buffer)),
    ContentDisposition:   aws.String("attachment"),
    ServerSideEncryption: aws.String("AES256"),
    StorageClass:         aws.String("INTELLIGENT_TIERING"),
})

I have checked amazon doc for PutObject function, but PutObjectOutput struct type
But there is no uploaded file url in this structure.
How can I get file url?
Is there other way to return uploaded file url in amazon s3 sdk as soon as upload success?
Thanks

A: You can construct the URL as:
https://BUCKETNAME.s3-REGIONNAME.amazonaws.com/KEY

For example:
https://my-bucket.s3-ap-southeast-2.amazonaws.com/foo/bar.txt

A: You will need to reconstruct the file url
Using the s3 path to which you uploaded the file + the file name

A: Try this just after your code:
import "github.com/aws/aws-sdk-go/private/protocol/rest"

...

req, _ := s3.New(s).GetObjectRequest(&s3.GetObjectInput{
    Bucket: aws.String("bucket"),
    Key:    aws.String(tempFileName),
})
rest.Build(req)
uploadedResourceLocation := req.HTTPRequest.URL.String()

A: You can get the path of uploaded S3 object with the help of below code.
import (
    "github.com/aws/aws-sdk-go-v2/aws"
    "github.com/aws/aws-sdk-go-v2/feature/s3/manager"
    "github.com/aws/aws-sdk-go-v2/service/s3"
    "github.com/aws/aws-sdk-go-v2/config"
    "github.com/aws/aws-sdk-go-v2/credentials"
)

...

func configS3() *s3.Client {

    creds := credentials.NewStaticCredentialsProvider(os.Getenv("ACCESS_KEY_ID"), os.Getenv("SECRET_ACCESS_KEY"), "")

    cfg, err := config.LoadDefaultConfig(context.TODO(), config.WithCredentialsProvider(creds), config.WithRegion(os.Getenv("S3_REGION")))

    if err != nil {
        log.Fatal(err)
    } else {
        fmt.Println(" S3 has been initializd ! ")
    }

    return s3.NewFromConfig(cfg)

}

func UploadImageToS3(imageFile string) error {

    // Open the file from the file path
    upFile, err := os.Open(imageFile)
    if err != nil {
        return fmt.Errorf("could not open local filepath [%v]: %+v", imageFile, err)
    }
    defer upFile.Close()

    uploader := manager.NewUploader(configS3())
    uploadResult, err := uploader.Upload(context.TODO(), &s3.PutObjectInput{
        Bucket:      aws.String("BubblyBucket"),
        Key:         aws.String("folder1/Image.jpeg"),
        Body:        upFile,
        ContentType: aws.String("image/jpg"),
    })

    if err != nil {
        fmt.Printf("Error: %v  \n", err)
        return err
    }

    fmt.Println("Location: " + uploadResult.Location)
    fmt.Printf("Image has been uploaded ->>> %v \t \n", imageFile)
    return nil
}

The result will be like this
Location: https://BubblyBucket.s3.ap-southeast-1.amazonaws.com/folder1/Image.jpeg
Image has been uploaded ->>> /home/my-machine/Pictures/Image-1.jpeg


text:
Q: How can I download a file with wget for which url is generated by the website? A website generates a zip file for download upon clicking the download button. I want to download it using wget. I tried cancelling the download and trying to copy the download link, however it was just the general url of the website and not a download link. I tried opening developer tools and clicking "copy POST data" to get
 csrfmiddlewaretoken=FPsq2lfGy******7file_B****001=on

and by clicking on copy as cURL:
curl 'https://f********.eu/download/' -H 'Host: f****5-db.s***t.eu' -H 'User-Agent: Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:60.0) Gecko/20100101 Firefox/60.0' -H 'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8' -H 'Accept-Language: en-GB,en;q=0.5' --compressed -H 'Referer: https://*******.s***t.eu/files/****/******' -H 'Content-Type: application/x-www-form-urlencoded' -H 'Cookie: csrftoken=FPs********qGy; sessionid=a4l4zaqtrtpvwts7pbadw9ny' -H 'Connection: keep-alive' -H 'Upgrade-Insecure-Requests: 1' --data ''

I tried using the previous answers, but couldn't understand how this file can be downloaded. Please explain.


text:
Q: How to handle parent child data relationships in redux I'm building a simple todo app where a user can create projects and then add todo items. I believe my state should look something like this:
{
  projects: {
    1: {
      id: 1,
      title: "New Project",
      todos: [1, 2]
    }
  },
  todos: {
    1: {
      id: 1,
      text: "This is the first todo",
      isComplete: true,
      project: 1
    },
    2: {
      id: 2,
      text: "This is the second todo",
      isComplete: false,
      project: 1
    }
  }
}

When creating a new todo I need to update the todos state with the new todo and I need to update the parent project in the projects state.
What is the best way to handle this? Do both of the reducers need actions to handle this? Or is there someway the todos reducer can call an update action in the projects reducer?
EDIT: Here's how I changed the data structure to work better with redux
{
  projects: {
    condition: {
      currentProject: 1
    },
    entities: {
      1: {
        id: 1,
        title: "New Project"
      }
    }
  },
  todos: {
    condition: {
      currentFilter: 'SHOW_ALL'
    },
    entities: {
      1: {
        id: 1,
        text: "This is the first todo",
        isComplete: true,
        project: 1
      },
      2: {
        id: 2,
        text: "This is the second todo",
        isComplete: false,
        project: 1
      }
    }
  }
}

This way each of my reducers being combined at the root level are scoped to one root key. entities are persisted but condition is not. All other parts of state are computed use reselect. I'd be curious to see how others are solving similar problems in a front end only app.

A: When projects reference their todos and vice versa, you're duplicating data. Unless you're working on an extremely large collection, I would recommend against that pattern. Instead, whenever you need a list of todos that match a project, filter the todos collection. Something like reselect is ideal for this.
This way when you dispatch CREATE_TODO, you only need the todos reducer to listen.
Keep your reducers decoupled.

*

*Dispatching actions in reducers is an anti-pattern. You can't do something in one reducer and pass that information to another directly. A better solution is
dispatch({ type: CREATE_TODO, payload: { text: 'dsfdf' })
dispatch({ type: ASSOCIATE_TODO_WITH_PROJECT, payload: { todo: todoid, project: 2 })

but even that won't work because you don't know what todoid is. Which brings me to...

*You shouldn't have to know the id of the todo before you create it. In your reducer setup, you need to know the todo's id in order to add it to a project. That means you need to provide it in the action payload. But then you're view would have to generate the next id is, which is not ideal.
Calling state.todos.filter(todo => todo.project == currentProject.id) in mapStateToProps is a better solution than figuring out what the next id should be in the view and passing it with the action.
If this is done with a db, then you would use something like this with redux-thunk
export function createTodo(text, project) {
  return function(dispatch) {
    dispatch({ type: CREATE_TODO_PENDING });
    fetch('/todos', { method: 'POST', body: { text: text, project: project } })
      .then(function(response) { // { id: 134452, text: text, project: project }
        dispatch({ type: CREATE_TODO_SUCCESS, payload: response })
      }.catch(err) { dispatch({ type: CREATE_TODO_FAIL }) }
  }
}

If you're using a backend that handles the id, then you can do the above and have both reducers listen to the events and assign todos to projects and projects to todos at the same time. But I still don't really recommend doing that.

*You risk having data out of sync because you lack a single source of truth. If your projects reducer says a project owns a todo with id === 3, but that todo says a different project owns it, who does that todo belong to? Obviously a bug has occured, but that could be prevented altogether by only having one child keep track of parent.
Though, again, if you're using a database, then the database should keep those things synced up (still more surface area for bugs, but less likely). In which case as long as your client data always reflected server data, you should be fine.


text:
Q: Match lookup value with importHTML and combine tables in Soogle Sheet I have total 2 url links both of which match lookup value and want column of second table in first table.
I have first taken a table from the importhtml formula. And the cell that is green is the column lookup value. Which is as follows.
1st table https://www.screener.in/screens/881782/rk-all-stocks/?page=21
=QUERY(IMPORTHTML("https://www.screener.in/screens/881782/rk-all-stocks?page=1", "table",1),"where Col1 is not null",1)

And there is another table in which I want to match the lookup values from the first table and all the values from that table. Which I have tried. Within this google sheet and you can also try in this google sheet.\
=VLOOKUP(B3,IMPORTHTML("https://www.screener.in/screens/881791/rk-holding/?page=1", "table",1),12,0)

2nd table https://www.screener.in/screens/881791/rk-holding/?page=1

In column next to roce I want column of promoter holding. Which you have to take from this url link.
get result like

try this in google sheet. : https://docs.google.com/spreadsheets/d/1yawdkBHkheaXeziWHFBFd3gngO3EQJr0d19lUH9cVfI/edit?usp=sharing
Thanks in Advance.

A: added formula to your sheet
Cell L3:
=BYROW(B3:B,LAMBDA(bx,IF(bx="",,IFNA(QUERY(IMPORTHTML("https://www.screener.in/screens/881791/rk-holding/?page=1", "table",1),"Select Col12, Col13 Where Col2='"&bx&"'",0)))))
-


text:
Q: How to see your new votes in the new user interface?
As per subject: looks like there has been a recent interface change (see picture above), and now that the little mail icon has gone missing, I am totally unable to find the page that used to show new votes on your questions and answers. So, if somebody up/down-voted me, I can't know where.
Is that page still available? How can it be reached?

A: It's here: https://stackoverflow.com/users/recent/ or https://stackoverflow.com/users/recent/USERNAME
Hopefully we will get it back as usual soon!

A: Just hover over the arrow or your username, and the current popup displays your recent rep changes:

A: Looks like I've found something similar:

Personally, I liked a lot more the previous layout.

A: Make it something like this


text:
Q: Bootstrap Columns Centered Let's say I have a basic HTML bootstrap layout like so:

Test Title

Test1

Test1

Test1

Test1

Test1

Test1

With this CSS:
h2{
  text-align: center;
}

The Title is correctly centered, but how can I move the col-md-6's so that the title is directly in the middle of both of them?
An example of what I am typing about.
Example
Any help is appreciated.

A: Just add text-center after the col-md-6 items, or the row itself per your update to place both those divs in a row. Also, leave the header tag outside the row.

h2{
  text-align: center;
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />

Test Title

Test1

Test1

Test1

Test1

Test1

Test1

See this section of the Bootstrap documentation for details on typography related matters. You can also add this as a class to your h2 tag to center the title text if you wish.

A: You can use the same CSS rule, and apply text-center to the .col-md-6 divs, like so:
h2,
.col-md-6 {
  text-align: center;
}

Depending on which version of Bootstrap you're using, you should probably use .center-block or .text-center, rather than overriding Bootstrap's built in functionality.

A: Simply add text-center to the row.

Test Title

Test1

Test1

Test1

Test1

Test1

Test1

Working example here: http://www.bootply.com/JvTYpubUeh#

A: Try the margin Style Attribute
http://learnlayout.com/margin-auto.html
Create a class(or use bootstrap classes)
#main {
  width: 600px;
  margin: 0 auto;
}


text:
Q: What does it mean, "luxury of worrying"? Dick Best speaks to pilot, who wants to withdraw from the war, about his father:

Dick Best: You know how I got his respect? By always staying in the
  fight. I wish I had the luxury of worrying about your confidence, but
  we're short on pilots, so, you gotta suck it up.

What does it mean, "luxury of worrying"?
I never saw "luxury" used as collective noun.
I find this line in movie Midway 2019.

A: A "luxury" is "a pleasure obtained only rarely".  The characters are using "luxury" rather ironically here.
A wartime pilot is very busy and lives a very dangerous life. They could be killed almost any time.  A wartime pilot does not have time to worry about "do I have the confidence of my peers".  From the point of view of a wartime pilot, having enough free time to worry about "confidence" would be better than always working in a job and being at risk of death. So, ironically, "worrying" is a luxury.

A: luxury is not a collective noun. In this context, a luxury is something that you would like, but cannot afford. You use this expression when you are not able to do something. If, for example, you have a backlog of work and a colleague invites you to join her for lunch, you would say:

I wish I had the luxury of being able to take a lunch break.

You don't have time to take a lunch break, so taking a lunch break seems like a luxury.


text:
Q: EventLogAppender write only my app events How to config EventLogAppender for write only events from my app. Because, currently I have next configuration:
    var elAppender = new EventLogAppender
                         {
                             ApplicationName = "My App",
                             LogName = "My Log",
                             Layout = new PatternLayout(default_format),
                             Threshold = Level.Error
                         };
    elAppender.ActivateOptions();

and in My Log present all messages from the all applications like Application, bu I need events only from My App.
Thank you.

A: You could create a filtered view within Event Viewer. This way, you don't need to change your application.

A: I found solution :),
I recreated my appender without spaces in the name and everything worked :) the code like this:
var elAppender = new EventLogAppender
                         {
                             ApplicationName = **"MyApp"**,
                             LogName = **"MyLog"**,
                             Layout = new PatternLayout(default_format),
                             Threshold = Level.Error
                         };
    elAppender.ActivateOptions();


text:
Q: Can't understand TwoPhaseCommitSinkFunction lifecycle I needed a sink to Postgres DB, so I started to build a custom Flink SinkFunction. As FlinkKafkaProducer implements TwoPhaseCommitSinkFunction, then I decided to do the same. As stated in O'Reilley's book  Stream Processing with Apache Flink, you just need to implement the abstract methods, enable checkpointing and you're up to go. But what really happens when I run my code is that commit method is called only once, and it is called before invoke, what is totally unexpected since you shouldn't be ready to commit if your set of ready-to-commit transactions is empty. And the worst is that, after committing, invoke is called for all of the transaction lines present in my file, and then abort is called, which is even more unexpected.
When the Sink is initialized, It is of my understanding that the following should occur:

*

*beginTransaction is called and sends an identifier to invoke

*invoke adds the lines to the transaction, according to the identifier received

*pre-commit makes all final modification on current transaction data

*commit handles the finalized transaction of pre-commited data

So, I can't see why my program doesn't show this behaviour.
Here goes my sink code:
package PostgresConnector

import java.sql.{BatchUpdateException, DriverManager, PreparedStatement, SQLException, Timestamp}
import java.text.ParseException
import java.util.{Date, Properties, UUID}
import org.apache.flink.api.common.ExecutionConfig
import org.apache.flink.configuration.Configuration
import org.apache.flink.streaming.api.functions.sink.{SinkFunction, TwoPhaseCommitSinkFunction}
import org.apache.flink.streaming.api.scala._
import org.slf4j.{Logger, LoggerFactory}

class PostgreSink(props : Properties, config : ExecutionConfig) extends TwoPhaseCommitSinkFunction[(String,String,String,String),String,String](createTypeInformation[String].createSerializer(config),createTypeInformation[String].createSerializer(config)){

    private var transactionMap : Map[String,Array[(String,String,String,String)]] = Map()

    private var parsedQuery : PreparedStatement = _

    private val insertionString : String = "INSERT INTO mydb (field1,field2,point) values (?,?,point(?,?))"

    override def invoke(transaction: String, value: (String,String,String,String), context: SinkFunction.Context[_]): Unit = {

        val LOG = LoggerFactory.getLogger(classOf[FlinkCEPClasses.FlinkCEPPipeline])

        val res = this.transactionMap.get(transaction)

        if(res.isDefined){

            var array = res.get

            array = array ++ Array(value)

            this.transactionMap += (transaction -> array)

        }else{

            val array = Array(value)

            this.transactionMap += (transaction -> array)

        }

        LOG.info("\n\nPassing through invoke\n\n")

        ()

    }

    override def beginTransaction(): String = {

        val LOG: Logger = LoggerFactory.getLogger(classOf[FlinkCEPClasses.FlinkCEPPipeline])

        val identifier = UUID.randomUUID.toString

        LOG.info("\n\nPassing through beginTransaction\n\n")

        identifier

    }

    override def preCommit(transaction: String): Unit = {

        val LOG = LoggerFactory.getLogger(classOf[FlinkCEPClasses.FlinkCEPPipeline])

        try{

            val tuple : Option[Array[(String,String,String,String)]]= this.transactionMap.get(transaction)

            if(tuple.isDefined){

                tuple.get.foreach( (value : (String,String,String,String)) => {

                    LOG.info("\n\n"+value.toString()+"\n\n")

                    this.parsedQuery.setString(1,value._1)
                    this.parsedQuery.setString(2,value._2)
                    this.parsedQuery.setString(3,value._3)
                    this.parsedQuery.setString(4,value._4)
                    this.parsedQuery.addBatch()

                })

            }

        }catch{

            case e : SQLException =>
                LOG.info("\n\nError when adding transaction to batch: SQLException\n\n")

            case f : ParseException =>
                LOG.info("\n\nError when adding transaction to batch: ParseException\n\n")

            case g : NoSuchElementException =>
                LOG.info("\n\nError when adding transaction to batch: NoSuchElementException\n\n")

            case h : Exception =>
                LOG.info("\n\nError when adding transaction to batch: Exception\n\n")

        }

        this.transactionMap = this.transactionMap.empty

        LOG.info("\n\nPassing through preCommit...\n\n")
    }

    override def commit(transaction: String): Unit = {

        val LOG : Logger = LoggerFactory.getLogger(classOf[FlinkCEPClasses.FlinkCEPPipeline])

        if(this.parsedQuery != null) {
            LOG.info("\n\n" + this.parsedQuery.toString+ "\n\n")
        }

        try{

            this.parsedQuery.executeBatch
            val LOG : Logger = LoggerFactory.getLogger(classOf[FlinkCEPClasses.FlinkCEPPipeline])
            LOG.info("\n\nExecuting batch\n\n")

        }catch{

            case e : SQLException =>
                val LOG : Logger = LoggerFactory.getLogger(classOf[FlinkCEPClasses.FlinkCEPPipeline])
                LOG.info("\n\n"+"Error : SQLException"+"\n\n")

        }

        this.transactionMap = this.transactionMap.empty

        LOG.info("\n\nPassing through commit...\n\n")

    }

    override def abort(transaction: String): Unit = {

        val LOG : Logger = LoggerFactory.getLogger(classOf[FlinkCEPClasses.FlinkCEPPipeline])

        this.transactionMap = this.transactionMap.empty

        LOG.info("\n\nPassing through abort...\n\n")

    }

    override def open(parameters: Configuration): Unit = {

        val LOG: Logger = LoggerFactory.getLogger(classOf[FlinkCEPClasses.FlinkCEPPipeline])

        val driver = props.getProperty("driver")
        val url = props.getProperty("url")
        val user = props.getProperty("user")
        val password = props.getProperty("password")
        Class.forName(driver)
        val connection = DriverManager.getConnection(url + "?user=" + user + "&password=" + password)
        this.parsedQuery = connection.prepareStatement(insertionString)

        LOG.info("\n\nConfiguring BD conection parameters\n\n")
    }
}

And this is my main program:
package FlinkCEPClasses

import PostgresConnector.PostgreSink
import org.apache.flink.api.java.io.TextInputFormat
import org.apache.flink.api.java.utils.ParameterTool
import org.apache.flink.cep.PatternSelectFunction
import org.apache.flink.cep.pattern.conditions.SimpleCondition
import org.apache.flink.cep.scala.pattern.Pattern
import org.apache.flink.core.fs.{FileSystem, Path}
import org.apache.flink.streaming.api.scala._
import org.apache.flink.streaming.api.TimeCharacteristic
import org.apache.flink.cep.scala.{CEP, PatternStream}
import org.apache.flink.streaming.api.functions.source.FileProcessingMode
import org.apache.flink.streaming.api.scala.{DataStream, StreamExecutionEnvironment}
import java.util.Properties

import org.apache.flink.api.common.ExecutionConfig
import org.slf4j.{Logger, LoggerFactory}

class FlinkCEPPipeline {

  val LOG: Logger = LoggerFactory.getLogger(classOf[FlinkCEPPipeline])
  LOG.info("\n\nStarting the pipeline...\n\n")

  var env : StreamExecutionEnvironment = StreamExecutionEnvironment.getExecutionEnvironment

  env.enableCheckpointing(10)
  env.setStreamTimeCharacteristic(TimeCharacteristic.ProcessingTime)
  env.setParallelism(1)

  //var input : DataStream[String] = env.readFile(new TextInputFormat(new Path("/home/luca/Desktop/lines")),"/home/luca/Desktop/lines",FileProcessingMode.PROCESS_CONTINUOUSLY,1)

  var input : DataStream[String] = env.readTextFile("/home/luca/Desktop/lines").name("Raw stream")

  var tupleStream : DataStream[(String,String,String,String)] = input.map(new S2PMapFunction()).name("Tuple Stream")

  var properties : Properties = new Properties()

  properties.setProperty("driver","org.postgresql.Driver")
  properties.setProperty("url","jdbc:postgresql://localhost:5432/mydb")
  properties.setProperty("user","luca")
  properties.setProperty("password","root")

  tupleStream.addSink(new PostgreSink(properties,env.getConfig)).name("Postgres Sink").setParallelism(1)
  tupleStream.writeAsText("/home/luca/Desktop/output",FileSystem.WriteMode.OVERWRITE).name("File Sink").setParallelism(1)

  env.execute()

}

My S2PMapFunction code:
package FlinkCEPClasses

import org.apache.flink.api.common.functions.MapFunction

case class S2PMapFunction() extends MapFunction[String,(String,String,String,String)] {

    override def map(value: String): (String, String, String,String) = {

            var tuple = value.replaceAllLiterally("(","").replaceAllLiterally(")","").split(',')

            (tuple(0),tuple(1),tuple(2),tuple(3))

    }
}

My pipeline works like this: I read lines from a file, map them to a tuple of strings, and use the data inside the tuples to save them in a Postgres DB
If you want to simulate the data, just create a file with lines in a format like this:
(field1,field2,pointx,pointy)
Edit
The execution order of the TwoPhaseCommitSinkFUnction's methods is the following:
Starting pipeline...
beginTransaction
preCommit
beginTransaction
commit
invoke
invoke
invoke
invoke
invoke
invoke
invoke
invoke
invoke
invoke
invoke
invoke
invoke
invoke
invoke
invoke
invoke
invoke
abort

A: I'm not an expert on this topic, but a couple of guesses:
preCommit is called whenever Flink begins a checkpoint, and commit is called when the checkpoint is complete. These methods are called simply because checkpointing is happening, regardless of whether the sink has received any data.
Checkpointing is happening periodically, regardless of whether any data is flowing through your pipeline. Given your very short checkpointing interval (10 msec), it does seem plausible that the first checkpoint barrier will reach the sink before the source has managed to send it any data.
It also looks like you are assuming that only one transaction will be open at a time. I'm not sure that's strictly guaranteed, but so long as maxConcurrentCheckpoints is 1 (which is the default), you should be okay.

A: So, here goes the "answer" for this question. Just to be clear: at this moment, the problem about the TwoPhaseCommitSinkFunction hasn't been solved yet. If what you're looking for is about the original problem, then you should look for another answer. If you don't care about what you'll use as a sink, then maybe I can help you with that.
As suggested by @DavidAnderson, I started to study the Table API and see if it could solve my problem, which was using Flink to insert lines in my database table.
It turned out to be really simple, as you'll see.
OBS: Beware of the version you are using. My Flink's version is 1.9.0.
Source code
package FlinkCEPClasses

import java.sql.Timestamp
import java.util.Properties

import org.apache.flink.api.common.typeinfo.{TypeInformation, Types}
import org.apache.flink.api.java.io.jdbc.JDBCAppendTableSink
import org.apache.flink.streaming.api.TimeCharacteristic
import org.apache.flink.streaming.api.scala.{DataStream, StreamExecutionEnvironment}
import org.apache.flink.table.api.{EnvironmentSettings, Table}
import org.apache.flink.table.api.scala.StreamTableEnvironment
import org.apache.flink.streaming.api.scala._
import org.apache.flink.table.sinks.TableSink
import org.postgresql.Driver

class TableAPIPipeline {

    // --- normal pipeline initialization in this block ---

    var env : StreamExecutionEnvironment = StreamExecutionEnvironment.getExecutionEnvironment

    env.enableCheckpointing(10)
    env.setStreamTimeCharacteristic(TimeCharacteristic.ProcessingTime)
    env.setParallelism(1)

    var input : DataStream[String] = env.readTextFile("/home/luca/Desktop/lines").name("Original stream")

    var tupleStream : DataStream[(String,Timestamp,Double,Double)] = input.map(new S2PlacaMapFunction()).name("Tuple Stream")

    var properties : Properties = new Properties()

    properties.setProperty("driver","org.postgresql.Driver")
    properties.setProperty("url","jdbc:postgresql://localhost:5432/mydb")
    properties.setProperty("user","myuser")
    properties.setProperty("password","mypassword")

    // --- normal pipeline initialization in this block END ---

    // These two lines create what Flink calls StreamTableEnvironment.
    // It seems pretty similar to a normal stream initialization.
    val settings = EnvironmentSettings.newInstance().useBlinkPlanner().inStreamingMode().build()
    val tableEnv = StreamTableEnvironment.create(env,settings)

    //Since I wanted to sink data into a database, I used JDBC TableSink,
    //because it is very intuitive and is a exact match with my need. You may
    //look for other TableSink classes that fit better in you solution.
    var tableSink : JDBCAppendTableSink = JDBCAppendTableSink.builder()
    .setBatchSize(1)
    .setDBUrl("jdbc:postgresql://localhost:5432/mydb")
    .setDrivername("org.postgresql.Driver")
    .setPassword("mypassword")
    .setUsername("myuser")
    .setQuery("INSERT INTO mytable (data1,data2,data3) VALUES (?,?,point(?,?))")
    .setParameterTypes(Types.STRING,Types.SQL_TIMESTAMP,Types.DOUBLE,Types.DOUBLE)
    .build()

    val fieldNames = Array("data1","data2","data3","data4")
    val fieldTypes = Array[TypeInformation[_]](Types.STRING,Types.SQL_TIMESTAMP,Types.DOUBLE, Types.DOUBLE)

    // This is the crucial part of the code: first, you need to register
    // your table sink, informing the name, the field names, field types and
    // the TableSink object.

    tableEnv.registerTableSink("postgres-table-sink",
        fieldNames,
        fieldTypes,
        tableSink
    )

    // Then, you transform your DataStream into a Table object.
    var table = tableEnv.fromDataStream(tupleStream)

    // Finally, you insert your stream data into the registered sink.
    table.insertInto("postgres-table-sink")

    env.execute()

}


text:
Q: I would like to know about examples of type theory applications. For what purpose was type theory invented? Can you give me some motivations? I'm an undergraduate math student.

A: Type Theory was invented as a possible foundation for mathematics. It was later tied to the lambda calculus, and is now a prime example of the Curry-Howard Correspondence. Later yet, it was connected to category theory (especially higher category theory), and is a very active field of research. For more information, see here or here.
Here are some quick applications:

*

*Foundations of mathematics (as a computer friendly alternative to set theory)

*Programming Language theory (programming languages are made safer by type systems)

*Homotopy theory (somewhat surprisingly, cf. HoTT)

If you want more resources, a friend of mine made a github page all about learning type theory. Reading through the table of contents will give you an idea of why people care, and it will also have direct links to resources for learning the relevant material:
here's the github page
good luck!

I hope this helps ^_^