text:
Q: How to get server response data in NSURLSession without completion block I am using NSURLSession for background image uploading. And according to uploaded image my server gives me response and I do change in my app accordingly. But I can't get my server response when my app uploading image in background because there is no completion block.
Is there way to get response without using completion block in NSURLUploadTask?
Here is my code :
 self.uploadTask = [self.session uploadTaskWithRequest:request fromData:body completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
            NSString *returnString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
            NSLog(@"returnString : %@",returnString);
            NSLog(@"error : %@",error);
        }];
 [self.uploadTask resume];

But i got this error..

Terminating app due to uncaught exception 'NSGenericException', reason: 'Completion handler blocks are not supported in background sessions. Use a delegate instead.'

But if I can't use completion handler than how should I get the server response. It says use delegate but I can't find any delegate method which can gives me server response.

A: A couple of thoughts:
First, instantiate your session with a delegate, because background sessions must have a delegate:
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:kSessionIdentifier];
self.session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];

Second, instantiate your NSURLSessionUploadTask without a completion handler, because tasks added to a background session cannot use completion blocks. Also note, I'm using a file URL rather than a NSData:
NSURLSessionTask *task = [self.session uploadTaskWithRequest:request fromFile:fileURL];
[task resume];

Third, implement the relevant delegate methods. At a minimum, that might look like:
- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data {
    NSMutableData *responseData = self.responsesData[@(dataTask.taskIdentifier)];
    if (!responseData) {
        responseData = [NSMutableData dataWithData:data];
        self.responsesData[@(dataTask.taskIdentifier)] = responseData;
    } else {
        [responseData appendData:data];
    }
}

- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error {
    if (error) {
        NSLog(@"%@ failed: %@", task.originalRequest.URL, error);
    }

    NSMutableData *responseData = self.responsesData[@(task.taskIdentifier)];

    if (responseData) {
        // my response is JSON; I don't know what yours is, though this handles both

        NSDictionary *response = [NSJSONSerialization JSONObjectWithData:responseData options:0 error:nil];
        if (response) {
            NSLog(@"response = %@", response);
        } else {
            NSLog(@"responseData = %@", [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding]);
        }

        [self.responsesData removeObjectForKey:@(task.taskIdentifier)];
    } else {
        NSLog(@"responseData is nil");
    }
}

Note, the above is taking advantage of a previously instantiated NSMutableDictionary called responsesData (because, much to my chagrin, these "task" delegate methods are done at the "session" level).
Finally, you want to make sure to define a property to store the completionHandler provided by handleEventsForBackgroundURLSession:
@property (nonatomic, copy) void (^backgroundSessionCompletionHandler)(void);

And obviously, have your app delegate respond to handleEventsForBackgroundURLSession, saving the completionHandler, which will be used below in the URLSessionDidFinishEventsForBackgroundURLSession method.
- (void)application:(UIApplication *)application handleEventsForBackgroundURLSession:(NSString *)identifier completionHandler:(void (^)())completionHandler {
    // This instantiates the `NSURLSession` and saves the completionHandler.
    // I happen to be doing this in my session manager, but you can do this any
    // way you want.

    [SessionManager sharedManager].backgroundSessionCompletionHandler = completionHandler;
}

And then make sure your NSURLSessionDelegate calls this handler on the main thread when the background session is done:
- (void)URLSessionDidFinishEventsForBackgroundURLSession:(NSURLSession *)session {
    if (self.backgroundSessionCompletionHandler) {
        dispatch_async(dispatch_get_main_queue(), ^{
            self.backgroundSessionCompletionHandler();
            self.backgroundSessionCompletionHandler = nil;
        });
    }
}

This is only called if some of the uploads finished in the background.
There are a few moving parts, as you can see, but that's basically what's entailed.


text:
Q: Java Swing Combobox removeAllItems calling ItemStateChanged also? My code is quite simple actually. I saw a simple and similar code was from this article.
At first, I have 1 combobox. I have a listener on it called itemStateChanged(). My purpose to add into this listener is that; "to execute some code when user click (select) an item from its dropbox".
Cmb_ItemCategory = new javax.swing.JComboBox();

Cmb_ItemCategory.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Loading..." }));

Cmb_ItemCategory.addItemListener(new java.awt.event.ItemListener() {
    public void itemStateChanged(java.awt.event.ItemEvent evt) {
        Cmb_ItemCategoryItemStateChanged(evt);
    }
});

private void Cmb_ItemCategoryItemStateChanged(java.awt.event.ItemEvent evt) {

        if(evt.getStateChange() == java.awt.event.ItemEvent.SELECTED){
        System.err.println("Sombody click or change my model content");
        }

    }

Behind the code, I grab some data, and then calling a method of removeAllItems() .
And then I set a new Model (from new data) into it.
-- at another line of code ---
Cmb_ItemCategory.removeAllItems();
Cmb_ItemCategory.setModel(newModel);

I juz realized that my itemStateChanged() is called when i do the removeAllItem() method. called once.
So, How to make it only called once user Click (select) only AND not when removeAllItems() called?
it similar to this article. But it's not removingItems case. CMIIW.

A: Here check this code out, this works flawlessly, might be you doing something wrong where you calling removeAllItems() :
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class ComboState
{
    private void createAndDisplayGUI()
    {
        JFrame frame = new JFrame("Combo State Testing : ");
        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

        final JComboBox cbox = new JComboBox();
        cbox.addItem("One");
        cbox.addItem("Two");
        cbox.addItem("Three");
        cbox.addItem("Four");
        cbox.addItemListener(new ItemListener()
        {
            public void itemStateChanged(ItemEvent ie)
            {
                if (ie.getStateChange() == ItemEvent.SELECTED)
                {
                    System.out.println("Item Selected is : " + ie.getItem());
                }
                /*else
                {
                    System.out.println("I am called for other reasons.");
                }*/
            }
        });

        /*
         * Click me to remove JComboBox's items.
         */
        JButton removeButton = new JButton("REMOVE");
        removeButton.addActionListener(new ActionListener()
        {
            public void actionPerformed(ActionEvent ae)
            {
                cbox.removeAllItems();
            }
        });

        frame.add(cbox, BorderLayout.CENTER);
        frame.add(removeButton, BorderLayout.PAGE_END);
        frame.pack();
        frame.setLocationByPlatform(true);
        frame.setVisible(true);
    }

    public static void main(String... args)
    {
        SwingUtilities.invokeLater(new Runnable()
        {
            public void run()
            {
                new ComboState().createAndDisplayGUI();
            }
        });
    }
}

A: As nIcE cOw already illustrated in his example, it should certainly work when you use a DefaultComboBoxModel (which is the case in his sample code, although it happens behind the screens).
I could explain the behavior you encounter for the non-DefaultComboBoxModel case, although your code snippet suggests you use one. Looking at the source code for JComboBox#removeAllItems there is a different code path since the removeAllElements method is not part of the MutableComboBoxModel interface
public void removeAllItems() {
    checkMutableComboBoxModel();
    MutableComboBoxModel<E> model = (MutableComboBoxModel<E>)dataModel;
    int size = model.getSize();

    if ( model instanceof DefaultComboBoxModel ) {
        ((DefaultComboBoxModel)model).removeAllElements();
    }
    else {
        for ( int i = 0; i < size; ++i ) {
            E element = model.getElementAt( 0 );
            model.removeElement( element );
        }
    }
    selectedItemReminder = null;
    if (isEditable()) {
        editor.setItem(null);
    }
}

So with a non-DefaultComboBoxModel you are going to remove the items one by one. This means that at a certain point in time, you will remove the selected element. A possible implementation of your model might change the selected element at that point. If you look for example at the implementation in DefaultComboBoxModel (although this code will not be triggered) you can clearly see it changes the selection.
public void removeElementAt(int index) {
    if ( getElementAt( index ) == selectedObject ) {
        if ( index == 0 ) {
            setSelectedItem( getSize() == 1 ? null : getElementAt( index + 1 ) );
        }
        else {
            setSelectedItem( getElementAt( index - 1 ) );
        }
    }

    objects.removeElementAt(index);

    fireIntervalRemoved(this, index, index);
}

Perhaps your model does something similar, which explains the event. Just for making this post complete, the code behind the DefaultComboBoxModel#removeAllElements where you can clearly see it sets the selection to null and does not select another object. Only weird thing in that code is that it does not fire a DESELECTED event first, although you know the selection has changed if you listen for the intervalRemoved event ... but that is not really relevant to your problem
public void removeAllElements() {
    if ( objects.size() > 0 ) {
        int firstIndex = 0;
        int lastIndex = objects.size() - 1;
        objects.removeAllElements();
        selectedObject = null;
        fireIntervalRemoved(this, firstIndex, lastIndex);
    } else {
        selectedObject = null;
    }
}

So to conclude: I say the solution for your problem is located in your model, and not in the code you posted

A: One quick way to do is to have a bool set to true before you call removeAllItem() and back false after. Execute the code in your itemStateChanged() only if the bool variable is false.
Ideally you could override the removeAllItem() function.

A: not clear from whole discusion,

*

*you have to remove all Listener(s) from JComboBox before removing all Items, after Items are removed you can add Listener(s) back,

*still not sure if you want to add & remove Items dynamically, or you can set whatever value for another JComponent(s),

*(against complicating simple things) did you see there remove,
.
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;

public class ComboBoxTwo extends JFrame implements ActionListener, ItemListener {

    private static final long serialVersionUID = 1L;
    private JComboBox mainComboBox;
    private JComboBox subComboBox;
    private Hashtable<Object, Object> subItems = new Hashtable<Object, Object>();

    public ComboBoxTwo() {
        String[] items = {"Select Item", "Color", "Shape", "Fruit"};
        mainComboBox = new JComboBox(items);
        mainComboBox.addActionListener(this);
        mainComboBox.addItemListener(this);
        //prevent action events from being fired when the up/down arrow keys are used
        //mainComboBox.putClientProperty("JComboBox.isTableCellEditor", Boolean.TRUE);
        getContentPane().add(mainComboBox, BorderLayout.WEST);
        subComboBox = new JComboBox();//  Create sub combo box with multiple models
        subComboBox.setPrototypeDisplayValue("XXXXXXXXXX"); // JDK1.4
        subComboBox.addItemListener(this);
        getContentPane().add(subComboBox, BorderLayout.EAST);
        String[] subItems1 = {"Select Color", "Red", "Blue", "Green"};
        subItems.put(items[1], subItems1);
        String[] subItems2 = {"Select Shape", "Circle", "Square", "Triangle"};
        subItems.put(items[2], subItems2);
        String[] subItems3 = {"Select Fruit", "Apple", "Orange", "Banana"};
        subItems.put(items[3], subItems3);
//      mainComboBox.setSelectedIndex(1);
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        String item = (String) mainComboBox.getSelectedItem();
        Object o = subItems.get(item);
        if (o == null) {
            subComboBox.setModel(new DefaultComboBoxModel());
        } else {
            subComboBox.setModel(new DefaultComboBoxModel((String[]) o));
        }
    }

    @Override
    public void itemStateChanged(ItemEvent e) {
        if (e.getStateChange() == ItemEvent.SELECTED) {
            if (e.getSource() == mainComboBox) {
                if (mainComboBox.getSelectedIndex() != 0) {
                    FirstDialog firstDialog = new FirstDialog(ComboBoxTwo.this,
                            mainComboBox.getSelectedItem().toString(), "Please wait,  Searching for ..... ");
                }
            }
        }
    }

    private class FirstDialog extends JDialog {

        private static final long serialVersionUID = 1L;

        FirstDialog(final Frame parent, String winTitle, String msgString) {
            super(parent, winTitle);
            setModalityType(Dialog.ModalityType.APPLICATION_MODAL);
            JLabel myLabel = new JLabel(msgString);
            JButton bNext = new JButton("Stop Processes");
            add(myLabel, BorderLayout.CENTER);
            add(bNext, BorderLayout.SOUTH);
            bNext.addActionListener(new ActionListener() {

                @Override
                public void actionPerformed(ActionEvent evt) {
                    setVisible(false);
                }
            });
            javax.swing.Timer t = new javax.swing.Timer(1000, new ActionListener() {

                @Override
                public void actionPerformed(ActionEvent e) {
                    setVisible(false);
                }
            });
            t.setRepeats(false);
            t.start();
            setLocationRelativeTo(parent);
            setSize(new Dimension(400, 100));
            setVisible(true);
        }
    }

    public static void main(String[] args) {
        JFrame frame = new ComboBoxTwo();
        frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }
}

A: The method removeAllItems does not call ItemStateChanged, but it call actionPerformed, you can check it by running this simple code:
public class Tuto {

    public static void main(String[] args) {
        //create the main frame
        JFrame frame = new JFrame();
        frame.setResizable(false);
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.setLayout(null);
        frame.setLocation(new Point(10, 10));
        frame.setPreferredSize(new Dimension(400, 300));

        JComboBox<String> combo = new JComboBox();
        combo.addItem("item 1");
        combo.addItem("item 2");
        combo.addItem("item 3");
        combo.setBounds(50, 30, 300, 20);
        combo.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent ae) {
                System.out.println(" action Performed ");
            }
        });
        frame.add(combo);

        JButton button = new JButton("Remove");
        button.setBounds(50, 100, 100, 30);
        button.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent ae) {
                combo.removeAllItems();
            }
        });
        frame.add(button);

        frame.pack();
        frame.setVisible(true);
    }

}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Exported variable X has or is using name Y from external module Z but cannot be named I get the following error in this case using TS 3.9 with { compilerOptions: {declaration: true }} in my tsconfig.json:
// a.ts
export const key = 1234
export const obj = {
    [key]: 1
};
export default obj;

// b.ts
import A from "./a";
import { key} from "./a"

// Exported variable 'theExport' has or is using name 'key' from external module "c:/tsexample/src/a" but cannot be named.ts(4023)
const theExport  = {
  A: A,
  B: 2,
  C: 3,
};
export default theExport

// Exported variable 'theExport' has or is using name 'key' from external module "c:/tsexample/src/a" but cannot be named.ts(4023)

In a comment on a related issue the PM of TS at the time suggested two workarounds:

*

*explicitly import the type

*explicitly declare the type of the export (where the error occurs)

(1) does not work in this case. I tried exporting everything from 'a' and importing everything in 'b' and there was no difference to the error message.
The only thing that worked was this very verbose and hard to maintain explicit type annotation:
// updated b.ts
import A from "./a";

const theExport: {
    // https://github.com/microsoft/TypeScript/issues/9944
  [index: string]: typeof A | number;
} = {
  A: A,
  B: 2,
  C: 3,
};
export default theExport;

My question is:

*

*what is a workaround I can use that doesn't involve repeating the shape of the object?

*why does importing the type not fix the problem?

This question is similar but distinct from:

*

*https://stackoverflow.com/a/44066867/2482570: not relevant because it says the problem was fixed in TS 2.9

*https://stackoverflow.com/a/49841010/2482570: none of the answers provide a workaround that is applicable to this case

*Typescript error: "Return type of exported function has or is using name <n> from external module <M> but cannot be named" and Typing error "Default export of the module has or is using private name" - switch from typescript v1.8 to 2: none of the solutions provided work in this case

A: It's not that pretty, but this is a minimally invasive change that seems to work in a sandbox:
const theExport = {
  A: A as {[K in keyof typeof A]: typeof A[K]},
  B: 2,
  C: 3
};

A: based on this comment, looks like one solution could be:
// a.ts
export const key = 1234
export const obj = {
    [key]: 1
};
export default obj;

// b.ts
import A from "./a";

interface ITheExport {
  A: typeof A;
  B: number;
  C: number;
}

const theExport: ITheExport = { // strong typing the object instead of using inference
  A: A,
  B: 2,
  C: 3,
};
export default theExport

See sandbox

A: Explicitly set obj type
// a.ts
export const key = 1234
export const obj = {
  [key as number]: 1
}
export default obj

// b.ts
import A from './a'

const theExport = {
  A: A,
  B: 2,
  C: 3
}
export default theExport


text:
Q: IE11: Search functionality with autosuggestion - IE11 fails to understand 'Enter' key is pressed I know this has been asked many times and I tried many solutions nothing seems to work. In my application, I have autosuggestion functionality written in javascript.
In which, if i start to write a term in search box, it appends the suggestions with the URL to the suggested products. On IE11, When I use 'down' key to select a product and enter it doesn't seem to recognise that 'Enter' key has been pressed and never goes in the method where it checks if the 'event.which === 13' hence doesn't work. I am attaching the piece of code (cant attach whole function as is) any help will be appreciated. Thank you!

  $('.searchInput').on('keyup', e => {
      const upKey = 38;
      const downKey = 40;
      const enterKey = 13;
      if (e.which === enterKey) {
        window.location.href = 'url to the product';
      }
    });
<form id="searchBox">
    <input type="text" name="searchTerm" class="searchInput" autocomplete="off">
    <button type="submit" class="icon-icon_search --active"></button>

                <a class="c-header__search-suggestions-item" href="<"URL_to_the_product_where_it_should_redirect_on_selection>">
                 boni

</form>


text:
Q: ntopng error: segmentation fault I want to use ntopng to monitor my internet availability. I installed it following the instructions shown here and Run ntopng. However I'm getting the following error:
...(some messages here)
07/Jan/2015 11:22:00 [Ntop.cpp:206] Welcome to ntopng i386 v.1.2.1 (r1.2.1) - (C) 1998-14 ntop.org
07/Jan/2015 11:22:00 [PeriodicActivities.cpp:53] Started periodic activities loop...
Segmentation fault

I compared what I got with the text given in the first link, and everything is ok except that at the end I don't know why I'm shown: Segmentation fault instead of
12/Sep/2014 08:32:34 [NetworkInterface.cpp:800] Started packet polling on interface en0 [id: 1]...
12/Sep/2014 08:32:34 [NetworkInterface.cpp:800] Started packet polling on interface en1 [id: 3]...
12/Sep/2014 08:32:34 [NetworkInterface.cpp:800] Started packet polling on interface lo0 [id: 5]...

as shown in the first link. I appreciate your help.


text:
Q: How do I know if I need AMD-64.deb or x86_64.rpm? Is there a simple command (like uname -r to know my kernel version) to know if I need to download a AMD-64.deb package or a x86_64.rpm one ?
For example, for downloading printer drivers, I need to decide which one to take.
Sorry, if this is a dupe, I've seen many questions around this matter, but didn't find how to know what is my processor.


text:
Q: Create "go to page" button using Javascript I am new to javascript, but have made an html page with 46 images on it which scroll horizontally. Each image is a different page of a magazine. Each image has an id of 1 through 46.
How can I use javascript to make this button be a link to the divs 1 through 46 and take the user to that # link when they press "Go"?
<form id="goto" name="gotoform">
    Go to Page: <input type="number" name="gotopage" min="1" max="46">
    <input type="submit" value="Go">
</form>

For example, if the user is on example.com/index.html and enters 6 and presses go, they will be taken to example.com/index.html#6
Thanks

A: You can navigate to any id with the help of the anchor tag.
<input type="submit" value="Go" onclick="return jump();">
and then:
function jump(){
    location.href = "#"+<any prefix for the div ids>+document.getElementsByName("gotopage")[0].value;
}

There's a jquery plugin just to do that in a fancy way - ScrollTo: http://demos.flesler.com/jquery/scrollTo/. It adds a nice little animation.

A: I suggest you have a good look at this page to find out how to ask a question here:
https://stackoverflow.com/help/how-to-ask
But to answer your question, something like this should suffice:
$(function() {
    $("form#goto input[type='submit']").click(function(e) {
        window.location = "#" + $("input[name=gotopage]").val();
        e.preventDefault();
    });
});

A: I would just use some jQuery to attach an event to your GO button...  like so
$('input[type="submit"]').click(function () {
  var page = $('input[type="number"]').val();
  location.href = "index.html#" + page;
});

This captures the value in your input field, and then appends it to the URL specified, in addition to taking you to that location.


text:
Q: How to get Nofication data of other apps on Flutter? I am trying to make an app that can get the notification data of all notifications that appear on the phone. I tried using notifications package, but using this package I can only access the name of app which sent the Notification and the timestamp, and not the actual notification itself.
I have no issue if the app asks for permission.

A: This feature has been added in the GitHub repo of the  Notification package recently.It is not yet updated int the pub.dev website.
Depend on the GitHub repository of the package to use the packageMessage property.


text:
Q: Change the default font of Back button in UINavigationController I am trying to change the default font of Back button in UINavigationController to a custom font
UIFont *myCustomFont = [UIFont fontWithName:@"MyCustomFont" size:18];

How can I set this custom font to the Back Button? I've browsed through other answers to similar questions in this site with no success.

A: [[UIBarButtonItem appearanceWhenContainedIn:[UINavigationBar class], nil] setTitleTextAttributes:
        @{UITextAttributeTextColor:[UIColor blackColor],
         UITextAttributeTextShadowOffset:[NSValue valueWithUIOffset:UIOffsetMake(0, 1)],
         UITextAttributeTextShadowColor:[UIColor whiteColor],
         UITextAttributeFont: myCustomFont
        }
         forState:UIControlStateNormal];


text:
Q: How can a venv shared between machines use the exact same interpreter? I have a directory accessible from multiple Linux machines on the same network (the precise terminology for this is a directory on a "mounted network drive", right?), within which I have a python virtual environment, made with python3 -m venv venv.
I've tried checking the python version from a few of the machines using this:
$ . venv/bin/activate
$ python --version

and I get back different versions depending on what machine it is. Some show 3.8.5, some 3.8.10. I believe I've figured out that this is because the "interpreter" in the venv is really a link to the interpreter in /usr/bin, which is machine-specific:
$ ls -lah ./venv/bin/ | grep python
lrwxrwxrwx  1 echols14 cs236ta    7 Sep 29 02:08 python -> python3
lrwxrwxrwx  1 echols14 cs236ta   16 Sep 29 02:08 python3 -> /usr/bin/python3

When I take a look at the contents of /usr/bin, it seems like there are more things there relating to python than just the single interpreter file python3.8:
$ ls -lah /usr/bin | grep python
-rwxr-xr-x  1 root   root    2.3K Jun 20  2017 dh_python3-ply
lrwxrwxrwx  1 root   root      23 Sep 28 16:10 pdb3.8 -> ../lib/python3.8/pdb.py
lrwxrwxrwx  1 root   root      31 Mar 13  2020 py3versions -> ../share/python3/py3versions.py
lrwxrwxrwx  1 root   root       9 Mar 13  2020 python3 -> python3.8
-rwxr-xr-x  1 root   root    5.3M Sep 28 16:10 python3.8
lrwxrwxrwx  1 root   root      33 Sep 28 16:10 python3.8-config -> x86_64-linux-gnu-python3.8-config
lrwxrwxrwx  1 root   root      16 Mar 13  2020 python3-config -> python3.8-config
-rwxr-xr-x  1 root   root     364 Dec 17  2019 python3-qr
-rwxr-xr-x  1 root   root    3.2K Sep 28 16:10 x86_64-linux-gnu-python3.8-config
lrwxrwxrwx  1 root   root      33 Mar 13  2020 x86_64-linux-gnu-python3-config -> x86_64-linux-gnu-python3.8-config

I'd like the venv to use the same python version regardless of which machine it is used from. Is that possible?
My first thought is to copy the python3.8 file from one machine's /usr/bin and place it in the venv's bin, then adjust the links so that it is the one that gets used when the venv is activated. Would I need to copy other python-related files from /usr/bin for it to function? Is this method safe, or should it be avoided for some reason?
If that method is not a good idea, what other way could I get the shared venv to always use the same version of python, regardless of the machine?
NOTE: I don't have root/sudo permissions on all machines in question, but I do have root/sudo permissions on one of the machines.

A: Found it. When creating the virtual environment, use the --copies option:

--copies              Try to use copies rather than symlinks, even when
symlinks are the default for the platform

documentation
Which looks like this:
python3 -m venv --copies venv

And results in this:
$ ls -lah venv/bin/ | grep python
-rwxr-xr-x  1 echols14 cs236ta 5.3M Oct  7 18:26 python
-rwxr-xr-x  1 echols14 cs236ta 5.3M Oct  7 18:26 python3


text:
Q: how to sync android contacts with firebase database I am new to android programming and I am Developing an App in which the user has an account in firebase and he wants to sync his/her mobile phone contacts with the firebase database contacts. One way is to get all the firebase contacts and compare with the user phone contacts and filter out the similar contacts and update the view.....But this Logic is absured, when the firebase database increases i.e. hit million users!
Please Help me....or at least give me right direction in which I Should Start working!
thanx in advance
My database Tree
-Users
   |
   ----959670000
   |      |
   |      ------name
   |
   + ----750890000
   +------859200000

Here Is How My dataBase tree looks Like How Should I save

A: In order to be as universal as possible, you can create a class with the prefix of all countries.
public class CountryToPhonePrefix {
    public static String getPhone(String code) {
        return country2phone.get(code.toUpperCase());
    }
    public static Map<String, String> getAll(){
        return country2phone;
    }
    private static Map<String, String> country2phone = new HashMap<String, String>();
    static {
        country2phone.put("AF", "+93");
        country2phone.put("AL", "+355");
        country2phone.put("DZ", "+213");
        country2phone.put("AD", "+376");
        country2phone.put("AO", "+244");
        country2phone.put("AG", "+1-268");
        country2phone.put("AR", "+54");
        country2phone.put("AM", "+374");
        country2phone.put("AU", "+61");
        country2phone.put("AT", "+43");
        country2phone.put("AZ", "+994");
        country2phone.put("BS", "+1-242");
        country2phone.put("BH", "+973");
        country2phone.put("BD", "+880");
        country2phone.put("BB", "+1-246");
        country2phone.put("BY", "+375");
        country2phone.put("BE", "+32");
        country2phone.put("BZ", "+501");
        country2phone.put("BJ", "+229");
        country2phone.put("BT", "+975");
        country2phone.put("BO", "+591");
        country2phone.put("BA", "+387");
        country2phone.put("BW", "+267");
        country2phone.put("BR", "+55");
        country2phone.put("BN", "+673");
        country2phone.put("BG", "+359");
        country2phone.put("BF", "+226");
        country2phone.put("BI", "+257");
        country2phone.put("KH", "+855");
        country2phone.put("CM", "+237");
        country2phone.put("CA", "+1");
        country2phone.put("CV", "+238");
        country2phone.put("CF", "+236");
        country2phone.put("TD", "+235");
        country2phone.put("CL", "+56");
        country2phone.put("CN", "+86");
        country2phone.put("CO", "+57");
        country2phone.put("KM", "+269");
        country2phone.put("CD", "+243");
        country2phone.put("CG", "+242");
        country2phone.put("CR", "+506");
        country2phone.put("CI", "+225");
        country2phone.put("HR", "+385");
        country2phone.put("CU", "+53");
        country2phone.put("CY", "+357");
        country2phone.put("CZ", "+420");
        country2phone.put("DK", "+45");
        country2phone.put("DJ", "+253");
        country2phone.put("DM", "+1-767");
        country2phone.put("DO", "+1-809and1-829");
        country2phone.put("EC", "+593");
        country2phone.put("EG", "+20");
        country2phone.put("SV", "+503");
        country2phone.put("GQ", "+240");
        country2phone.put("ER", "+291");
        country2phone.put("EE", "+372");
        country2phone.put("ET", "+251");
        country2phone.put("FJ", "+679");
        country2phone.put("FI", "+358");
        country2phone.put("FR", "+33");
        country2phone.put("GA", "+241");
        country2phone.put("GM", "+220");
        country2phone.put("GE", "+995");
        country2phone.put("DE", "+49");
        country2phone.put("GH", "+233");
        country2phone.put("GR", "+30");
        country2phone.put("GD", "+1-473");
        country2phone.put("GT", "+502");
        country2phone.put("GN", "+224");
        country2phone.put("GW", "+245");
        country2phone.put("GY", "+592");
        country2phone.put("HT", "+509");
        country2phone.put("HN", "+504");
        country2phone.put("HU", "+36");
        country2phone.put("IS", "+354");
        country2phone.put("IN", "+91");
        country2phone.put("ID", "+62");
        country2phone.put("IR", "+98");
        country2phone.put("IQ", "+964");
        country2phone.put("IE", "+353");
        country2phone.put("IL", "+972");
        country2phone.put("IT", "+39");
        country2phone.put("JM", "+1-876");
        country2phone.put("JP", "+81");
        country2phone.put("JO", "+962");
        country2phone.put("KZ", "+7");
        country2phone.put("KE", "+254");
        country2phone.put("KI", "+686");
        country2phone.put("KP", "+850");
        country2phone.put("KR", "+82");
        country2phone.put("KW", "+965");
        country2phone.put("KG", "+996");
        country2phone.put("LA", "+856");
        country2phone.put("LV", "+371");
        country2phone.put("LB", "+961");
        country2phone.put("LS", "+266");
        country2phone.put("LR", "+231");
        country2phone.put("LY", "+218");
        country2phone.put("LI", "+423");
        country2phone.put("LT", "+370");
        country2phone.put("LU", "+352");
        country2phone.put("MK", "+389");
        country2phone.put("MG", "+261");
        country2phone.put("MW", "+265");
        country2phone.put("MY", "+60");
        country2phone.put("MV", "+960");
        country2phone.put("ML", "+223");
        country2phone.put("MT", "+356");
        country2phone.put("MH", "+692");
        country2phone.put("MR", "+222");
        country2phone.put("MU", "+230");
        country2phone.put("MX", "+52");
        country2phone.put("FM", "+691");
        country2phone.put("MD", "+373");
        country2phone.put("MC", "+377");
        country2phone.put("MN", "+976");
        country2phone.put("ME", "+382");
        country2phone.put("MA", "+212");
        country2phone.put("MZ", "+258");
        country2phone.put("MM", "+95");
        country2phone.put("NA", "+264");
        country2phone.put("NR", "+674");
        country2phone.put("NP", "+977");
        country2phone.put("NL", "+31");
        country2phone.put("NZ", "+64");
        country2phone.put("NI", "+505");
        country2phone.put("NE", "+227");
        country2phone.put("NG", "+234");
        country2phone.put("NO", "+47");
        country2phone.put("OM", "+968");
        country2phone.put("PK", "+92");
        country2phone.put("PW", "+680");
        country2phone.put("PA", "+507");
        country2phone.put("PG", "+675");
        country2phone.put("PY", "+595");
        country2phone.put("PE", "+51");
        country2phone.put("PH", "+63");
        country2phone.put("PL", "+48");
        country2phone.put("PT", "+351");
        country2phone.put("QA", "+974");
        country2phone.put("RO", "+40");
        country2phone.put("RU", "+7");
        country2phone.put("RW", "+250");
        country2phone.put("KN", "+1-869");
        country2phone.put("LC", "+1-758");
        country2phone.put("VC", "+1-784");
        country2phone.put("WS", "+685");
        country2phone.put("SM", "+378");
        country2phone.put("ST", "+239");
        country2phone.put("SA", "+966");
        country2phone.put("SN", "+221");
        country2phone.put("RS", "+381");
        country2phone.put("SC", "+248");
        country2phone.put("SL", "+232");
        country2phone.put("SG", "+65");
        country2phone.put("SK", "+421");
        country2phone.put("SI", "+386");
        country2phone.put("SB", "+677");
        country2phone.put("SO", "+252");
        country2phone.put("ZA", "+27");
        country2phone.put("ES", "+34");
        country2phone.put("LK", "+94");
        country2phone.put("SD", "+249");
        country2phone.put("SR", "+597");
        country2phone.put("SZ", "+268");
        country2phone.put("SE", "+46");
        country2phone.put("CH", "+41");
        country2phone.put("SY", "+963");
        country2phone.put("TJ", "+992");
        country2phone.put("TZ", "+255");
        country2phone.put("TH", "+66");
        country2phone.put("TL", "+670");
        country2phone.put("TG", "+228");
        country2phone.put("TO", "+676");
        country2phone.put("TT", "+1-868");
        country2phone.put("TN", "+216");
        country2phone.put("TR", "+90");
        country2phone.put("TM", "+993");
        country2phone.put("TV", "+688");
        country2phone.put("UG", "+256");
        country2phone.put("UA", "+380");
        country2phone.put("AE", "+971");
        country2phone.put("GB", "+44");
        country2phone.put("US", "+1");
        country2phone.put("UY", "+598");
        country2phone.put("UZ", "+998");
        country2phone.put("VU", "+678");
        country2phone.put("VA", "+379");
        country2phone.put("VE", "+58");
        country2phone.put("VN", "+84");
        country2phone.put("YE", "+967");
        country2phone.put("ZM", "+260");
        country2phone.put("ZW", "+263");
        country2phone.put("GE", "+995");
        country2phone.put("TW", "+886");
        country2phone.put("AZ", "+374-97");
        country2phone.put("CY", "+90-392");
        country2phone.put("MD", "+373-533");
        country2phone.put("SO", "+252");
        country2phone.put("GE", "+995");
        country2phone.put("CX", "+61");
        country2phone.put("CC", "+61");
        country2phone.put("NF", "+672");
        country2phone.put("NC", "+687");
        country2phone.put("PF", "+689");
        country2phone.put("YT", "+262");
        country2phone.put("GP", "+590");
        country2phone.put("GP", "+590");
        country2phone.put("PM", "+508");
        country2phone.put("WF", "+681");
        country2phone.put("CK", "+682");
        country2phone.put("NU", "+683");
        country2phone.put("TK", "+690");
        country2phone.put("GG", "+44");
        country2phone.put("IM", "+44");
        country2phone.put("JE", "+44");
        country2phone.put("AI", "+1-264");
        country2phone.put("BM", "+1-441");
        country2phone.put("IO", "+246");
        country2phone.put("", "+357");
        country2phone.put("VG", "+1-284");
        country2phone.put("KY", "+1-345");
        country2phone.put("FK", "+500");
        country2phone.put("GI", "+350");
        country2phone.put("MS", "+1-664");
        country2phone.put("SH", "+290");
        country2phone.put("TC", "+1-649");
        country2phone.put("MP", "+1-670");
        country2phone.put("PR", "+1-787and1-939");
        country2phone.put("AS", "+1-684");
        country2phone.put("GU", "+1-671");
        country2phone.put("VI", "+1-340");
        country2phone.put("HK", "+852");
        country2phone.put("MO", "+853");
        country2phone.put("FO", "+298");
        country2phone.put("GL", "+299");
        country2phone.put("GF", "+594");
        country2phone.put("GP", "+590");
        country2phone.put("MQ", "+596");
        country2phone.put("RE", "+262");
        country2phone.put("AX", "+358-18");
        country2phone.put("AW", "+297");
        country2phone.put("AN", "+599");
        country2phone.put("SJ", "+47");
        country2phone.put("AC", "+247");
        country2phone.put("TA", "+290");
        country2phone.put("CS", "+381");
        country2phone.put("PS", "+970");
        country2phone.put("EH", "+212");
    }
}

In MainActivity, you can call the following function to get the contact list in the device.
private void getContactList(){

    String ISOPrefix = getCountryISO();

    Cursor phones = getContext().getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,null,null,null,null);

    while (phones.moveToNext()){
        String name = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
        String phone = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));

        phone = phone.replace(" ","");
        phone = phone.replace("-","");
        phone = phone.replace("(","");
        phone = phone.replace(")","");

        if (!String.valueOf(phone.charAt(0)).equals("+")) {
            phone = ISOPrefix + phone;
        }

        UserObject mContact = new UserObject("",name, phone);
        contactList.add(mContact);
        getUserDetails(mContact);
    }
}

Here you can get the CountryISO from the device.
private String getCountryISO(){
    String iso = null;

    TelephonyManager telephonyManager = (TelephonyManager) getContext().getSystemService(getContext().TELEPHONY_SERVICE);
    if (telephonyManager.getNetworkCountryIso() != null) {
        if (!telephonyManager.getNetworkCountryIso().toString().equals("")) {
            iso = telephonyManager.getNetworkCountryIso().toString();
        }
    }

    return CountryToPhonePrefix.getPhone(iso);
}

And here you can search in Firebase Realtime Database who has an account in your app according to your contact list.
private void getUserDetails(UserObject mContact) {
    DatabaseReference mUserDB = FirebaseDatabase.getInstance().getReference().child("user");
    // Only lists the users that have an account in the app into Firebase
    Query query = mUserDB.orderByChild("phone").equalTo(mContact.getPhone());
    query.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
            if (dataSnapshot.exists()) {
                String uid, name = "", phone = "", email, image;

                for (DataSnapshot childSnapshot : dataSnapshot.getChildren()){
                    uid = childSnapshot.getKey().toString();
                    if (childSnapshot.child("phone").getValue() != null) {
                        phone = childSnapshot.child("phone").getValue().toString();
                    }
                    if (childSnapshot.child("name").getValue() != null) {
                        name = childSnapshot.child("name").getValue().toString();
                    }
                    email = childSnapshot.child("email").getValue().toString();
                    image = childSnapshot.child("image").getValue().toString();

                    UserObject mUser = new UserObject(childSnapshot.getKey(), name, phone);
                    mUser.setImageUrl(image);

                    if (name.equals(phone)) {
                        for (UserObject mContactIterator : contactList) {
                            if (mContactIterator.getPhone().equals(mUser.getPhone())) {
                                mUser.setName(mContactIterator.getName());
                            }
                        }
                    }

                    return;
                }
            }
        }

        @Override
        public void onCancelled(@NonNull DatabaseError databaseError) {

        }
    });
}

I hope it helps!

A: You need to get list of contacts from system first, and then save those into database.
Decide, what way you shoud store info of your contacts in database (maybe some additional information), and then tweak sample project from database to do so (it saves single messages as node's child)


text:
Q: How to scrape the data of nutrition facts for products from walmart.com? I have tried urllib with Beautifulsoup. I always get an empty result by using soup.select with related tags.
I am new to Python. Thank you so much for your help in advance!
Attached codes are for your reference.
import urllib.request, urllib.parse, urllib.error
from bs4 import BeautifulSoup
import pandas as pd
url="https://www.walmart.com/ip/Twin-Pack-Kellogg-s-Frosted-Mini-Wheats-Breakfast-Cereal-48-Oz/940504168"
html = urllib.request.urlopen(url).read()
soup = BeautifulSoup(html, "html.parser")
name_box = soup.select('div.nutrition-facts-all-facts-servingSize.div.span')
print(name_box)

A: You have picked a rather awkward page to start playing with web scraping as the page you are trying to get has a lot of javascript rendering. As such you cannot simply pass the information to BeautfulSoup and get the information you want. i.e. the HTML you get will be different to the HTML you see when viewing source in a browser.
You could investigate using something like selenium to obtain the final HTML via a browser and parse that using BeautifulSoup. Alternatively, the quickest approach is to see if the information you want is already buried somewhere in what you have. In this case you can find it as JSON buried inside one of the <script> sections that is returned.
The JSON can be extracted using the following code:
import urllib.request
from bs4 import BeautifulSoup
import json
import re

url = "https://www.walmart.com/ip/Twin-Pack-Kellogg-s-Frosted-Mini-Wheats-Breakfast-Cereal-48-Oz/940504168"
html = urllib.request.urlopen(url).read()
soup = BeautifulSoup(html, "html.parser")

for script in soup.find_all('script'):
    if '_setReduxState' in script.text:
        re_json = re.search('__WML_REDUX_INITIAL_STATE__ = ({.*\});}', script.text)
        data = json.loads(re_json.group(1))
        product_id = data['product']['midasContext']['productId']
        print(data['product']['idmlMap'][product_id]['modules']['NutritionFacts'])

This will give you data holding a very deep JSON structure containing all of the information you probably want. I suggest printing data to see all the information you have available.
For example data['product']['idmlMap'][product_id]['modules']['NutritionFacts'] gives you all the nutrition information, but you will probably need to be a bit more specific to get the exact information you want.
Some of the elements in this structure contain the HTML used on the page, so you might then need to further parse some of these to extract the bits you want.


text:
Q: Using jquery to hide dynamically added divs The jquery code below will hide divs ending with -value-wrapper when the page loads.  My issue is, that the "Add more values" button will append another row (with the number incremented).  When it does, all the divs are revealed.  Is there a way to keep the original ones hidden and hide those in the new set as well?
The html markup looks like this:

    <fieldset>
        <legend>Member Information</legend>
        Form label 1

                    <input type="radio" class="form-radio" checked="checked" value="0" name="gci[0][fa][value]" id="edit-gci-value-0"> A
                    <input type="radio" class="form-radio" value="1" name="gci[0][fa][value]" id="edit-gci-value-0">B

                    List:
                    <textarea name="gci[0][fa_list][value]" rows="5" cols="60"></textarea>

            <input type="submit" value="Add more values" id="edit-gci-add-more" name="gci_add_more">

    </fieldset>

The code that does the initial hide is below:
$("#group-information-items div").each(function() {
        $("div[id$='-value-wrapper']").each(function() {
                        $(this).hide();
        });
});

A: First, unless I'm missing something, you can greatly simplify that hiding code:
$("#group-information-items").find("div[id$='-value-wrapper']").hide();

This begs the question, though. Why not set a regular static style so the default condition for any of these divs is hidden? As a practice it makes sense to align the default styles with the default logical state of your page elements. So:
div#group-information-items div.form-item { display: none; }

Now all the "new" divs will be hidden. Change your code to show() divs as needed (You haven't shown enough to know how, where, and when you'd do this). If you're looking to attach behaviors to elements created after the initial page load, you should take a look at live() or delegate().

A: try hiding the divs on the click of the input button:
  $("#edit-gci-add-more").click(function() {
             $("div[id$='-value-wrapper']").hide();
  });


text:
Q: Listen to pushed data in Blackberry app without help of BES How can I listen to data pushed by the server using http connection ? I dont want to use BES server.
How this can be achieved?
My Blackberry Os version is 4.5.

A: If you mean pushed in the sense of MDS Push data, the only way to do that is from an MDS server which means either a BES or using RIM's BIS with Web Signals. Otherwise I think you need more specifics.


text:
Q: Generating customized vector OSM map files from OpenStreetMap and other data? I am looking for a way (e.g. tutorial?) to generate my own customized (offline) maps in OSM format. By "customized" I mean adding data (not just define a region of interest) to an existing OSM map (e.g. OpenTopoMap), then export the augmented map into a new .osm-file.
What I managed to do:

*

*load OSM maps (e.g. OpenTopoMap) in QGIS, download the canvas into an .osm-file and convert it to a sqlite db, and import points, polygons, polylines

*load other data into QGIS (e.g. manually generated (vector) points)

*export the canvas to tiles using QTiles either to a directory or to a .mbtiles-file. However, this is the critical point: this export is way too large and the resolution of the tiles is bad, so I am looking to export the canvas in the vectorized form

How can I augment maps in OSM format with own data and store it as a new (vector) .osm-file?
Preferably in QGIS, other programs are fine as long as they are free and run in Linux. The full style e.g. the shading in OpenTopoMap and the elevation curves should be preserved.

A: Given your response to my comment, you could try FME.
NB: I work for the people who make FME
It's free for non-commercial use. Anyway, here's what it would look like if I added extra emergency data to an OSM layer:

After installing (yes there is a Linux version)...

*

*Start Workbench. Press Ctrl+G to set up an OSM to OSM translation

*In the translation, press Ctrl+Alt+R to add a reader to read the additional data

*Just map the additional data into the OSM output layers

There's probably more work to it than that, depending on how you want to map the data/attributes, and what OSM layers allow which geometries. I know a little about OSM data structures but am not expert. Still I can get data into an OSM file in some form fairly easily. I think it's a good starting point, and there are other supported formats that may be of use too.


text:
Q: Decimais sem arredondar em javascript Como faria para conseguir o seguinte resultado.
quero diminuir um numero de casas decimais após a virgula sem que o numero arredonde ?
ex: 5,8608 --> 5,860
já testei diversas funções e formas mas todas sobem o numero para 5,861.
Desde já agradeço quem puder contribuir.

A: Multiplica os números que queres pela ordem de grandeza igual ao número de casas decimais. Depois tiras a parte decimal e divides de novo pela mesma ordem de grandeza. Algo assim:

function ajuste(nr, casas) {
  const og = Math.pow(10, casas)
  return Math.trunc(nr * og) / og;
}

console.log(ajuste(3.456, 2)); // 3.45
console.log(ajuste(4.123, 2)); // 4.12
console.log(ajuste(-4.123, 2)); // -4.12

EDIT: Editei a resposta para usar Math.trunc em vez de Math.floor

A: Complementando a outra resposta (que antes de ser editada estava usando Math.floor), para funcionar também com números negativos, uma opção é usar Math.trunc em vez de Math.floor:

function ajuste(nr, casas) {
    const og = Math.pow(10, casas);
    return Math.trunc(nr * og) / og;
}

console.log(ajuste(-3.456, 2)); // -3.45
console.log(ajuste(-4.123, 2)); // -4.12

console.log(ajuste(3.456, 2));  //  3.45
console.log(ajuste(4.123, 2));  //  4.12

Também daria para fazer assim:

function ajuste(nr, casas) {
    const sign = Math.sign(nr);
    if (sign === -1)
        nr *= -1;
    const og = Math.pow(10, casas);
    return Math.floor(nr * og) / og * sign;
}

console.log(ajuste(-3.456, 2)); // -3.45
console.log(ajuste(-4.123, 2)); // -4.12

console.log(ajuste(3.456, 2));  //  3.45
console.log(ajuste(4.123, 2));  //  4.12

No caso, usei Math.sign, que retorna 1 para números positivos e -1 para negativos.
Depois, se o número é negativo, ajusto-o para que seja positivo, e no final eu multiplico pelo sign (assim, caso seja -1, o resultado volta a ser negativo).

Por fim, outra opção é usar Math.floor ou Math.ceil dependendo do sinal do número:

function ajuste(nr, casas) {
    const og = Math.pow(10, casas);
    return (nr > 0 ? Math.floor(nr * og) : Math.ceil(nr * og)) / og;
}

console.log(ajuste(-3.456, 2)); // -3.45
console.log(ajuste(-4.123, 2)); // -4.12

console.log(ajuste(3.456, 2));  //  3.45
console.log(ajuste(4.123, 2));  //  4.12

A: let nteste=5.8608
console.log(nteste.toFixed(3))  //dessa maneira arredonda para 5.861
let numero=5.8608
let numero2=numero*1000  // como nesse caso tu quer 5.860 então é preciso guardar na variavel numero2 todos esses algarismos multiplicando por 1000
numero2=parseInt(numero2)/1000  // o parseInt é necessário para que apenas a parte inteira seja dividida por 1000
console.log(numero2.toFixed(3)) // estou fixando 3 casas decimais


text:
Q: How to complete for loop with pdfplumber? Problem
I was following this tutorial https://www.youtube.com/watch?v=eTz3VZmNPSE&list=PLxEus0qxF0wciRWRHIRck51EJRiQyiwZT&index=16
when the code has returned my this error.
Goal
I need to scrape a pdf that looks like this (I wanted to attach the pdf but I do not know how):
170001WO01
English (US) into Arabic (DZ)
Trans./Edit/Proof. 22.117,00 Words 1,350 29.857,95
TM - Fuzzy Match 2.941,00 Words 0,500 1.470,50
TM - Exact Match 353,00 Words 0,100 35,30

Approach
I am following the tutorial aforementioned with pdfplumber.
import re
import pdfplumber
import PyPDF2
import pandas as pd
from collections import namedtuple
ap = open('test.pdf', 'rb')

I name the column of the dataframe that I want as a final product.
Serv = namedtuple('Serv', 'case_number language num_trans num_fuzzy num_exact')

Issues
I have 5 different lines compared to the tutorial example which has 2.
case_li = re.compile(r'(\d{6}\w{2}\d{2})')
language_li = re.compile(r'(nglish \(US\) into )(.*)')
trans_li = re.compile(r'(Trans./Edit/Proof.              )(\d{2}\.\d{3})')
fuzzy_li = re.compile(r'(TM - Fuzzy Match                )(\d{1}\.\d{3})')
exact_li = re.compile(r'(M - Exact Match                )(\d{3})')

Issue
When I introduce the third line in the code, I got an error which I do not know. I have modified the code as 2e0byo suggested but I still get an error.
This is the new code:
line_items = []
with pdfplumber.open(ap) as pdf:
    page = pdf.pages
    for page in pdf.pages:
        text = page.extract_text()
        for line in text.split('\n'):

            line = case_li.search(line)
            if line:
                case_number = line

            line = language_li.search(line)
            if line:
                language = line.group(2)

            line = trans_li.search(line)
            if line:
                num_trans = line.group(2)

            line = fuzzy_li.search(line)
            if line:
                num_fuzzy = line.group(2)

            line = exact_li.search(line)
            if line:
                num_exact = line.group(2)

            line_items.append(Serv(case_number, language, num_trans, num_fuzzy, num_exact))```
---------------------------------------------------------------------------

and this is the new error:
TypeError                                 Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_13992/1572426536.py in <module>
     10                 case_number = line
     11
---> 12             line = language_li.search(line)
     13             if line:
     14                 language = line.group(2)

TypeError: expected string or bytes-like object
TypeError: expected string or bytes-like object

# GOAL
It would be to append the lines to line_items and eventually

df = pd.DataFrame(line_items)

A: You have reassigned line, here:
for line in text.split("\n"):
    # line is a str (the line)
    line = language_li.search(line)
    # line is no longer a str, but the result of a re.search

so line is no longer the text line, but the result of that match.  Thus trans_li.search(line) is not searching the line you thought it was.
To fix your code, adopt a consistent pattern:
for line in text.split("\n"):
    match = language_li.search(line)
    # line is still a str (the line)
    # match is the result of re.search
    if match:
        do_something(match.groups())
        ...

    # line is *still* a str

match = trans_li.search(line):
if match:
    ...

For completeness' sake, with the dreaded walrus operator you can now write this:
if match := language_li.search(line) is not None:
    do_something(match.groups())

Which I briefly thought was neater, but now think ugly. I fully expect to get downvoted just for mentioning the walrus operator.  (If you look at the edit history of this post you will see that I have even forgotten how to use it and wrote it backwards first.)
PS: you may wish to read up on variable scope in python, although no language I know would allow this particular scope collision (overwriting a loop variable within the loop).  Incidentally doing this kind of thing by mistake is why conventionally we avoid similarly-named variables (like line and Line) and go with things like line and match instead.


text:
Q: .Net making of setup including solution,.net framework, crystal reports 2010, is it possible? I wana made a setup or MSI Installer in .Net 4, which should install my C# project plus .Net framework 4 and crystal reports 2010 viewer. Right now, i have MSI Installer for my solution only and the two things are installed separately. But i want just one installer.
Please let me know any tutorial or best free solution.
Thanks
Atif

A: Visual Studio lets you to make a simple setups, for example Sql Server needs very advance configuration like specifying instance name, SA user's password and so on ... doing this things in visual studio is impossible, yes you can chose to install them but you have to write some code to configure them in application start up.
You may find something here
Hope this help.


text:
Q: FxCop custom rule for nested If I am trying to get following metrics report for .Net assemblies
1. Boolean expression
2. Nested If
3. Method Parameters
3. Nested try
4. Missing switch default
5. Class fan-out complexity
Basically, I want to generate toxicity report for these complexities. I see that Sonar could generate same for java applications. But I don't see anything available with .Net using FxCop or nDepend. I tried creating custom rules, but not able to get it done with any of tool.
Is it possible to create custom rules with FxCop and get analysis report, and then create complexity measure from it?
I have generated nested try rule with FxCop. But nested If seems difficult, because IL generate lot of goto statements which makes difficult to identify if "If" statements are nested or parallel placed. Same with Boolean complexity because of stack push-pop operations.
I think sonar make use of checkstyle for java to generate these reports. Is it source code based analyser? or also works with IL? Do I need to work with styleCop to get it worked?
Any help will be appreciated.

A: Have you seen that NDepend supports the code metric IL Nesting Depth. While it doesn't distinguishes between causes of the depth (if, goto, switch/case, loop...) it is computed from the IL and is pretty accurate in most situations.


text:
Q: Why does Dask seem to store Parquet inefficiently When I save the same table using Pandas and Dask into Parquet, Pandas creates a 4k file, wheres Dask creates a 39M file.
Create the dataframe
import pandas as pd
import pyarrow as pa
import pyarrow.parquet as pq
import dask.dataframe as dd

n = int(1e7)
df = pd.DataFrame({'col': ['a'*64]*n})

Save it in different ways
# Pandas: 4k
df.to_parquet('example-pandas.parquet')

# PyArrow: 4k
pq.write_table(pa.Table.from_pandas(df), 'example-pyarrow.parquet')

# Dask: 39M
dd.from_pandas(df, npartitions=1).to_parquet('example-dask.parquet', compression='snappy')

At first I thought that Dask doesn't utilize dictionary and run-length encoding, but that does not seem to be the case. I am not sure if I'm interpreting the metadata info correctly, but at the very least, it seems to be exactly the same:
>>> pq.read_metadata('example-pandas.parquet').row_group(0).column(0)
<pyarrow._parquet.ColumnChunkMetaData object at 0x7fbee7d1a770>
  file_offset: 548
  file_path:
  physical_type: BYTE_ARRAY
  num_values: 10000000
  path_in_schema: col
  is_stats_set: True
  statistics:
    <pyarrow._parquet.Statistics object at 0x7fbee7d2cc70>
      has_min_max: True
      min: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
      max: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
      null_count: 0
      distinct_count: 0
      num_values: 10000000
      physical_type: BYTE_ARRAY
      logical_type: String
      converted_type (legacy): UTF8
  compression: SNAPPY
  encodings: ('PLAIN_DICTIONARY', 'PLAIN', 'RLE')
  has_dictionary_page: True
  dictionary_page_offset: 4
  data_page_offset: 29
  total_compressed_size: 544
  total_uncompressed_size: 596

>>> pq.read_metadata('example-dask.parquet/part.0.parquet').row_group(0).column(0)
<pyarrow._parquet.ColumnChunkMetaData object at 0x7fbee7d3d180>
  file_offset: 548
  file_path:
  physical_type: BYTE_ARRAY
  num_values: 10000000
  path_in_schema: col
  is_stats_set: True
  statistics:
    <pyarrow._parquet.Statistics object at 0x7fbee7d3d1d0>
      has_min_max: True
      min: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
      max: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
      null_count: 0
      distinct_count: 0
      num_values: 10000000
      physical_type: BYTE_ARRAY
      logical_type: String
      converted_type (legacy): UTF8
  compression: SNAPPY
  encodings: ('PLAIN_DICTIONARY', 'PLAIN', 'RLE')
  has_dictionary_page: True
  dictionary_page_offset: 4
  data_page_offset: 29
  total_compressed_size: 544
  total_uncompressed_size: 596

Why is Dask-create Parquet so much larger? Alternatively, how can I inspect the possible problems further?

A: Dask appears to be saving an int64 index...
>>> meta.row_group(0).column(1)
<pyarrow._parquet.ColumnChunkMetaData object at 0x7fa41e1babd0>
  file_offset: 40308181
  file_path:
  physical_type: INT64
  num_values: 10000000
  path_in_schema: __null_dask_index__
  is_stats_set: True
  statistics:
    <pyarrow._parquet.Statistics object at 0x7fa41e1badb0>
      has_min_max: True
      min: 0
      max: 9999999
      null_count: 0
      distinct_count: 0
      num_values: 10000000
      physical_type: INT64
      logical_type: None
      converted_type (legacy): NONE
  compression: SNAPPY
  encodings: ('PLAIN_DICTIONARY', 'PLAIN', 'RLE', 'PLAIN')
  has_dictionary_page: True
  dictionary_page_offset: 736
  data_page_offset: 525333
  total_compressed_size: 40307445
  total_uncompressed_size: 80284661

You can disable this with write_index:
dd.from_pandas(df, npartitions=1).to_parquet('example-dask.parquet', compression='snappy', write_index=False)

Pyarrow won't generate any indices.
Pandas does generate an index but, at least when using the arrow engine, simple linear indices will be saved as metadata and not an actual column.
>>> table = pq.read_table('example-pandas.parquet')
>>> pandas_meta = json.loads(table.schema.metadata[b'pandas'])
>>> pandas_meta['index_columns'][0]
{'kind': 'range', 'name': None, 'start': 0, 'stop': 10000000, 'step': 1}


text:
Q: Dropping database in by passing values in url I need to drop the database by passing the values of a and b in the giving below code
I have set the value of a as 5 for first level testing and b to give the database name
i.e., index.php?a=5&b=test
<?php
include ('config.php');
$a=$_GET["a"];
$b=$_GET["b"];
if ($a==5)
{
$sql = 'drop database'.'$db';
if (mysql_query($sql))
{
    echo "Database test was successfully dropped\n";
}
else
{
    echo 'Error dropping database: ' . mysql_error() . "\n";
}
}
{
    echo "Not Success";
}
?>

I am getting the Error
Error dropping database: 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 'databasee$db' at line 1 Not Success

I know that i can't drop the database by mysql query in php
Error Dropping Database (Can't rmdir '.test\', errno: 17)
The error is by contatinating the database name in the code
$sql='drop database'.'$b';

How can i do this ?

A: You forgot to add a space .. Also the variables under single quotes will not be parsed.
The proper way to do...
$sql = "drop database ".$db;
                     ^------ Here

A:    <?php
        //connect to the database and authenticate the user
        include ('config.php');
        $a=$_GET["a"];
        $b=$_GET["b"];
        if ($a==5)
        {
           $sql = 'drop database '."$b";
           if (mysqli_query($sql))
           {
              echo "Database test was successfully dropped\n";
           }
           else
           {
              echo 'Error dropping database: ' . mysql_error() . "\n";
              echo "Not Success";
           }//End if/else error dropping database
        }//End if $a==5
   ?>

*

*Database name should be in double quote marks or no quotes at all. Eg. "$b". Single quotes will make it  literally $b and not the value $b  actually represents.

*Missing a space after the words 'drop database', it should be 'drop database '

*it's not very secure to allow someone to delete a database without being authenticated first, especially using an http get where they can specify the name of any database to delete. I'm going so assume that is handled by config.php. Make sure you assign database users the correct permission

*mysql_query is deprecated and will not work with newer versions of php. You should be using mysqli for any mysql queries. Mysql 5.6 end of lifes quite soon. See link below for dates. You can get the version of php running on your server using the line phpinfo(); in your code. If it under 7.x you should consider planning an upgrade path*

*To avoid using if statements within if statements you could consider using case/switch statements.
http://php.net/supported-versions.php
*upgrading to later versions of php can break applications that were written for 5.6 and below.

A: You have skipped else and started { echo "Not Success"; };


text:
Q: Multi Desktop with Ubuntu 10.04 and the Catalyst Control Center I have Ubuntu 10.04 installed on my laptop, with an ATI Mobility Radeon HD 3670. I would like to connect this to an external monitor and use multiple desktops, as opposed to a single extended desktop.
I have tried selecting "Display Manager -> Multi Display -> Single display desktop (Multi-desktop)" and rebooting. This does give me two desktops, but after I move my mouse from the first desktop to the second desktop I can not move it back, and there appears to be no way to switch between the desktops.
I have read that people suggest enabling "Display Options -> Xinerama" but as far as I understand this would not dynamically adjust the set up depending on whether I have an external desktop connected.
I need a solution that will let me easily transition between one and two desktops as I often transition between using one and two screens (laptop + external monitor).
The "Single display desktop (Multi-desktop)" setting would be appropriate, if only I could figure out how to switch between these desktops.
Some people have mentioned using open source graphics drivers instead - is this likely to solve the problem? I assumed that the propriety drivers would be better.


text:
Q: Keeping an image in view after removed from superview I have extracted some code from the PhotoScroller sample code from Apple to use the CATiledLayer. I have an image of 8000x7000px loaded from internet, in tiles.
This is kind of a map-function in my app. I also have two almost identical images, with different overlays (tried to only add the overlay without luck).
I have an UISegmentedControl to toggle between the three choices, and I want the imageView to load the images from the selected image. So if the user zoomes in on one of the images, and selects another option, then the scale and coordinated stays the same, and the imageView loads the chosen image in the necessary tile-spots.
I have partially managed this. Or, I have actually managed this, but when I select another option, the whole screen goes black when the function [imageView removeFromSuperview]; is called. After being black in a couple of seconds(depending on internet speed) it shows the correct tiles.
I want the layer to "fade" over to the next layer if possible. As you maybe know, when using CATiledLayer, the first layer is the whole image in low resolution, but when zooming in, the necessary tiles "fade" in to the next layer with smaller tiles.
I basically need to give the (TilingView*)imageView a "reload"-command, and want it to "fade" over the last image.
I tried to comment out the [imageView removeFromSuperview];, and that actually got me close to what I want. When I zoomed in, and selected another option, the new image actually faded over the old one, however, when I zoomed back out, the old image was clearly sticking around in the background(behind the new image), not responding to anything. I need to remove it from the superView at a later point, but I have no longer access to it as the new image has taken its place as imageView. I know people might want to see code here, but I have really no idea what code to show.. And the CATiledLayer is SO POORLY documented I am really having a hard time understanding what's going on.

A: I made it work through some sketchy code. There probably are other better solutions, but this is the only one I know of at the moment.
The problem was that when I removed [imageView removeFromSuperview];, it did not unload the last image, thus letting it be in the memory forever. As it was not affected by zooming and scrolling, when I zoomed out, it was always there in the background. If I was to switch between options multiple times, multiple images would add up in the background.
I simply created a "helper" as I call it. A new imageView, which gets the content of the old imageView when switching option, without removing it from the superview just yet, as a premature removal results in black screen when the new image hasn't loaded quite yet.
I now call the [helper removeFromSuperview]; in the delegate methods scrollViewWillBeginZooming AND in scrollViewWillBeginDragging. This results in memory containing at the most two images in the time between clicking the other option, and user scrolls or zoomes.
Note: If the user scrolls or zoomes immediately after switching option in the UISegmentedControl, it turns black because the new image hasn't been loaded yet.


text:
Q: Why not document.write? Why is it generally not considered good practice to use document.write in Javascript? I know it is not the most elegant or best way to do it, but are there any true errors with it? Is it ever ok? And in what case would it be better than inner.HTML
I understand that it will rewrite the document, if used after the loading. However, should I be using innerHTML even if I am trying to rewrite the document? If so, why?
I know some have asked if I even looked at the related questions before posting; I did. But I did not find anything satisfactory.

A: When used correctly, it's fine, but of very limited use.
You can't use it in XHTML, but I would recommend not using XHTML anyway unless you have a really, really good reason to.
The problem comes when you call document.write after the initial page load is complete. During page load is fine, but afterward, it causes an implicit document.open, which clears the document from the window and starts fresh.
Using document.write also means you can't demand-load your scripts or use the async or defer attributes on your script elements.
Finally, I usually recommend putting your JavaScript in a separate (single) JavaScript file at the very end of the document (just before the closing </body> tag). If you want to use document.write to output to the page, you'd have to include that script file higher up or use code directly within the HTML, neither both of which I recommend against.
So since it's of such limited use compared with other methods, it's best to get proficient with the other methods.

A: yeah, calling document.write after the document has finished loading will wipe the document. Fire up your console, and do a document.write("test") call. The page will get overwritten with this new content. Except maybe for setting iframe innerHTML in a single step, never use document.write.

A: One reason can be that document.write does not work in XHTML
Also document.write only works while the page is loading; If you call it after the page is done loading, it will overwrite the whole page ie, after your document has been full rendered and closed, using document.write() will clear your current document and start a new one, wiping out all previous content.

A: From the MDN :

Writing to a document that has already loaded without calling
  document.open() will automatically perform a document.open call. Once
  you have finished writing, it is recommended to call document.close(),
  to tell the browser to finish loading the page. The text you write is
  parsed into the document's structure model. In the example above, the
  h1 element becomes a node in the document.

In short : code that must be executed past the initial load (for example in an event handler) can't include a document.write or they trigger a replacement of the whole document.

A: Because it replaces entire document. In 99% of cases you just need to replace content of some specific elements.
document.write does have it uses - for example when you need to write an executable script to a newly created document.

A: As a good pratice, sometimes we have information on the client side and using javascript we write these informations in div and span elements because they are in the right position of the html layout. And as the guys said, document.write does not work with xhtml.


text:
Q: iconv terminated by signal 7 I was running a little bash script on some text files:
find . -name "*.dat" -exec iconv --from-code='UTF-8' --to-code='ASCII//TRANSLIT' {} --output={} \;

My machine is a Ubuntu 14.04 LTS.
After a while, I found that like half of the data in the files disappeared; simply cut off in the middle of a line/word. It is the mysterious signal 7 or core dump (as I heard). The problem is somehow, when the files are too large. Some of my file have >60kB but iconv made them around 30kB.
What can I do about this? Is this a bug? Is there a workaround? Is there any other convenient way to transliterate diacritics?

A: As pointed out in the comments to my question, the problem occurs when two conditions are met:

*

*Source and target file are the same.

*File is larger than 32768 bytes.

There are two solutions: Either cast a temporary file which then automatically replaces the source file, or use recode.
As to the first solution see for example. https://unix.stackexchange.com/a/10243/94483. For sponge, there is a very good question on SO (https://stackoverflow.com/q/64860/362146) and also an answer here: https://unix.stackexchange.com/a/19980/94483
I will now use iconv as recode supports less character sets (and I also failed to make it run):
FILELIST=$(find . -type f -name "*.dat")

for file in $FILELIST
do
  iconv --from-code='UTF-8' --to-code='ASCII//TRANSLIT' "$file" | sponge "$file"
done

sponge does the replacing job. It's from moreutils.


text:
Q: Why is my Promise.all() triggering when my Promise Chain has not been completed I'm trying to work with a Promise.all() function in combination with a for loop where I chained multiple promises. When I have completed the iterations and for each iteration all my promises have been resolved I want the Promise.all() to fire.
Underneath you can find my code. According to what I've read on other fora I try to push my promises to an array which would then be used in the "Promise.all()" function. I would expect my promises to be fulfilled when when I succesfully have done the "createrows" function however the promise.all() is fulfilled even before my creatrows function is executing.
Does anyone have any idea what I might be doing wrong or which misconceptions I have around the promises framework?
    for (i in scheduledRunsObjValue) {

    promisearray.push(
            getpropertiesObject(i,scheduledRunsObjValue).then(
            propertiesObj=>{
                utcDate=propertiesObj['startTime'];
                localDate=new Date(utcDate);
                const trackingid=propertiesObj['correlation']['clientTrackingId'];
                returnhttpinputobjectforworkflow(bearertoken,trackingid).then(HttpInputObject=>{
                    ReturnInputHttpRequestData(HttpInputObject).then(HttpRequestData=>{
                        createrows(HttpRequestData,scheduledRunsHTML,i,localDate,propertiesObj,trackingid,scheduledRunsObj).then(htmldoc=>{
                            scheduledRunsHTML=htmldoc;
                            resolve(scheduledRunsHTML);
                        })

                    })
                })

            })
        );

    }
    Promise.all(promisearray).then(values=>{
        resolve(scheduledRunsHTML);
        })


text:
Q: Is there a chance to lose all your enchantments when enchanting an item? In the first game, there was only one enchanter in the game who could enchant your items as many times as you want if you had the money and were brave enough to chance at losing all your enhancements.  The more you enchant an item, the more likely that he'd screw it up and you lose your enchantments on that item forever.
Fast forward to the next game, you have a limited amount of enchantments that can be applied to an item but you now have the option to remove enchantments for some money.
Is there a chance that attempting to enchant an item now can remove all enchantments on your item?
I've saved up enough money to enchant my best weapons so I will be enchanting as much as I can.  I'd just hate to lose everything.

A: Enchanting is very different from what was found in Torchlight 1.  Enchanting adds magical properties that can also be removed (deliberately) by an enchanter.  But enchanting can no longer wipe an item; that is, enchanting cannot affect existing stats in any way.  The removal mechanic exists so you can spend gold to get an item "just right".


text:
Q: Bookmarklet to simulate button click in a Google service iframe The goal is to add keyboard shortcuts to Google's Google Translator Toolkit. Most functions there have keyboard shortcuts, but these two don't.
The first function is called Merge Down. It fires correctly when this bookmarklet is executed:
javascript:document.evaluate("//div[(@id='gtc-merge-arent')]/div[(@class='modal-dialog
gtc-merge')]/div[(@class='modal-dialog-buttons')]/button[(text()='OK')]",    document, null, XPathResult.FIRST_ORDERED_NODE_TYPE,
null).singleNodeValue.click();

The Apply to All function is trickier. Normally you have to click three times to execute this function:
#1 to click the button that makes visible the Repetitions dialog and sets the parameters: what to replace what with.
#2 to click 'Apply to all' and trigger the actual replacement throughout
#3 to hide the dialog element.
I don't want to mess with Google's internal code, so a normal click as if by mouse would be best.
#2 and #3 fire easily enough: same bookmarklet, with a pause:
javascript:(function(pause) {
document.evaluate("//div[(@id='fnrDialogParent')]/div[(@class='modal-dialog gtc-rep-modal-dialog')]/div[(@class='modal-dialog-buttons')]/button[(text()='Apply to all')]", document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.click();
setTimeout(() => document.evaluate("//div[(@id='fnrDialogParent')]/div[(@class='modal-dialog gtc-rep-modal-dialog')]/div[(@class='modal-dialog-buttons')]/button[(text()='Exit')]", document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.click(), pause)
            })(400);

I can't simulate a click on the Repetitions button, which is supposed to pop up with the two buttons I need to click to finish the job. The button itself is a div with an img inside an iframe. I tried most of the methods I found here for click simulation, the latest being this one, but it doesn't work all the same (the references are taken correctly)
var ifrm = document.querySelectorAll('iframe')[2];

$(ifrm).contents().find('img.jfk-button-img.gtc-img-rep').click();

(The button itself is a div with an img inside. Depending on whether a segment repeats elsewhere or not, the button is either -enabled or -disabled. Here's the HTML code for an enabled button:

A: javascript: (function() {
    const a = f => new MouseEvent(f, { bubbles: !0 }),
        b = f => () => document.querySelector(f).click(),
        c = f => `#fnrDialogParent .gtc-rep-modal-dialog .modal-dialog-buttons button[name=${f}]`,
        d = { imgSel: (f => () => {
                const g = a('mousedown'),
                    h = a('mouseup'),
                    i = document.querySelector(f);
                i.dispatchEvent(g), i.dispatchEvent(h) })('img.jfk-button-img.gtc-img-rep'), applyToAll: b(c('repDialogReplaceAll')), exit: b(c('repDialogExit')) };
    d.imgSel(), d.applyToAll(), d.exit() })();

This is the bookmarklet that answers my question and does the 3 clicks. This answer tipped me off.


text:
Q: Does the integral $\int ^{+\infty}_{0}\frac{x}{1+x^6\sin^2(x)}dx$ + converge? Does the improper integral $$\int ^{+\infty}_{0}\frac{x}{1+x^6\sin^2(x)}dx$$ converge?
Most of the basic methods (substituiton, integration by parts...) probably don't work
What I tried :
Since the function $f(x)= \frac{x}{1+x^6\sin^2(x)}$ is positive the Function $F(t)=\int ^{t}_{0}\frac{x}{1+x^6\sin^2(x)}\,dx$ has a limit when $t$ tends to infinity.
Then \begin{align}
\int ^{n\pi}_{0}\frac{x}{1+x^6\sin^2(x)}dx & = \sum ^{n-1}_{k=0}\int ^{(k+1)\pi}_{k\pi}\frac{x}{1+x^6\sin^2(x)}dx
 \\
 & = \sum ^{n-1}_{k=0}\int ^{\pi}_{0}\frac{u+k\pi}{1+(u+k\pi)^6\sin^2(u)}dx
 \end{align}
This is a trick we usually have improper integrals with $\sin$ or $\cos$.
However now I don't know how to proceed. I tried looking for upper-bounds (to prove that it converges) or lower bounds(to prove that it diverges) but I couldn't.
Thanks

A: First, we need a lemma (proof at end):

Let $f : [0,\infty) \to [0,\infty)$ be any non-negative intergrable function such that for some $c > 0$, $f(x)$ is increasing on $[0,c]$ and decreasing on $[c,\infty)$.  We have
$$\sum_{k=0}^\infty f(k) \le \int_0^\infty f(x) dx + f(c)$$

As a corollary, for such a $f$ and any $a,h > 0$, we have
$$\sum_{k=0}^\infty f(a+kh) \le \frac1h \int_0^\infty f(x) dx + \sup_{x\ge 0} f(x)$$
For any $u \in (0,\pi)$, let $\rho = \sin^2 u$. In above lemma, substitute $a$ by $u$, $h$ by $\pi$ and $f(x)$ by $\frac{x}{1 + x^6\rho}$, we obtain:
$$\begin{align}
\sum_{k=0}^\infty \frac{u+k\pi}{1 + (u+k\pi)^6\sin^2 u}
&\le \frac1\pi \int_0^\infty \frac{x}{1+x^6\rho}dx + \sup_{x\ge 0} \frac{x}{1+x^6\rho}\\
&= \frac{1}{3\sqrt{3}}\rho^{-1/3} + \frac{5^{5/6}}{6} \rho^{-1/6}
\end{align}$$
As a function of $u$, RHS is singular at $u \sim 0$ and $u \sim \pi$.
The leading divergences are

*

*$\frac{1}{3\sqrt{3}} u^{-2/3}$ for $u \sim 0$.

*$\frac{1}{3\sqrt{3}} (\pi - u)^{-2/3}$ for $u \sim \pi$.

This sort of singularities are tame enough and RHS is Lebesgue intergrable over $[0,\pi]$. Let
$$\mathcal{I}(t) = \int_0^t \frac{xdx}{1+x^6\sin^2 x}
\quad\text{ and }\quad
\varphi_n(u) = \sum_{k=0}^{n-1} \frac{u+k\pi}{1+(u+k\pi)^6\sin^2u}$$
Since $\varphi_n(u)$ is a sum of non-negative functions
whose pointwise limit $\varphi_{\infty}(u) \stackrel{def}{=} \lim\limits_{n\to\infty}\varphi_n(u)$ is bounded from above by a Lebesgue  intergrable function. By DCT, $\varphi_\infty(u)$ is also Lebesgue intergrable over $[0,\pi]$.
Translate this to the Riemann definite integral $\mathcal{I}(t)$, we have
$$\lim_{n\to\infty}\mathcal{I}(n\pi) = \lim_{n\to\infty}\int_0^\pi \varphi_n(u) du$$
exist and equal to the Lebesgue integral $\int\limits_0^\pi \varphi_\infty(u) du$.
Since $\mathcal{I}(t)$ is an increasing function in $t$. The existence of limit for $t \in \{ \pi, 2\pi, \ldots \}$ implies $\lim\limits_{t\to \infty}\mathcal{I}(t)$ also exists and converges to same limit. In other words, the Riemann improper integral
$$\int_0^\infty \frac{xdx}{1 + x^6\sin^2 x}$$
converges.

Proof of Lemma
Let $N = \lfloor c \rfloor$.

*

*$f(x)$ is increasing on $[0,N]\implies \sum\limits_{k=0}^{N-1} f(k) \le \int_0^N f(x)dx$

*$f(x)$ is decreasing on $[N+1,\infty) \implies
\sum\limits_{k=N+2}^\infty f(k) \le \int_{N+1}^\infty f(x)dx$

*$f(x) \ge \begin{cases}f(N), & x \in [N,c]\\ f(N+1), & x \in [c,N+1]\end{cases}$ $\implies \min(f(N),f(N+1)) \le \int\limits_N^{N+1} f(x)dx$

*By definition of $c$, $\max(f(N),f(N+1)) \le f(c)$.

Combine all these, our lemma follows.


text:
Q: Sqlite loop through all tables I'm using swift 3 and I'd like to be able to loop through all the tables in my sqlite database. Is there an easy function to do this? I just want to retrieve the table names.

A: In sqlite database schema is sqlite_master  table. It contains name of all the schema (table, Indexes, Views, etc).
to see a list of the tables in the SQLLite database,  Command is ".tables".
and equivalent SQlite  query to get all table names is :
select name   from sqlite_master where type='table'

You can use SQL wrapper class for swift 3.0 to execute above query and fetch result.


text:
Q: Restart an Activity I'm currently working on a Wear application, I display a ListView on an Activity (let's call it ActA). When the user clicks on an item, it triggers different actions on the handheld, and sends a result back to an activity on the watch (ActB). I want to update the list with this result (I need to go through the ActB for future features).
My problem is that I want to resume my ActA from ActB without restarting it. I tried using startActivityForResult before finding out that there's an issue with this on Wear. So I tried to use the flag FLAG_ACTIVITY_REORDER_TO_FRONT, but the stack isn't modified. I don't have any error, nothing, just my ActB displayed and doing nothing.
Does anyone has an idea or any information about a different activity stack on Wear ?
EDIT
Forgot to say that when using FLAG_ACTIVITY_REORDER_TO_FRONT, finish() which is called just below isn't executed.


text:
Q: How to add a security group to a VM via the nova-client I'm trying to use the OpenStack Nova client and create a script in order to launch an instance.  I was able to create a VM with a specific key but the problem is that i can't add an existing security group to that instance.
I know how to create a security group and add some rules to it using the nova client.
Thank you in advance

A: After launching an instance you can add a security group to it using the CLI
nova add-secgroup my-special-server sec-group-3

See the help for more info
nova help add-secgroup
usage: nova add-secgroup <server> <secgroup>

Add a Security Group to a server.

Positional arguments:
  <server>    Name or ID of server.
  <secgroup>  Name or ID of Security Group.

Personally I would add the security group during the boot of an instance using the --security-groups like below
nova boot --image cirros-0.3.1-x86_64-uec --flavor m1.tiny --security-groups my-sec-group


text:
Q: Player disappears when it collides with a tagged object I am working on a simple game where the goal is to help a Player catch specific objects with a tag "Present".
After taking care of the models, animations I am now working on the collisions and counting UI.
For the collisions, on my Player Controller (I am using the ThirdPersonUserController from the player Unity Standard Assets - which simplified the whole animation process), I added the following functions:
void OnCollisionEnter(Collision other)
{
    if (other.gameObject.tag == "Present")
    {
        Destroy(gameObject);
        count = count - 1;
        SetCountText();
    }
}

void SetCountText()
{
    countText.text = "Count: " + count.ToString();
    if (count == 0)
    {
        winText.text = "Thanks to you the Christmas will be memorable!";
    }
}

However, like this, when the Player hits an object with the tag "Present", even though the counting is working properly, the player disappears.
I have tried to change the OnCollisionEnter to an OnTriggerEnter, like this:
void OnTriggerEnter(Collider other)
{
    if (other.gameObject.CompareTag("Present"))
    {
        Destroy(gameObject);
        count = count - 1;
        SetCountText();
    }
}

However when the Player hits the objects with the tag "Present", they don't disappear.
My Player has a Capsule Collider and a Rigidbody.
The objects with the tag "Present" have a Box Collider and a Rigidbody.
Any guidance on how to make my Player stay in scene while removing the other objetcs and reducing the count is appreciated.

A: Few things. You are destroying the incorrect game object:
void OnCollisionEnter(Collision other)
    {
        if (other.gameObject.tag == "Present")
        {
            Destroy(gameObject); // this is destroying the current gameobject i.e. the player
            count = count - 1;
            SetCountText();
        }
    }

Update to:
void OnCollisionEnter(Collision other)
    {
        if (other.gameObject.CompareTag("Present"))
        {
            Destroy(other.gameObject); // this is destroying the other gameobject
            count = count - 1;
            SetCountText();
        }
    }

Always use CompareTag() which is optimized for performance.
Setting the Collider IsTrigger property will then make use of the OnTriggerEnter events and not the OnCollisionEnter anymore.

On the first physics update where the collision is detected, the
OnCollisionEnter function is called. During updates where contact is
maintained, OnCollisionStay is called and finally, OnCollisionExit
indicates that contact has been broken. Trigger colliders call the
analogous OnTriggerEnter, OnTriggerStay and OnTriggerExit functions.

See the docs

A: Your present object is using a non-trigger collider, so you should use OnCollisionEnter. The CompareTag call you tried in OnTriggerEnter is preferable. You should use that.
Also, you are currently trying to destroy the gameobject that the ThirdPersonUserController is attached to (gameObject). Instead, destroy the gameobject of the colliding collider (other.gameObject) with Destroy(other.gameObject);:
void OnCollisionEnter(Collision other)
{
    if (other.gameObject.CompareTag("Present"))
    {
        Destroy(other.gameObject);
        count = count - 1;
        SetCountText();
    }
}


text:
Q: Как сделать проверку наличия интернета на основе QNetworkAccessManager или что пошло не так? Есть код:
MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    // Check internet connection
    QNetworkAccessManager nam;
    QNetworkRequest req(QUrl("https://translate.yandex.ru"));
    QNetworkReply *reply = nam.get(req);
    QEventLoop loop;
    QObject::connect(reply, SIGNAL(readyRead()), &loop, SLOT(quit()));
    QObject::connect(reply, SIGNAL(finished()), &loop, SLOT(quit()));
    if(!reply->isFinished())
    loop.exec();
    if(reply->bytesAvailable())
    qDebug() << "You are connected to the internet :)"; else qDebug() << "You are not connected to the internet :(";
}

Вылетает ошибка:

D:\DWAKU2\DWAKU2\mainwindow.cpp:37: ошибка: no matching member
function for call to 'connect'

Скрин:

Код заголовочного файла:
#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>
#include <QDebug>
#include <QNetworkAccessManager>
#include <QObject>

QT_BEGIN_NAMESPACE
namespace Ui { class MainWindow; }
QT_END_NAMESPACE

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    MainWindow(QWidget *parent = nullptr);
    ~MainWindow();

private slots:
    void SettingsLabelPressed();

private:
    Ui::MainWindow *ui;
};
#endif // MAINWINDOW_H

Код PRO файла:
QT       += core gui
QT       += network

greaterThan(QT_MAJOR_VERSION, 4): QT += widgets

CONFIG += c++11

# You can make your code fail to compile if it uses deprecated APIs.
# In order to do so, uncomment the following line.
#DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000    # disables all the APIs deprecated before Qt 6.0.0

SOURCES += \
    bglabelclass.cpp \
    closelabelclass.cpp \
    main.cpp \
    mainwindow.cpp \
    settingslabelclass.cpp

HEADERS += \
    bglabelclass.hpp \
    closelabelclass.hpp \
    mainwindow.h \
    settingslabelclass.hpp

FORMS += \
    mainwindow.ui

# Default rules for deployment.
qnx: target.path = /tmp/$${TARGET}/bin
else: unix:!android: target.path = /opt/$${TARGET}/bin
!isEmpty(target.path): INSTALLS += target

RESOURCES += \
    res.qrc

DISTFILES += \
    bg.svg \
    pictures/svg/dynamic/close/main.svg \
    pictures/svg/dynamic/close/on_click.svg \
    pictures/svg/dynamic/close/on_enter.svg \
    pictures/svg/dynamic/loading/3.svg \
    pictures/svg/dynamic/loading/4.svg \
    pictures/svg/dynamic/loading/5.svg \
    pictures/svg/dynamic/loading/6.svg \
    pictures/svg/dynamic/loading/loader.svg \
    pictures/svg/dynamic/loading/main.gif \
    pictures/svg/dynamic/loading/on_click.svg \
    pictures/svg/dynamic/loading/on_enter.svg \
    pictures/svg/dynamic/settings/main.svg \
    pictures/svg/dynamic/settings/on_click.svg \
    pictures/svg/dynamic/settings/on_enter.svg \
    pictures/svg/main/bg.svg \
    pictures/svg/main/logo.svg

Версия Qt: 5.12.2 MinGW x64
В чем ошибка или как правильно проверить доступ к сайту?

A: *

*проверить что все подключено

#include <QNetworkAccessManager>
#include <QNetworkRequest>
#include <QNetworkReply>

*сигнал finished у QNetworkReply отсутствует. это сигнал QNetworkAccessManager. Плюс к этому у него другая сигнатура

*Проверять пожалуй лучше по коду ошибки.

    QNetworkAccessManager nam;
    QNetworkRequest req(QUrl("https://translate.yandex.ru"));
    QNetworkReply *reply = nam.get(req);
    QEventLoop loop;
    QObject::connect(reply, SIGNAL(readyRead()), &loop, SLOT(quit()));
    QObject::connect(&nam, SIGNAL(finished(QNetworkReply*)), &loop, SLOT(quit()));
    if(!reply->isFinished())
    loop.exec();
    if(reply->error()==QNetworkReply::NoError)
    qDebug() << "You are connected to the internet :)"; else qDebug() << "You have an net error:"<<reply->errorString();