text:
Q: Using FileReader causes a compiler error "unhandled exception type FileNotFoundException" Ive read a few threads here that relate the same problem, but the solutions arent working. :/
I use Eclipse, here is my program.
package mypackage;
import java.io.*;

public class myclass {

public static void main(String[] args) {
    //String myfile = "/home/jason/workspace/myproject/src/mypackage/myscript.abc";
    String myfile = "src/mypackage/myscript.abc";
    File file1 = new File(myfile);
    if(file1.exists()) {
        log(myfile + " exists. length : " + myfile.length());
    }
    else{
        log(myfile + " does not exist");
        //System.exit(1);
    }

    //FileReader fr = new FileReader("myscript.abc");//I uncomment this and die inside

    System.out.println("\nAbsPath : " + new File(".").getAbsolutePath());
    System.out.println("\nuser.dir : " + System.getProperty("user.dir"));

}

public static void log(String s){
    System.out.println(s);
}

}
The error I get, no matter what I try, or where I put myscript.abc (its peppered throughout the projects directory now) is this :

Unhandled exception type
  FileNotFoundException myclass.java    /myproject/src/mypackage

Wits end, pulling hairs.

A:
Unhandled exception type FileNotFoundException myclass.java /myproject/src/mypackage

This is a compiler error. Eclipse is telling you that your program does not compile to java byte code (so of course you can't run it). For now, you can fix it by simply declaring that your program may throw this exception. Like so:
public static void main(String[] args) throws FileNotFoundException {

FileNotFoundException is a "checked exception" (google this) which means that the code has to state what the JVM should do if it is encountered. In code, a try-catch block or a throws declaration indicate to the JVM how to handle the exception.
For future reference, please note that the red squiggly underline in Eclipse means there is a compiler error. If you hover the mouse over the problem, Eclipse will usually suggest some very good solutions. In this case, one suggestion would be to "add a throws clause to main".

A: Use the file descriptor that you created and verified before creating the file reader. Also, you will probably run into problems using relative paths. Why is the line with the full path commented out? In any case, here is the code:
if(file1.exists()) {
     log(myfile + " exists. length : " + myfile.length());
     FileReader fr = new FileReader(file1);
}

A: I see that you tried to specify the full path to your file, but failed because of the following mistake:
you haven't declared or tried to catch java.io.FileNotFoundException.
To fix it, you can replace the line
FileReader fr = new FileReader("myscript.abc");

with the code:
try {
    FileReader fr =
    new FileReader("/home/jason/workspace/myproject/src/mypackage/myscript.abc");
} catch (FileNotFoundException ex) {
    Logger.getLogger(myclass.class.getName()).log(Level.SEVERE, null, ex);
}

The following code is successfully compiled, and it should work:
package mypackage;
import java.io.*;
// It's better to use Camel style name for class name, for example: MyClass.
// In such a way it'll be easier to distinguish class name from variable name.
// This is common practice in Java.
public class myclass {

    public static void main(String[] args) {
        String myfile =
            "/home/jason/workspace/myproject/src/mypackage/myscript.abc";

        File file1 = new File(myfile);
        if (file1.exists()) {
            log("File " + myfile + " exists. length : " + myfile.length());
        } else {
            log("File " + myfile + " does not exist!");
        }

        try {
            FileReader fr = new FileReader(myfile);
        } catch (FileNotFoundException ex) {
            // Do something with mistake or ignore
            ex.printStackTrace();
        }

        log("\nAbsPath : " + new File(".").getAbsolutePath());
        log("\nuser.dir : " + System.getProperty("user.dir"));
    }

    public static void log(String s) {
        System.out.println(s);
    }
}

A: This is a compiler error. Eclipse is telling you that your program does not compile to java byte code (so of course you can't run it). For now, you can fix it by simply declaring that your program may throw this exception. Like so:
public static void main(String[] args) throws IOException{
}

A: You are expecting Eclipse to run the program in the project root directory.  Unless you did something special with your "Run" configuration, I'd be suprised if it really starts there.
Try printing out your current working directory to make sure this is the right path.
Then try verifying that the bin / build directory contains your "*.abc" files, as they are not Java source files and may have not been copied into the compilation output directory.
Assuming that they are in the compliation directory, rewrite your file loader to use a relative path based on the class laoder's path.  This will work well in exanded collections of .class files in directories (and later in packed JAR files).

A: Instead of trying to figure out what's going on, why not print what's going on...
Make this change to your code:
log(myfile.getName() + "(full path=" + myfile.getAbsolutePath() + ") does not exist");

You might find it either isn't using the directory you think, or (depending on your filesystem) it might be trying to create a file whose name is literally "src/mypackage/myscript.abc" - ie a filename with embedded slashes.

A: you can fix it  simply declaring that  throw this exception. Like this:

public static void main(String args[]) throws FileNotFoundException{

        FileReader reader=new FileReader("db.properties");

        Properties p=new Properties();
        p.load(reader);
    }


text:
Q: How do I solve a "dyld: Library not loaded:" error in Xcode 4 unit tests? I have an Xcode 4 project, a Cocoa application with Spotlight, Core Data and unit tests. The app uses a custom framework named TBPluginManager I wrote to load bundles. I originally wrote the framework in Xcode 3 but when I used it in Xcode 4 GDB kept complaining, so I recreated the framework in Xcode 4. This made GDB happy, until I tried to run the built-in unit-test and got:

[Switching to process 3840 thread 0x0]
  dyld: Library not loaded: > Library/Frameworks/TBPluginManager.framework/Versions/A/TBPluginManager
    Referenced from: /Users/elise/Library/Developer/Xcode/DerivedData/BookManager-cooglmktssmptpatjuetculukiqd/Build/Products/Release/BookManager.app/Contents/MacOS/BookManager
Reason: image not found
  sharedlibrary apply-load-rules all
  No memory available to program now: unsafe to call malloc

Now I can understand why the unit test cannot find the framework since it lives not at Library/Frameworks/TBPluginManager.framework but at /Library/Frameworks/TBPluginManager.framework. But how do I tell that to the unit-test bundle? I've tried setting the Framework, Header and Library Search path build setting, but to no avail.
BTW, I've gone back to GHUnit but I'd like to get this working as well.
FOLLOW-UP: Much as it bugs me that Grady Player got an account just to tell me that I'm an idiot, it just may be that he or she is right. My lovely, dependable framework is generating warnings and errors like they're going out of fashion and so I've turned the problem over to Apple Developer Technical Support. If anything interesting comes out of it, I'll post it here. Otherwise, I'll delete the question.

A: make sure that the framework installed at /Library/Frameworks/TBPluginManager.framework is valid and the same arch as you are trying to link it to. If you are in doubt recompile the framework again, put it in a custom location and set that custom location in your framework search path.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to change a Path in DataContext in Element? I have a
<Grid DataContext="{Binding Path=ListOFFighters[0],
                            Mode=TwoWay,
                            UpdateSourceTrigger=PropertyChanged}">
</Grid>

How can I change the index 0 in my Path? Perhaps I can do it with converter, but I have no idea how bind it to my DataContext Path.

A: You can create a multi-value converter that takes an array or list as well as an index.
public class IndexedBindingConverter : IMultiValueConverter
{
   public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
   {
      return values.Length < 2 || !(values[0] is IList list) || !(values[1] is int index) ? Binding.DoNothing : list[index];
   }

   public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
   {
      throw new InvalidOperationException();
   }
}

The converter expects the first parameter to implement the IList interface in order to have indexed access (arrays and common list types support this). The second parameter is the index. You have to create an instance of the converter in any resource dictionary in scope, e.g.:
<Window.Resources>
   <local:IndexedBindingConverter x:Key="IndexedBindingConverter"/>
</Window.Resources>

Finally, use the converter in a MultiBinding that binds the list and index.
<Grid>
   <Grid.DataContext>
      <MultiBinding Converter="{StaticResource IndexedBindingConverter}">
         <Binding Path="ListOFFighters"/>
         <Binding Path="YourIndex"/>
      </MultiBinding>
   </Grid.DataContext>
   <!-- ...your markup. -->
</Grid>


text:
Q: how do I go to next iteration of a for loop in R? I am trying to read CSV files with different names.
In my for loop, with different values of i, it checks for the file and import the file. There are some values of i, which is not associated with any file name.
Here, my question is how do I go to next iteration?
Thank you in advance!
for (i in 17:23)
{
  path= file.path(paste0("2017-02-23 ", i, "_00_00/Registrations.csv"))
  if(!file.exists(path))
  data= read.table(path, header = F,    sep=",")
  datalist= list(data)
  else print(NA)
}

> for (i in 17:23)
+ {
+   path= file.path(paste0("2017-02-23 ", i, "_00_00/Registrations.csv"))
+   if(!file.exists(path))
+   data= read.table(path, header = F,  sep=",")
+   datalist= list(data)
+ }
Error in file(file, "rt") : cannot open the connection
In addition: Warning message:
In file(file, "rt") :
  cannot open file '2017-02-23 19_00_00/Registrations.csv': No such file or directory

A: You could use next:
datalist = list()
for (i in 17:23) {
  file = paste0("2017-02-23 ", i, "_00_00/Registrations.csv")
  path = file.path(file)
  if(!file.exists(path)) {
     next
  }
  data = read.table(path, header = F, sep = ",")
  datalist[[file]] = data
}

I have

*

*used next to skip iterations where the file doesn't exist

*initialized the list and added files by name to the list

*gotten rid of the useless print(NA) line.

But this does the same thing more efficiently (and I would say, more clearly):
paths = file.path(paste0("2017-02-23 ", 17:23, "_00_00/Registrations.csv"))
extant_paths = paths[file.exists(paths)]
datalist = lapply(extant_paths, read.table, header = FALSE, sep = ",")

paste, file.path, and file.exists are all vectorized, so it will be easier and faster to use those all at once. The only operation that needs to be in the loop is read.csv. Here we use lapply as a convenient syntax instead of a for loop - it saves us needing to initialize the list and assign elements to it manually.


text:
Q: Is there a distro of Linux without GUI? What do hosting companies install? I believe OS GUI takes some machine resources and is not really needed for a web server.
What OS do people install to make a Linux-based web server without GUI?

A: Ubuntu server is fairly common I think.

A: We've been using CentOS for our SaaS app for a long time. Just configure the install to not include any GUI (X)
You can fully automate the install starting from a simple kickstart approach, to a full PXE setup.
BTW, the advantage of CentOS, is that it will be supported for a longer time than other distros. I think 7 years at the moment.

A: The distributions I most often encounter are:

*

*Debian

*Ubuntu Server

*CentOS

And Fedora.
All of them come with a CLI only setup for server use AFAIK.

A: Ubuntu server only has CLI.
Most other distributions offer a server or headless install.

A: I think most Linux servers operate in runlevel 3, which doesn't run a GUI.  As part of the install process, just don't install X and you should be all set.  I'm not sure what will happen if you try to switch to runlevel 5 (normal windowing system on most systems) on a system that doesn't have a GUI... it may just act like runlevel 3.
I've used SuSE, RedHat, Fedora, CentOS, and Ubuntu for servers.  The ones that I set up, I just let have the GUI (in runlevel 5)... it comes in handy when you need to remote in, and with no one logged in the overhead is negligible.  The ones that I didn't set up myself I think normally ran in runlevel 3, but I don't know if they had a GUI installed.  I prefer the Fedora/CentoOS/RedHat family for any system just because of the massive number of well-maintained packages available for install.

A: Personally I like Debian the most for servers.
The installer gives you the option to install a desktop environment, print server, file server, base system.
For your case you would just select install base system.
In that case the installer will just install the base packages to get your server up and running.
From that moment you have a rock-solid and very lightweight server and it's trivial to install other packages that you may need via apt-get or aptitude

A: Most linux distros can be installed without a GUI.  Personally I would recommend Debian for servers, but you'll probably also hear from the Gentoo, Linux from scratch, and Red Hat crowd.  Pretty much any distro could handle a web server pretty easily.

A: I don't think Ubunutu Server Edition has a GUI, and in some distros, you can choose what GUI (or lack of GUI) you want.

A: You might want to check out the Ubuntu Server Edition "JeOS" (Just Enough Operating System).  It is a stripped down version of Ubuntu and targeted at virtual appliances, but we've used it for some of our VM servers.  The URL is http://www.ubuntu.com/products/whatisubuntu/serveredition/jeos.

A: Note that even if the GUI (that is, the X Window System) is installed, you don't have to start it.  So you can configure normal startup to not start X, and still have the capability of running a GUI should you want to.  The only resource this takes is some disk space.
Note also, that the way X works, it may be very useful to have the X client applications on your web server host, allowing them to use the local X Server on your desktop.  (Yes, I know the terminology is confusing, but it's consistent).

A: Hmm. Just uncheck GNOME and KDE while installing any linux OS on DESKTOP or SERVER, so that it will install only CLI and only Command Prompt will be available once the installation is finished. No need to change run levels also.

A: sudo apt-get remove gnome;
sudo apt-get remove gdm;
sudo apt-get remove kde;
sudo apt-get remove kdm;
sudo apt-get remove xfce;
sudo apt-get remove xdm;
This should work for Ubuntu. Do it by entering CTRL+ALT+F1, log into root, and type the commands above depending on the DE.


text:
Q: Is there a way for a TextInput to behave like a button i.e. be able to be selected (onPress) or can the user enter the title of a button? I am making a react native health app in which the user can select tags to describe certain symptoms they are facing. I am trying to let the user create their own tags, at the moment the user can enter tags but cannot select them. Is there a way to allow them to select text inputs?
Here is how I have allowed users to create text inputs
 addTextInput = (index) => {
    let textInput = this.state.textInput;
    textInput.push(
        <TextInput
            style={styles.textInput}
            onChangeText={(text) => this.addValues(text, index)}
            editable={true}
        />
    );

    this.setState({ textInput });
}
removeTextInput = () => {
    let textInput = this.state.textInput;
    let inputData = this.state.inputData;
    textInput.pop();
    inputData.pop();
    this.setState({ textInput, inputData });
}

and this is what my current tags look like:
https://i.stack.imgur.com/5znWo.jpg
on the picture when the user presses the plus a new tag/TextInput is created, what I want is when the user presses it, it should be able to change color or the like.
here is the code for the plus button:
        <View style={{ flexDirection: 'row', flexGrow: '1', flexWrap: 'wrap', width: Responsive.width(300) }}>
                            {this.state.textInput.map((value) => {
                                return value
                            })}
                            <TouchableWithoutFeedback onPress={() => {
                                this.addTextInput(this.state.textInput.length)
                            }
                            }>
                                <Image
                                    style={{ marginLeft: 8, width: 38, height: 38 }}
                                    source={require('../../../assets/plusButton.png')}
                                />
                            </TouchableWithoutFeedback>
                            {/* <Button title='Get Values' onPress={() => this.getValues()} /> */}
                        </View>
                        <View style={styles.row}>
                            <View style={{ margin: 10, top: Responsive.height(75) }}>
                                <Button onPress={() => this.removeTextInput()}>Remove</Button>
                            </View>
                        </View>


text:
Q: jQuery. Не работают кнопки, помогите пожалуйста исправить ошибку Создала модальное окно, которое должно вызываться при нажатии на кнопку и по нажатию на кнопки ок или cancel должны в консоле соответствующие сообщения выходить. В данный момент в консоле показывает ошибки и модальное окно после нажатия кнопки не исчезает, не смогла понять почему.

$(() => {
  $('.backdrop').hide();
  $('.newConfirm').hide();
  let agree = $('.ok').on('click', () => console.log('User pressed OK'));
  let disagree = $('.cancel').on('click', () => console.log('User pressed cancel'));

  let createConfirm = (text, callback1, callback2) => {
    $('.backdrop').show();
    $('.newConfirm').show();
    $('.title').text(text);
    callback1(item);
    callback2(item);
  };
  $('.rules').on('click', () => {
    createConfirm('Are you accept with rules?', agree, disagree);
  });
});
body {
  background: rgb(189, 221, 189);
}

.rules {
  width: 200px;
  height: 50px;
  background: grey;
  color: #fff;
  border-radius: 5px;
  margin: 100px 40%;
  font-family: Arial, Helvetica, sans-serif;
  font-size: 25px;
  display: flex;
  justify-content: center;
  align-items: center;
  cursor: pointer;
}

.rules:active {
  background: rgb(226, 225, 225);
  color: grey;
}

.backdrop {
  width: 100%;
  height: 100%;
  position: absolute;
  background: rgba(0, 0, 0, 0.7);
  z-index: 1000;
  top: 0;
  left: 0;
}

.newConfirm {
  width: 400px;
  height: 150px;
  background: #fff;
  z-index: 1100;
  position: absolute;
  margin-left: 35%;
  border-radius: 3px;
  padding: 10px;
  display: flex;
  flex-direction: column;
  justify-content: space-around;
}

.title,
.textForConfirm {
  font-family: Arial, Helvetica, sans-serif;
  color: gray;
}

.title {
  font-size: 30px;
}

.textForConfirm {
  font-size: 20px;
}

.ok,
.cancel {
  width: 80px;
  height: 30px;
  background: #3498DB;
  border: 1px solid #3498DB;
  border-radius: 5px;
  color: #fff;
  padding: 5px;
}

.but {
  width: 170px;
  display: flex;
  justify-content: space-between;
  margin-left: 210px;
}

.ok:active,
.cancel:active {
  background: #246997;
  border: none;
}

RULES

    <button class="ok">OKAY</button>
    <button class="cancel">CANCEL</button>

https://jsfiddle.net/botagoz/z6myk8xa/2/

A: Вы забыли подключить библиотеку jQuery, поэтому выпадала ошибка
let agree = () => {
  console.log('User pressed OK')
$('.newConfirm').hide();
};
let disagree = () => {
   console.log('User pressed cancel')
$('.newConfirm').hide();
};
let createConfirm = (text) => {
    $('.title').text(text);
    $('.ok').on('click', () => {
    agree()
});
    $('.cancel').on('click', () => {
    disagree()
});
}

$('.backdrop').hide();
$('.newConfirm').hide();
$('.rules').on('click', () => {
$('.newConfirm').toggle();
createConfirm('Are you accept with rules?')

A: Посмотрите может так вы примерно хотели
$(() => {
$('.backdrop').hide();
$('.newConfirm').hide();
$('.rules').on('click', () => {
  $('.backdrop').show();
  $('.newConfirm').show();

  $('.title').text('Are you accept with rules?');
  $('.ok').on('click', () => {
    agree();
    $('.backdrop').hide();
    $('.newConfirm').hide();
  });
  $('.cancel').on('click', () => {
    disagree();
    $('.backdrop').hide();
    $('.newConfirm').hide();
  });

});
  let agree = () => console.log('User pressed OK');
  let disagree = () => console.log('User pressed cancel');

  let createConfirm = (text) => {
    $('.title').text(text);
  }
});

https://jsfiddle.net/botagoz/z6myk8xa/2/

A: let showModal = () => {
    $('.backdrop').show();
    $('.newConfirm').show();
  };
  let hideModal = () => {
    $('.backdrop').hide();
    $('.newConfirm').hide();
  };

  hideModal();

  let agree = $('.ok').on('click', () => {
    console.log('User pressed OK');
    hideModal()
  });
  let disagree = $('.cancel').on('click', () => {
    console.log('User pressed cancel');
    hideModal()
  });

  let createConfirm = (text, callback1, callback2) => {
    showModal();
    $('.title').text(text);
  };

  $('.rules').on('click', () => {
    createConfirm('Are you accept with rules?', agree, disagree);
  });


text:
Q: How to get bins position from df.hist not np.hist I know from this solution that we can find bins using plt.hist function or using np.histogram. However, I want to get the bins from df.hist. How is it possible?
Note:
I do not want to get my data from each column and then pass it to plt.hist or np.histogram like the following:
index = pd.date_range('7-22-2022', '7-22-2023', freq='min')
df = pd.DataFrame(np.random.randn(len(index)), index=index)
c, bins, bar = plt.hist(df.values, bins=50)
c, bins = np.histogram(df.values, bins=50)

A: My impression is that you can't do this.  df.hist() doesn't have any options for specifying outputs aside from the plotting axes themselves.
However, by default plotting with pandas is plotting with matplotlib - pandas just provides a different API.  Note that if you compare the bins returned by plt.hist or np.histogram in your example, you get identical arrays.  Doing df.hist(bins=50) should also give you the same bins.
Just to be thorough, I can say if you look at the source code and follow the bins parameter starting here here (which is linked from the docs for df.hist()), you eventually get to this line which calls ax.hist() (the ax being a matplotlib Axes object).  And if you look at the implementation of matplotlib.axes.Axes.hist(), you will see it relies on np.histogram.  Thus, my impression they all reduce to using np.histogram.  It's a little hard to trace through these large libraries, however, so perhaps I have missed something.
You say you do not want to get the bins from np.histogram for each column - maybe if you could clarify why that is an issue, someone else could provide a more tailored solution.  But I imagine it will involve using np.histogram to calculate the bins, because that is what pandas is doing.

The only other way I can think of to get the bin edges out of df.hist() is to access the bar objects in the plot it creates:
# plot
nbins = 50
bar = df.hist(bins=nbins)

# create container for edges
bin_edges = np.zeros(nbins + 1)

# access the bar objects from the ax
ax = bar[0, 0]
patches = ax.patches

# collect the left sides using patch.get_x()
# for the last right edge, add the width
bin_edges[:nbins] = [p.get_x() for p in patches]
bin_edges[-1] = patches[-1].get_x() + patches[-1].get_width()

With bin_edges being the thing you are requesting:
>>> bin_edges
array([-4.53401407, -4.34364948, -4.1532849 , -3.96292032, -3.77255574,
       -3.58219116, -3.39182657, -3.20146199, -3.01109741, -2.82073283,
       -2.63036825, -2.44000366, -2.24963908, -2.0592745 , -1.86890992,
       -1.67854534, -1.48818075, -1.29781617, -1.10745159, -0.91708701,
       -0.72672243, -0.53635784, -0.34599326, -0.15562868,  0.0347359 ,
        0.22510048,  0.41546507,  0.60582965,  0.79619423,  0.98655881,
        1.17692339,  1.36728798,  1.55765256,  1.74801714,  1.93838172,
        2.1287463 ,  2.31911089,  2.50947547,  2.69984005,  2.89020463,
        3.08056921,  3.2709338 ,  3.46129838,  3.65166296,  3.84202754,
        4.03239212,  4.22275671,  4.41312129,  4.60348587,  4.79385045,
        4.98421503])

However, note the difference between bin_edges and the bins you computed with np.histogram is infinitesimal (presumably due to some floating point inaccuracy or rounding error):
>>> bin_edges - bins
[ 0.00000000e+00 -8.88178420e-16  0.00000000e+00  0.00000000e+00
  0.00000000e+00  4.44089210e-16  0.00000000e+00  0.00000000e+00
  4.44089210e-16  0.00000000e+00  0.00000000e+00  4.44089210e-16
  0.00000000e+00  0.00000000e+00  0.00000000e+00  2.22044605e-16
  2.22044605e-16  0.00000000e+00  2.22044605e-16  0.00000000e+00
  2.22044605e-16  2.22044605e-16  0.00000000e+00  0.00000000e+00
  0.00000000e+00  0.00000000e+00  0.00000000e+00  0.00000000e+00
  0.00000000e+00  0.00000000e+00  0.00000000e+00  0.00000000e+00
  0.00000000e+00  0.00000000e+00  0.00000000e+00  0.00000000e+00
  0.00000000e+00  0.00000000e+00  0.00000000e+00  0.00000000e+00
  0.00000000e+00  0.00000000e+00  0.00000000e+00  0.00000000e+00
  0.00000000e+00  0.00000000e+00  0.00000000e+00  0.00000000e+00
  0.00000000e+00  0.00000000e+00  0.00000000e+00]

I'd say using np.histogram is more efficient and cleaner for arriving at the same (almost) result.

The above is based on the assumption you are not using a different plotting backend for pandas.   The binning implementation could be different for other plotting libraries.


text:
Q: ViewController reference not being maintained I have a service class, AuthManager, that has a method in it as below:
public func logoutAuth(from viewController: UIViewController, completion:((_ result: Bool) -> Void)? = nil) {
        let logoutString = "\(self.oAuthBaseServerURL)/logout.jsp"
        // Present the Sign Off ViewController
        if let logoutURL = URL(string: logoutString) {
            let logoutController = SFSafariViewController(url: logoutURL)
            let logoutDelegate = SFSafariViewDelegate(completion: completion)
            logoutController.delegate = logoutDelegate
            viewController.present(logoutController, animated: true, completion: nil)
        }
    }

I call this service from an instance of it (singleton in a global state) in my view controller like this:
GlobalState.AUTHMANAGER().logoutAuth(from: self, completion: self.completeLogout)

However, I am getting this error:
 [Warning] Attempting to load the view of a view controller while it is deallocating is not allowed and may result in undefined behavior (<SFSafariViewController: 0x7ff9b1060800>)

I'm not sure why that is deallocating too early. I've tried making the SFSafariViewController an instance variable and assigning it in the method instead, which yields the same error.


text:
Q: What "wrong crowd" is he referring to? In Serenity (2005), after locking River, Malcolm had a talk with his members:

Jayne: She goes woolly again, we're gonna have to put a bullet to her.
Malcolm: It's crossed my mind.
Hoban: Can I make a suggestion that doesn't involve violence, or is
this the wrong crowd?

What "wrong crowd" is he referring to?

A: Wash is simply asking if his comrades are dead set on the idea of resolving their problems with gunplay, or whether they're open to a more benign idea, in this case going to see their friend Mr Universe to determine what damage has been caused by River's display in the bar.
In this instance, the line should probably read "wrong audience" (e.g. the incorrect group of people to be 'selling' something to), but these are a group of desperados we're dealing with, so they're also the wrong crowd (e.g. people who are a bad influence generally)

The line could be rewritten:
"Can I please make a suggestion that doesn't involve violence, or is this the wrong group of people to be trying to suggest that to, because you seem very keen on using violence to resolve this situation."]


text:
Q: On delete cascade is not working I have two table: users and 'bills'. In bills as a foreign key to users.
I want to automatically delete rows from the bills table when I delete from the users table. For that I alter table with following query, still it doesn't delete entry from bills table.
My alter statement is:
ALTER TABLE bills
ADD CONSTRAINT fk_pid
FOREIGN KEY (pid)
REFERENCES users(id)
ON DELETE CASCADE

here pid is foreign key in bills table, whereas id primary key in users table
Please help me to resolve above issue, thank you in advance.

A: Use create instead of alter,Otherwise your syntax is ok
Create TABLE bills(
Your columns details
------
------
ADD CONSTRAINT fk_pid
FOREIGN KEY (pid)
REFERENCES users(id)
ON DELETE CASCADE
)

Try this..
If it's doesn't work then try for this thing as well.
if your both tables having mismatch primary key and foreign key problem then you cannot add Delete Cascade.For that you need to fix that key problem.like you don't have primary key value in your user table and you are using that same id in your bills table as a foreign key then you cannot add cascade in bills table.For that remove that key from bills table and then try your adding cascade script with Alter.I had same problem but i use this way and it worked.Hope it will work for you as well.Thanks

A: I think this solution for create  can help you in figuring out what actually you are missing.
Go thru it and try customizing it as per your need, as you haven't provided enough detail
along with your question.
I suspect it has to do something with your create table statement
OR try this for ALTER1
OR ALTER2


text:
Q: HTTP 404 - File not found Internet Explorer V6 I have ang 404 code that will redirect to the site if the page is not found. It working properly in firefox. However, when I use the Internet Explorer v6. the site will get and error mesaage: "HTTP 404 - File not found Internet Explore". How can I fix this? any help is appreciated
Thanks

A: Try to use a longer 404 page. That's no joke. If the 404 page is less than 512b if I remember correctly, IE will step in and show its own error message.
Adding in some comments will do.
Reference: http://www.reddit.com/r/web_design/comments/ee4zc/so_i_looked_at_plesks_404_page/
Just for completeness:

<TITLE>404 Not Found</TITLE>

Not Found

The requested document was not found on this server.

<ADDRESS>
Web Server at example.com
</ADDRESS>


text:
Q: Show form only after DocumentCompleted event gets finished I am having a form form1 from which I am calling another form form2.
There is a Web Browser Control in form2.
What happens is at once form2 gets shown and then after document completed event of web browser, form2 gets resized.
void wbBrowser_DocumentCompleted(object sender, System.Windows.Forms.WebBrowserDocumentCompletedEventArgs e)
{
    //Set the height/width of form2, so web page gets visible completely without scroll bars.
    this.Height = wbBrowser.Document.Body.ScrollRectangle.Height;
    this.Width = wbBrowser.Document.Body.ScrollRectangle.Width;
}

This looks non professional as the same form gets loaded twice. What I want is to show the form2 only after DocumentCompleted event of web browser control gets completed.


text:
Q: JQuery input field focus inside angularjs demo modal I try to apply a demo modal shown in url:
http://getbootstrap.com/javascript/
after "Varying modal content based on trigger button".

And also use a html code
<input name="email" type="email" id="email" />

...and javascript code
$('#exampleModal').on('show.bs.modal', function (event) {
  var button = $(event.relatedTarget)
  var modal = $(this)
  modal.find('.modal-title').text('Log In')
  modal.find('.modal-body input').val("This Body..")
  $(this).find('#email').focus();//why it doesn't work????????
})

How to set the focus function in email-input automatically?
Thank you

A: use shown.bs.modal instead of show.bs.modal
Try something like below:
$('#exampleModal').on('shown.bs.modal', function (event) {
  var button = $(event.relatedTarget)
  var modal = $(this)
  modal.find('.modal-title').text('Log In')
  modal.find('.modal-body input').val("This Body..")
  $(this).find('#email').focus(); //now it will work
})


text:
Q: How to use createAutoCorrectedDatePipe and createNumberMask feature from text-mask in vue? i am using this awesome vue component called text-mask, it offer a simple yet elegant solution for input mask that i use for inputting datetime format and number format. i can make it works for the most part based from documentation like this
<template>

    Phone Number
    <masked-input
      type="text"
      name="phone"
      class="form-control"
      v-model="phone"
      :mask="['(', /[1-9]/, /\d/, /\d/, ')', ' ', /\d/, /\d/, /\d/, '-', /\d/, /\d/, /\d/, /\d/]"
      :guide="false"
      placeholderChar="#">
    </masked-input>

</template>

but it only offer some basic functionality and i need more like for datetime input i want to make sure maximum number for month (only 12) and for date (30 or 31 according to the month) and there is those features in text-mask that act as an addons
but i can't find or understand how to make it work in vue. i tried to create an issue on the github but seeing activity on there i think my question will never be answered. so i think it is so much faster if i just ask you all in here.
Maybe there is someone who have ever been using this or maybe have other much better recomendation for input mask component that works in vue way?

A: Here is what worked for me:

*

*I created the "createNumberMask" function in the "data()" section of the vue component

NumberMaskTestComponent.js file
import MaskedInput from 'vue-text-mask';
import createNumberMask from 'text-mask-addons/dist/createNumberMask';

export default Vue.component('number-mask-test-component', {
    name: 'NumberMaskTestComponent',
    data () {
        return {
            numberMask: createNumberMask({
                prefix: '$',
                allowDecimal: true,
                decimalLimit: 2,
                integerLimit: 1
            }),
            testNumber: '123.3445'
        }
    },
    components: {
        MaskedInput
    }
})

NumberMaskTestComponent.vue file
<template>

        <masked-input
            type="text"
            name="numberTest"
            class="form-control"
            v-model="testNumber"
            :mask="numberMask"
            :guide="false"
            placeholderChar="#">
        </masked-input>

</template>


text:
Q: Having trouble using sprintf or snprintf for transmitting ADC value through UART I am new to C and programming in general. I am transmitting an ADC value through UART but it is encoded as an ASCII value in the CCS terminal. I want to convert it to a Decimal value in the terminal for easy debugging. When I try to use snprintf or sprintf I get the warning:
"a value of type char* cannot be assigned to an entity of type "unsigned int""
Does this have to do with the way the MSP430 UART Buffer works or more likely is my usage wrong and how?
How large does the buffer need to be for a 16 bit value?
I am receiving a constant value in the terminal not in the ASCII range despite the value in the ADCMEM0 changing as expected.
I am attempting to get my ADC values in a decimal value in the terminal. I am only able to get the correct ASCII values.
Code:
int i;
while(1){
    ADCCTL0 |= ADCENC | ADCSC; // Enable and Start Conv

    while((ADCIFG & ADCIFG0) == 0);

    for(i=0; i<32000; i=i+1 ){
        char buffer[20];
        int Sensor = ADCMEM0;
        snprintf(buffer, 10, "%d", Sensor);

        UCA1TXBUF = buffer;    //transmit ADC_Value over UART A1 Tx
    }
}


text:
Q: Download file from a user control wrapped in a master page update panel I a have problem sounds strange to me! I am going to download a file using asp.net C# from a user control. Here is the structure of my web forms:

*

*There is a Site.Master file in which the content place holder is wrapped  with an update panel

*There is User Control named Library.ascx that display lists of books so that users may download each of which they like to. Note that, books are displayed using a ListView web control.

*The above user control is used in different pages at the same web site (imagine a school website that includes different levels and each of which has a library page)

The code to download the file is as the following:
  protected void listViewBooks_ItemCommand(object sender, ListViewCommandEventArgs e)
    {
        if (e.CommandName != "Download") return;

        var books = _lib.GetBookInfo(Convert.ToInt32(e.CommandArgument));
        var filePath = string.Empty;

        foreach (var s in books)
        {
            filePath = s.FilePath;
        }

        var fileName = filePath.Substring(filePath.LastIndexOf(@"/", StringComparison.Ordinal) + 1);
        filePath = Server.MapPath("~/PDF/") + fileName;

        var file = new FileInfo(filePath);

        if (!file.Exists) return;

        Response.ClearContent();
        Response.Clear();
        Response.AddHeader("Content-Disposition", "attachment;filename=" + file.Name);
        Response.AddHeader("Content-length", file.Length.ToString(CultureInfo.InvariantCulture));
        Response.ContentType = "application/octet-stream";
        Response.TransmitFile(file.FullName);
        Response.End();
    }

Actually, it goes up to the line before Response.End() and I don't know why it never catches the last bracket of the event, i.e. "}" and from the view point of users nothing happens! I have searched the web and similar questions for hours, but couldn't find any solution! For example, this linke or this one and some other ones
Any help highly appreciated!

A: It never reaches the last bracket because you are using Response.End():

The End method causes the Web server to stop processing the script and return the current result. The remaining contents of the file are not processed.

You can't download a file from an UpdatePanel. You have to trigger a full postback instead.

A: Finally I've come over the issue I rose yesterday. Since the flow of the code in the specified user control I had to write the update panel trigger code inside the list view data bound event, and it simply resolved :) thanks for the guys helped me on this.


text:
Q: Error: unknown error: DevToolsActivePort file doesn't exist, when executing ruby script with watir I am fairly new to Centos7 and trying to develop a solution for browser automation in the below environment:
OS: Centos7
Ruby: 2.6
Watir
Browser:Google Chrome 72.0.3626.109
Driver: ChromeDriver 2.46.628388
My script:
require 'watir'

# Initialize the browser with the driver path
site="https://google.com"
browser = Watir::Browser.new :chrome
browser.goto site

Getting error:
`assert_ok': unknown error: Chrome failed to start: exited abnormally (Selenium::WebDriver::Error::UnknownError)
  (unknown error: DevToolsActivePort file doesn't exist)
  (The process started from chrome location /usr/bin/google-chrome is no longer running, so ChromeDriver is assuming that Chrome has crashed.)
  (Driver info: chromedriver=2.46.628388 (4a34a70827ac54148e092aafb70504c4ea7ae926),platform=Linux 3.10.0-957.5.1.el7.x86_64 x86_64)

I found multiple solutions on net that are recommending to modify chrome options like:
chrome_options.add_argument('--headless')
chrome_options.add_argument('--no-sandbox')
chrome_options.add_argument('--disable-dev-shm-usage')

But I don't know where to set these. The nearest I was able to reach is the answers provided here: How do I pass options to the Selenium Chrome driver using Python?
Can anyone please help me to resolve it in a step-by-step manner?

A: Also faced similar issue but with npm and protractor configuration but I guess the solution would be similar. You have to install chrome browser in your linux system.
The chromedriver is just a wrapper written to use the chromebrowser for running the test cases.
Also if google-chrome is installed you might want to check the path were it is installed in linux based operating system the path expected is under /usr/bin/google-chrome. This file is generally a link to the actual binary of the chrome.
Hope so this helps


text:
Q: FB ui feed does not work - how to change my javascript? I'm currently learning to script some facebook applications and some parts of the code of my book don't work coz of the constantly updating facebook dev php and javascript sdk!
My example app works like this: it selects one of the friends randomly, shows a pic and writes the name. Then it shall pop up a feed dialogue box to give the user the opportunity to post it on his wall.
This is the code i have been using (which does not work, the other stuff works perfectly):
$(document).ready(function() {
FB.ui({
method: 'feed',
name: 'App Name',
link: 'http://apps.facebook.com/[your_app_url]/',
picture: 'http://yourwebsite.com/images/app.PNG',
caption: 'My App Caption',
description: 'Today\'s blahblah is
<?php echo $random_friend['name']; ?>.',
message: 'check out this name
<?php echo $random_friend['name']; ?>.',
to: '<?php echo $random_friend['id']; ?>'
},

please consider and keep in mind that i'm new to Javascript and Php so i'm learning both in combination with facebook app developement :)
Thanx guys.

A: Feed Dialog allows users to post a message only to their own timeline which would then appear on their friends' News Feeds.
For message: property, Facebook's policy is that you shouldn't pre-fill this field so you should probably avoid using it.
I've provided the solution to posting a Feed using PHP SDK or Javascript SDK in another thread... Suggest Page to friends using PHP-SDK


text:
Q: How to get different maximum matchings I have a large bipartite graph and I can find a maximum matching quickly using Hopcroft-Karp. But what I would really like is a few hundred different maximum matchings for the same graph. How can I get those?
Here is an example small bipartite graph with a maximum matching shown.

Similar graphs can be made with:
import igraph as ig
from scipy.sparse import random, find
from scipy import stats
from numpy.random import default_rng
import numpy as np
from igraph import Graph, plot
np.random.seed(7)
rng = default_rng()
rvs = stats.poisson(2).rvs
S = random(20, 20, density=0.35, random_state=rng, data_rvs=rvs)
triples = [*zip(*find(S))]
edges = [(triple[0], triple[1]+20) for triple in triples]
print(edges)
types = [0]*20+[1]*20
g = Graph.Bipartite(types, edges)
matching = g.maximum_bipartite_matching()
layout = g.layout_bipartite()
visual_style={}
visual_style["vertex_size"] = 10
visual_style["bbox"] = (600,300)
plot(g, bbox=(600, 200), layout=g.layout_bipartite(), vertex_size=20, vertex_label=range(g.vcount()),
    vertex_color="lightblue", edge_width=[5 if e.target == matching.match_of(e.source) else 1.0 for e in g.es], edge_color=["red" if e.target == matching.match_of(e.source) else "black" for e in g.es]
    )

A: There's an enumeration algorithm due to Fukuda and Matsui ("Finding all the perfect matchings in bipartite graphs"), (pdf) which was improved for non-sparse graphs by Uno ("Algorithms for enumerating all perfect,
maximum and maximal matchings in bipartite graphs") at the cost of more implementation complexity.
Given the graph G, we find a matching M (e.g., with Hopcroft–Karp) to
pass along with G to the root of a recursive enumeration procedure. On
input (G, M), if M is empty, then the procedure yields M. Otherwise, the
procedure chooses an arbitrary e ∈ M. A maximum matching in G either
contains e or not. To enumerate the matchings that contain e, delete e's
endpoints from G to obtain G′, delete e from M to obtain M′, make a
recursive call for (G′, M′), and add e to all of the matchings returned.
To enumerate the matchings that don't contain e, delete e from G to
obtain G′′ and look for an augmenting path with respect to (G′′, M′). If
we find a new maximum matching M′′ thereby, recur on (G′′, M′′).
With Python you can implement this procedure using generators and then
grab as many matchings as you like.
def augment_bipartite_matching(g, m, u_cover=None, v_cover=None):
    level = set(g)
    level.difference_update(m.values())
    u_parent = {u: None for u in level}
    v_parent = {}
    while level:
        next_level = set()
        for u in level:
            for v in g[u]:
                if v in v_parent:
                    continue
                v_parent[v] = u
                if v not in m:
                    while v is not None:
                        u = v_parent[v]
                        m[v] = u
                        v = u_parent[u]
                    return True
                if m[v] not in u_parent:
                    u_parent[m[v]] = v
                    next_level.add(m[v])
        level = next_level
    if u_cover is not None:
        u_cover.update(g)
        u_cover.difference_update(u_parent)
    if v_cover is not None:
        v_cover.update(v_parent)
    return False

def max_bipartite_matching_and_min_vertex_cover(g):
    m = {}
    u_cover = set()
    v_cover = set()
    while augment_bipartite_matching(g, m, u_cover, v_cover):
        pass
    return m, u_cover, v_cover

def max_bipartite_matchings(g, m):
    if not m:
        yield {}
        return
    m_prime = m.copy()
    v, u = m_prime.popitem()
    g_prime = {w: g[w] - {v} for w in g if w != u}
    for m in max_bipartite_matchings(g_prime, m_prime):
        assert v not in m
        m[v] = u
        yield m
    g_prime_prime = {w: g[w] - {v} if w == u else g[w] for w in g}
    if augment_bipartite_matching(g_prime_prime, m_prime):
        yield from max_bipartite_matchings(g_prime_prime, m_prime)

# Test code

import itertools
import random

def erdos_renyi_random_bipartite_graph(n_u, n_v, p):
    return {u: {v for v in range(n_v) if random.random() < p} for u in range(n_u)}

def is_bipartite_matching(g, m):
    for v, u in m.items():
        if u not in g or v not in g[u]:
            return False
    return len(set(m.values())) == len(m)

def is_bipartite_vertex_cover(g, u_cover, v_cover):
    for u in g:
        if u in u_cover:
            continue
        for v in g[u]:
            if v not in v_cover:
                return False
    return True

def is_max_bipartite_matching(g, m, u_cover, v_cover):
    return (
        is_bipartite_matching(g, m)
        and is_bipartite_vertex_cover(g, u_cover, v_cover)
        and len(m) == len(u_cover) + len(v_cover)
    )

def brute_force_count_bipartite_matchings(g, k):
    g_edges = [(v, u) for u in g for v in g[u]]
    count = 0
    for m_edges in itertools.combinations(g_edges, k):
        m = dict(m_edges)
        if len(m) == k and is_bipartite_matching(g, m):
            count += 1
    return count

def test():
    g = erdos_renyi_random_bipartite_graph(7, 7, 0.35)
    m, u_cover, v_cover = max_bipartite_matching_and_min_vertex_cover(g)
    assert is_max_bipartite_matching(g, m, u_cover, v_cover)

    count = 0
    for m_prime in max_bipartite_matchings(g, m):
        assert is_bipartite_matching(g, m_prime)
        assert len(m_prime) == len(m)
        count += 1
    assert brute_force_count_bipartite_matchings(g, len(m)) == count

for i in range(100):
    test()


text:
Q: Query MongoDB with dynamic selector in Camel I found a solution here: How do I create a dynamic equals query using Apache Camel and MongoDB?
But this looks like a lot of work. Doesn't Camel have a simpler way to pass values to a MongoDB query? I wish we could just pass the actual find({}) language that Mongo uses.
Here is what I have working, with some logging showing what it's doing:
.setHeader(MongoDbConstants.CRITERIA, new Expression() {
    @Override
    public <T> T evaluate(Exchange exchange, Class<T> type) {
        Long drRequestId = exchange.getIn().getHeader("orderid", Long.class);

        Bson equalsClause = Filters.eq("id", drRequestId);

        return exchange.getContext().getTypeConverter().convertTo(type, equalsClause);
    };
})
.log(MongoDbConstants.CRITERIA)
.log("${headers.CamelMongoDbCriteria}")
.to("mongodb:mongo?database={{spring.data.mongodb.database}}&collection=ftx_orders&operation=findOneByQuery")

A: did you try with ${body.id}?
Also, you can also send it in header, setting using
exchange.getIn().setHeader("id","value");

and then using the same way you mentioned above.
.setHeader(MongoDbConstants.CRITERIA, constant(Filters.eq("name", simple("${header.id}"))))


text:
Q: Mysql: how to design a database to display one article in different menus I want to append one article to different menus. Please take a look at a procedure for adding a new article. My implementation works fine, but seems to be far from perfect.
DROP PROCEDURE IF EXISTS new_article;
DELIMITER $$
CREATE PROCEDURE new_article(IN title VARCHAR(255), IN alias VARCHAR(255), IN text MEDIUMTEXT, IN description TEXT, IN articles_users_id INT, IN menus_id INT)
BEGIN
    /*how do i know a first VALUE for articles_menus INSERT?*/
    SET @articles_id_ai =  (SELECT AUTO_INCREMENT
    FROM information_schema.tables
    WHERE table_name = 'articles'
    AND table_schema = DATABASE());
    INSERT INTO articles VALUE (@articles_id_ai, articles_users_id, title, alias, text, description, DEFAULT, DEFAULT, DEFAULT, DEFAULT, DEFAULT, DEFAULT, DEFAULT, DEFAULT, DEFAULT, DEFAULT, DEFAULT);
    INSERT INTO articles_menus VALUE (@articles_id_ai, articles_users_id, menus_id);
END$$
DELIMITER ;

A: I'm not familiar with the way you are getting the next auto generated value for the table. So I don't know what would happen if a different user wrote to the table after your first SELECT but before your first INSERT. MySQL provides an easy way to retrieve the last generated value, LAST_INSERT_ID():
INSERT INTO articles( users_id, title, alias, text, desc )
    VALUES( articles_users_id, title, alias, text, description );
INSERT INTO articles_menus( articles_id, articles_users_id, menus_id )
    VALUES( LAST_INSERT_ID(), articles_users_id, menus_id );

This uses only two database accesses instead of three and it uses the function provided for the purpose. It's generally a good idea to use the system-provided methods to get information unless you have a good reason. Nobody knows the system better than the developers of system functions.


text:
Q: Python: How do I give an bunch of audio files BPM information? I am trying to figure out what the best Python tools would be to add BPM information to a file. The yaafe and LibXtract libraries seem to have Python bindings, but seem to be sparsely documented. How can I go about doing this in Python?

A: If you're willing to upload your data to an external server, try using the EchoNest API -- it has good Python bindings and lots of tools for music information retrieval tasks such as this.

A: I recently found this. Usage is found in the README.
python metaBPM.py -s [path to your music collection]


text:
Q: Problem with Entity Framework after adding column to DB table I needed to add a new NVARCHAR column to a table in my DB. So I added the column, and then fired up Visual Studio to update the EDMX-file for the Entity Framework.
I ran update model from database on everything, which only resulted in "data reader is incompatible"-errors. So I renamed the whole table in the DB, updated EDMX from database, renamed the table back to the original name, ran update again, and then created new function imports for all affected stored procedures. But I still get the same error:

The data reader is incompatible with
  the specified '[Model].[Entity]'. A
  member of the type,
  '[Column]', does not have a
  corresponding column in the data
  reader with the same name.

I've looked around a bit, and this seems to be a common error if the column name is different in the database and framework. This is however not the case, they have the same name.
I can access the column in the code via [Entity].Context.[Column], so I don't quite see what the data reader is complaining about.
I've run out of ideas, so any help welcome.

A: Updating the model replaces the store schema, but not the client schema or the mapping. To start with "a clean slate", back up your current EDMX, then open it as XML. Remove all references to the table, then close and open in the graphical error. Build. If you have any errors (perhaps broken links to the deleted table), fix them. Then update model to re-add the table.

A: Just had the same issues as above. Tried removing the entity from the edmx, tried removing and re-adding the function import, and finally rebuilt using a complex type in the function import and that didn't work either.
I realize this error can occur for really any scenario where there is a mismatch but we found the issue was in the stored proc we used for the function import. The stored proc was using specific select columnname, columnname etc and the new column we added to the table was not in that list. To test, we used the *, updated the EDMX and it resolved our issue.

A: Turns out the EDMX was fine, but the designer has, for some odd reason, stopped update Designer.cs in my project.
Had to go in and manually edit it.

A: For me it was an issue where I altered an entity (vertical entity splitting), but one of my stored procedures wasn't pulling data for that new field. I added it (in the SP) and now everything runs fine.

A: Unless it's simply adding a new item, This throws an error just about every time I try to "Update model from database" ...
The solution is luckily very simple -
1) Open Web.config, find <connectionStrings> node
2) Delete the DBNameEntities <connectionStrings>
     - this way you do not have to modify any references to your emdx model
2) Delete the ADO.NET Entity Data Model (.emdx)
3) Re-add the ADO.NET Entity Data Model (.emdx) with the same name.

Its faster and bulletproof. (so far!?)

A: If you Re-Add the DataModel you will lose all DataBindings - especially bindings of controls on your form (like DbGrid). I have fixed this issue manually editing the DataModel.edmx file in external Editor.


text:
Q: cannot create a raster geometry from a single y coordinate I cropped a raster using a polygon which looks like below.

I want to adjust the values of the 2 raster cells to account for their area contribution to the polygon. For e.g. if cell 1 has 90% of its area inside the polygon, I want to multiply its value by 0.9 and same for the other cell.
The way I approached is to extract the cell value along with its weight using terra::extract with xy = T and weights = T
library(terra)
library(dplyr)

crop_rast_df <- terra::extract(crop_rast, my_shp , weights = T, touches = T, xy = T)
crop_rast_df

ID GDP_PPP_3       x      y   weight
1  79067856 -85.875 32.125 0.874914
1 344945408 -85.625 32.125 0.932744

# adjust the value
crop_rast_df <- crop_rast_df %>%
                  dplyr::mutate(eff_gdp = GDP_PPP_3 * weight) %>% # account for cell contribution
                  dplyr::select(x, y, eff_gdp)
crop_rast_df
x      y   eff_gdp
-85.875 32.125  38269172
-85.625 32.125 177990394

However, when I want to turn it back to a raster again, I get the following error:
crop_rast_adj <- terra::rast(crop_rast_df, type = 'xyz', crs = crs(temp_gdp))
Error: [rast] cannot create a raster geometry from a single y coordinate

How can I correct it?

A: Reproduction of the error
library(terra)
library(dplyr)

crop_rast <- rast(matrix(1:2, nrow = 1, ncol = 2))
names(crop_rast) <- "GDP_PPP_3"
my_shp <- vect("POLYGON ((.5 0, .5 1, 1.5 0, .5 0))")

plot(crop_rast)
lines(my_shp)

crop_rast_df <- terra::extract(crop_rast, my_shp , weights = T, touches = T, xy = T)
crop_rast_df

  ID GDP_PPP_3   x   y weight
1  1         1 0.5 0.5  0.375
2  1         2 1.5 0.5  0.125

crop_rast_df <- crop_rast_df %>%
  dplyr::mutate(eff_gdp = GDP_PPP_3 * weight) %>% # account for cell contribution
  dplyr::select(x, y, eff_gdp)
crop_rast_df

    x   y eff_gdp
1 0.5 0.5   0.375
2 1.5 0.5   0.250

crop_rast_adj <- terra::rast(crop_rast_df, type = 'xyz', crs = crs(temp_gdp))
Error: [rast] cannot create a raster geometry from a single y coordinate

Proposed solution
I don't think there is a way for terra::rast to create a raster from a dataset with a single y (or x) coordinate.
So I rather suggest to duplicate your initial raster and to change its values with the adjusted ones as follows:
crop_rast_adj <- crop_rast
values(crop_rast_adj) <- crop_rast_df$eff_gdp
crop_rast_adj

class       : SpatRaster
dimensions  : 1, 2, 1  (nrow, ncol, nlyr)
resolution  : 1, 1  (x, y)
extent      : 0, 2, 0, 1  (xmin, xmax, ymin, ymax)
coord. ref. :
source(s)   : memory
name        : GDP_PPP_3
min value   :     0.250
max value   :     0.375

plot(crop_rast_adj)
lines(my_shp)

A: L--'s example data
library(terra)

r <- rast(matrix(1:2, nrow = 1, ncol = 2), crs="+proj=utm +zone=1")
v <- vect("POLYGON ((.5 0, .5 1, 1.5 0, .5 0))")

Approach 1
e <- extract(r, v, exact=TRUE, cell=TRUE)
# if there were multiple polygons, you would need to sum the fractions
e <- aggregate(e[,"fraction", drop=FALSE], e[,"cell", drop=FALSE], sum)

x <- rast(r)
x[e$cell] <- e$fraction
x * r
#class       : SpatRaster
#dimensions  : 1, 2, 1  (nrow, ncol, nlyr)
#resolution  : 1, 1  (x, y)
#extent      : 0, 2, 0, 1  (xmin, xmax, ymin, ymax)
#coord. ref. : +proj=utm +zone=1 +datum=WGS84 +units=m +no_defs
#source(s)   : memory
#name        :     lyr.1
#min value   : 0.2499978
#max value   : 0.3750118

Approach 2
a <- rasterizeGeom(v, r, "area")
b <- cellSize(a, transform=FALSE) # use TRUE with real data
d <- a/b
d * r
#class       : SpatRaster
#dimensions  : 1, 2, 1  (nrow, ncol, nlyr)
#resolution  : 1, 1  (x, y)
#extent      : 0, 2, 0, 1  (xmin, xmax, ymin, ymax)
#coord. ref. : +proj=utm +zone=1 +datum=WGS84 +units=m +no_defs
#source(s)   : memory
#name        :  area
#min value   : 0.250
#max value   : 0.375

These approaches also work if not all cells are at least partly covered by the polygon.


text:
Q: twemproxy (nutcracker) performance degradation with .net ServiceStack.Redis client Setup redis and nutcracker on CentOS 6.4. and trying to connect using ServiceStack.Redis client. Found major performance issue.
For testing left only 1 redis instance
beta:
  listen: 0.0.0.0:22122
  hash: fnv1a_64
  distribution: ketama
  auto_eject_hosts: true
  #timeout: 5000
  #server_retry_timeout: 2000
  #server_failure_limit: 3
  redis: true
  servers:
  #- 127.0.0.1:6379:1
   - 127.0.0.1:6380:1

In the following unit test I'm trying to send 100k strings to redis via nutcracker.
[TestClass]
public class RedisProxyTest
{
    public string host = "192.168.56.112";
    //public int port = 6379;
    public int port = 22122;

    [TestMethod]
    public void TestMethod1()
    {
        var key = "l2";
        var count = 100000;
        using (var redisClient = new RedisClient(host, port))
        {
            var list = new List<string>();
            for (int i = 0; i < count; i++)
            {
                list.Add(Guid.NewGuid().ToString());
            }

            Utils.TimeLog("Remove", () => redisClient.Remove(key));

            Utils.TimeLog("AddRangeToList", () => redisClient.AddRangeToList(key, list));
        }

        using (var redisClient = new RedisClient(host, port))
        {
            redisClient.GetListCount(key);

            Utils.TimeLog("GetRangeFromList", () =>
            {
                var ret = redisClient.GetRangeFromList(key, count / 2, count - 1);
                Console.WriteLine(ret.Count);
            });
        }

    }
}

On first few runs after nutcracker restarted AddRangeToList works with 1-2 sec. But with subsequent runs AddRangeToList performance drops significantly from few minutes even more than 20 mins (if no timeout configured). I cannot reproduce same when using redis directly. I didn't try any other client yet. Any ideas why?
This what I see in console after unit test run:
Test Name:  TestMethod1
Test Outcome:   Passed
Remove: 0.0331171
AddRangeToList: 806.8219166
50000
GetRangeFromList: 1.741737

A: Looks like the issue is related to high memory usage when transferring that amount of data.
By default nutcracker allocates 16k buffer size for each key. In my case it is going to be 16k*100000 = 1.5Gb. I saw around 2Gb peak when watching nutcracker process. My Cent OS VM was overloaded and there was no enough memory to handle that spike.

A: If nutcracker is proxing several tens of thousands of connections or sending multi-get request with several thousands of keys, you should use mbuf size of 512
The following link talks about how to interpret mbuf size?  - https://github.com/twitter/twemproxy/issues/141

Every client connection consumes at least one mbuf. To service a request we need two connections (one from client to proxy and another from proxy to server). So we would need two mbufs.
A fragmentable request like 'get foo bar\r\n', which btw gets fragmented to 'get foo\r\n' and 'get bar\r\n' would consume two mbuf for request and two mbuf for response. So a fragmentable request with N fragments needs N * 2 mbufs
The good thing about mbuf is that the memory comes from a reuse pool. Once a mbuf is allocated, it is never freed but just put back into the reuse pool. The bad thing is that once mbuf is allocated it is never freed, since a freed mbuf always goes back to the reuse pool - https://github.com/twitter/twemproxy/blob/master/src/nc_mbuf.c#L23-L24 (this can be fixed by putting a threshold parameter on the reuse pool)
So, if nutcracker is handling say 1K client connections and 100 server connections, it would consume (max(1000, 100) * 2 * mbuf-size) memory for mbuf. If we assume that clients are sending non-pipelined request, then with default mbuf-size of 16K this would in total consume 32M.
Furthermore, if on average every requests has 10 fragments, then the memory consumption would be 320M. Instead of handling 1K client connections, lets say you were handling 10K, then the memory consumption would be 3.2G. Now instead of using a default mbuf-size of 16K, you used 512 bytes, then memory consumption for the same scenario would drop to 1000 * 2 * 512 * 10 = 10M
This is the reason why for 'large number' of connection you want to choose a small value for mbuf-size like 512


text:
Q: Do nodes in a single-switch ethernet network governed by dnsmasq communicate directly, or via the router? Variations on this question exist, but I cannot be certain my exact situation has been asked.
I am setting up a simple ethernet network that looks like this:

On Node 0 ("rpi1") I am running dnsmasq as both a DNS and DHCP server. Here is a section of its /etc/dnsmasq.conf (minus the MAC Address details):
# Assign static IPs to cluster members
# Format = MAC:hostname:IP
dhcp-host=ZZ:YY:XX:WW:VV:UU,rpi1,10.0.0.1 # Node 0
dhcp-host=ZZ:YY:XX:WW:VV:UU,rpi2,10.0.0.2 # Node 1
dhcp-host=ZZ:YY:XX:WW:VV:UU,rpi3,10.0.0.3 # Node 2
dhcp-host=ZZ:YY:XX:WW:VV:UU,rpi4,10.0.0.4 # Node 3

Both the DNS and DHCP aspects are working. Each node is getting assigned its intended 10.0.0.X IP Address, and I can resolve any domain on any node by running e.g. dig rpi4 (-> ... 10.0.0.4). And, for example, if I am inside rpi2 then I can get into rpi3 with ssh rpi3, and I can e.g. ping rpi4 or ping 10.0.0.4 and get 0% packet loss.
What is not clear to me though is whether I am communicating between nodes directly through the switch, or via rpi1 (which is operating dnsmasq and providing router services).
If the nodes are communicating directly then I assume they must know each other's MAC address in order to emit frames that go directly to each other through the switch. If that is so, then my questions in summary are:

*

*At what point does a node learn the MAC addresses of the other nodes?

*And how can I examine the MAC address of e.g. rpi3 on rpi2 to see that they have learned of each other?

Thanks in advance!

A: At what point does a node learn the MAC addresses of the other nodes?
First they will inquire about the IP address of other nodes from the DNS server. After that, they will send 'arp' request to all the nodes, and the node which has the IP address will reply to that 'arp' request with its MAC address.
And how can I examine the MAC address of e.g. rpi3 on rpi2 to see that they have learned of each other?
'arp -a' will usually give you arp table, and you can examine the entries to see if they have learned MAC addresses of each other.


text:
Q: How to make whole div clickable and put a dynamic url in Django template? I am trying to display a post (like a tweet in twitter) and when I display it I want the whole div to be clickable.
So this works. Website is working the way I wanted with this code;

   some other links  // it will take user to another page
   //some image

 some content

   some other links

But it gives me some warnings in the terminal (VScode), each of the error is showing the same thing (div onclick line ) but strangely giving different errors. And I don't use javascript for this part of the code.
I tried different syntax like changing " " to ''. but it doesn't solve the problem.

Also in the code, it shows the line with red color as below, if it helps to figure what the problem is.

Any advice would be appreciated. Thanks in advance.

A: Your code is absolutely correct ignore the warnings and red-underlines by VScode. Red-underlines are there because by default the language mode is HTML therefore sometimes use of '' and "" shows error but it is fine as per Django Templating Engine
If for any reason onclick='location.href="{% url 'post' post.id %}";' does not work use this onclick='location.href="post/{{post.id}}";'

A: before your "div" tag, put an "a" tag and give it the url. You don't need to repeat the url manytimes.
EXAMPLE:


text:
Q: If $p$ is an irreducible element of an integral domain $D$, and if $e$ belongs to $D^\ast$ prove that $ep$ is also ireducible If $p$ is an irreducible element of an integral domain $D$, and if $e$ belongs to $D^\ast$, prove that $ep$ is also ireducible .
To me it seems so profound, but I cannot get the proof . I'm trying to say that it is not irreducible, so there exists $a,b$ so that $ep=ab$ where $a,b$ don't belong to $D^\ast$....

A: This is, as has been mentioned, ill-written, but that said, if $ep=ab$ then $p=e^{-1}ab$. And if $a$ is not a unit, neither is $e^{-1}a$.

A: Hint $\, p\,$ isn't irreducible  iff $\, p=0\,$ or $\,p$ is a unit or $\,p = ab\,$ for nonunits $\,a,b.\,$  All are preserved by scaling by a unit $\,e,\,$ e.g. $\ (ab)e = a(be)\,$ stays a product of nonunits, by $\,be\,$ unit $\!\iff\! b,e\,$ units. Therefore $\,pe\,$ isn't irreducible $\iff p\,$ isn't irreducible. Negating yields the sought result.


text:
Q: Interpolation with constraint on singular values of differentials Let $f \colon \mathbb{R}^n \to \mathbb{R}^n$ be a differentiable map. At any point $x \in \mathbb{R}^n$, I define (for the lack of knowing a better term) the 'singularity' $S(f,x)$ of $f$ at $x$ to be
$$ S(f,x) = \sqrt{\sum_{i=1}^n (\log \sigma_i)^2} $$
where the sum is taken over the singular values $\sigma_i$ of the matrix $df_x$. Define the 'total singularity' $S(f)$ as
$$ S(f) = \int S(f,x) \text{ } dx $$
I am given a collection of pairs $(x_1,y_1),\ldots,(x_k,y_k)$ in $\mathbb{R}^n \times \mathbb{R}^n$, and I would like to find the differentiable map $f \colon \mathbb{R}^n \to \mathbb{R}^n$ which minimizes the total singularity. My question is: Is there an easy characterization of $f$?
A linear approximation of $E(f, x)$ would be
$$ E(f, x) \approx \sqrt{\sum_{i = 1}^n (\sigma_i - 1)^2} $$
Perhaps, finding $f$ with respect to this simplified singularity measure is easier. I would be interested in this as well.


text:
Q: commons-io-2.4.jar is showing as Native Platform with 0 supported device I have developed an APP using apache commons-io-2.4.jar for network data operations now
I want to deploy my APK in Google's Play Store.
I have deployed my app with version 1.0 with commons-io-2.4.jar then it's not showing any supported device and commons-io-2.4.jar is showing as Native Platform  but when I have removed this commons-io-2.4.jar in 1.3 version its showing me something 9K supported devices.
Now Problem is, I have not define any NDK configuration but this jar file still showing as native Platform.
can Anyone help me to deploy my App with commons-io-2.4.jar at Play Store.
Any help would be appreciated great.

A: Following up on this I had the same issue.
All Android devices were incompatible with my app. The message was 'Doesn't support required ABI - commons-io-2.4.jar'
I had to exclude the commons.io from apache in the build.gradle.
configurations.all {
    resolutionStrategy {
        exclude module: 'org.apache.commons.io'
    }
}

Then include my own downloaded commons-io 2.6 from mvnrepo
implementation files('libs/commons-io-2.6.jar')

Make sure to add the jar file in libs directory and right click to 'Add as Library'. Hope this helps someone.


text:
Q: About the connectivity to IBM database using JDBC in Java I have a problem connecting to IBM (universal) database using JDBC. I wrote the code in Notepad using Java and I loaded drivers of IBM database i.e(driver name and connection URl).  When I run the code using general compilation (javac code.java and java code) I am getting an error message "cannot find the driver" but I specified the correct driver name for that.  Actually I did this program using Eclipse using the same database with same driver name and all and finally I succeeded, but I cant get this without using an IDE.  So please help me how to connect without the IDE and how to run it in a command prompt.

A: You need to include the necessary JAR files on the classpath when you run your program on the command line.
If you're using IBM's DB2 UDB database, the required driver file is db2jcc.jar, and I think db2jcc_license_cisuz.jar and db2jcc_license_cu.jar are necessary for licensing as well.  Search for those files, and include them on the classpath when you run your program from the command line.


text:
Q: How to get list of .so that python script use? For example I run python3 my_script.py, my_script.py uses tensorflow package inside, that use cuda libs, how can I get list of .so libs that are loaded at script execution?
UPDATE:
strace -e trace=open python3 my_script.py

don't print .so files, also how to suppress output of script itself, i.e. get only output of strace?


text:
Q: WebRTC - No Streams Apparently Means No ICE Transitions WebRTC peer to peer setup works perfectly with both audio and video locally and remotely. The ICE connection state transitions as expected and finally lands in the "connected" state.
Now if I don't add any audio or video streams to the peer, the session descriptions and ice candidates are exchanged and applied successfully, but the ice connection state never changes to anything. Not to checking, connected, disconnect, failed, or closed. No exceptions are thrown either.
If I add just an audio stream, again everything is exchanged and applied successfully, and the ice connection state this time transitions to "checking" but nothing after that.
Any insight as to why this is?

A: If you look at the SDP generated you'll see it has no m= sections. Those are necessary in order to have a=candidate lines and without those you can not establish a connection (and it would be surprising if you got candidates). There is some discussion around this issue here.
For the second question the answer is "it depends". This discusses how to use chrome's webrtc-internal for analysing the issue.


text:
Q: How to access a dynamic textbox that doesn't exist until a later frame in the timeline? I'm doing a project using ActionScript 2 where I'm loading in text from an XML file to dynamic text boxes. I'm loading everything in on the first frame, but there are boxes that do not exist in the timeline until frame 5 or so. Is there anyway I can access those to set their text property from the first frame?? Thanks!

A: Quick and dirty answer:
If you know exactly which frame the text boxes appear on, you can use this procedure to populate their text as soon as they're available:
1.  Set their visibility to false in Flash
2.  In an action keyframe on the same frame number when the text field appears, apply the value to the newly instanced text field
3.  In the same action keyframe, set their visibility to true.  This will avoid flicker as text will already be populated when they become visible.
If you were using AS3, I'd suggest the OOP answer instead:

*

*Write a function that listens for ADDED events and add the handler function to the stage in the first frame.  As new items are added on the stage they will bubble up and be caught by this handler

*In the handler function inspect the target of the event; if it is a textField and is named after one of the text fields you are interested in, apply the cached value from your loaded XML file

In our dev team we use the latter approach all the time.  Works like a charm.


text:
Q: Cloudant-client query with nested array fields using #elemMatch selector Is it possible to create the same query explained here: Cloudant Selector Query using the next java client: https://github.com/cloudant/java-cloudant?

A: You can pass the query selector string to the query method e.g.
String selector = "{\"selector\":{\"loansBorrowed\":{\"$elemMatch\":{\"loanamount\":{\"$gt\":1000}}}}}";
QueryResult<ProfileDocumentPojo> result = db.query(selector, ProfileDocumentPojo.class);
List<ProfileDocumentPojo> profiles = result.getDocs();


text:
Q: How can i access element value in SOAP response with lxml objectify I have SOAP response:
<?xml version='1.0' encoding='utf-8'?><soapenv:envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"><soapenv:body><createsessionresponse soapenv:encodingstyle="http://schemas.xmlsoap.org/soap/encoding/"><createsessionreturn xsi:type="xsd:string">59C3F170141E9CF6F5BF98FB39B0237B</createsessionreturn></createsessionresponse></soapenv:body></soapenv:envelope>

objectify.dump returns this:
{http://schemas.xmlsoap.org/soap/envelope/}Envelope = None [ObjectifiedElement]
    {http://schemas.xmlsoap.org/soap/envelope/}Body = None [ObjectifiedElement]
        createSessionResponse = None [ObjectifiedElement]
          * {http://schemas.xmlsoap.org/soap/envelope/}encodingStyle = 'http://schemas.xmlsoap.org/soap/encoding/'
            createSessionReturn = '701C301EAA37A965B1B54A8EFD9ACD6F' [StringElement]
              * xsi:type = 'xsd:string'

How can i access the value of createSessionReturn ?

A: createSessionResponse is not using the http://schemas.xmlsoap.org/soap/envelope/ namespace
>>> import lxml.objectify
>>> doc = """<?xml version='1.0' encoding='utf-8'?><soapenv:envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"><soapenv:body><createsessionresponse soapenv:encodingstyle="http://schemas.xmlsoap.org/soap/encoding/"><createsessionreturn xsi:type="xsd:string">59C3F170141E9CF6F5BF98FB39B0237B</createsessionreturn></createsessionresponse></soapenv:body></soapenv:envelope>"""
>>> obj = lxml.objectify.fromstring(doc)
>>> obj
<Element {http://schemas.xmlsoap.org/soap/envelope/}envelope at 0x2978eb0>
>>> for e in obj.iter():
...     print repr(e)
...
<Element {http://schemas.xmlsoap.org/soap/envelope/}envelope at 0x2978eb0>
<Element {http://schemas.xmlsoap.org/soap/envelope/}body at 0x2978f50>
<Element createsessionresponse at 0x297c050>
'59C3F170141E9CF6F5BF98FB39B0237B'
>>>

lxml.objectify documentation mentions:

Lookups, however, inherit namespaces implicitly:

so obj.body.createsessionresponse.createsessionreturn won't work
>>> obj.body
<Element {http://schemas.xmlsoap.org/soap/envelope/}body at 0x2978f00>
>>> obj.body.createsessionresponse
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "lxml.objectify.pyx", line 218, in lxml.objectify.ObjectifiedElement.__getattr__ (src/lxml/lxml.objectify.c:3488)
  File "lxml.objectify.pyx", line 437, in lxml.objectify._lookupChildOrRaise (src/lxml/lxml.objectify.c:5743)
AttributeError: no such child: {http://schemas.xmlsoap.org/soap/envelope/}createsessionresponse
>>>

Still in the documentation

To access an element in a different namespace than its parent, you can
  use getattr():
For convenience, there is also a quick way through
  item access: c = root["{http://other/}c"]

Applied to your case it becomes:
>>> obj.body["{}createsessionresponse"]
<Element createsessionresponse at 0x2978f50>
>>> obj.body["{}createsessionresponse"].createsessionreturn
'59C3F170141E9CF6F5BF98FB39B0237B'
>>>

>>> obj.body["{}createsessionresponse"].createsessionreturn
'59C3F170141E9CF6F5BF98FB39B0237B'
>>> type(obj.body["{}createsessionresponse"].createsessionreturn)
<type 'lxml.objectify.StringElement'>
>>> obj.body["{}createsessionresponse"].createsessionreturn.text
'59C3F170141E9CF6F5BF98FB39B0237B'
>>> type(obj.body["{}createsessionresponse"].createsessionreturn.text)
<type 'str'>
>>>


text:
Q: XPath expression to get a node and exclude a node within I'm trying to get everything inside the div "entry" accept for the paragraph tag with the class = "metadata"

The senator's lack of action on gun legislation is glaring after
       two mass shootings this weekend killed 31.

McConnell has for months now been the plug halting nearly every piece
       of legislation Democrats pass through the House, including gun
       measures that enjoy bipartisan support.

            This entry was posted on Tuesday, August 6th, 2019 at 10:23 am

A: This XPath selects anything under your div with class entry.
Then uses /*[not(@class="metadata alt") which looks at all child nodes that do not have a class value of "metadata alt", which includes nodes which do not have a class attribute...
//div[@class="entry"]/*[not(@class="metadata alt")]

This gives two elements...

The senator's lack of action on gun legislation is glaring after
       two mass shootings this weekend killed 31.

McConnell has for months now been the plug halting nearly every piece
       of legislation Democrats pass through the House, including gun
       measures that enjoy bipartisan support.

If you want to check if the class attribute contains metadata, from How can I match on an attribute that contains a certain string? ...
//div[@class="entry"]/*[not(contains(concat(' ', @class, ' '), ' metadata '))]

The full code to test is...
$html = '

The senator\'s lack of action on gun legislation is glaring after
       two mass shootings this weekend killed 31.

McConnell has for months now been the plug halting nearly every piece
       of legislation Democrats pass through the House, including gun
       measures that enjoy bipartisan support.

            This entry was posted on Tuesday, August 6th, 2019 at 10:23 am

';

$doc = new DOMDocument();
$doc->loadHTML($html);

$xp = new DOMXPath($doc);

$p = $xp->query('//div[@class="entry"]/*[not(@class="metadata alt")]');
foreach ($p as $out )   {
    echo $doc->saveHTML($out).PHP_EOL;
}

A: If I understand correctly what your are looking for, the expression
//div[@class='entry']/p[position() = 1 to count(../p[not(@class="metadata alt")])]

selects

The senator's lack of action on gun legislation is glaring after two mass shootings this weekend killed 31.The senator's lack of action on gun legislation is glaring after two mass shootings this weekend killed 31.
  McConnell has for months now been the plug halting nearly every piece of legislation Democrats pass through the House, including gun measures that enjoy bipartisan support.


text:
Q: Rspec testing conditional routing constraints I'm trying to write some rspec integration tests to test that my conditional routes are routing correctly, but I'm getting a bunch of problems.
In routes.rb:
root :to => "error#ie6", :constraints => {:user_agent => /MSIE 6/}
root :to => "protocol_sets#index", :constraints => UserRoleConstraint.new(/doctor/i)
root :to => "refill_requests#create", :constraints => UserRoleConstraint.new(/member/i)
root :to => "refill_requests#create", :constraints => {:subdomain => "demo"}
root :to => "site#index"

In spec/requests/homepage_routing_spec.rb
require 'spec_helper'

describe "User Visits Homepage" do
  describe "Routings to homepage" do
    it "routes / to site#index when no session information exists" do
      visit root_path
    end
  end
end

I get the following error when I try to run the test.

Failures:

  1) User Visits Homepage Routings to homepage routes / to site#index when no session information exists
     Failure/Error: visit root_path
     NoMethodError:
       undefined method `match' for nil:NilClass
     # :10:in `synchronize'
     # ./spec/requests/homepage_routings_spec.rb:6:in `block (3 levels) in '

Finished in 0.08088 seconds
1 example, 1 failure

Failed examples:

rspec ./spec/requests/homepage_routings_spec.rb:5 # User Visits Homepage Routings to homepage routes / to site#index when no session information exists

From Googling around I'm guessing there may be a problem with how rspec/capybara handle conditional routes.
Is there anyway to test constraints on routes with rspec and capybara?

A: As this drove me nuts over the last days, I found the solution with the help of a colleague.
When using named route constraints, like UserRoleConstraint in the example, I resorted to actually stubbing the matches? method of the constraint int he specs that needed it, i.e.:
describe 'routing' do
  context 'w/o route constraint' do
    before do
      allow(UserRoleConstraint).to receive(:matches?).and_return { false }
    end

    # tests without the route constraint
  end
  context 'w/ route constraint' do
    before do
      allow(UserRoleConstraint).to receive(:matches?).and_return { true }
    end
  end

  # tests with the route constraint
end

Note that this requires you to have named constraints, which might not apply to your case.

A: For the protocol constraint you can just specify an entire url with dummy domain. See this answer.


text:
Q: xcode - Label changes value when I change views I have searched around and cannot find anything, help would be appreciated. I am very new to objective-C and Xcode.
In my app the player starts with 100 coins, this is represented in a label. When the user clicks a button to spend 10 coins, a popup box appears and asks 'are you sure', the user can click ok, or cancel.
If the user clicks 'ok' they spend 10 coins. At the moment, in the simulator when i'm in the same view everything is fine, the 100 goes down to 90 etc...
But when I go to another view and then back again, the coin amount goes back up to 100. This is the same when the user exits the app.
Here is my code:
.h file
//Coin
IBOutlet UILabel * coinCount;

.m file
int coinAmount = 100;

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
if (buttonIndex == 0)
{
    NSLog(@"user pressed Cancel");
    // Any action can be performed here
}
else
{
    NSLog(@"user pressed OK");

    coinAmount -= 10;
    [coinCount setText:[NSString stringWithFormat:@"%d", coinAmount]];
    NSString * string = [NSString stringWithFormat:@"%d", coinAmount];

    //Save coin amount
    NSString * saveCoinAmount = string;
    NSUserDefaults * defaultsCoinAmount = [NSUserDefaults standardUserDefaults];
    [defaultsCoinAmount setObject:saveCoinAmount forKey:@"saveCoinLabel"];
    [defaultsCoinAmount synchronize];
}

}
That seems to save the new coin amount, so now when the user goes to another view and back i try and load the saved coin amount:
   - (void)viewDidLoad
{
[super viewDidLoad];
//Coin Label
NSUserDefaults * defaultsLoadCoin = [NSUserDefaults standardUserDefaults];
NSString * loadCoinLabel = [defaultsLoadCoin objectForKey:@"saveCoinLabel"];
[coinCount setText:loadCoinLabel];

}

Any help would be greatly appreciated!

A: Your problem is that you are storing your coins in two places - an integer variable and the label.  When you return to your view you restore the saved coin amount directly into the label, but when you perform the "purchase" you use the integer, which has been re-initialised to 100.
I also suggest you get out of the habit of using instance variables and use properties.
You should do something like this -
.m file
@interface MyClass ()             // Change this to suit your class name

@property NSInteger coinAmount;
@property (weak,nonatomic) IBOutlet UILabel *coinLabel;

@end

@implementation MyClass

- (void)viewDidLoad
{
   [super viewDidLoad];
//Coin Label
   NSUserDefaults * defaultsLoadCoin = [NSUserDefaults standardUserDefaults];
   if ([defaultsLoadCoin objectForKey:@"coins] == nil) {
      self.coinAmount=100;
      [defaultsLoadCoin setInteger:self.coinAmount forKey:@"coins"];
   }
   else {
      self.coinAmount = [defaultsLoadCoin integerForKey:@"coins"];
   }

   self.coinLabel.text=[NSString stringWithFormat:@"%ld",self.coinAmount];

}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
if (buttonIndex == 0)
{
    NSLog(@"user pressed Cancel");
    // Any action can be performed here
}
else
{
    NSLog(@"user pressed OK");

    self.coinAmount -= 10;
    self.coinLabel.text=[NSString stringWithFormat:@"%ld",self.coinAmount];

    //Save coin amount
    NSString * saveCoinAmount = string;
    NSUserDefaults * defaultsCoinAmount = [NSUserDefaults standardUserDefaults];
    [defaultsCoinAmount setInteger:self.coinAmount forKey:@"coins"];;
    [defaultsCoinAmount synchronize];
}

A: Your coinAmount property is not persistent through app launches or initialisations of the view controller in which it is created. You should consider persisting this value in database (like CoreData) or in NSUserDefaults.
My advice: start with basics (links to docs):
CoreData
NSUserDefaults


text:
Q: ¿Por qué no esta redirigiendo a la pagina de mercadopago con node/express? Desde Angular le envio los productos a comprar a node/express, éste se encarga de enviar esos productos a mercadopago. Desde node/express en la linea de código
res.redirect(response.body.init_point);. deberia abrir la interfaz/pagina de mercadopago para que el usuario pueda pagar. Pero desde Angular por consola muestra este error:

Access to XMLHttpRequest at 'https://www.mercadopago.com.ar/checkout/v1/redirect?pref_id=blablabla blabla bla'
(redirected from 'http://localhost:3000/checkout') from origin 'http://localhost:4200' has been blocked by CORS policy:
Response to preflight request doesn't pass access control check: Redirect is not allowed for a preflight request.

Acá el codigo desde node/express:
archivo server.ts

import express from 'express'
var multer  = require('multer')
const uuid = require('uuid')
const app = express(); // inicializo express
const cors = require('cors'); // para que el server acepte peticiones de cualquier puerto ej 4200 de Angular
const path = require('path');

// para que acepte peticiones de cualquier puerto ej 4200 de Angular, caso contrario desde Angular va a dar un error de Police cors
app.use(cors());
// middlewares son funciones que procesan y transforman las peticiones entrantes en el servidor
app.use(express.json());
// para que al enviar datos de un formulario los convierta a objeto json
app.use(express.urlencoded({extended: false}));

app.use((req, res, next) => {
  res.header('Access-Control-Allow-Origin', '*');
  res.header('Access-Control-Allow-Headers', 'Authorization, X-API-KEY, Origin, X-Requested-With, Content-Type, Accept, Access-Control-Allow-Request-Method');
  res.header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, DELETE');
  res.header('Allow', 'GET, POST, OPTIONS, PUT, DELETE');
  next();
});

app.use(mercadopagoRoutes);

app.use(express.static('public')); // Carpeta public la hago de acceso publica. para poder ver las imagenes desde el navegador

// Configuro el puerto. Tomo el puerto del sistema operativo o el 3000
app.set('port', process.env.PORT || 3000);

// Inicio el servidor
app.listen(app.get('port'), () => {
  console.log('usuarios server on port:', app.get('port'));
});

app.get('/', (req, res) => {
  res.send('Welcome to my API');
})

Esta es la ruta:
router.post('/checkout', checkout);

controlador:
// SDK de Mercado Pago
const mercadopago = require("mercadopago");
import {Compramp} from '../compramp';
import { Request, Response } from "express";

mercadopago.configure({
  // el token es el de "produccion" que te da mercadopago, seria el token del vendedor el que recibe la plata.
  access_token:
    "APP_USR-xxxxxxxxxxxxxxxx xxxxxxxxxxxxxxx xxxxxxxxx",
});

export const checkout = async (
  req: Request,
  res: Response
): Promise<Response> => {

  let compra = [{
    title: '',
    unit_price: 0,
    quantity: 0
  }]

  let items: Compramp[] = [];

  compra = req.body;

  for(let data of compra){
    items.push({
      title: data.title,
      unit_price: parseInt(data.unit_price.toString()),
      quantity: parseInt(data.quantity.toString())
    });
  }

  try {
    // objeto de preferencia
    let preference = {
      items
    }
      mercadopago.preferences
      .create(preference)
      .then(function (response) {
        console.log(response.body);
        // redirije a pagina de mercadopago 'https://www.mercadopago.com.ar/checkout/v1/redirect?pref_id=bla bla bla'
        res.redirect(response.body.init_point);
      })
      .catch(function (error) {
        console.log(error);
      });

  } catch (e) {
    console.log(e);
    return res.status(500).json("Internal server error");
  }
};

Aca desde Angular muestro como le envio los productos a node/express:

sendData() {

    let compra: Compramp[] = [];

    for (let book of this.bookList) {
      compra.push({
        title: book.name,
        unit_price: book.price,
        quantity: book.quantity
      });
    }

    this.mercadopagoService.checkout(compra).subscribe(
      res => {
        //console.log(res);
      },
      err => console.error('Error al recibir la data de compra en el servidor. ' + err)
    );
  }

El servicio mercadopago.service:

private SERVER = 'http://localhost:3000/checkout';

 checkout(compra: any) {
    return this.http.post(`${this.SERVER}`, compra);
  }


text:
Q: In R, how do I code to analyse patients with follow up at any given time point? I have patients with baseline pain scores and follow up of 6 months, 1 year and 2 years (each their own variable column). I have 26,000+ patients. There is missing data at those various time points. I can easily analyse pain score outcomes at one year excluding missing, 6mths and two years etc.... What I would like to do is analyse outcomes in those with data at EITHER 6mths, one year or two year. Some patients will have more than one and some will have missing data for all three. Any ideas how to code this? Maybe another column with mutate() ... that creates 'vas.outcome' and then in this variable I can have one-year data, if missing one-year then two-year, and if missing two-year then 6-month. If all three missing then code as NA.
# A tibble: 6 x 4
        vas.base      vas.6mth       vas.year      vas.two
          <dbl>         <dbl>         <dbl>         <dbl>
1           5            NA              NA           4
2           9            2.3             1.2          NA
3           8.1          NA              NA           NA
4           10           NA              NA           3.3
5           6.5          6.5             NA           NA
6           8            NA              NA           3

A: one approach:
library(dplyr)

your_data_frame %>%
  mutate(vas.outcome = coalesce(vas.6mth, vas.year, vas.two))

A: I'm not 100% sure what you want your final dataset to look like, and I'm sure there are more elegant ways, but to choose the first occurrence of an outcome (after baseline), you can do:
Data
df <- read.table(text = "id        vas.base      vas.6mth       vas.year      vas.two
1           5            NA              NA           4
2           9            2.3             1.2          NA
3           8.1          NA              NA           NA
4           10           NA              NA           3.3
5           6.5          6.5             NA           NA
6           8            NA              NA           3", header = TRUE)

dplyr approach:
library(tidyr)
df %>% pivot_longer(starts_with("vas")[-1], names_to = "visit") %>%
  group_by(id) %>% mutate(vas.outcome = first(na.omit(value))) %>%
  slice(1) %>% select(id, vas.outcome) %>%
  left_join(df, by = "id")

Output:
#      id vas.outcome vas.base vas.6mth vas.year vas.two
# <int>       <dbl>    <dbl>    <dbl>    <dbl>   <dbl>
# 1     1         4        5        NA       NA       4
# 2     2         2.3      9        2.3      1.2      NA
# 3     3         NA       8.1      NA       NA       NA
# 4     4         3.3      10       NA       NA       3.3
# 5     5         6.5      6.5      6.5      NA       NA
# 6     6         3        8        NA       NA       3

A: You could use a case_when()/fcase() approach
dt[, pain:=fcase(
  !is.na(vas.year), vas.year,
  !is.na(vas.two), vas.two,
  !is.na(vas.6mth), vas.6mth,
  default = NA
)]

or
dt %>%
  mutate(pain:=case_when(
    !is.na(vas.year)~vas.year,
    !is.na(vas.two)~vas.two,
    TRUE~vas.6mth
  ))

Output:
   vas.base vas.6mth vas.year vas.two pain
1:      5.0       NA       NA     4.0  4.0
2:      9.0      2.3      1.2      NA  1.2
3:      8.1       NA       NA      NA   NA
4:     10.0       NA       NA     3.3  3.3
5:      6.5      6.5       NA      NA  6.5
6:      8.0       NA       NA     3.0  3.0


text:
Q: Create-react-app weird folder structure on Github I'm using create-react-app (https://github.com/facebookincubator/create-react-app) to start my React application. Here's what I did:

*

*create-react-app barrex (inside Documents directory)

*cd barrex

*git add -u

*git commit -m "Starting new project"

*git push -u origin master
I have a new repo made on my Github called "barrex" and I would assume that when I push it to my Github, it would just show the files inside my folder such as src, public, index.html, etc. However, it somehow got my Documents folder in there too.

Only when I click inside this folder will I get the project files.

Why is this happening?

A: Follow this steps instead:

*

*create-react-app barrex

*cd barrex

*git init

*git remote add origin (https://)git@github.com:UserName/barrex.git
Note: Ignore "(https://)" if you are using ssh

*git add .

*git commit -m "Initial Commit"

*git push -u origin master

I hope that works for you.


text:
Q: Pwa show always chrome logo in shurtcut I've recently try to install multiple PWA, but I don't really understand why shurtcut icon have always chrome logo.
I've try 4 PWA installation, 4 this case.
Anyone know if i need to change chrome parameters ?
You can try using this PWA :
https://a2hs.glitch.me/
Thank you !


text:
Q: Geom_dotplot() does not distinguish levels of a factor, falling all points in the same X-axis I have densities of a marine species according to the year (two levels: 2020 and 2021), the protection level of the area (three levels: NP (Non-Protected), PP (Partially-Protected) and FP (Fully-Protected)) and the depth (two levels: shallow and deep). Here I show an example dataframe:
set.seed(100)
df <- data.frame(Year=as.factor(c(rep(2020,18),rep(2021,18))),
                 Prot=c(rep(c("NP","PP","FP"),each=6,2)),
                 Depth=c(rep(c("Shallow","Deep"),each=3,6)),
                 Density=c(runif(n = 36, min = 1, max = 20)))
str(df)

'data.frame':   36 obs. of  4 variables:
 $ Year   : Factor w/ 2 levels "2020","2021": 1 1 1 1 1 1 1 1 1 1 ...
 $ Prot   : Factor w/ 3 levels "FP","NP","PP": 2 2 2 2 2 2 3 3 3 3 ...
 $ Depth  : Factor w/ 2 levels "Deep","Shallow": 2 2 2 1 1 1 2 2 2 1 ...
 $ Density: num  6.85 5.9 11.49 2.07 9.9 ...

I would like to make a boxplot considering the three factors mentioned, including sample points using 'geom_dotplot()'. Here I show the simplified code I am using:
Plot <- ggplot(df, aes(x=Prot, y=Density)) +
  geom_boxplot(aes(fill=Year)) +
  geom_dotplot(aes(fill=Year),
               binaxis = "y",
               binwidth=0.7,
               drop=FALSE,
               stackdir = "center",
               dotsize = 0.5) +
  xlab("Protection Level") +
  ylab("Density") +
  facet_wrap(~Depth)

Plot

As you can see, the points are not properly aligned within the 'Year' factor. That is, points for the year 2020 and 2021 are all aligned together within each protection level (either 'NP', 'PP' or 'FP').
Does anyone know how to solve this?
Thanks in advance

A: You could use the position argument with position_dodge:
ggplot(df, aes(x=Prot, y=Density)) +
  geom_boxplot(aes(fill=Year)) +
  geom_dotplot(aes(fill=Year),
               binaxis = "y",
               binwidth=0.7,
               drop=FALSE,
               stackdir = "center",
               position=position_dodge(0.75),
               dotsize = 0.5) +
  xlab("Protection Level") +
  ylab("Density") +
  facet_wrap(~Depth)


text:
Q: Could not determine datatype of Instant I am using Hibernate with a Postgres DB and have a problem with the following query:
@Query("Select l from Leasing l where l.user = :user " +
        "   and (:fromDate is null or l.from >= :fromDate)")
Page<Leasing> findAllByUserAndStatusAndFromAndTo(Pageable pageable, @Param("user") User user,
                                                 @Param("fromDate") Instant from);

I got the error message:
Caused by: org.hibernate.exception.SQLGrammarException: could not extract ResultSet
Caused by: org.postgresql.util.PSQLException: ERROR: could not determine data type of parameter $2

The field is defined like this:
@Column(name = "from_time")
@NotNull
private Instant from;

I know this is a problem with Postgres, because in the test-environment an H2 database is used and it worked fine.
In the postgres database the datatype of the field is: timestamp without time zone
I tried to use LocalDateTime instead of Instant but it didn't work either.
EDIT:
If I remove :fromDate is null it works, but I need this check?