text:
Q: Connect a standalone application to web browser-Java I'm developing a stand alone timetable scheduling system using netbeans IDE and i would like to link the output (ie a created schedule/timetable) to the web browser so that it can be viewed from there once a user logs in.
How should i go about it?

A: Write a service that both desktop and browser UIs can access the same way.  Both can display the same data.

A: You could encapsulate the logic in a service, say ScheduleService (or TimetableService). Suppose you have the following interface definining your ScheduleService:
public interface ScheduleService {

    public List<Appointment> getAppointments(Date when);
    public void setAppointment(Date when, Appointment appointment);

}

Then you provide your implementation under ScheduleServiceImpl:
public class ScheduleServiceImpl implements ScheduleService {

    public List<Appointment> getAppointments(Date when) {
        // TODO: get list of appointments
    }

    public void setAppointment(Date when, Appointment appointment) {
        // TODO: create appointment
    }
}

In your GUI code, you would directly use your ScheduleServiceImpl, while the WebService would use a proxy method. Obviously, these proxy methods should also implement the ScheduleService interface, but in their implementation they would delegate all calls to the real implementation.
public class ScheduleServiceWebServiceImpl implements ScheduleService {
    ScheduleService realImplementation = new ScheduleServiceImpl();

    public List<Appointment> getAppointments(Date when) {
        return realImplementation.getAppointments(when);
    }

    public void setAppointment(Date when, Appointment appointment) {
        realImplementation(when, appointment);
    }
}

}

For the WebService part, of course, you might want to transform the output (via a JSP, or XSLT) to generate HTML or any other output format.

A: My friend "Dhiral Pandya" develop this browser for his college project may be, this will help you
My Button is open source java web browser.
Develop for school and college projects and learning purpose.
Download source code extract .zip file and copy "mybutton" folder from "parser\mybutton" to C:\
Import project "omtMyButton" in eclipse.
Require Java 6.
Download .exe and source code :
https://sourceforge.net/projects/omtmybutton/files/


text:
Q: No Resource found that matches given name error(AppCompat_v7) in android I tried creating an Android activity with Action Bar in Eclipse. I ended up in facing some error in appcompat_7 dependency.
And the error was No resource found that matches the given name on item tag under style

and its corresponding error is

Someone help me to get out of this.

redpajama_set_name: RedPajamaStackExchange


text:
Q: get value from function in exported function JS today I'm working on a project in JavaScript. I've an exported function A that is in an other file then my location.js. When I click I get the location of an user.
But how do I get the values from a function in an exported function?
I need the coordinates in the function.
Code:
if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(
                function(position) {
                    lat = position.coords.latitude;
                    long = position.coords.longitude;
                    coordinates = {
                        latitude: lat,
                        longitude: long
                    };
                    console.log(JSON.stringify(coordinates));
                    return coordinates;
                }, {
                   (errorHandling)
                }};

Could someone help me out?
Thanks for advance!

A: navigator.geolocation.getCurrentPosition is an async function which works on callback principle and not promises.
In order to get the returned values, you either need to convert it into a promise based function or pass a callback function to it which you call when data is available like
const getLocation = (callback) => {
    ....

    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(
            function myLocation(position) {
                lat = position.coords.latitude;
                long = position.coords.longitude;
                callback({
                    latitude: lat,
                    longitude: long
                }); // the callback method
            },
            function(error) {
                ...
            }
        );
    }
    ...
};

module.exports = { getLocation };

Now you can call the function and set the coordinates in state of react like
import Button from './button.js';

import { getLocation } from './functions/getLocation.js';

class Card extends React.Component {
    state = {
       coordinates: {}
    }
    getLocationCoordinates = () => {
        getLocation((coordinates) => {
            this.setState({coordinates})
        })
    }
    render() {
        const { lat, lng } = this.state.coordinates;
        return (
            <div id={'location'} className={'card'}>
                    ...
                    <Button function={this.getLocationCoordinates} text={'Allow Location'} />
                    ...
            </div>
        );
    }
}

export default Card;


text:
Q: Reload SharedPreferences I'm quite new to Android Prorgramming and have a problem understandig SharedPreferences.
I have a Main Activity and a Settings Activity.
I want to be able to change a SharedPreference (here called firstWaitTime) in the Settings Activity and work with it in the Main Activity.
I can Set the new value in the settings, but in the Main Activity i only see the new value when i close and reopen the app.
I Think i would need a OnPrefrenceChanged Listender but i have no idea how to implement it...
The Main one looks like this:

public class MainActivity extends ActionBarActivity {

    //Radio Button
    private int stufe;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        SharedPreferences settings = this.getSharedPreferences("settings", Context.MODE_PRIVATE);
        int firstWaitTime = settings.getInt("firstWaitTime", 12);
        int secondWaitTime = settings.getInt("secondWaitTime", 8);
        int thirdWaitTime = settings.getInt("thirdWaitTime", 6);

        //TEST
        final TextView test = (TextView) findViewById(R.id.test);
        test.setText("" + firstWaitTime);

}

The Settings Activity looks like this:

 @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_settings);

 final SharedPreferences settings = this.getSharedPreferences("settings", MODE_PRIVATE);

//BUTTON

        final EditText edit1 = (EditText) findViewById(R.id.edit1);
        Button save=(Button) findViewById(R.id.savebtn);

        save.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {

                //prefs = getSharedPreferences(prefName, MODE_PRIVATE);
                //SharedPreferences.Editor editor = prefs.edit();
                SharedPreferences.Editor editor = settings.edit();

                //---save the values in the EditText view to preferences---
                editor.putInt("firstWaitTime", Integer.parseInt(edit1.getText().toString()));

                //---saves the values---
                editor.commit();

                Toast.makeText(getBaseContext(), "Saved", Toast.LENGTH_SHORT).show();
            }
        });
}

What is the best way to achieve this?

A: onCreate() will not be called as Android hasn't killed the Activity. Try putting your code in onResume() instead. For more info read up on the  Android Activity lifecycle.


text:
Q: Linux kernel programming i want to catch pipe() syscall, so i've changed source code in pipe.c
static pipe_hook_t pipe_hook;
pipe_hook_t set_pipe_hook(pipe_hook_t hook)
{
    pipe_hook_t old_hook = pipe_hook;
    pipe_hook = hook;
    printk(KERN_INFO, "pipe hook: %p", hook);
    return old_hook;
}

EXPORT_SYMBOL_GPL(set_pipe_hook);

then i tried to define pipe_hook_t in file syscalls.h (included in pipe.c)
typedef void (*pipe_hook_t)(int *filedes);
pipe_hook_t set_pipe_hook(pipe_hook_t hook);

and i have error:
fs/pipe.c:1130: error: expected '=', ',', ';', 'asm' or '__attribute__' before 'pipe_hook'
fs/pipe.c:1131: error: expected '=', ',', ';', 'asm' or '__attribute__' before 'set_pipe_hook'
fs/pipe.c:1138: error: 'set_pipe_hook' undeclared here (not in a function)
fs/pipe.c:1138: warning: type defaults to 'int' in declaration of 'set_pipe_hook'
fs/pipe.c: In function 'sys_pipe2':
fs/pipe.c:1153: error: 'pipe_hook' undeclared (first use in this function)
fs/pipe.c:1153: error: (Each undeclared identifier is reported only once
fs/pipe.c:1153: error: for each function it appears in.)
fs/pipe.c:1154: error: implicit declaration of function 'pipe_hook'

i've tried to create my own .h file and define pipe_hook_t there but the error was the same

A: Problem has been solved. I've just confused directory where header files are.


text:
Q: Tree without cofinal branches and with levels of bounded size My question is: let's say that a tree T has no cofinal branch and has all levels of size $< \mu$. Can we prove (in ZFC) that the set of branches of T has cardinality $\leq \mu$? I have a very strong intuition that it is so, but I can't come up with a proof (or a counterexample).

A: No.
Suppose that $T$ is a normal Aronszajn tree (so any point has splitting successors) and $2^{\aleph_0}>\aleph_1$. Then there are no cofinal branches, but easily due to splitting at any successor point, any limit stage will have continuum many branches, of which only countably many are allowed to be realised and extended.


text:
Q: how to Socket io with swift language Here is my socket io swift language code
and main.js file code also here
I have not properly idea why is not with socket io server.
  let manager = SocketManager(socketURL: URL(string: "http://localhost:3000")!, config: [.log(true), .compress])
  self.socket = manager.socket(forNamespace: "/")
  establishSocketConnection()

  func establishSocketConnection() {

    self.socket.connect()
    self.socket.on("connection") { ( dataArray, ack) -> Void in
        print("connected to external server")

    }
  }

  func cloesSocketConnection() {
    self.socket.disconnect()
  }

log:
2019-03-27 23:38:36.228040+0530 scoket[1693:38288] LOG SocketIOClient{/}: Handling event: statusChange with data: [connecting, 2]
2019-03-27 23:38:36.228241+0530 scoket[1693:38288] LOG SocketIOClient{/}: Joining namespace /
2019-03-27 23:38:36.228353+0530 scoket[1693:38288] LOG SocketManager: Tried connecting socket when engine isn't open. Connecting
2019-03-27 23:38:36.228437+0530 scoket[1693:38288] LOG SocketManager: Adding engine
2019-03-27 23:38:36.229083+0530 scoket[1693:38288] LOG SocketIOClient{/}: Adding handler for event: connection
2019-03-27 23:38:36.229115+0530 scoket[1693:38343] LOG SocketEngine: Starting engine. Server: http://localhost:3000
2019-03-27 23:38:36.229203+0530 scoket[1693:38343] LOG SocketEngine: Handshaking
2019-03-27 23:38:36.229239+0530 scoket[1693:38288] LOG SocketManager: Manager is being released
2019-03-27 23:38:36.232066+0530 scoket[1693:38343] LOG SocketEnginePolling: Doing polling GET http://localhost:3000/socket.io/?transport=polling&b64=1
2019-03-27 23:38:36.331457+0530 scoket[1693:38346] LOG SocketEnginePolling: Got polling response
2019-03-27 23:38:36.331618+0530 scoket[1693:38346] LOG SocketEnginePolling: Got poll message: 96:0{"sid":"yaMqmjKGkhok6TuqAAAC","upgrades":["websocket"],"pingInterval":25000,"pingTimeout":5000}2:40
2019-03-27 23:38:36.331884+0530 scoket[1693:38346] LOG SocketEngine: Got message: 0{"sid":"yaMqmjKGkhok6TuqAAAC","upgrades":["websocket"],"pingInterval":25000,"pingTimeout":5000}
2019-03-27 23:38:36.341490+0530 scoket[1693:38346] LOG SocketEngine: Got message: 40
2019-03-27 23:38:36.341726+0530 scoket[1693:38346] LOG SocketEngine: Writing poll:  has data: false
2019-03-27 23:38:36.342051+0530 scoket[1693:38346] LOG SocketEnginePolling: Sending poll:  as type: 2
2019-03-27 23:38:36.342505+0530 scoket[1693:38346] LOG SocketEnginePolling: Created POST string: 1:2
2019-03-27 23:38:36.342910+0530 scoket[1693:38346] LOG SocketEnginePolling: POSTing
2019-03-27 23:38:36.343202+0530 scoket[1693:38346] LOG SocketEngine: Engine is being released

A: your socket property it isn't true
your connection method must be like this:
func establishSocketConnection() {
  let socket = manager.defaultSocket
      self.socket.on("connection") { ( dataArray, ack) -> Void in
    print("connected to external server")

     }
}

and every time you want to create handler in socket (like socket.on or socket.emit)
you must create socket variable again.
hope to this help you.

A: Here is the latest swift 4.2 code
Connect with socket io server and get data in xcode
    func ConnectToSocket() {

      manager  = SocketManager(socketURL: URL(string: "http://localhost:3000")!, config: [.log(true), .compress])

    socketIOClient = manager.defaultSocket

    socketIOClient.on(clientEvent: .connect) {data, ack in
        print(data)
        print("socket connected")

        self.socketIOClient.emit("GetData", "dad")

    }

    socketIOClient.on("newChatMessage") { (dataArray, socketAck) -> Void in

        print(dataArray)
    }

    socketIOClient.on(clientEvent: .error) { (data, eck) in
        print(data)
        print("socket error")
    }

    socketIOClient.on(clientEvent: .disconnect) { (data, eck) in
        print(data)
        print("socket disconnect")
    }

    socketIOClient.on(clientEvent: SocketClientEvent.reconnect) { (data, eck) in
        print(data)
        print("socket reconnect")
    }

    socketIOClient.connect()

}

A: Use this SocketIOManger for communicate with socket and make changes according to your need.
    class SocketIOManager: NSObject {
 static let sharedInstance = SocketIOManager()
 var manager : SocketManager?
 var socket : SocketIOClient?

 override init() {
     super.init()
 }

 /**
  Create socket connection.
  - parameter completionHandler : Called when complition will occure.
  - parameter connected : True when socket connected.
  - returns: nil
  */
 func createSocketConnection (completionHandler: @escaping (_ connected: Bool) -> Void) {
     let token = UserDefaults.standard.string(forKey: ConstantsBroadcast.Access_Token)!
     manager = SocketManager(socketURL: URL(string: ConstantsBroadcast.socketBaseUrl)!
        ,config: [.log(true),  .connectParams(["token": token]) ])

     socket = manager?.defaultSocket

     socket?.on(clientEvent: .connect) { data, ack in
         print("socket connected.")
         completionHandler(true)
     }
     socket?.connect()
 }

 /**
  Disconnect socket.
  */
 func closeConnection() {
     socket?.disconnect()
 }

 /**
  Add new user to socket.
  - parameter username: current user name.
  - parameter userid: current user id.
  - parameter image: current user profile image url.
  - returns: nil
  */
 func addUserToServer(username: String, userid: String, image: String) {
     let dict = ["username" : username, "userId": userid, "profileImage":image] as [String : Any]
     self.socket?.emit("adduser", dict) //adduser

 }

 /**
  Add handler for total connected user.
  - parameter completionHandler : Called when complition will occure.
  - parameter userCount : Total number of  connected users.
  - returns: nil
  */
 func userConnectionHandlers(completionHandler: @escaping (_ userCount: String) -> Void) {
     socket?.on("updateconnecteduser") { data,ack in //updateconnecteduser
         debugPrint("connected user : ",data)
         if let snippet = data[0] as? NSDictionary {
             completionHandler("\(String(describing: snippet.value(forKey: "viewers")!))")
         }
     }
 }

 /**
  Send new message.
  - parameter message: user text message.
  - returns: nil
  */
 func sendMessage(message :String){
     if socket?.status == .connected {
         self.socket?.emit("sendchat", ["message": message]) //sendchat
     }
     else{
         print("socket not connected")
     }
 }

 /**
  Add handler for get new messages.
  - parameter completionHandler : Called when complition will occure.
  - parameter messageInfo : New message data.
  - returns: nil
  */
 func newMessageHandlers(completionHandler: @escaping (_ messageInfo: ChatItemModel) -> Void) {
     socket?.on("updatechat") { data,ack in //updatechat
         print(data)
         var msgData = ChatItemModel()
         if let chatData = data[0] as? NSDictionary {
             if let mId = chatData.value(forKey: "chatCommentId") as? String{
                 msgData.ChatCommentId = mId
             }
             if let userId = chatData.value(forKey: "userId") as? String {
                 msgData.UserID = userId
             }
             if let username = chatData.value(forKey: "username") as? String{
                 msgData.UserName = username
             }
             if let image = chatData.value(forKey: "profileImage") as? String{
                 msgData.ProfileImage = image
             }
             if let message = chatData.value(forKey: "message") as? String{
                 msgData.Message = message
             }
             if let createdAt = chatData.value(forKey: "createdAt") as? String{
                 msgData.CreatedAT = createdAt
             }

             completionHandler(msgData)
         }
     }
 }

 /**
  Block user.
  - parameter userId: user id.
  - returns: nil
  */
 func blockUser(userId : String){
     if socket?.status == .connected {
         self.socket?.emit("blockuser", ["userId" : userId]) //blockuser
         print("blockuser emmited : ", userId)
     }
     else{
         print("socket not connected")
     }
 }

 /**
  Add handler for block user.
  - parameter completionHandler : Called when complition will occure.
  - parameter userId : Blocked user id.
  - returns: nil
  */
 func blockUserHandler(completionHandler: @escaping (_ status : Int, _ userId: String) -> Void) {
     socket?.on("updateblockeduser") { data,ack in //updateblockeduser
         print("blcked userId  : ",data)

         if let blockedItem = data[0] as? NSDictionary {
             if let status = blockedItem.value(forKey: "status") as? Int{
                 if let userId = blockedItem.value(forKey: "userId") as? String{
                     completionHandler(status, userId)

                 }
             }

         }

     }
 }

}


text:
Q: How can I restore the "Open or save as" prompt in Firefox? I often download temporary files. I don't want to save them anywhere permanent I just want to look at them and then have them go away automatically after I read them.
I am using Firefox 98.0.2 (64-bit) and in older versions of Firefox, I used to be able to do this by selecting "open" instead of "save as".  In a recent update, that dialog went away and I don't see a way to restore it. Now, instead, I have to save the files somewhere manually and then remember to delete them later (or manually navigate to temp, which is approximately as annoying).
This is the screen I want back:

Is there a way to restore this prompt?

A: Go into Preferences> General, and select the "Ask before opening" option for (in your example) Microsoft Word 98-2003 Document.

A: I installed 98.0.2 to test this, it worked for me.

*

*Go to about:config

*Search for browser.download.improvements_to_download_panel

*Double click the row to change it to false

Yes, it is an awful variable name.


text:
Q: ListView item stays selected after returning to page I am on the most current version of Xamarin Forms. I have a Content Page. The Content Page has a content that has a ListView that has a ItemTemplate that contains some ImageCell. When I touch one list element I use Tapped_Event which navigate to other page. When I go back this page the ImageCell tapped color stay with Orange. I dont want to stayed with this Orange color. Anybody can help me?
This is my XAML code:
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
         xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
         x:Class="Spirocco.MedicationPage"
         Title="Gyógyszerek">
<ContentPage.Content>
    <ListView x:Name="Medications" ItemsSource="{Binding Medications}">
        <ListView.ItemTemplate>
            <DataTemplate>
                <ImageCell ImageSource="{Binding Icon}" Text="{Binding Name}" Detail="{Binding Type}" Tapped="ImageCell_Tapped" />
            </DataTemplate>
        </ListView.ItemTemplate>
    </ListView>
</ContentPage.Content>

ImageCell_Tapped method:
private async void ImageCell_Tapped(object sender, EventArgs e)
    {
        await Navigation.PushAsync(new MedicationDetailPage((Medication)Medications.SelectedItem));
    }

A: "Deselected" the SelectedItem after your PushAsync:
private async void ImageCell_Tapped(object sender, EventArgs e)
{
    await Navigation.PushAsync(new MedicationDetailPage((Medication)Medications.SelectedItem));

    // Manually deselect item
    Medications.SelectedItem = null;
}


text:
Q: How to increase Angular's (2+) change detection performance? I have been developing Angular applications for more than 8 months. I am overwhelmed by Angular 2+ architecture (compared to Angular JS). I read few articles/ guidelines about the best practices and all, but none of them doesn't address about improving the performance in change detection.
Could anyone please advise me on this?


text:
Q: Carrying along params in a form Let's say I have a Students table on my main page, with Country, Name, Age columns.
Suppose I want to have a dropdown box that lets users filter students by country, and also a search box that lets users search for students with a particular name.
I know how to create the country dropdown filter by itself:
<% form_tag('/students', :method => :get) do %>
  <%= collection_select(:country, :id, Country.all, :id, :name, :include_blank => true) %>
  <%= submit_tag 'Filter by Country' %>
<% end %>

And I know how to create the name search filter by itself:
<form name="sform" id="sform" action="" style="display:inline;">
  <label>
    Search names:
  </label>
  <%= text_field_tag("name", params['name'], :size => 10 ) %>
  <%= submit_tag("Go") %>
</form>

But what if I want to filter by country, and then search for names only within that country? I'm passing all my parameters around in the URL, but I don't know how to ensure that any existing params get passed along in the form.
[And in general, the forms I'm using above are kinda hacky, since I don't really understand Rails forms, so suggestions on improving them are also welcome.]

A: Seriously consider dumping all of the homegrown code for searchlogic. It handles everything you're asking for here, and greatly streamlines your view and controller code.


text:
Q: Ubuntu 12.04 using b43-fwcutter I have used 10.04 with the b43-fwcutter driver to drive my BCM4318 Broadcom card (a Linksys WPC54G v3) on my old Dell Inspiron 8100 for two years+ with no troubles.  I just upgraded to 12.04 and although everything worked fine after install, before I added the b43-fwcutter driver, once I installed the driver, the system refuses to boot.  Even before I install the Linksys card!!  It just hangs on boot with graphical garbage on the screen.  I tried several attempts to recover the system using the live CD, and finally reinstalled completely.  I have been thru the cycle, install fresh system, verify everything works, then install b43-fwcutter and it is hung, several times.  Consistent hard fail.
The system runs fine on hardwire Ethernet, and wireless was fine on 10.04.  But I cannot get there with 12.04.  So after several attempts, I am now ready to admit defeat and ask for help.
I have read every thread that search turned up, and either the advice is to do what I did, i.e. install fwcutter, or does not apply (Different Broadcom, STA, legacy, whatever)
So what do I need to do to fix it?  Or is the B43-fwcutter driver broken for 12.04?
Thoughts?  Tips?  Log files needed??

A: SOLVED!  This was a multifaceted problem.  First my own unfamiliarity with Grub did not let me recognize that Grub was trying to tell me something but it's incorrect video setting was just showing garbage.  Reconfiguring Grub solved that.  Second, something bogus was installed that was conflicting with the card, causing it to be activated even with no b43 driver installed, and it was then hanging the system.  I removed several things I could not identify and then suddenly I could get it to run, with complaints that the firmware was not installed.  I am not sure exactly what I removed that got around the problem.  Then I installed the firmware per the standard instructions here and is all started working.  Note I had installed the firmware before but it didn't work, since the bogus something or other was hanging things up.  It is working now, and I am posting this answer over the Wifi link.  Thanks for all the help...


text:
Q: Missing Style Library in Site collection in SharePoint 2013 I am Newbie in SharePoint 2013. I am creating a site Collection and I want to add my png files on Style Library but I am having problem finding Style Library.
Is there any way to activate Style Library for Team Site or Site Collection?
The site I have created cannot be opened from SharePoint Designer 2013. I am using SharePoint Foundation 2013.
Is there any way out to edit page using SharePoint Designer 2013?

A: *

*only the root site of site collections will contain a style library, not subsites

*You should find the style library upon site creation, but you can try enabling the publishing infrastructure feature and see if that helps

*as a last resort, you can create a new site collection, and save the style library as a template and add it to your site that is missing it

as for editing, you should use sharepoint designer, although you do have the possibility of creating a mapped folder in windows by using the url of your website

A: With the sharepoint foundation, they is not possible to enabled the publishing infrastructures for the collection or the site itself, this option is available only on the sharepoint server 2013.
You can try to access by url : http://MyWebSiteName/Style%20Library/Language*/Themable

*

*language like this format : fr-fr

If it's ok, you can edit the file you want in the ribbon menu "File" (that's open it in SharePoint Design 2013, not in the sharepoint web site).
If it's not ok, maybe you don't have rights, or maybe the foundation version lock it...


text:
Q: How to update array of objects in mongodb? I don't know whether this question has been asked before. However, I need to ask this to get help from you guys:
I have a document like below:
{
    "taskboard_id": "6149a3de8f604511e6883bae",
    "user_id": "61399af5d6294f56aa1116f0",
    "task_groups": [{
        "task_group_id": "614975a0e8fad7ef68561b36",
        "task_id": "614869a706ff00ab459460e5",
        "is_completed": true,
        "completion_date":"2021-10-07T05:04:50.760Z",
    },
    {
        "task_group_id": "614975a0e8fad7ef68561b37",
        "task_id": "614869a706ff00ab459460e5",
        "is_completed": false,
        "completion_date":"",
    }]
}

The difference between the array of two objects is the task_group_id.
Now I want to update the is_completed and completion_date by taskboard_id, user_id, "task_groups.task_group_id" and "task_groups. task_id". And below is my query:
db.task_status.updateOne(
{
        user_id: new ObjectId(payload.user_id),
        taskboard_id: new ObjectId(payload.taskboard_id),
        "task_groups.task_group_id": new ObjectId(payload.task_group_id),
        "task_groups.task_id": new ObjectId(payload.task_id),
 },
 $set: {
          "task_groups.$.is_completed": payload.is_completed,
          "task_groups.$.completion_date": new Date(),
 },
);

The problem is whenever I try to update the first object is updated fine but whenever it comes to the second one it doesn't update.
Can anyone help me with this?

A: use arrayfilter in update
db.collection.update({
  user_id: "61399af5d6294f56aa1116f0",
  taskboard_id: "6149a3de8f604511e6883bae",
  "task_groups.task_group_id": "614975a0e8fad7ef68561b37",
  "task_groups.task_id": "614869a706ff00ab459460e5",

},
{
  "$set": {
    "task_groups.$[item].is_completed": true,
    "task_groups.$[item].completion_date": new Date(),

  }
},
{
  arrayFilters: [
    {
      "item.task_group_id": {
        $eq: "614975a0e8fad7ef68561b37"
      },
      "item.task_id": {
        $eq: "614869a706ff00ab459460e5"
      }
    }
  ],
  multi: true
})

mongoplayground


text:
Q: Writing streamed files into zip stream in java I want to write multiple CSVs generated from different tables to a zip file without having a read/write operation required to store the generated CSV files or the generated zip files to a memory.
This zip I need to send as an output stream to a response. Is this possible to do in Java? If yes, then how? I am using OpenCSV library to generate CSVs.

A: *

*create a GZIPOutputStream

*loop over your csv data units:

*

*open an InputStream for the csv data unit

*read it, write it to GZIPOutputStream

*close InputStream

*close GZIPOutputStream
If you are working with a servlet, you can wrap ServletOutputStream with GZIPOutputStream. If you like, I can give you more information on that.


text:
Q: How to use $_SESSION to pass on values from multiple pages and $_POST together I have sequence of forms on different pages and want to temporary store the values across all the pages and mail them once all the forms have been filled in.
Apparently $_SESSION is the best way??? Here's what I got:
index.php
<!DOCTYPE html>

    <title>Whats your name?</title>

    <form action="two.php" method="post">
        Fav color:

        <input name="color" type="text" value="blue">

        Fav sport:

        <input name="sport" type="text" value="soccer">

        <input type="submit" value="Next">
    </form>

two.php
<!DOCTYPE html>

    <title>Where do you live?</title>

    <form action="post.php" method="post">
        Shoe size:

        <input name="size" type="text" value="4">

        left or right handed?:

        <input name="hand" type="text" value="left">

        <input type="submit" value="Next">
    </form>

post.php
<?php

$to  = "myemail@host.com";
$sub = "Testing session out";

mail($to, $sub, $message);

header('Location: finish.php');

?>

finish.php
<!DOCTYPE html>

<title>Thanks</title>
<meta http-equiv="refresh" content="2; URL='http://new-website.com' " />

All done, thanks

I want "post.php" to mail all the values to my email in one go e.g.
$message = $_POST['color'];
$message .= $_POST['sport'];
$message .= $_POST['size'];
$message .= $_POST['hand'];

A: just add $_POST to $_SESSION
<?php

$_SESSION['firstname']  = $_POST['firstname'];
$_SESSION['lastname']  = $_POST['lastname'];

?>

but in "post.php" you can't call firstname and lastname with post,
$message = $_SESSION['firstname'];
$message .= $_SESSION['lastname'];
$message .= $_POST['door'];
$message .= $_POST['zip'];

don't forget to use session_start at the beginning script
or you can add again to tag input without $_SESSION inside form
<input name="firstname" type="hidden" value="<?php echo $_POST['firstname']; ?>" />
<input name="lastname" type="hidden" value="<?php echo $_POST['lastname']; ?>" />


text:
Q: Search for clipboard text in emacs is it possible to search for the text that currently is present in the clipboard when hitting C-s, probably with some sort of hook that is triggered when hitting C-s and then inserts the clipboard into the minibuffer?

A: Isearch provides a set of standard keys to change the behaviour of the search process. Typing C-s M-y invokes isearch-yank-kill that pulls string from kill ring (i.e., clipboard) into search string.

A: You could yank the text after starting isearch:
(defun my-isearch-yank-clipboard ()
  (interactive)
  (isearch-yank-string (or (x-get-selection 'PRIMARY)
                           (x-get-selection 'CLIPBOARD)
                           "")))

(define-key isearch-mode-map (kbd "M-s c") 'my-isearch-yank-clipboard)

Start isearch then "M-s c"

A: You can either use defadvice to alter the behaviour of the command isearch-forward, that is bound by default to C-s, or define another function that maybe wraps isearch-forward and bind it to C-s in place of isearch-forward.


text:
Q: How to build a type-safe multiple property groupBy in typescript I already had a groupBy function which receives an array of objects and a key. It is capable to group by a single property.
const groupBy = <T extends Record<string, unknown>, U extends keyof T>(
  objArr: T[],
  key: U,
): { [key: string]: T[] }

Since I get a depth=1 object as a result, I was pretty satisfied with the return type being { [key: string]: T[] }
But now I need to extend this function to be able to group by multiple properties and create a nested object with depth=keys.length.
the groupBy function:
const groupBy = <T extends Record<string, unknown>, U extends keyof T>(
  objArr: T[],
  key: U,
): { [key: string]: T[] } => objArr
    .reduce((memo, x) => {
      if (x[key]) {
        const value = (x[key] as any).toString();
        if (!memo[value]) {
          memo[value] = [];
        }
        memo[value].push(x);
      }
      return memo;
    }, {} as { [key: string]: Array<T> });

The groupByMulti function, that just calls the groupBy function recursively until it reaches the last grouping key.
const groupByMulti = <T extends Record<string, unknown>, U extends keyof T>(
  arr: T[],
  keys: U[],
  propIndex = 0,
) => {
  const grouppedObj = groupBy(arr, keys[propIndex]);
  Object.keys(grouppedObj).forEach((key) => {
    if (propIndex < keys.length - 1) {
      grouppedObj[key] = groupByMulti(grouppedObj[key], keys, propIndex + 1);
    }
  });
  return grouppedObj;
}

I was wondering if it is possible to build an object type with a fixed depth like:
  groupByMulti(someArray, ['key1', 'key2']): {
    [key: string]: {
      [key: string]: T[]
    }
  }

// Depending on the keys length, for example

    groupByMulti(someArray, ['key1', 'key2', 'key3']): {
      [key: string]: {
        [key: string]: {
          [key: string]: T[]
        }
      }
    }

I know that this might be possible only if the keys are a ReadonlyArray, but I could live with that.
If not possible, How can I achieve any amount of type-safety here?
Example converted to JS, to exemplify:

const cars = [{
    car: 'Audi',
    model: 'A6',
    style: 'Sedan',
    year: '2005',
  },
  {

    car: 'Audi',
    model: 'A4',
    style: 'Sedan',
    year: '2018',
  },
  {

    car: 'Toyota',
    model: 'Corola',
    style: 'Sedan',
    year: '2006',
  },
  {

    car: 'Toyota',
    model: 'Camry',
    style: 'Sedan',
    year: '2006',
  },
]

const groupBy = (
    objArr,
    property,
  ) => objArr
  .reduce((memo, x) => {
    if (x[property]) {
      const value = (x[property]).toString();
      if (!memo[value]) {
        memo[value] = [];
      }
      memo[value].push(x);
    }
    return memo;
  }, {});

const groupByMulti = (arr, keys, propIndex = 0) => {
  var grouppedObj = groupBy(arr, keys[propIndex]);
  Object.keys(grouppedObj).forEach((key) => {
    if (propIndex < keys.length - 1) {
      grouppedObj[key] = groupByMulti(grouppedObj[key], keys, propIndex + 1);
    }
  });
  return grouppedObj;
}

console.log(JSON.stringify(groupByMulti(cars, ['car', 'year', 'model']), null, 2));

A: I'm going to assume you care more about type safety from the caller's side, especially since your existing groupBy() function has at least one as any type assertion inside its implementation.
Let's say that the call signature of groupByMulti() should look like:
<T extends Record<K[number], {}>, K extends readonly (keyof T)[]>(
  arr: readonly T[],
  keys: readonly [...K],
  propIndex?: number
) => GroupByMulti<T, K>

for some appropriate definition of GroupByMulti.
Before we get to GroupByMulti, let me explain the rest of that call signature:
We want K to be a tuple type of keys, and we want T to be an object type with properties at K whose values at those properties are assignable to {}, the so-called empty object type which (despite the name) accepts all primitives (like string or number) and only rejects null and undefined. I did this because you call .toString() on those properties, and we don't want possibly-undefined or null properties to be in there.
If you're wondering about readonly XXX[], it's because readonly arrays and readonly tuples are less restrictive than "normal" arrays.  (The names are deceptive; readonly here means "can definitely be read, but may or may not be written", while regular arrays are "can definitely be read, and can definitely be written").
And finally the fact that keys is [...K] instead of just K is using variadic tuple types to give the compiler a hint that we want it to keep track of the exact length of that array, since it makes a big difference.

Okay, now let's define GroupByMulti:
type GroupByMulti<T, K extends readonly any[]> =
    K extends readonly [any, ...infer KR] ?
    Record<string, GroupByMulti<T, KR>> : readonly T[];

That's a recursive conditional type that walks through the K tuple.  If K is empty, we just want readonly T[], that is, grouping by no keys just gives you an array.  Otherwise, we want Record<string, GroupByMulti<T, KR>> where KR is an array that's shorter by one than K.  (It's the Rest of the K array so I call it KR. ♂).
The implementation is full of type assertions I won't spend time explaining:
const groupByMulti = <
    T extends Record<K[number], {}>,
    K extends readonly (keyof T)[]
>(arr: readonly T[], keys: readonly [...K], propIndex = 0) => {
    var grouppedObj: any = groupBy(arr, keys[propIndex]);
    Object.keys(grouppedObj).forEach((key) => {
        if (propIndex < keys.length - 1) {
            grouppedObj[key] = groupByMulti<any, any[]>(
                grouppedObj[key], keys, propIndex + 1);
        } else {
            grouppedObj[key] = grouppedObj[key]
        }
    });
    return grouppedObj as GroupByMulti<T, K>;
}

The only important bit is that we are returning a value of type GroupByMulti<T, K>.  Let's test it out:

const result = groupByMulti(cars, ['car', 'year', 'model']);
/* const result: Record<string, Record<string, Record<string, readonly {
    car: string;
    model: string;
    style: string;
    year: string;
}[]>>> */

Object.keys(result).forEach(k =>
    Object.keys(result[k]).forEach(l =>
        Object.keys(result[k][l]).forEach(m => {
            result[k][l][m].forEach(c => console.log(c.car));
        })
    )
)

Looks good.  The type of result is a triply-nested object with string keys, whose deep object type is the an of T objects.  That allows us to process the result with some type safety (the compiler knows that result[k][l][m] is an array).
Playground link to code


text:
Q: Multiple api call in android retrofit I am building an android application. In which in need to handle multiple api calls in queue to avoid collision using retrofit and also i need to manage this in common Applicationclass. It is possible?

A: You can achieve this using RxJava and Retrofit. RxJava provides us zip operator.
Sample code for this would be in your repository class
Observable.zip(
    getCricketFansObservable(),
    getFootballFansObservable(),
    BiFunction<List<User>, List<User>, List<User>> { cricketFans, footballFans ->
        // here we get both the results at a time.
        return@BiFunction filterUserWhoLovesBoth(cricketFans, footballFans)
    })
    .subscribeOn(Schedulers.io())
    .observeOn(AndroidSchedulers.mainThread())
    .subscribe(getObserver())


text:
Q: Discord py: Why are 2 conditions met when only 1 must be met? I have been finishing adapting my old bot to the Cogs system, however suddenly I have found a strange problem that I cannot understand why it is happening
The code is very simple, I generate a variable between 1-4 and depending on the number that has been generated it must respond with a different image
The problem is that, however, 2 conditions are met when only 1 single condition should be met, And I don't understand why it could be happening-
I have tried to use elif, a unique variable for each command, etc. But the problem persists
import discord
import random
from discord.ext import commands

class sfw(commands.Cog):
    def __init__(self, bot):
        self.bot = bot
        self._last_member = None

    @commands.command(pass_context=True)
    async def kiss(self,ctx, member:discord.Member):
        author = self.bot.get_user(ctx.author.id)
        embed = discord.Embed()
        image = random.randint(1,4)
        if image == 1:
            embed.set_image(url="https://i.imgur.com/UcTK9YF.gif")
        if image == 2:
            embed.set_image(url="https://i.imgur.com/jX2iVsz.gif")
        if image == 3:
            embed.set_image(url="https://i.imgur.com/Jhgzh9B.gif")
        if image == 4:
            embed.set_image(url="https://i.imgur.com/KAlaAJS.gif")
        await ctx.send(f"{author.mention} give kiss to {member.mention}",embed=embed )

However, it always returns 2 answers, instead of just 1.
I have thought about setting the range from 0 to 4, but the problem still persists

A: You should first remove all 'variables' from your problem.
Dissect it, take simple steps, remove async, libraries and add them carefully, one thing a time and test each time, until you detect who is generating the two calls and generating the unexpected call.
Probably you are invoking the member function twice.

A: The problem was generated in another cog file, which took a double input due to a bad indentation of the await command ```self.bot.process_commands (message)´´´
For some reason this caused any message to be heard 2 times by the bot. I hope that if someone else has my problem in the future this answer will help


text:
Q: fill data automatically in excel file i have an excel file that have a list of EmployeeID and empty EmployeeFirst and Last name
and i have another file that have the employee id, first name and last name
for example :
First File
EmployeeID
5
2
5
11
12
2
3
5

Second File
EmplyeeID   EmplyeeFirstName  EmployeeLastName
1           Will              Smith
2           Michael           Jackson
3           Bob               Marley
4           Barack            Obama
5           Donald            Trump

How can i fill the first and last name in the first file in the correct places according to the EmployeeID automatically ?
Appreciate any help!

A: Assume files are referred to as File1.XLSX and File2.XLSX respectively.
Data is posessed on a worksheet named Sheet1 in both files starting from A1 cell.

*

*Open both files.

*Activate File1

*Select B1.

*Enter the formula:
=IF(ISNA(VLOOKUP($A1,[file2.xlsx]Sheet1!$A:$C,COLUMN(),FALSE)),"",VLOOKUP($A1,[file2.xlsx]Sheet1!$A:$C,COLUMN(),FALSE))

*Select B1.

*Drag it right till C2.

*Drad selection down till B9:C9.

That's all.
PS. If you need the final data to be static, then use Copy - Paste special - Values.

@Akina please check the file mediafire.com/file/j4iuw79rt7rgvoi/backup.xlsx/file – M J 10 mins ago

Use the formula:
=IF(ISNA(VLOOKUP($B2,Feuil2!$A:$C,COLUMN()-1,FALSE)), "", VLOOKUP($B2,Feuil2!$A:$C,COLUMN()-1,FALSE))

Enter it into worksheet Feuil1, cell C2. Enter it into D2. The rest cells will be filled automatically.

i'm getting error about '=1+1

If there are some problems then try to enter formula via VBA:

*

*open VBA editor (Alt-F11)

*open Immediate window (Ctrl-G)

*enter first two commands directly like on my screenshot (check for quotes, do not forget to press Enter after each separate command)

*close VBA editor

Then check where worksheet cell function differs, and remember this difference for future.


text:
Q: Grouping JavaScript if statements of the same 'smaller than' So I have this long if statement.
if(dupeCheck[0].length > 1 || dupeCheck[1].length > 3 || dupeCheck[2].length > 1 || dupeCheck[3].length > 1){
    alert('Copy!');
}

It is possible to group together the dupeCheck[0].length > 1 parts? Like:
if((dupeCheck[0].length||dupeCheck[2].length||dupeCheck[3].length) > 1 || dupeCheck[1].length > 3){
    alert('Copy!');
}

Or:
if(dupeCheck[0].length||dupeCheck[2].length||dupeCheck[3].length > 1 || dupeCheck[1].length > 3){
    alert('Copy!');
}

I tried both, neither of them worked.

A: Depending on how many tests you need to run you could also try something like this.
function isGreater(minimum){
  for(var i=1;i<arguments.length;i++){
    if(arguments[i] > minimum){
      return true;
    }
  }
  return false;
}

if(isGreater(1, dupeCheck[0].length, dupeCheck[2].length, dupeCheck[3].length) || isGreater(3, dupeCheck[1].length)){
  alert('Copy!');
}

This will let you test any number of values against a number e.g.
if(isGreater(5, 0,0,0,0,2,1,2,3,4) || isGreater(7, 1,3,1,2,1,9,2,1)){
  alert('Copy!');
}

Since JavaScript will let you pass as many parameters as you want to a function the 2nd to Nth parameters are tested against the 1st parameter "minimum" and as soon as one passes the test the function returns true.  You could adjust the logic to test for other conditions or even ensure that all parameters pass the condition not just one.

A: There is no built-in language construct to do that.
But what you could do is something like this:
if(Math.min(dupeCheck[0].length, dupeCheck[2].length, dupeCheck[3].length) > 1 || dupeCheck[1].length > 3) {
    alert('Copy!');
}


text:
Q: Is there a way to get the JMSMessageID using Spring Integration Message Object We have a need to Pass the JMSMessageID  (generated by IBM Mq Queuemanger).
My problem is the how do i populate the value in the MessageHeaders
org.springframework.messaging.MessageHeaders and pass it to my Activator.

A: Yes.
The DefaultJmsHeaderMapper will add the inbound JmsMessageId as header jms_messageId to the spring integration message's MessageHeaders.

A: Yes the jms_messageId is getting populated. I was using a JUNIT test which was not going through the Quemanager so those header values are not being set by my program, So i had the change the Junit to copy the Headers it worked.
Thanks a bunch.
Something like this in my junits
    Map<String, String> headersToCopy = new HashMap<String, String>();
    headersToCopy.put("JMSXUserID", "suren");
    headersToCopy.put("jms_messageId", "ID:1234567894444444444444");
    headersToCopy.put("JMS_IBM_MsgType", "8");
    headersToCopy.put("JMSXDeliveryCount", "1");


text:
Q: Dynamics crm onchange event Validating if a specified date falls within a date range I am trying to set up an onchange event within MS Dynamics CRM that brings up an alert if a date entered in a field falls outside of a specified range.
{
if (crmForm.all.fielddate.DataValue < 01/01/2010 || crmForm.all.fielddate.DataValue >= 01/01/2011)
{
alert("Specified date falls outside of the date range") ;
}
}

This doesnt seem to work, am I using the correct date format? or am I missing something out?
Thanks in advance for your help
Brett

A: You'll need to parse each value as a date before comparing:
if (Date.parse(fromDate) > Date.parse(toDate)) {
    alert("Specified date falls outside of the date range");
}


text:
Q: Get time within radius Lets imagine we have time line with two points:

*

*A - start time of day

*B - end time of day
extension Date: {
var startOfDay: Date {
    return Calendar.current.startOfDay(for: self)
}

var endOfDay: Date? {
    var components = DateComponents()
    components.day = 1
    components.second = -1
    return Calendar.current.date(byAdding: components, to: startOfDay)
}
}

On the time line there is going one event -> it goes from specifed time, has event time stamp as an interval from 1970 ( event.eventTimestamp ) and there are two options :

*

*It doesn't have end time -> it goes out of bounds after B- point ( duration = 0, to check for it we need to use Int(Date().timeIntervalSince1970) - event.eventTimeStamp

*It does have specified end time -> We do have duration.
In both cases It might start few days before A and finish few days after B.

How could I check whenever event is in current day -> specifed by user. After we detect this let's save in variable 24h.
let duration = 24 * 60 * 60

struct Event {
   var eventTimestamp: Int
   var duration: Int = 0
}


text:
Q: Format of an ODATA filter specifying an enum I have built an EdmModel which contains an enum property, Level.
var level = new EdmEnumType("Log.Api.Models",
                            "Level",
                            EdmPrimitiveTypeKind.Int32,
                            false);
level.AddMember(new EdmEnumMember(level, "Debug", new EdmIntegerConstant(0)));
level.AddMember(new EdmEnumMember(level, "Error", new EdmIntegerConstant(1)));
level.AddMember(new EdmEnumMember(level, "Info", new EdmIntegerConstant(2)));
Model.AddElement(level);

// add a property, named 'Level', of type 'Level'
logEntry.AddProperty(new EdmStructuralProperty(logEntry,
                                               "Level",
                                               new EdmEnumTypeReference(level, false)));

OData requests are then parsed in C# using
ODataUriParser.ParseFilter(filter,
                           Model,
                           (IEdmSchemaType) schemaElmnt);

But I'm so far unsuccessful in sending a request which specifies an enum value. I've tried with the fully-qualified enum...
"Level eq Log.Api.Models.Level.Error"

And without
"Level eq Error"

And I've tried enclosing it in single quotes
"Level eq 'Error'"

The exception message is

A binary operator with incompatible types was detected. Found operand
  types 'Log.Api.Models.Level' and 'Edm.String' for operator kind
  'Equal'.'

What is the correct format? Or does the problem lie in my EdmModel?

A: The correct format is odd and is unintuitive, but it looks like this:
Fully.Qualified.Enum.Type'EnumValue'

Used in your example:
Level eq Log.Api.Models.Level'Error'

The official V4 documentation describes the format of literals in the $filter system query option:
http://docs.oasis-open.org/odata/odata/v4.0/errata03/os/complete/part2-url-conventions/odata-v4.0-errata03-os-part2-url-conventions-complete.html#_Toc371341809


text:
Q: Link selection on Opera Mini 4.2 acting strangely I'm developing a mobile site in HTML for use on 2 Blackberry models, one quite old (8700v) and one newer (8520) as specified by the client.
The native browser on the 8520 is rendering my HTML/CSS pages perfectly. The native browser on the old 8700 is far from perfect however as the CSS support is minimal.
As a solution I decided to try installing Opera Mini 4.2 on the 8700. The rendering is great, speed is even improved but there's some rather strange behaviour happening with the hyperlinks on the page.
When I scroll down through my pages links are automatically highlighted and made ready for selection. This is fine until I have a number of links close together, for example in my nav menu. The nav menu is a set of links arranged within a . When I scroll to the menu all the links within the menu highlight at once. Even within the body if 2 links are on 2 separate lines (one  stacked on top of another) the same issue appears.
I'm trawling Opera documentation but haven't found anything useful yet. Anyone got any ideas on why this happens and if it can be resolved?

A: Without seeing the actual HTML/CSS code, it's hard to pinpoint the exact cause of this, but it's most likely one of the following:

*

*The links in question point to the same URL. The browser will highlight them as a group to visualize this.

*Some script is adding a click event listener or similar to the group of links.

*An <a>-tag has been left open.


text:
Q: "Arming ConditionNeedsUpdate" error when Building Arch Linux Package I'm trying to build an Arch Linux package for some icon theme, so I used this PKGBUILD file :
pkgname=masalla
pkgver=1.1
pkgrel=1
pkgdesc="A flat design icon theme by Hayder Majid"
arch=('any')
url="https://github.com/masalla-art/masalla-icon-theme"
license=('GPL3')
makedepends=('git')
conflicts=('masalla-icon-theme-git' 'masalla-icon-theme' 'masalla')
source=("${url}/releases/download/${pkgver}/${pkgname}_${pkgver}.tar.xz")
md5sums=('8c11f0fd04abc6c7f9086f7275d939be')

package() {
  cd $srcdir
  install -d -m 755 ${pkgdir}/usr/share/icons
  cp -r ${srcdir}/${pkgname}_${pkgver}/masalla ${pkgdir}/usr/share/icons
  cp -r ${srcdir}/${pkgname}_${pkgver}/masalla-dark ${pkgdir}/usr/share/icons

}

and the compiling process is work fine, but when i installing it, i got this message :
(1/2) Updating icon theme caches...
gtk-update-icon-cache: The generated cache was invalid.
error: command failed to execute correctly
(2/2) Arming ConditionNeedsUpdate...

so,what i missed in my PKGBUILD file, and what should i change to fix this error

A: That is not an error message, it is one of pacman's hooks.
It was introduced in an update to systemd, and is essentially explained by Lennart here:

A new condition ConditionNeedsUpdate= has been added. With this
  mechanism it is possible to conditionalize execution of services
  depending on whether /usr is newer than /etc or /var. The idea is that
  various services that need to be added into the boot process on
  upgrades make use of this to not delay boot-ups on normal boots, but
  run as necessary should /usr have been update since the last boot.
  This is implemented based on the mtime timestamp of the /usr: if the
  OS has been updated the packaging software should touch the directory,
  thus informing all instances that an upgrade of /etc and /var might be
  necessary.

In essence, the hook ensures that those services that need to be run on boot if /usr has been updated will be run. You can read more in man 5 systemd.unit


text:
Q: How to stop this constant stream of logs in webview screen? D/BufferQueueProducer(30418): [SurfaceTexture-0-30418-0](this:0x94f72000,id:0,api:1,p:392,c:30418) cancelBuffer: slot 2

D/BufferQueueProducer(30418): SurfaceTexture-0-30418-0 cancelBuffer: slot 0
D/BufferQueueProducer(30418): SurfaceTexture-0-30418-0 cancelBuffer: slot 2
D/BufferQueueProducer(30418): SurfaceTexture-0-30418-0 cancelBuffer: slot 0
D/BufferQueueProducer(30418): SurfaceTexture-0-30418-0 cancelBuffer: slot 2
D/BufferQueueProducer(30418): SurfaceTexture-0-30418-0 cancelBuffer: slot 0
D/BufferQueueProducer(30418): SurfaceTexture-0-30418-0 cancelBuffer: slot 2
D/BufferQueueProducer(30418): SurfaceTexture-0-30418-0 cancelBuffer: slot 0
D/BufferQueueProducer(30418): SurfaceTexture-0-30418-0 cancelBuffer: slot 2
D/BufferQueueProducer(30418): SurfaceTexture-0-30418-0 cancelBuffer: slot 0
D/BufferQueueProducer(30418): SurfaceTexture-0-30418-0 cancelBuffer: slot 2
D/BufferQueueProducer(30418): SurfaceTexture-0-30418-0 cancelBuffer: slot 0
D/BufferQueueProducer(30418): SurfaceTexture-0-30418-0 cancelBuffer: slot 2
I'm getting the constant stream of the above-mentioned log as soon as webview activity is loaded. This stream is annoying and I'm unable to see my own logs. How to stop them or at least filter them? I'm using visual studio code.

A: Quick hack is to type !BufferQueueProducer in the search field of the debug console, this way any log message contains the word BufferQueueProducer* will be exclude.

A: if you are using android studio or other jet brains products there is an option to use right click on a log line and choose "Fold Lines Like This", then press "Ok".
Then the similar logs will be hidden by green area. To show again click on a green area.

A: In my case I run an ads on my app and it seems like I can not turn off the ads log. I think it's because the way the ads work by refreshing it's content, therefore I comment my code that run the ads and the constant stream disappeared. Maybe it can works on your case as well


text:
Q: UITableView is laggy and jumps when scrolling I'm using an UITableView with dynamic cells. Every cell has some buttons, an image and a label. The image's width is equal to tableview width and the height is variable.
I am updating the height of the image in cellForRowAtIndexPath by a function... to respect the aspect ratio. The label can have 1 or more lines.
I'm using heightForRowAtIndexPath to set the height of the cell. I'm calculating it there and return the value.
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {

    let queficient = CGFloat(dataController.Data[indexPath.row].width) / self.view.frame.size.width

    let imgHeight = CGFloat(dataController.Data[indexPath.row].height) / queficient

    return 134 + imgHeight + heightForView(dataController.Data[indexPath.row].description)
}

I don't know why the table is a little laggy and jumping when I scroll.

A: If you are sure that the lag is caused by heightforRowAtIndexPath, why dont you calculate the height for each cell data/indexpath only once, when the image changes?
you should just return dataController.Data[indexPath.row].calculatedCellHeight or something


text:
Q: Will this sweep function work? I am currently working on implementing a frequency sweep function on a embedded device, and aren't sure that the math I am trying to implement actually does what I expect it to do.
The code I am trying to implement is  supposed to ramp up the signal from 0 hz to 48000 hz.
The Math:
Mathwise would a ramp be described as f(t) = a*t In which a is the slope and t is the time.
integrating f(t) gives F(t) which would be a function providing the time at which a cycle has been completed. such that if F = 1, then would t have the information of the period time of the cycle.
By reordering things I can get t(F) being a function that tells me at what time each cycle should be completed, which can be used to compute the next period time , and hence increase the frequency as it based on the ramp signal.
Question:
Is this correct, or I am misinterpreting something?


text:
Q: Is the wavelength of matter proportional to momentum or uncertainty thereof? I am confused about de Broglie waves and their relationship with the uncertainty principle.  Both have similar formula and seem to be the same thing with a slight conceptual difference.  De Broglie waves predict that matter has a wavelength proportionate momentum whereas uncertainty claims the uncertainty of the position of matter is proportionate to the uncertainty of momentum.  Assuming the wave represents uncertainty the two formula are basically just off by 1/4*pi .
So are these the same concept or are they different?

A: de Broglie waves were the hypothesis, pre-quantum theory, that particles can be represented as a matter wave. In treatments of mathematical foundations of quantum mechanics the matter wave is replaced by a probability amplitude, defined by the Born rule. The probability amplitude is not, in general, assumed to be material, but is a way to represent the probability for where the particle will be found.
Uncertainty is a measure of the spread of the probability distribution. This is a different concept from the probability amplitude, but it can be calculated from the probability amplitude.


text:
Q: How to create 2 column form using bootstrap 3 I have created form using bootstrap 3. how can I make a 2 column form. that is the label on the left and the input, drop down  box etc on the right
          <fieldset>

                    Map info

                    <input type="text" class="form-control" id="exampleInput" placeholder="">

                    Class

                    <input type="text" class="form-control" id="exampleInputTeam" placeholder="Team Project information">

                      info

                    <input type="text" class="form-control" id="exampleInput" placeholder="Build Defintion">

                  </fieldset>

                  <fieldset>

                    Name

                    <input type="text" class="form-control" id="exampleInputTeam" placeholder="Build Def Name">

                    Location

                    <input type="text" class="form-control" id="exampleInputTeam" placeholder="Config Location">

</fieldset>

A: by adding
 surrounding the two fieldsets

     <fieldset>
    ...
     </fielset>

       <fieldset>
    ...
      </fielset>

http://www.bootply.com/JziKUuxQYM


text:
Q: How can I use '\' in SQL LIKE ... ESCAPE '\' I'm trying to delete all cache items where the description hasn't got a snap chat username in. I keep running into syntax issues when trying to escape the dash character?
Query:
$cacheItems = CacheItem::whereRaw("description NOT LIKE '%'")
      ->whereRaw("description NOT LIKE '%%'")
      ->whereRaw("description NOT LIKE '% %'")
      ->whereRaw("description NOT LIKE '% :%'")
      ->whereRaw("description NOT LIKE '%%'")
      ->whereRaw("description NOT LIKE '%sc\'%'")
      ->whereRaw("description NOT LIKE '%sc\_%' ESCAPE '\'")
      ->whereRaw("description NOT LIKE '%sc \- %' ESCAPE '\'")
      ->whereRaw("description NOT LIKE '%sc %'")
      ->whereRaw("description NOT LIKE '%sc:%'")
      ->whereRaw("description NOT LIKE '%scm %'")
      ->whereRaw("description NOT LIKE '%scm;%'")
      ->whereRaw("description NOT LIKE '%sc- %'")
      ->whereRaw("description NOT LIKE '%sc.%'")
      ->whereRaw("description NOT LIKE '%sc-%'")
      ->whereRaw("description NOT LIKE '%SC -  %'")
      ->whereRaw("description NOT LIKE '%Sc ~%'")
      ->whereRaw("description NOT LIKE '%sc ~%'")
      ->whereRaw("description NOT LIKE '%sc;%'")
      ->whereRaw("description NOT LIKE '%sc~%'")
      ->whereRaw("description NOT LIKE '%sc/%'")
      ->whereRaw("description NOT LIKE '%snapchat:%'")
      ->whereRaw("description NOT LIKE '%snapchat - %'")
      ->whereRaw("description NOT LIKE '%snapchat-%'")
      ->whereRaw("description NOT LIKE '%snap~%'")
      ->whereRaw("description NOT LIKE '%snap =%'")
      ->whereRaw("description NOT LIKE '%snap•%'")
      ->whereRaw("description NOT LIKE '%snap%'")
      ->whereRaw("description NOT LIKE '%snap~%'")
      ->whereRaw("description NOT LIKE '%snapchat%'")
      ->whereRaw("description NOT LIKE '%snapchat ~ %'")
      ->whereRaw("description NOT LIKE '%snap:%'")
      ->whereRaw("description NOT LIKE '%add my sc%'")
      ->whereRaw("description NOT LIKE '%add me on sc%'")
      ->whereRaw("description NOT LIKE '%add me sc%'")
      ->whereRaw("description NOT LIKE 'snap %'")
->get();

Error:
SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '%sc \- %' ESCAPE '\' and description NOT LIKE '%sc %' and description NOT LIKE '' at line 1 (SQL: select * from `cache_items` where description NOT LIKE '%' and description NOT LIKE '%%' and description NOT LIKE '% %' and description NOT LIKE '% :%' and description NOT LIKE '%%' and description NOT LIKE '%sc\'%' and description NOT LIKE '%sc\_%' ESCAPE '\' and description NOT LIKE '%sc \- %' ESCAPE '\' and description NOT LIKE '%sc %' and description NOT LIKE '%sc:%' and description NOT LIKE '%scm %' and description NOT LIKE '%scm;%' and description NOT LIKE '%sc- %' and description NOT LIKE '%sc.%' and description NOT LIKE '%sc-%' and description NOT LIKE '%SC -  %' and description NOT LIKE '%Sc ~%' and description NOT LIKE '%sc ~%' and description NOT LIKE '%sc;%' and description NOT LIKE '%sc~%' and description NOT LIKE '%sc/%' and description NOT LIKE '%snapchat:%' and description NOT LIKE '%snapchat - %' and description NOT LIKE '%snapchat-%' and description NOT LIKE '%snap~%' and description NOT LIKE '%snap =%' and description NOT LIKE '%snap•%' and description NOT LIKE '%snap%' and description NOT LIKE '%snap~%' and description NOT LIKE '%snapchat%' and description NOT LIKE '%snapchat ~ %' and description NOT LIKE '%snap:%' and description NOT LIKE '%add my sc%' and description NOT LIKE '%add me on sc%' and description NOT LIKE '%add me sc%' and description NOT LIKE 'snap %')

A: You use \ as your ESCAPE character in this:
  description NOT LIKE '%sc\_%' ESCAPE '\'

That's a problematic choice because \ itself gets used all over the place as an escape character at MySQL's string-literal level, and also in various client software packages.
If this were my code I wouldn't trust \ in this context at all (because I'm lazy and I don't want to figure out where and how it gets used as an escape character).
Either, best, choose some other escape character like this (| in this example)
  description NOT LIKE '%sc|_%' ESCAPE '|'

or double the \ in the ESCAPE part of your sql, like this
  description NOT LIKE '%sc\_%' ESCAPE '\\'

(And, keep in mind that column LIKE '%whatever' is a notorious query-performance antipattern, because it can't use any index on column.)


text:
Q: Passing multiple parameter in OpenWithParm in Powerbuilder Here are the codes for passing single parameter in another pb window object.
in dw_header clicked event
long ll_customer
datetime dt_from, dt_to
ll_customer = getitemnumber(1,"customer_id")
dt_from = datetime(date(f_today()),time('00:00:00'))
dt_to = datetime(date(f_today()),time('23:59:59.99'))

openwithparm(w_customer_balance,ll_customer)

in w_customer_balance open event
long ll_id
datetime dt_from, dt_to
ll_id = message.doubleparm
dw_1.settransobject(sqlca)
dw_1.retrieve(ll_id)

This perfectly working fine in passing single parameter.
But i want to pass another parameters  w/c are dt_from and dt_to to a to customer balance window.
Anybody?

A: If you need to pass multiple parameters, you can use the following this method:
The definition of structural variables: lstr_declaredstr, which includes you want to pass the parameters:
Variable type variable name:
ID Unsignedlong; Name Character; Email Character; Homepage Character
... ...
Calling script, use the following code:
lstr_declaredstr lstr_parmtotrans
lstr_parmtotrans.id = 1
lstr_paramtotrans.name = "panya"
lstr_paramtotrans.email = "panya@163.net"
lstr_paramtotrans.homepage = "http://panya.163.net"

...
openwithparm (w_wantparm, lstr_paramtotrans)

Then open the window in the w_wantparm the open case, to obtain structural information:
lstr_declaredstr lstr_getparm
integer li_getid
string ls_getname
string ls_getemail
string ls_gethomepage
lstr_getparm = message.powerobjectparm
li_getid = lstr_getparm.id
ls_getname = lstr_getparm.name
ls_geemail = lstr_getparm.email
ls_gethomepage = lstr_getparm.homepage

For more examples, in this web: web

A: You can also define a non-visual object with instance variables which you set then pass with an Openwithparm method call.  The called window would have to have the nvo created (normally as an instance variable) and then 'received' in the open event via the powerobjectparm parameter type.

A: As suggested by Matt Balent, instead of defining a structure specially for passing some parameters to a window, you can create a dedicated object passed to OpenWithParm() and that can be retrieved in the open() with message.powerobjectparm (because you can pass any powerobject to this method).
By extension, you can create a generic object type that can receive an arbitrary number of named parameters of any type that you can get by their name in the open() event in a way similar as the structure. A kind of poor man's dictionary.
Here is an exemple based on some existing code:

*

*the nv_va_arg object (like C's variable arguments type) - the source is copied from the object "edit source" context menu, to recreate the object, add a new "custom class" object named nv_va_args, save it then right-click "edit source" and paste the following code:

      forward
      global type nv_va_args from nonvisualobject
      end type
      end forward

      global type nv_va_args from nonvisualobject autoinstantiate
      end type

      type variables

      private:
      string _is_names[]
      any _ia_items[]

      end variables
      forward prototypes
      public subroutine add_item (string as_name, any aa_val)
      private function integer search (string as_name)
      public subroutine set_item (string as_name, any aa_val)
      public function any get_item (string as_name)
      private subroutine set_item (integer ai_index, string as_name, any aa_val)
      public function integer size ()
      public function string get_name (integer ai_index)
      public function any get_item (integer ai_index)
      end prototypes

      public subroutine add_item (string as_name, any aa_val);
      /* add a new item if not already present */

      int idx

      idx = search(as_name)
      if idx = -1 then
            idx = upperbound(_is_names) + 1
            set_item(idx, as_name, aa_val)
      end if

      end subroutine

      private function integer search (string as_name);
      /* search for an item */

      int i, n
      n = upperbound(_is_names)

      for i = 1 to n
            if _is_names[i] = as_name then return i
      next

      return -1

      end function

      public subroutine set_item (string as_name, any aa_val);
      /* public setter */
      int idx

      idx = search(as_name)
      if idx =-1 then
            idx = upperbound(_is_names) + 1
      end if
      set_item(idx, as_name, aa_val)

      end subroutine

      public function any get_item (string as_name);
      /* get the named item */

      int idx
      any la_val

      idx = search(as_name)
      if idx > 0 then
            la_val = _ia_items[idx]
      end if

      return la_val

      end function

      private subroutine set_item (integer ai_index, string as_name, any aa_val);
      /* internal setter */

      _is_names[ai_index] = as_name
      _ia_items[ai_index] = aa_val

      end subroutine

      public function integer size ();
      /* return the number of elements */
      return upperbound(_is_names)

      end function

      public function string get_name (integer ai_index);
      /* return the name of the nth item */

      string ls_ret = ""
      if ai_index > 0 and ai_index <= upperbound(_is_names) then
            ls_ret = _is_names[ai_index]
      end if

      return ls_ret

      end function

      public function any get_item (integer ai_index);
      /* get the named item */

      any la_val

      if ai_index > 0 and ai_index <= upperbound(_is_names) then
            la_val = _ia_items[ai_index]
      end if

      return la_val

      end function

      on nv_va_args.create
      call super::create
      TriggerEvent( this, "constructor" )
      end on

      on nv_va_args.destroy
      TriggerEvent( this, "destructor" )
      call super::destroy
      end on

*

*an example of parameter filling, you can use any name and any type that will be stored in the internal any array of nv_va_args object:

        nv_va_args lva_args

        //set some values
        lva_args.add_item("arg_1", 42)
        lva_args.add_item("arg_2", "foo bar")

        //change a value
        lva_args.set_item("arg_2", "foo baz")

        openwithparm(w_test, lva_args)

*

*2 examples of arguments retrieving, put in the open() event of the window. Note that the object retrieval from the message object must be done at the beginning of the event for not loosing its value (the message object is a global object that can be overwritten quite rapidly)

        powerobject lpo_arg //do not create it, as it is autoinstanciated
        lpo_arg = message.PowerObjectParm //make immediate copy of the message
        nv_va_args lva_args

        if isvalid(lpo_arg) and not isnull(lpo_arg) then
            lva_args = lpo_arg
        end if

        //example: enumerate all the parameters
        string ls_msg = "", ls_class
        int i
        any la_val
        for i = 1 to lva_args.size()
            ls_msg = ls_msg + lva_args.get_name(i) + ': '
            la_val = lva_args.get_item(i)
            ls_class = classname(la_val)
            if ls_class = "string" or ls_class = "long" then
                ls_msg = ls_msg + string(la_val, "[general]")
            else
                ls_msg = ls_msg + '[' + ls_class + ']'
            end if
            ls_msg = ls_msg + "~r~n"
        next
        messagebox("list of parameters", ls_msg)

        //example: just get a named parameter
        string ls_name = "arg_2"
        la_val = lva_args.get_item(ls_name)
        ls_msg = ls_name + " is " + string(la_val, "[general]")
        messagebox("named parameter", ls_msg)


text:
Q: Is finite and strictly positive variances all that is needed for the CLT Lindeberg condition? I cannot understand what I am doing wrong here, so please somebody, point it out from me.
The issue? I keep finding that the Lindeberg sufficient condition for the Central Limit Theorem for independent non-identically distributed random variables, holds  already by the premises (i.e. holds always given the premises). The condition is
$$\lim_{n \to \infty} \frac{1}{s_n^2}\sum_{k = 1}^{n} \mathbb{E}\big[(X_k - \mu_k)^2 \cdot \mathbf{1}_{\{ | X_k - \mu_k | > \varepsilon s_n \}}  \big] = 0,\;\;\;
\forall \varepsilon > 0$$
where $s_n^2 \equiv \sum_{k=1}^n \sigma_k^2$,
and I keep finding that as long  as
$$0<c\leq\sigma^2_k< \infty,\;\;\; \forall\,k$$
which is part of the premises, the condition will hold. We have
$$\mathbb{E}\big[(X_k - \mu_k)^2 \cdot \mathbf{1}_{\{ | X_k - \mu_k | > \varepsilon s_n \}}  \big]  \\= \mathbb{E}\left[(X_k - \mu_k)^2\mid \{| X_k - \mu_k | > \varepsilon s_n\}\right] \cdot \text{Prob}\left(| X_k - \mu_k | > \varepsilon s_n\right)$$
$$ \leq \sigma^2_k \cdot \text{Prob}\left(\frac{|X_k - \mu_k|}{\sigma_k}> \varepsilon s_n/\sigma_k\right)  $$
because conditional variance is not greater than unconditional variance
$$\leq\sigma^2_k \cdot \frac {\sigma^2_k}{\varepsilon^2 s_n^2}= \frac {(\sigma^2_k)^2}{\varepsilon^2 s_n^2}$$
by the basic Chebychev inequality. Then
$$\lim_{n \to \infty} \frac{1}{s_n^2}\sum_{k = 1}^{n} \mathbb{E}\big[(X_k - \mu_k)^2 \cdot \mathbf{1}_{\{ | X_k - \mu_k | > \varepsilon s_n \}} \leq \lim_{n \to \infty} \frac{1}{s_n^2}\sum_{k = 1}^{n} \frac {(\sigma^2_k)^2}{\varepsilon^2 s_n^2}$$
$$=\frac 1{\varepsilon^2 } \cdot \lim_{n \to \infty} \frac{\sum_{k = 1}^{n}(\sigma^2_k)^2}{\left(\sum_{k=1}^n \sigma_k^2\right)^2} =  \frac 1{\varepsilon^2 } \cdot \lim_{n \to \infty} \frac{\sum_{k = 1}^{n}(\sigma^2_k)^2}{\sum_{k = 1}^{n}(\sigma^2_k)^2 + \sum_{k \neq j}\sigma^2_k\sigma^2_j}$$
Having all variances strictly positive and finite makes this limit zero which sandwiches the Lindeberg condition to zero.  Where is the mistake here?
(Hmmm... except if what is needed for the last limit to go to zero is that all variances are not just finite, but also bounded, which is not part of the premises)

A: User @CliffAB spotted the unjustified step here, which is to assume that the conditional variance is never greater than the unconditional one.
A quick simulation: $100,000$ draws from a standard normal, $Z$.
Sample standard deviation of the full sample : $0.997$.
Now, cut out the body of the distribution and keep the tails (which is in the spirit of the conditioning event in the Lindeberg condition) : specifically, keep only the draws where $|Z|>1.65$. Survived: $9,805$ draws. Standard deviation of them : $2.097$.
Intuition : when we keep both tails, it is as though we tend to transform a continuous distribution into a discrete one, creating two lumps of probability mass, and this tends to increase the variance. Consider the Bernoulli $(0.5)$ distribution and the Uniform $(0,1)$. The first is the extreme discrete version of the second, and it has three times greater variance ($1/4$ as opposed to $1/12$). And the evolution is gradual : consider a discrete uniform taking values $\{0,0.25,0.75,1\}$. Its variance is $9/64$, which is inbetween the previous two.


text:
Q: The parameters requested by GET are pasted together The client requests http://www.example.com and passes the parameters via GET, and the final request is http://www.example.com/api/page?timestamp%3D1485404388%26sign%3De91a73150d87ebcb3ae00a26d85ce93b.
Normal situation
```
$_GET = [
     'timestamp' => 1485404388,
     'sign' => 'e91a73150d87ebcb3ae00a26d85ce93b'
]
```

Abnormal situation
```
$_GET = [
     'timestamp=1485404388&sign=e91a73150d87ebcb3ae00a26d85ce93b' => ''
]
```

$_SERVER
```
'REQUEST_URI' => '/api/page?timestamp%3D1485404388%26sign%3De91a73150d87ebcb3ae00a26d85ce93b'
```

This situation will not happen 100%, by looking at the log I found this problem, I suspect that the client is the problem, but can not determine where the problem is in the end.
web.php
```
'urlManager' => [
            'enablePrettyUrl' => true,
            'showScriptName' => false,
        ],
```

nginx.conf
```
server
{
        listen 80;
        server_name  www.example.com;
        root   /www/example/web;
        index   index.php index.html index.htm;
        access_log /www/log/nginx/access_example.log;
        #error_log /www/log/nginx/error_example.log;

        location / {
            try_files $uri $uri/ /index.php$is_args$args;
        }

        location ~ \.php$ {
            root   /www/example/web;
            fastcgi_pass   127.0.0.1:9000;
            fastcgi_index  index.php;
            log_not_found  off;
            fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name;
            include        fastcgi_params;
        }
        error_page   500 502 503 504 /50x.html;
        location = /50x.html {
            root   /usr/local/nginx/html;
        }
}
```


text:
Q: ELBO interpretation in Variational Autoencoder (VAE) for anomaly detection How to interpret different ELBO values when checking anomaly detection possibilities of VAE model on different "testing" datasets?
The higher the ELBO value of the model when testing it on different datasets, the better our model in detection of anomaly which follows "testing dataset distribution"?

A:
the better our model in detection of anomaly

VAE is a generative model, not a discriminative one, so I'm not sure what you mean here.
More generally, higher mean ELBO over the test dataset doesn't mean that you have a better model of the test dataset. If you train a VAE to model the standard gaussian, and then test it on a dataset with just 0's, the model is going to assign higher mean ELBO rather than if you'd tested with a standard gaussian dataset.


text:
Q: Web-sql event not completed when combined with either form-submit or window.location Heyo,
Basic workflow:

*

*Form submit button is clicked

*Submit event is captured

*Capture function runs a callback script

*

*If the script returns false e.preventDefault() is called

*ELSE Form submits

The above is all working fine. I have just provided it for context. The issue I am having is that as part of the callback script, a series of SQL UPDATE events are fired off. The script for this is below:
function writeNewProductDetails() {
    for(var i = 0; i < $('#productForm').children('input').length; i++) {
        var input = $('#productForm').children('input')[i];
        var inputType = $(input).attr('id').split('---');
        var inputVal = $(input).val();

        switch(inputType[1]) {
            case 'quantity' :
                localDB.webdb.runSQL('UPDATE orderLines SET "collected" = "'+inputVal+'" WHERE orderLineID = '+inputType[0])
                break;
            case 'code' :
                localDB.webdb.runSQL('UPDATE orderLines SET "code" = "'+inputVal+'" WHERE orderLineID = '+inputType[0])
                break;
        }
    }
    window.location(history(-1));
    return false;
}

Now a lot of this code is irrelevant to the question, the key part is the switch statement and the following two lines. The window.location and return false commands are used to avoid actually submitting the form (as the processing is already done).
Here is the crux of the issue. If I comment out the window.location(history(-1)) command and just have the function return false (ie stop the page submitting), the web-sql commands kick off and run as expected. If I leave it in, then the window seems to shift away before the sql commands have finished processing. This means that the database doesn't update.
Is this sort of issue a known problem, and is there a 'best-practice' to deal with it? I can't imagine that using the web-sql backend on form submit is a completely foreign concept?
---EDIT---
In the end I went with the following solution, its not the prettiest one in the world but it works.

*

*Firstly I defined a global variable var queryCountWNPD = 0; the wnpd stands for writeNewProductDetails.

*I then incremented the variable whenever a query was sent ie queryCountWNPD++; \\ localDB.webdb.runSQL('UPDATE orderLines...

*After that I added a callback function to the sql command detailsWritten

*This function (below) decrements the queryCountWNPD then checks if it is equal to 0. If it is then it runs the original window.history.go(-1) command.
function detailsWritten() {
    queryCountWNPD--;

    if(queryCountWNPD == 0) {
        window.history.go(-1);
    }
}

The answer below was credited because it pointed me in the right direction.

A: Interesting problem. It looks like you're having a concurrency issue. It appears as if the JS parser is not waiting for runSQL to finish before moving on to the next statement. At which point, JS continues to execute, until you hit window.location, which instantly loads a page from the history, and you lose your context. This also means, I don't think you ever hit your return false, because window.location acts like an interrupt, it fires immediately.
Also note that control statements (for, switch, if, etc.) do not increment the stack in JavaScript. I'm not sure how this applies, but I have a funny feeling that it might matter.
See if you can put the window.location outside of this function, higher in the stack so to speak. So let this function return false, then in the caller, if false, window.location(history(-1)). Functions DO increment the stack, so the parser might wait until all calls finish before "closing off" that stack level.


text:
Q: ReactJS. All parts of the hook have different value of the same state Here is a program. By pushing Add Button you can add a button. Pushing the Show current number of buttons you can show current number of buttons.
But it appears every button has its own idea about how many buttons we currently have. Every button somehow "remembers" the number_of_buttons we had when it was "born", and does not see the current value of this state.
I want state property number_of_buttons to be the same for every element in the hook. How to do this?
import React, { useState, useEffect } from 'react';
import ReactDOM from "react-dom";

var just_key = 50;

class App extends React.Component {
    render() {
        return (
                <SomeCrazyButtons/>
        );
    }
}

function SomeCrazyButtons() {
    const [number_of_buttons, setButtonsNumber] = useState(1);
    const [some_html, setSomeHtml] = useState([]);

    function addClickNumber() {
        setButtonsNumber(number_of_buttons + 1);
    }

    function showCurrentNumberOfButtons() {
        console.log("Current number of buttons is " + number_of_buttons);
    }

    useEffect(() => {
        just_key++;
        console.log("We have " + number_of_buttons + " buttons");
        var new_button = [
            <button key = {just_key + "b"} onClick = {showCurrentNumberOfButtons}>Show current number of buttons</button>
        ];
        var new_buttons = some_html.concat(new_button);
        setSomeHtml(new_buttons);
      }, [number_of_buttons]);

    return (

            {some_html}
            <button onClick = {addClickNumber}>Add button</button>

    )
}

ReactDOM.render(
    <App />,
    document.getElementById('root')
);

A: Don't store components in state. As you've discovered, it's an easy way to end up rendering stale components, because you forgot to update your stored components to match your new state. Instead, just store the minimal data needed to define the state (in this case, the number of buttons), and create the components when you render.
function SomeCrazyButtons() {
  const [number_of_buttons, setButtonsNumber] = useState(1);

  function addClickNumber() {
    setButtonsNumber(number_of_buttons + 1);
  }

  function showCurrentNumberOfButtons() {
    console.log("Current number of buttons is " + number_of_buttons);
  }

  const buttons = [];
  for (let i = 0; i < number_of_buttons; i++) {
    buttons.push((
      <button key={i + 'b'} onClick={showCurrentNumberOfButtons}>
        Show current number of buttons
      </button>
    );
  }

  return (

      {buttons}
      <button onClick={addClickNumber}>Add button</button>

  );
}


text:
Q: How to prove that limit cycle can exist in 2D curl field? I know limit cycle can definitely exist in a 2D curl field (that is field with no divergence, $\nabla \cdot F = 0$), but how to explicitly construct such an example? Kind of stuck where to start. Any help is appreciated!

A: A limit cycle cannot exist in a 2D curl vector field. A 2D curl vector field is a hamiltonain vector field and as such it has a first integral, so if you have at least one closed curve trajectory, then there will be a whole smooth foliation of closed curve trajectories in an open neighbourhood of the given closed curve trajectory.
Indeed, let the vector field in question is $$X \, =\, P(x, y)\frac{\partial}{\partial x} \, +\, Q(x, y)\frac{\partial}{\partial y}$$ assume the $\gamma_0$ is a closed curve trajectory tangent to the vector field, i.e. $\gamma_0$ is the trajectory of a periodic solution of  the system of ODEs
$$\frac{dx}{dt} \, =\, P(x, y)$$
$$\frac{dy}{dt} \, =\, Q(x, y)$$
We assume that the vector field $X$ is smooth and well defined in a large enough open domain in the plane that contains $\gamma_0$. Now, $\gamma_0$ is a smooth embedded submanifold of the plane, diffeomorphic to the unit circle, and it bounds a simply connected closed compact domain $K(\gamma_0)$ which is diffeomorphic to the closed unit disc. Let us take a small enough neighbourhood $D(\gamma_0)$ of $K(\gamma_0)$, diffeomorphic to an open disc of the plane. Then the vector field $X$ is smooth and well defined on the this simply connected open domain $D(\gamma_0)$ and $\gamma_0 \, \subset \, D(\gamma_0)$. So from now on all arguments will take place in $D(\gamma_0)$.
Define the smooth differential one form
$$\omega \, = \,  - \,Q(x, y)\,dx \, +\, P(x, y)\, dy$$ and observe that $$\omega(X) \equiv 0$$ Now,
\begin{align}
d\omega \, &=\, d \Big(-Q(x, y)\,dx \, +\, P(x, y)\, dy \,\Big)
\, =\,   - \, \,dQ(x, y)\wedge dx \, +\, dP(x, y)\wedge dy \\
&= -\, \frac{\partial Q}{\partial y}(x, y)\, dy \wedge dx \, +\, \frac{\partial P}{\partial x}(x, y)\, dx  \wedge dy\\
&= \frac{\partial Q}{\partial y}(x, y)\, dx \wedge dy \, +\, \frac{\partial P}{\partial x}(x, y)\, dx  \wedge dy \\
&= \left( \, \frac{\partial Q}{\partial y}(x, y)\, dx\, + \, \frac{\partial P}{\partial x}(x, y)\right) dx  \wedge dy \\&\equiv 0
\end{align}
Since $D(\gamma_0)$ is simply connected, more precisely it deformation retracts onto a point, there exists a smooth function $f(x, y)$ defined at least on $D(\gamma_0)$ such that
$$df\, =\, \omega$$
Hence,
$$P(x, y) \, =\, \frac{\partial f}{\partial y}(x, y)$$
$$Q(x, y) \, =\, -\, \frac{\partial f}{\partial  x}(x, y)$$
which means that the original vector field can be written as
$$X \, =\, \frac{\partial f}{\partial y}(x, y)\frac{\partial}{\partial x} \, - \, \frac{\partial f}{\partial  x}(x, y) \frac{\partial}{\partial y}$$
and is therefore hamiltonian with first-integral (hamiltonian) $f(x, y)$ so every trajectory in the domain $D(\gamma_0)$ follows a level curve of the function $f$, i.e.
$$f(x, y) = c$$ for some constant $c$.
Since $\gamma_0 \, \subset \, f(x, y) = c_0$, then the trajectories of the vector field $X$ in a small enough tubular neighbourhood of $\gamma_0$ are also closed curve trajectories.


text:
Q: Send through office 365 account in salesforce Today suddenly one of our users is seeing this message in salesforce while sending emails.
Earlier it was working fine and he used to send email using office 365.
Our other users are not seeing this issue.
I'll ask him to connect again with office 365.
But anyone knows why this happened or is there a validity for 365 accounts let's say 6 months and after that, we need to validate again.

A: Is this using Lightning Sync? As documented in the release notes for Winter 21 it's being discontinued for new users in favour of using Einstein Activity Capture so it's possible the reconnection prompt is related to the recent update.
As far as I'm aware there isn't a timeout on the connection with Lightning Sync, I have only had to reconfirm the O365 connection when I have updated capture settings for EAC or changed the user's access settings.
There isn't any reference to it in the documentation either, except to note that users will be prompted on their first use of the send email action after configuration.


text:
Q: Inner DIVs scrolling/sliding up to the top of the DIV they inhabit I have a column of div elements set within another div element.  The parent or main div is set to a particular height and scrollable.
When I call a function, based on the ID of the inner div I call, I want the inner div to animate/scroll to the top of the main div.
Note, I don't want the div elements to change position - just to scroll up while staying in the original position.
JsFiddle HERE
Here's my code:

document.addEventListener('click', goStart);

function goStart(event) {
  // Call the function
  clicknext('3');
};

function clicknext(id) {
  jQuery('#subdiv-' + id).animate({
    scrollTop: (jQuery('#main-div').offset().top)
  }, 500);
}
.inner {
  height: 50px;
  width: 100px;
  background: #c0c0c0;
  color: white;
  margin-bottom: 20px;
}

#main-div {
  height: 100px;
  overflow-y: scroll;
  background: #EFEFEF;
}

    DIV 1

    DIV 2

    DIV 3

<input type="button" value="TRIGGER THE FUNCTION" id="triggerbutton">

A: the scroll value is relative to parent offsetTop  ('#main-div')

const TabInner = [
  (document.getElementById('subdiv-1').offsetTop - document.getElementById('main-div').offsetTop),
  (document.getElementById('subdiv-2').offsetTop - document.getElementById('main-div').offsetTop),
  (document.getElementById('subdiv-3').offsetTop - document.getElementById('main-div').offsetTop)
  ];

var Trigg_ref = 1;
triggerbutton.onclick = function()
{
  Trigg_ref = (Trigg_ref +1) % 3;
  clicknext(Trigg_ref);
};

function clicknext(id)
{
  jQuery('#main-div').animate({
    scrollTop: TabInner[id]
  }, 500);
}
.inner {
  height:50px;
  width:100px;
  background: #c0c0c0;
  color:white;
  margin-bottom:20px;
}
#main-div {
  height:100px;
  overflow-y:scroll;
  background:#EFEFEF;
}

    DIV 1

    DIV 2

    DIV 3

<input type="button" value="TRIGGER THE FUNCTION" id="triggerbutton">

A: Updated to CSS Transition Animation on Transform for Optimal Performance
New Answer: https://jsfiddle.net/t5f6e9k3/
You should check out https://developers.google.com/web/fundamentals/performance/rendering/stick-to-compositor-only-properties-and-manage-layer-count
    .inner {
  height:100%;
  width:100%;
  background: #c0c0c0;
  color:white;
  position:absolute;
  top:0;
  left:0;
  transition: transform linear 300ms, opacity linear 300ms;
  }
#main-div {
 display:inline-block;
 width:100px;
 height:100px;
 overflow:hidden;
 background:#EFEFEF;
 position:relative;
}
.inner:not(.active) {
  transform: translate3d(0,100%,0);
}
    function clicknext(id) {
    var active = document.querySelectorAll('.inner.active');
  for(var i=0; i<active.length; i++){
    active[i].classList.remove('active');
    }
    var current = document.querySelector('#subdiv-'+id);
  if(!current.classList.contains('active')){
        current.classList.add('active');
  }

}

Original answer:
You are sliding the wrong element.
If you are wanting a 'window' type of scroll effect that just scrolls content into the viewing container: https://jsfiddle.net/yo45601j/1/
  var main = jQuery('#main-div');
  var elm = jQuery('#subdiv-'+id);
  main.animate({
      scrollTop: (elm[0].offsetTop - main[0].offsetTop)
  },500);

or reset just to 0
https://jsfiddle.net/yo45601j/
function clicknext(id) {

  jQuery('#main-div').animate({
      scrollTop:0
  },500);

}

A: The element position property must be absolute to animate it over the other elements. Try this

document.addEventListener('click', goStart);

function goStart(event) {
  // Call the function
  clicknext('3');
};

function clicknext(id) {
  jQuery('#subdiv-' + id).css("position","absolute").animate({
    top: 0
  }, 500);
}
.inner {
  height: 50px;
  width: 100px;
  background: #c0c0c0;
  color: white;
  margin-bottom: 20px;
}

#main-div {
  height: 100px;
  overflow-y: scroll;
  background: #EFEFEF;
  position: relative;
}

    DIV 1

    DIV 2

    DIV 3

<input type="button" value="TRIGGER THE FUNCTION" id="triggerbutton">


text:
Q: Проблема с выводом c++ (sort, copy) Проблема с copy.В "Task 1" все работает, но в "Task 2" после выполнения sort выводит только название группы и ссылается на
void Group::outputStudents(ostream& out)const
    {
        copy(students.begin(), students.end(), ostream_iterator<Stud>(out, " "));
    }

При этом сортировка выполняется. Пишет, что vector iterators incompatible.
Вот весь код:
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <string>
#include <algorithm>
#include<functional>
#include<numeric>
#include <iterator>
#include <ctime>
#include <vector>
#include <fstream>
#include <sstream>
using namespace std;
struct Stud
{
    string firstName;
    string secondName;
    int averageScore;
};
ostream& operator <<(ostream& out, const Stud& stud);
istream& operator >>(istream& in, Stud& stud);
class Group
{
private:
    string nameGroup;
    vector<Stud> students;
public:
    Group();
    Group(const Group&obj);
    Group(const string& nameGroup_);
    ~Group();
    const string&   getNameGroup()const;
    int             getNumberStudents()const;
    void            outputStudents(ostream& out)const;
    void            setNameGroup(const string& nameGroup_);
    const vector<Stud>& getStud() const;
    void            setStud(const vector<Stud>& students_);
    Group& operator =(const Group& obj);
    bool operator <(const Group& arg2) const;
};
Group::Group() : nameGroup("ITINF-17"){}
Group::Group(const Group&obj)
{
    nameGroup = obj.nameGroup;
    students = obj.students;
}
Group::Group(const string& nameGroup_) : nameGroup(nameGroup_){}
Group::~Group(){ students.clear(); }
const string& Group::getNameGroup()const
{
    return nameGroup;
}
int Group::getNumberStudents()const { return students.size(); }
string getNameStudent(const Stud& a)

{
    string name = a.firstName + ' ' + a.secondName;
    return name;
}
void Group::setStud(const vector<Stud>& students_) { students = students_; };
void Group::setNameGroup(const string& nameGroup_) { nameGroup = nameGroup_; }
void Group::outputStudents(ostream& out) const
{
    copy(students.begin(), students.end(), ostream_iterator<Stud>(out, " "));
}
bool cmpByQuantityStudents(const Group& a, const Group& b)
{
    return a.getNumberStudents() < b.getNumberStudents();
}
Group& Group::operator =(const Group& obj)
{
    if (this == &obj) return (*this);
    this->~Group();
    nameGroup = obj.nameGroup;
    students = obj.students;
}
bool Group::operator < (const Group& arg2) const
{
    return (this->nameGroup < arg2.nameGroup);
}
ostream& operator <<(ostream& out, const Stud& stud)
{
    out << "\t" << stud.firstName
        << "\t" << stud.secondName
        << "\t" << stud.averageScore << "\n";
    return out;
}
istream& operator >>(istream& in, Stud& stud)
{
    getline(in, stud.firstName, ':');
    getline(in, stud.secondName, ':');
    string strTmp;
    getline(in, strTmp, ':');
    stud.averageScore = atoi(strTmp.c_str());
    return in;
}
ostream& operator <<(ostream& out, const Group& group)
{
    out << group.getNameGroup();
    group.outputStudents(out);
    return out;
}
istream& operator >>(istream& in, Group& group)
{
    string strTmp;
    getline(in, strTmp, '$');
    group.setNameGroup(strTmp);
    getline(in, strTmp, '$');
    stringstream streamStudents(strTmp);
    vector<Stud> stud;
    copy(istream_iterator<Stud>(streamStudents), istream_iterator<Stud>(), back_inserter(stud));
    group.setStud(stud);
    return in;
}
int main()
{
    ifstream fin("groups.txt");
    if (!fin)
    {
        cerr << "File not found";
        system("pause");
        return 0;
    }
    vector<Group> groups;
    copy(istream_iterator<Group>(fin), istream_iterator<Group>(), back_inserter(groups));
    cout << "Task 1:\n";
    copy(groups.begin(), groups.end(), ostream_iterator<Group>(cout,"\n"));
    ofstream fout("result.txt");
    copy(groups.begin(), groups.end(), ostream_iterator<Group>(fout, "\n"));
    fin.close();
    fout.close();

    cout << '\n' << "Task 2: \n";
    cout << "Sort by name group: \n";
    sort(groups.begin(), groups.end());
    copy(groups.begin(), groups.end(), ostream_iterator<Group>(cout ));
    cout << '\n';
    cout << "Sort by students: \n";
    sort(groups.begin(), groups.end(), cmpByQuantityStudents);
    copy(groups.begin(), groups.end(), ostream_iterator<Group>(cout));
    system("pause");
    return 0;
}

Пример groups.txt
ITM$
Ivan:Ivanov:85:
Oleg:Olegov:100:
$
IFA$
Olga:Olegova:95:
$


text:
Q: Automatically transform `VARBINARY` column in SQL GUI/editor I use a VARBINARY(16) field to store an IPv6 address in our database.
I can use a query like the following to transform the binary to a textual representation:
SELECT INET6_NTOA(ip) FROM table

However, when I use an SQL GUI/editor/viewer to access the table, the entire ip column appears blank or includes 'garbage' characters that result from interpreting the binary field as text.
Is there some way to configure MySQL and/or my GUI (Sequel Pro or any other GUI) to always transform the ip column when viewing the table?
Perhaps the best way is to create a view?
UPDATE: The best approach I could think of was to use a view. This is the quick and dirty solution I've gone with:
CREATE OR REPLACE VIEW tableTransformIP AS SELECT *, INET6_NTOA(ip) AS ipTransformed FROM table;