text:
Q: How we use our own collection for Lazy loading in eclipseLink? I want to use MyCollection implementing the collection interfaces provided by java. It is working fine for EAGER loading but for lazy loading eclipselink uses its own implemntation(IndirectList) . Is it possible to use MyCollection for Lazy loading ?
MyCollection code goes here :
package com.alta.convertor;

import java.util.Collection;
import java.util.Iterator;
import java.util.Vector;

public class MyCollection<E> implements Collection<E>,Cloneable{

    Collection<E> collection;
    @SuppressWarnings({ "unchecked", "rawtypes" })
    public MyCollection() {
        this(new Vector());
    }

    public MyCollection(Collection<E> collection) {
        this.collection=collection;
    }
    @Override
    public int size() {

        return collection.size();
    }

    @Override
    public boolean isEmpty() {

        return collection.isEmpty();
    }

    @Override
    public boolean contains(Object o) {

        return collection.contains(o);
    }

    @Override
    public Iterator<E> iterator() {

        return collection.iterator();
    }

    @Override
    public Object[] toArray() {

        return collection.toArray();
    }

    @Override
    public <T> T[] toArray(T[] a) {

        return collection.toArray(a);
    }

    @Override
    public boolean add(E e) {

        return false;
    }

    @Override
    public boolean remove(Object o) {

        return collection.remove(o);
    }

    @Override
    public boolean containsAll(Collection<?> c) {

        return collection.containsAll(c);
    }

    @Override
    public boolean addAll(Collection<? extends E> c) {

        return collection.addAll(c);
    }

    @Override
    public boolean removeAll(Collection<?> c) {

        return collection.removeAll(c);
    }

    @Override
    public boolean retainAll(Collection<?> c) {

        return collection.retainAll(c);
    }

    @Override
    public void clear() {

        collection.clear();
    }

}

My Entity Class as:
@Entity

public class Person implements Serializable{

    /**
     *
     */
    private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    @Column(name="personid")
    private Long personId;
    private String firstName;
    private String lastName;
    private String email;

    @OneToMany(cascade = CascadeType.ALL,mappedBy="person",targetEntity=Address.class,fetch=FetchType.EAGER)

private MyCollection addressArray;
    public Person() {

    }

    public Person(String firstName, String lastName, String email) {
        super();
        this.firstName = firstName;
        this.lastName = lastName;
        this.email = email;

    }
    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public MyCollection<Address> getAddressArray() {
        return addressArray;
    }

    public void setAddressArray(MyCollection<Address> address) {
        this.addressArray = address;
    }

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public Long getPersonId() {
        return personId;
    }

    public void setPersonId(Long personId) {
        this.personId = personId;
    }

}

A: Not currently, you need to use one of the collection interfaces to allow LAZY (List, Set, Map).  You can use your own collection type if you use EAGER.
However, I am presently working on the issue, and will most likely check in a fix to 2.6 soon,
https://bugs.eclipse.org/bugs/show_bug.cgi?id=411819
In general it is still better to use the collection interfaces if you can.
You could also wrap the relationship in an Embeddable which represents your collection.


text:
Q: pyspark dataframe reference vs value I learn pyspark. I'm trying to build DataFrame from sql, for example
DF=spark.sql("with a as (select ....) select ...")

My sql is a little complex, so it's executed for 20 minutes.
I feel like DF is a refer to my SQL, it means when I execute DF.head(10) it takes 20 minuts, next step DF.count() takes also 20 minuts etc.
I'd like to have DataFrame like in pandas with value in RAM where DF.head(10), DF.count() take a few seconds.
The only way I can think of is to use "create table", for example:
xx=spark.sql("create table yyy as with a as (select ....) select ...")
DF=sqlContext.sql("select * from yyy")

It works but it looks strange to me.
What are the best practices to create DataFrame in pyspark from complex SQL ? I would like to skip the step with "create table".

A:
I'd like to have DataFrame like in pandas with value in RAM where DF.head(10), DF.count() take a few seconds.

Pandas load your data into memory from the moment you read that data, that's why it's lightning-fast. But remember the data size you can load is limited to your computer's memory

My sql is a little complex, so it's executed for 20 minutes. I feel like DF is a refer to my SQL, it means when I execute DF.head(10) it takes 20 minuts, next step DF.count() takes also 20 minuts etc.

Spark does not load the data when you read it. It only read data when there is an "action" like cache or count or head.

The only way I can think of is to use "create table"

Yes, creating a table is also an action, where your query is executed entirely. Next time when you read it, it doesn't have to re-compute it. Tha alternative of creating table is caching, you can do something like this DF.cache().count(), spark will load entire data into memory and all other actions later will be much faster.

redpajama_set_name: RedPajamaStackExchange


text:
Q: The Specified network name is no longer available I have an application the uses a shared drive drive to access some data it uses.  I currently have about 100 people using the application fine but it will not allow new connection.
I can not access the share via UNC either typing the IP or the server name.  I can ping the server name and IP though.
A restart will fix this but not ideal during working hours.  Any ideas would be much appreciated.

A: Looks to me as through your application might be keeping connections persistently open rather than only opening a connection when required and closing them when done.  You're likely getting some high resource utilisation on the server in question too.
You can check this in Computer Management under Shared Folders | Sessions or Open Files.
In general, Windows file sharing is not suitable for this kind of use, and you should probably be looking to implement a proper database.


text:
Q: How can I add multiple rows in a CSV, but overwrite every time the script is run? So I am running a script which pulls data for 60 different items, for easy use i want to store this data in a csv file. Every time i run the script i want to store all 60 items and then overwrite all previous data. When i run it at the moment using the 'w' argument it only adds the very last item it pulls. If i change it to 'a' it will add all 60 items however it will not overwrite when i run it next. Any help is appreciated!!
import os, random, csv

vin = '1600'
n = 1
for path, subdirs, files in os.walk(r'\\sorion-app01\Shares\ProcessData\Broadcasts\Good'):
   for filename in files:
        if not 'XX' or not '0X' or not 'XXXXXX' or not '000X' in filename:
            f = os.path.join(path, filename)
            vins = str(f)[50:67]
            if not 'X' in vins[13:17]:
                vin = int(vins[13:17])
                if vin > 1600:

                    from sys import platform
                    import pyodbc

                    if platform == "linux" or platform == "linux2":
                        print("linux")
                        driver = 'mydriver.so'

                        conn = pyodbc.connect(
                            driver = driver,
                            TDS_Version = '7.2', # Use for
                            server = 'aserver',
                            port = 1433,
                            database = 'TraceDB',
                            uid = 'EXTUser',
                            pwd = 'EXTPass!')

                    elif platform == "win32":
                        #print("Win32")
                        conn = pyodbc.connect('DRIVER={SQL Server};SERVER=database')

                   #pull the data here#

                    with open('file.csv', 'w', newline='') as csvfile:
                        filewriter = csv.writer(csvfile, delimiter=',',
                                                quotechar='|', quoting=csv.QUOTE_MINIMAL, lineterminator = '\n',)
                        header = [('column1'), ('column1'), ('column2'), ('column3'), ('column4'), ('column5')]
                        if not csvfile:
                            filewriter.writeheader(header)
                        filewriter.writerow([data, data2, data3, data4, data5, data6])

                        n=n+1

A: It's because you're re-opening the file every time round the loop; you want to open it before the loop and close it after the loop.

A: Overwriting it as a empty file at the very beginning of your code works for you?
import os, random, csv

with open("file.csv", "w") as my_empty_csv:
         pass

vin = '1600' n = 1

[...]

Best!


text:
Q: The simple one to make callback in android - AndroidX I am trying to figure out how callback work and the simplest way to do it, but I can't manage to solve it
This is my Listener Interface
public interface OnTestingCBListener {
     void onSuccessCB(String SomeValue);}

This is my MainActivity.java
OnCreate(){
    //FIRST
    deviceSetup();
}

public void deviceSetup() {
    String DeviceID = "asdfg";
    final String[] FirebaseID = {""};

    //SECOND
    GetFireBaseIDCall(new OnTestingCBListener() {
        @Override
        public void onSuccessCB(String ResultValue) {
            //FOURTH
            FirebaseID[0] = ResultValue;
        }
    }, "Value1", "Value2");

    //FIFTH
    Toast.makeText(MainActivity.this, "Result: "+DeviceID+"#"+FirebaseID, Toast.LENGTH_LONG).show();
}

OnTestingCBListener onTestingCBListener;
public void GetFireBaseIDCall(OnTestingCBListener onTestingCBListener, String x, String y){
    if(x.equals("Value1") && y.equals("Value2")) {
        FirebaseInstanceId.getInstance().getInstanceId().addOnSuccessListener(MainActivity.this, new OnSuccessListener<InstanceIdResult>() {
            @Override
            public void onSuccess(InstanceIdResult instanceIdResult) {
                final String newToken = instanceIdResult.getToken();
                Log.d("newToken", "Success :)");

                //THIRD
                onTestingCBListener.onSuccessCB(newToken);
            }
        });

        Log.d("newToken", "Failed :(");
    }
}

It's doesn't work, any solution?

A: Follow these steps:

*

*First you have to make your activity extend the callback interface like:
public class MainActivity extends AppCompatActivity(), OnTestingCBListener {

*Then implement all non implemented functions of that interface in your activity.

*Then create an object of that interface and initialize it in onCreate() of your Activity like:
OnTestingCBListener onTestingCBListener;

in onCreate() initialize it like:
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        onTestingCBListener = this
    }

*Then call it's functions whenever you want like:
onTestingCBListener.onSuccessCB(newToken);

A: Please make sure that the log Log.d("newToken", "Success :)"); is logged in logcat hence we are certain that onSuccessCB() of the local onTestingCBListener listener is triggered.
The only issue with your code is that you are showing the Toast too early, and before the Firebase callback gets called, so the onTestingCBListener's onSucess() gets called after your Toast is shown, so transfer the Toast message within the listener onSucess(); so change below part of your code to be
...
//SECOND
GetFireBaseIDCall(new OnTestingCBListener() {
    @Override
    public void onSuccessCB(String ResultValue) {
        //FOURTH
        FirebaseID[0] = ResultValue;
        //FIFTH
        Toast.makeText(MainActivity.this, "Result: "+DeviceID+"#"+FirebaseID, Toast.LENGTH_LONG).show();
    }
}, "Value1", "Value2");
...

Also please notice that Firebase is working in background thread so it takes a while to get your data back to your activity.

A: The problem was solved, I need to initialize the listener first
final OnTestingCBListener onTestingCBListener;
    public void GetFireBaseIDCall(OnTestingCBListener onTestingCBListener, String x, String y){
        if(x.equals("Value1") && y.equals("Value2")) {
            FirebaseInstanceId.getInstance().getInstanceId().addOnSuccessListener(MainActivity.this, new OnSuccessListener<InstanceIdResult>() {
                @Override
                public void onSuccess(InstanceIdResult instanceIdResult) {
                    final String newToken = instanceIdResult.getToken();
                    Log.d("newToken", "Success :)");

                    //This is the problem!!
                    onTestingCBListener = onTestingCBListener;
                    //THIRD
                    onTestingCBListener.onSuccessCB(newToken);
                }
            });

            Log.d("newToken", "Failed :(");
        }
    }


text:
Q: Cannot use Encrpyted Home directory after upgrade to 14.04 My $HOME directory is encrypted. It was ok in 13.10, but, after upgraded to 14.04 desktop by do-release-upgrade, I can log in, however, the home hasn't been decrypted, and cause many application crash.
If I open nautilus for $HOME, I can see this:

After I clicked the Access-Your-Private-Data.desktop and input my password, which is not changed during the upgrade, I can see my HOME directory for a while, not very long.
I found if I log in the system through SSH, I can see my all files in $HOME, which means ssh can trigger the decryption correctly. But it doesn't work if I log in through gdm or lightdm.
What I have to do now is create another user, and log in the new user first, and ssh olduser@localhost to trigger the decryption, and SWITCH back to old user, then the HOME directory works for some times.
Another strange thing is that, sometimes, even the ssh still can access decrypted files, but the GUI failed to access anything.
Is there anyone have the same problem with me? Does anyone know how to fix this?
Thanks.

A: Make sure the ecryptfs filesystem is installed:
sudo apt-get install ecryptfs-utils


text:
Q: Use of global variables in static methods I need to assign a value to a global variable in a static method. Since I need that variable in a derived class.
But the problem is we are not able to use global variables in static methods.

A: Use global variables.  They're pretty easy.  See here:
http://msdn.microsoft.com/en-us/library/aa891830.aspx
One thing to note...if you're using global variables for something, it's most likely a flawed implementation design and there are probably other ways of accomplishing what you're trying to do.

A:
Tejashree S: I need to assign a string value in the parent class and use them in the child class.

To do this, you add a variable to the parent class's Class Declaration, then create a parm method in the parent class.
From the child class, you will be able to access the variable directly or via the parm method.

A: Create an object of the parent class in the static method and access the variable with the object name.
Suppose Class is Test then create an object
like,
Test obj= new Test();


text:
Q: Рефлексия для командной строки У меня есть кастомный атрибут, которым я помечаю поля, свойства и методы. Класс Commands содержит разные консольные команды. Класс CMD должен парсить строку args[i] и смотреть, есть ли такая команда в классе. Если есть, то проверить, является ли она полем, свойством или методом. В каждом case я сделал проверку на тип и приведение строки к этому типу. С методами все работает корректно, но если ввести поля или свойства, то он их не находит. Я мог накосячить в регулярном выражении или в условиях.
 using System.Diagnostics;
    using System.Reflection;
    using System.Text.RegularExpressions;

    [AttributeUsage(AttributeTargets.Method|AttributeTargets.Field|AttributeTargets.Property)]
    public class CommandLineAttribute : Attribute
    {
        public string CommandSwitch { get; set; }
        public CommandLineAttribute() {
            CommandSwitch = " ";
        }
        public CommandLineAttribute(string name)
        {
            this.CommandSwitch = name;
        }

    }

    class Commands
    {
        [CommandLine] public bool IpConfig;
        [CommandLine] public bool GetMac;
        [CommandLine] public bool Netstat;
        [CommandLine] public string Pathping { get; set; }

        [CommandLine]
        public void ping(string address)
        {
            Process.Start("ping", address);
            Console.WriteLine("ping is complete");
        }

        [CommandLine]
        public void tracert(string address)
        {
            Process.Start("tracert", address);
            Console.WriteLine("tracert is complete");
        }
    }

    class CMD
    {
        static bool IsValidCommand(string command)
        {
            string pattern = @"^-[a-zA-Z]+?(=[a-zA-Z0-9\.]*)?$";
            return Regex.IsMatch(command, pattern);
        }
        public static T ParseCommandLine<T>(string[] args) where T : new()
        {
            Type type = typeof(T);
            T obj = new T();

            bool found = false;
            string command="";
            string value;

            var Members = type.GetMembers();

            for(int m = 0; m < args.Length;m++)
            {

                for (int i = 0; i < Members.Length; i++)
                {

                    if (!args[m].Contains("="))
                    {
                        command=args[m].Substring(1);
                        value = "true";
                    }
                    else
                    {
                        command = args[m].Substring(1, args[m].IndexOf('=') - 1);
                        value = args[m].Substring(args[m].IndexOf('=') + 1);
                    }
                    if (Members[i].Name == command)
                    {
                        found = true;
                        switch (Members[i].MemberType)
                        {
                            case MemberTypes.Field:
                                {
                                    FieldInfo field = Members[i] as FieldInfo;
                                    var fieldType = field.FieldType;
                                    // Проверяем, входит ли тип поля в список допустимых для командной строки типов данных
                                    if (fieldType == typeof(int) || fieldType == typeof(double) || fieldType == typeof(bool) || fieldType == typeof(string))
                                    {
                                        Console.WriteLine("Type is valid");
                                    }
                                    else
                                    {
                                        Console.WriteLine("Type isn't valid");
                                        break;
                                    }

                                    object convertedValue = null;
                                    try
                                    {
                                        // Пытаемся провести преобразование строкового представления значения параметра командной строки к типу данных поля
                                        convertedValue = Convert.ChangeType(value, fieldType);
                                    }
                                    catch (Exception ex)
                                    {
                                        // Если такое преобразование невозможно, генерируем исключение InvalidCastException
                                        throw new InvalidCastException($"Cannot convert value '{value}' to type {fieldType.FullName}.", ex);
                                    }

        // Используем рефлексию, чтобы присвоить значение преобразованного значения параметра полю объекта
        ((FieldInfo)Members[i]).SetValue(obj, convertedValue);
                                      Process.Start(field.Name);
                                    break;
                                }
                                break;
                            case MemberTypes.Property:
                                {
                                    PropertyInfo property = Members[i] as PropertyInfo;
                                    var propertyType = property.PropertyType;
                                    if (propertyType == typeof(int) || propertyType == typeof(double) ||
                                        propertyType == typeof(bool) || propertyType == typeof(string))
                                    {
                                        Console.WriteLine("Type is valid");
                                    }
                                    else
                                    {
                                        Console.WriteLine("Type isn't valid");
                                    }

                                    object convertedValue = null;
                                    try
                                    {
                                        // Пытаемся провести преобразование строкового представления значения параметра командной строки к типу данных поля
                                        convertedValue = Convert.ChangeType(value, propertyType);
                                    }
                                    catch (Exception ex)
                                    {
                                        // Если такое преобразование невозможно, генерируем исключение InvalidCastException
                                        throw new InvalidCastException($"Cannot convert value '{value}' to type {propertyType.FullName}.", ex);
                                    }
                                    if (!property.CanWrite)
                                    {
                                        throw new InvalidOperationException();
                                    }
                                    property.SetValue(obj, convertedValue);
                                     Process.Start(property.Name);
                                }
                                break;
                            case MemberTypes.Method:
                                {
                                    var methodInfo = type.GetMethod(command);

                                    if (methodInfo == null)
                                    {
                                        throw new InvalidOperationException($"Method {value} not found.");
                                    }

                                    var parameters = methodInfo.GetParameters();

                                    if (parameters.Length != 1 || (parameters[0].ParameterType != typeof(int) && (parameters[0].ParameterType != typeof(double))
                                        && (parameters[0].ParameterType != typeof(bool)) && (parameters[0].ParameterType != typeof(string))))
                                    {
                                        throw new InvalidOperationException($"Method {args[1]} must have exactly one parameter of valid type.");
                                    }

                                    object convertedValue = null;
                                    try
                                    {
                                        // Пытаемся провести преобразование строкового представления значения параметра командной строки к типу данных поля
                                        convertedValue = Convert.ChangeType(value, parameters[0].ParameterType);
                                    }
                                    catch (Exception ex)
                                    {
                                        // Если такое преобразование невозможно, генерируем исключение InvalidCastException
                                        throw new InvalidCastException($"Cannot convert value '{value}' to type {parameters[0].ParameterType.FullName}.", ex);
                                    }
                                    methodInfo.Invoke(obj, new object[] { convertedValue });
                                }
                                break;
                        }
                    }
                }

            }

            if (!found) throw new ArgumentException(String.Format("Command", command,"isn't found"), "num");

            return obj;
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            CMD.ParseCommandLine<Commands>(new string[3] { "-ping=3dnews.ru", "-tracert=3dnews.ru","ipconfig" });
        }
    }


text: Q: How to install CVX in Python, along with chompack in windows 64 bit? Can anyone please give me the links to download the links to  install CVX in Phyton, along with chompack? I tried several version but never able to install chompack. I get error message like "failed building wheel CVXOPT" while installing chompack. But no error message in installing cvxopt. My machine windows 64 bit.


text:
Q: React-Native panResponder array with functional component I have a slider with 6 images and I want to be able to move each one of them using panResponder.
I wrote this code (which works, but it moves all the slider, not just one image)
    const pan = useState(new Animated.ValueXY())[0];

  const panResponder = useState(
    PanResponder.create({
      onMoveShouldSetResponderCapture: () => true, //Tell iOS that we are allowing the movement
      onMoveShouldSetPanResponderCapture: () => true, // Same here, tell iOS that we allow dragging
      onMoveShouldSetPanResponder: () => true,

      onPanResponderGrant: (e, gestureState) => {
        pan.setOffset({
          y: pan.y._value
        });
      },
  onPanResponderMove: Animated.event(
    [
      null,
      { dy: pan.y }
    ],
    {
      useNativeDriver: false,
      listener: (evt, gestureState) => {

      }
    }
  ),
  onPanResponderRelease: (evt, gestureState) => {
    //pan.flattenOffset();

    console.log(gestureState);

    if (gestureState.moveY > 710) {

      Alert.alert("Added to cart.");
    }
    else {
      Animated.spring(pan, {
        toValue: 100,
        useNativeDriver: false
      },
      ).start();
    }
  }
})
)[0];

return (
<View style={styles.container}>
  <View style={{ width, height: '100%' }}>
    <ScrollView
      horizontal
      style={{ width }}
      showsHorizontalScrollIndicator={false}
    >
      {
        products.map((product) => (
          <Animated.View key={product.id}
            style={{
              transform: [{ translateY: pan.y }]
            }}
            {...panResponder.panHandlers}
          >
            <Image
              style={{ width: width / 3, height, flex: 1 }}
              resizeMode="contain"
              source={{
                uri: product.product_image,
              }}
            />
          </Animated.View>

        ))

      }

    </ScrollView>
  </View>
  <View style={styles.cart}>
    <Text style={styles.cartText}>Here comes the cart</Text>
  </View>
</View >
  );
}

I want to be able to drag every image, not the whole slider. Is it possible? I understand we need an array of panResponders, but how to actually do it?
Many thanks

A: what you have to do for. everyone. image transform it into a single component, and to each of them add a panResponder , if you do it with only one, it takes the entire current component to raise the event


text:
Q: How do I enumerate network adapters on a Hyper-V guest using WMI? I've got a Hyper-V host, with several guests, each with one or more network adapters. How do I enumerate the network adapters on those guests?
Specifically, I'm looking for a particular guest, given a MAC address.
I'm using C# and System.Management.

A: I'll leave out some of the details:

*

*Connect to Hyper-V on the host.

*Enumerate the machines (SELECT * FROM Msvm_ComputerSystem).

*For each machine, find the associated Msvm_SyntheticEthernetPort objects.

var ports = computerSystem.GetRelated("Msvm_SyntheticEthernetPort");
foreach (ManagementObject port in ports)
{

*

*Get hold of the settings:

    var portSettings = port.GetRelated("Msvm_SyntheticEthernetPortSettingData");
    foreach (ManagmentObject portSetting in portSettings)
    {

*

*Look for the configured MAC address:

        string macAddress = (string)portSetting .GetPropertyValue("Address");


text:
Q: how get only specific fields from elsticsearch i have elasticsearch indice i have  filed name "titile":Rolex i want to write DSL to save
ratemax,ratemin fields as variable
can this be done here is my sample json
 "vente": [
      "62402c696a271a7d0ceeef2f"
    ],
    "status": [
      0
    ]
  },
  "ignored_field_values": {
    "description.keyword": [
      "ROLEX  \nPRINCE BRANCARD \"EATON QUARTER CENTURY CLUB\"  \nVERS 1930  \nMontre bracelet en or jaune 14K sur cuir.   \nBOITIER : rectangulaire curvex cintré en or jaune 14K (belle oxydation de l'or). Fond gravé d'une dédicace: \"Presented to Fred Peartree to mark a quarter century of continuous service with the T. Eaton, 1916-1941.\"   \nCADRAN : duodial, argenté deux tons, personnalisé Eaton, inscrit \"1/4 Century Club\" à la place des index. Aiguilles en acier bleui.  \nMOUVEMENT: mécanique, certifié chronometre, Ultra-Prima.   \nBRACELET : cuir avec boucle ardillon en or Rolex.  \nBoîtier et mouvement signés Rolex.  \nNumérotée 53207.  \nDIM. 42 x 24 mm.  \n \nCette montre fait partie d'une série personnalisée par un industriel canadien nommé Eaton. Cet entrepreneur avait l'habitude d'en faire cadeau à ses employés pour les remercier de leur fidélité.  \nA 14K gold manual winding wristwatch by Rolex from the 30's."
    ]
  }
}


text:
Q: How to implement a JTable selection interacting with a JTable What I'm trying to do:
I want to have two JTables side by side, and when you make a selection on the left JTable you see more detailed information about that row in the JTable to the right.
What's my problem?:
I have no idea how to implement this. I have tried using the addListSelectionListener, but I'm unsure on how I can use a listener from one table to interact with a completely different table. Such as, having the listener replace table2 with a new table that has completely new data.
I've included an SSCCE which shows the gist of what I did. I would appreciate any help, as I've been scouring the internet trying to piece this problem together.
import java.awt.BorderLayout;
import java.awt.Dimension;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.ListSelectionModel;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.AbstractTableModel;

public class TableInteraction extends JPanel
{
    private JTable table1;
    private JTable table2;

    public TableInteraction()
    {
        super();

        String[][] tableOneData = {{"Kathy", "Smith"}};
        String[][] tableTwoData = {{"Kathy", "Smith"}};
        String[][] tableThreeData = {{"Matt", "Bird"}};

        setLayout(new BorderLayout());
        FirstTableModel model1 = new FirstTableModel(tableOneData);
        table1 = new JTable(model1);
        table1.setPreferredScrollableViewportSize(new Dimension(500,200));
        table1.setFillsViewportHeight(true);
        table1.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        table1.setRowSelectionInterval(0,0);
        JScrollPane scrollPane1 = new JScrollPane(table1);

        SecondTableModel model2 = new SecondTableModel(tableTwoData);
        table2 = new JTable(model2);
        table2.setPreferredScrollableViewportSize(new Dimension(500,200));
        table2.setFillsViewportHeight(true);
        table2.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        JScrollPane scrollPane2 = new JScrollPane(table2);

        table1.getSelectionModel().addListSelectionListener(
                new ListSelectionListener()
                {
                    public void valueChanged(ListSelectionEvent event)
                    {
                        int index = table1.getSelectedRow();
                    }
                });

        add(scrollPane1, BorderLayout.WEST);
        add(scrollPane2, BorderLayout.EAST);
    }

    public class FirstTableModel extends AbstractTableModel
    {
        private String[] columnNames = {"First Name", "Last Name"};
        private String[][] data;

        public FirstTableModel(String[][] data)
        {
            this.data = data;
        }

         public int getColumnCount() {
             return columnNames.length;
         }

         public int getRowCount() {
             return data.length;
         }

         public String getColumnName(int col) {
             return columnNames[col];
         }

         public Object getValueAt(int row, int col) {
             return data[row][col];
         }
    }

    public class SecondTableModel extends AbstractTableModel
    {
        private String[] columnNames = {"First Name", "Last Name"};
        private String[][] data;

        public SecondTableModel(String[][] data)
        {
            this.data = data;
        }

         public int getColumnCount() {
             return columnNames.length;
         }

         public int getRowCount() {
             return data.length;
         }

         public String getColumnName(int col) {
             return columnNames[col];
         }

         public Object getValueAt(int row, int col) {
             return data[row][col];
         }
    }

    private static void createAndShowGUI() {
        JFrame frame = new JFrame("TableFilterDemo");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        TableInteraction newContentPane = new TableInteraction();
        newContentPane.setOpaque(true);
        frame.setContentPane(newContentPane);

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

    public static void main(String[] args) {
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGUI();
            }
        });
    }
}

A: Consider this (extension of my comment)
private String[] columnNames1 = {"First Name", "Last Name"};
private String[][] data1 = {{"Kathy", "Smith"},{"John","Doe"}};

private String[] columnNames2 = {"First Name", "Last Name"};
private String[][] data2 = {{"Kathy", "Smith"},{"John","Doe"}};

DefaultTableModel tableModel1 = new DefaultTableModel(data1, columnNames1);
DefaultTableModel tableModel2 = new DefaultTableModel(data2, columnNames2);

JTable jTable1 = new JTable(tableModel1);
JTable jTable2 = new JTable(tableModel1);

jTable1.getSelectionModel().addListSelectionListener(
                                   new ListSelectionListener()
{
     public void valueChanged(ListSelectionEvent event)
     {
          int index = jTable1.getSelectedRow();
          jTable2.removeRow(index);

     }
});

When a row from table1 is selected, The same row from table2 is deleted. This is a bizarre example that would not work without some null checks, but it shows how two tables can interact using the table model
Edit: with OP added comment
If you want to set the second table based on the first table, you can do something like this
jTable2.setModel(jTable1.getModel());

Also, you should place you listener AFTER creating  tables and models, so that you can can use the model. If they haven't been declared yet, you cant use them in the listener, unless they are declared as global


text:
Q: aptana custom auto-formatting? Using Aptana Studio 3 for php, curious if I can customize how the auto-format formats (pressing CRTL-SHIFT-F formats the current file for you)
I'd like to change something rather small, make it so brackets end up below their conditionals, for's, whiles, etc.
if(blah)
{
    stuff...
}

instead of
if(blah) {
    stuff...
}

cheers!

A: Go to:
Window => Preferences
Select the Aptana dropdown
Select Formatter
This gives you some pretty nifty control on some common a


text:
Q: What are the best ways to join two vectors without changing dimensions? sum, mean, median..etc I am looking for a way to represent 2 same dimension vectors as 1 like summation of corresponding elements of vector.
EDIT
I have 5 vectors from 5 word embedding models(string2vec, word2vec, doc2vec, topic2vec, and glove2vec) and now I want to combine them to form one representational vector to be fed into ml classification models. I have tried addition, multiplication, mean, median and distance formula. I am looking for techniques to join vectors other than the ones i mentioned

A: Your Question is incomplete. As far as I can understand you are willing to do operations on the vectors element-wise. Let the two vectors be
arr1=np.array([1,2,3])

and
arr2=np.array([4,5,6])

So, simple addition and subtraction element-wise can be done as arr1+arr2 or arr1-arr2. For element wise multiplication of the above vectors, you can use np.multiply(arr1,arr2) like syntax.
Hope it can help you. Else state your question clearly.

A: Having the same dimension does not guarantee identical features / structure among multiple models. In fact adding vectors for the same word from 2 different Doc2Vec models would probably be meaningless.
That being said, it might be interesting concatenating (some of) them and feeding them as input to another deep network. Ie: build and entirely new model.
This thread might help as well.
https://groups.google.com/g/gensim/c/N5SCiq1F45w/m/QqVuoTUYCQAJ

A: Using Numpy, you can do element wise operation very easily.
import numpy as np

a = np.ones((3,3))
b = np.ones((3,3))
c = a + b

Same goes to other operation. - , *, / (division is a bit more tricky)


text:
Q: I upgraded fron 12.04 to 12.10 and can not find my pictures I did an upgrade installation (not new) but now I can not find my pictures. And the reason I did the upgrade version was to keep all of my "old files" intact.
How can I find my pictures?

A: You could use GDmap to map out your hard drive and break down files by type and physical size. It should make it easier to locate your pictures.


text:
Q: Running maven-shade-plugin only for package phase Within my pom.xml I define following plugins - maven-shade, maven-compiler and maven-failsafe:
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-shade-plugin</artifactId>
            <version>3.1.0</version>
            <executions>
                <execution>
                    <id>shade-main</id>
                    <phase>package</phase>
                    <goals>
                        <goal>shade</goal>
                    </goals>
                    <configuration>
                        <outputFile>target/assembly/${project.artifactId}.jar</outputFile>
                        <filters>
                            <filter>
                                <artifact>*:*</artifact>
                                <excludes>
                                    <exclude>META-INF/*.SF</exclude>
                                    <exclude>META-INF/*.DSA</exclude>
                                    <exclude>META-INF/*.RSA</exclude>
                                </excludes>
                            </filter>
                        </filters>
                        <transformers>
                            <transformer implementation="org.apache.maven.plugins.shade.resource.AppendingTransformer">
                                <resource>META-INF/spring.handlers</resource>
                            </transformer>
                            <transformer implementation="org.apache.maven.plugins.shade.resource.AppendingTransformer">
                                <resource>META-INF/spring.schemas</resource>
                            </transformer>
                        </transformers>
                    </configuration>
                </execution>
            </executions>
        </plugin>

        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.7.0</version>
            <executions>
                <execution>
                    <id>default-compile</id>
                    <phase>none</phase>
                </execution>
                <execution>
                    <id>default-testCompile</id>
                    <phase>none</phase>
                </execution>
                <execution>
                    <id>java-compile</id>
                    <phase>compile</phase>
                    <goals> <goal>compile</goal> </goals>
                </execution>
                <execution>
                    <id>java-test-compile</id>
                    <phase>test-compile</phase>
                    <goals> <goal>testCompile</goal> </goals>
                </execution>
            </executions>
            <configuration>
                <source>1.8</source>
                <target>1.8</target>
                <encoding>${project.build.sourceEncoding}</encoding>
            </configuration>
        </plugin>

        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-failsafe-plugin</artifactId>
            <version>2.20.1</version>
            <executions>
                <execution>
                    <goals>
                        <goal>integration-test</goal>
                        <goal>verify</goal>
                    </goals>
                </execution>
            </executions>
        </plugin>

        ...
    </plugins>
</build>

When I run mvn package it nicely compiles the project and builds a jar with shade-plugin. However when I run mvn verify the shade-plugin should not be run, but it does and it takes unnecessary time before the tests are executed.
How can I prevent the shade plugin to run on mvn verify?
EDIT:
After some comments I want to clarify I still need to do the package phase, I just want to skip the execution of shade plugin.


text:
Q: When to use String#concat() method in Java? I've been through different topics about String concatenation performance. Almost answer recommend using StringBuilder or StringBuffer to reduce overhead cost (or + operator if concatenation statement outside the loop). It's pretty clear, but I still wonder why Java has String format() and concat() method although it's ineffective. Performance test here: link. Someone mentioned String format() may be useful for Localization purpose (I don't understand much, howsoever I already have a keyword to search later), but what's the purpose of the remaining one? Does it only useful for compatibility backward?

A: String#concat and + exist to provide a minimalistic set of operations on the type String.
They are not efficient if used multiple times.
But they have their own right as type operations "xxx" + "yyy" you do not want to specify using a StringBuilder. (Furthermore there it is a compile time concatenation.)
StringBuffer is a mistake IMHO. It is slower that the newer StringBuilder as it is synchronized, but one would rarely add something rom two threads (unordered).
String::concat may be a method reference useful for stream reduction or such.


text:
Q: enforce https request on a non https website - Mixed Content error in chrome This might be a weird case, and feel free to let me know if there is better way in general.
So I have an application with a load balancer. The load balancer takes in HTTPs only traffic. So far so good.
The load balancer then sends it as HTTP to my asp.netcore.
What it implies :

*

*Although the access to the website is in Https, the asp.netcore app doesn't know about it.

*I only specify it as HTTPs in Development environment as I have my cookies in HTTPS only
But that gives me this problem :

Mixed Content: The page at 'pagePath' was loaded over HTTPS, but
  requested an insecure manifest 'path/site.webmanifest'. This request
  has been blocked; the content must be served over HTTPS.

Here is my startup
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
        app.UseHttpsRedirection();
    }
    else
    {
        app.UseHsts();
    }

    app.UseStaticFiles();
    app.UseCookiePolicy();

    app.UseAuthentication();

    app.UseExceptionHandler("/error/500");
    app.UseMiddleware<WebRequestLoggerMiddleWare>();
    app.UseMiddleware<UserTimeZoneMiddleWare>();

    app.UseMvc(routes =>
    {
        routes.MapRoute(
            name: "default",
            template: "{controller=Home}/{action=Index}/{id?}");
    });
}

And my cookie policy, still in statup.cs
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
    .AddCookie(options =>
    {
        options.LoginPath = new PathString("/account/login/");
        options.AccessDeniedPath = new PathString("/account/forbidden/");
        options.SlidingExpiration = true;
        options.ExpireTimeSpan = TimeSpan.FromHours(cookieSettings.CookieExpirationInHours);
        options.Cookie.SecurePolicy = CookieSecurePolicy.Always;
        options.Cookie.HttpOnly = true;

    });

What would be the best way to make sure the webmanifest is requested through HTTPS ?
Should I just force the whole website to be HTTPS and route traffic from the LB as https? That's one way, but it shouldn't be necessary...

A: The traffic between your reverse proxy and your ASP.NET Core application doesn't have to be encrypted via https, but two conditions have to be met so your ASP.NET Core application knows if the original HTTP Request was came over https or http.

*

*Your reverse proxy has to Send the correct headers with the original protocol and IP of the original host. The default headers for that are X-Forwarded-For for the remote IP and X-Forwarded-Proto for the protocol

*The forwarded headers middleware is set up by default when running on IIS and (according to the docs) needs to be enabled for other hosting scenarios.

The documentation can be read under Configure ASP.NET Core to work with proxy servers and load balancers.

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc();

    services.Configure<ForwardedHeadersOptions>(options =>
    {
        options.ForwardedHeaders =
            ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto;
    });
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    app.UseForwardedHeaders();

    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }
    else
    {
        app.UseExceptionHandler("/Home/Error");
    }

    app.UseStaticFiles();
    // In ASP.NET Core 1.x, replace the following line with: app.UseIdentity();
    app.UseAuthentication();
    app.UseMvc();
}

If your proxy names headers differently than X-Forwarded-For, X-Forwarded-Proto and X-Forwarded-Host, you can use the ForwardedForHeaderName, ForwardedProtoHeaderName and ForwardedHostHeaderName properties on ForwardedHeadersOptions to change it.
Additionally your Startup class should look like this
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }
    else
    {
        app.UseHsts();
    }

    // redirect to Https
    app.UseHttpsRedirection();

as per official examples and to ensure the user is redirected to http on his/her first visit, HSTS should handle consecutive requests


text:
Q: Probability distribution of dot product? Sorry if this is a basic question. I don't know much about statistics and the closest thing I found involved unit vectors, a case I don't think is easily generalizable to this problem.
I have a reference vector $\mathbf V$ in some $\mathbb R^n$.
I have another vector in $\mathbb R^n$ of independent random variables, each with Gaussian distribution, each with the same standard deviation $\sigma$. Let's call the vector $\mathbf X$.
What is the probability distribution of $\mathbf V\cdot \mathbf X$?
Surely this is a famous problem with a widely known solution. Or is there an elegant approach to the problem?

A: You are asking for the distribution of $Y=a_1X_1+\cdots +a_n X_n$, where more generally the $X_i$ are independent normal, means $\mu_i$, variances $\sigma_i^2$. The random variable $Y$ has  normal distribution, mean $\sum_1^n a_i \mu_i$, variance $\sum_1^n a_i^2 \sigma_i^2$.

A: V.X will be Normal, as linear combination of normal rvs is again normal. Check this.


text:
Q: Can a I add more than 1 dimensions in an array at same axis? I am not getting the concept of dimensions/axis properly. I tried the following code:
import numpy as np
l = [1,2,3,4,5,6]
x = np.expand_dims(l,0)
print(x)
print(x.shape)
x = np.expand_dims(l,0)
print(x)
print(x.shape)

As the result I am getting:
[[1 2 3 4 5 6]]
(1, 6)
[[1 2 3 4 5 6]]
(1, 6)

why am I not getting:
[[1 2 3 4 5 6]]
(1, 6)
[[[1 2 3 4 5 6]]]
(1, 1, 6)

A: You need to change l to x in your second attempt to extend the dimensions:
x = np.expand_dims(l,0)
x = np.expand_dims(x,0)
print(x.shape)

(1, 1, 6)


text:
Q: Does the simplicial-set internal hom of quasicategories give a quasicategory? The internal hom structure on simplicial sets is described here. This provides us with a functor $h : C^{\text{op}} \times C \rightarrow C$ where $C := \mathrm{Sets}^{\mathbf{\Delta}^{\text{op}}}$.
My question is, if some given $X,Y \in \mathrm{Obj}(C)$ are in fact quasicategories, then is $h(X,Y) \in \mathrm{Obj}(C)$ also a quasicategory? Would anyone know of a reference that discusses this?

Update: I have found a discussion of this in Lurie's Higher Topos Theory, Proposition 1.2.7.3, and the Proposition following 2.2.5.7.

A: Reference: see Lurie, Higher Topos Theory, Proposition 1.2.7.3.
Also see the Proposition following 2.2.5.7; it is a proof of 1.2.7.3.


text:
Q: How do I make this model query work? I'm trying to find a solution that will return the objects with a specific id.
I have these models:
class ModelB(models.Model):
    customid = models.CharField(max_length=32)
    <-- data -->
class ModelA(models.Model):
    b = models.ForeignKey(ModelB, blank=True, null=True, related_name="Bs")

and I have this code in my views:
a = ModelA.objects.filter(ModelB__customid = Bobject_id)

I want to be able to find all of the A objects with a given B object.
Any ideas?

A: a_objects = ModelA.objects.filter(b__customid=Bobject_id)

Check out the documentation for creating queries that span relationships

A: Assuming you have an instance of ModelB, the easiest way is to follow the reverse relationship from there:
a_objects = b_object.Bs.all()

This uses the explicit related_name you have set: without that, it would have been b_object.modela_set.all(). Note that your related_name should really be "As", not "Bs", since it refers to the A objects that are related to that B.


text:
Q: LDAP authentication on CentOS 7 After upgrading to CentOS 7 it's no longer possible to login via LDAP. With CentOS 6 I used the package pam_ldap which worked fine, but now pam_ldap is no longer available for the new version of CentOS.
Connecting via ldapsearch still works fine, but trying to authenticate via ssh does not work.
I reinstalled the package nss-pam-ldapd and reconfigured authentication via authconfig-tui, but it still does not work.
Below I replace my username with user.name and the base with dc=sub,dc=example,dc=org.
My host OS is a CentOS 7. All currently available updates are installed.
$ uname -a
Linux isfet 3.10.0-123.8.1.el7.x86_64 #1 SMP Mon Sep 22 19:06:58 UTC 2014 x86_64 x86_64 x86_64 GNU/Linux

Installed packages
$ rpm -qa | grep -i ldap
openldap-2.4.39-3.el7.x86_64
nss-pam-ldapd-0.8.13-8.el7.x86_64
openldap-clients-2.4.39-3.el7.x86_64

Content of /etc/openldap/ldap.conf
URI ldap://172.16.64.25
BASE dc=sub,dc=example,dc=org

Content of /etc/nslcd.conf
ldap_version 3
uri ldap://172.16.64.25
base dc=sub,dc=example,dc=org
ssl no

Output of /var/log/secure
Oct  6 12:12:16 isfet sshd[3937]: pam_unix(sshd:auth): authentication failure; logname= uid=0 euid=0 tty=ssh ruser= rhost=172.16.64.1  user=user.name
Oct  6 12:12:17 isfet sshd[3937]: Failed password for user.name from 172.16.64.1 port 18877 ssh2

Output of /var/log/audit/audit.log
type=USER_AUTH msg=audit(1412590243.286:364): pid=3912 uid=0 auid=4294967295 ses=4294967295 msg='op=PAM:authentication acct="user.name" exe="/usr/sbin/sshd" hostname=172.16.64.1 addr=172.16.64.1 terminal=ssh res=failed'
type=USER_AUTH msg=audit(1412590243.287:365): pid=3912 uid=0 auid=4294967295 ses=4294967295 msg='op=password acct="user.name" exe="/usr/sbin/sshd" hostname=? addr=172.16.64.1 terminal=ssh res=failed'

Output of the command ldapserach
$ ldapsearch -H ldap://172.16.64.25/ -D cn=Manager,dc=sub,dc=example,dc=org -W -x -b dc=sub,dc=example,dc=org -d1

ldap_url_parse_ext(ldap://172.16.64.25/)
ldap_create
ldap_url_parse_ext(ldap://172.16.64.25:389/??base)
Enter LDAP Password:
ldap_sasl_bind
ldap_send_initial_request
ldap_new_connection 1 1 0
ldap_int_open_connection
ldap_connect_to_host: TCP 172.16.64.25:389
ldap_new_socket: 3
ldap_prepare_socket: 3
ldap_connect_to_host: Trying 172.16.64.25:389
ldap_pvt_connect: fd: 3 tm: -1 async: 0
attempting to connect:
connect success
ldap_open_defconn: successful
ldap_send_server_request
ber_scanf fmt ({it) ber:
ber_scanf fmt ({i) ber:
ber_flush2: 61 bytes to sd 3
ldap_result ld 0x7f9b07402110 msgid 1
wait4msg ld 0x7f9b07402110 msgid 1 (infinite timeout)
wait4msg continue ld 0x7f9b07402110 msgid 1 all 1
** ld 0x7f9b07402110 Connections:
* host: 172.16.64.25  port: 389  (default)
  refcnt: 2  status: Connected
  last used: Mon Oct  6 12:04:38 2014

** ld 0x7f9b07402110 Outstanding Requests:
 * msgid 1,  origid 1, status InProgress
   outstanding referrals 0, parent count 0
  ld 0x7f9b07402110 request count 1 (abandoned 0)
** ld 0x7f9b07402110 Response Queue:
   Empty
  ld 0x7f9b07402110 response count 0
ldap_chkResponseList ld 0x7f9b07402110 msgid 1 all 1
ldap_chkResponseList returns ld 0x7f9b07402110 NULL
ldap_int_select
read1msg: ld 0x7f9b07402110 msgid 1 all 1
ber_get_next
ber_get_next: tag 0x30 len 50 contents:
read1msg: ld 0x7f9b07402110 msgid 1 message type bind
ber_scanf fmt ({eAA) ber:
read1msg: ld 0x7f9b07402110 0 new referrals
read1msg:  mark request completed, ld 0x7f9b07402110 msgid 1
request done: ld 0x7f9b07402110 msgid 1
res_errno: 0, res_error: <>, res_matched: <cn=Manager,dc=sub,dc=example,dc=org>
ldap_free_request (origid 1, msgid 1)
ldap_parse_result
ber_scanf fmt ({iAA) ber:
ber_scanf fmt (}) ber:
ldap_msgfree
ldap_err2string
ldap_bind: Success (0)
        matched DN: cn=Manager,dc=sub,dc=example,dc=org
...

Content of _/etc/pam.d/password-auth
auth        required      pam_env.so
auth        sufficient    pam_unix.so nullok try_first_pass
auth        requisite     pam_succeed_if.so uid >= 1000 quiet_success
auth        sufficient    pam_ldap.so use_first_pass
auth        required      pam_deny.so

account     required      pam_unix.so broken_shadow
account     sufficient    pam_localuser.so
account     sufficient    pam_succeed_if.so uid < 1000 quiet
account     [default=bad success=ok user_unknown=ignore] pam_ldap.so
account     required      pam_permit.so

password    requisite     pam_pwquality.so try_first_pass retry=3 type=
password    sufficient    pam_unix.so sha512 shadow nullok try_first_pass use_authtok
password    sufficient    pam_ldap.so use_authtok
password    required      pam_deny.so

session     optional      pam_keyinit.so revoke
session     required      pam_limits.so
-session     optional      pam_systemd.so
session     [success=1 default=ignore] pam_succeed_if.so service in crond quiet use_uid
session     required      pam_unix.so
session     optional      pam_ldap.so

Content of _/etc/pam.d/system-auth
auth        required      pam_env.so
auth        sufficient    pam_unix.so nullok try_first_pass
auth        requisite     pam_succeed_if.so uid >= 1000 quiet_success
auth        sufficient    pam_ldap.so use_first_pass
auth        required      pam_deny.so

account     required      pam_unix.so broken_shadow
account     sufficient    pam_localuser.so
account     sufficient    pam_succeed_if.so uid < 1000 quiet
account     [default=bad success=ok user_unknown=ignore] pam_ldap.so
account     required      pam_permit.so

password    requisite     pam_pwquality.so try_first_pass retry=3 type=
password    sufficient    pam_unix.so sha512 shadow nullok try_first_pass use_authtok
password    sufficient    pam_ldap.so use_authtok
password    required      pam_deny.so

session     optional      pam_keyinit.so revoke
session     required      pam_limits.so
-session     optional      pam_systemd.so
session     [success=1 default=ignore] pam_succeed_if.so service in crond quiet use_uid
session     required      pam_unix.so
session     optional      pam_ldap.so

A: Running nslcd in debug mode shows the problem:
$ $(which nslcd) -d
...
nslcd: [8b4567] <authc="user.name"> DEBUG: myldap_search(base="dc=sub,dc=example,dc=org", filter="(&(objectClass=posixAccount)(uid=user.name))")
...
nslcd: [8b4567] <authc="user.name"> DEBUG: ldap_result(): end of results (0 total)
nslcd: [8b4567] <authc="user.name"> DEBUG: "user.name": user not found: No such object
...

nslcd sets a filter by default. It's not possible to remove this filter or set it to blank.
Because none of my LDAP users has an objectClass called posixAccount the users cannot be found and the login is denied.
To fix this problem I had to overwrite this filter with an own one. Because I'm looking for the uid it's useful to set the filter on an attribute which is searched for anyways.
New content of my /etc/nslcd.conf:
filter passwd (uid=*)
uri ldap://172.16.64.25
base dc=sub,dc=example,dc=org
ssl no

After changing the nslcd.conf I had to restart the service nslcd: systemctl restart nslcd
Source: http://lists.arthurdejong.org/nss-pam-ldapd-users/2014/msg00025.html
.
This seems to be a problem for _nss-pam-ldapd-0.8.13-8.el7.x86_64_ on CentOS 7!
$ nslcd -V
nss-pam-ldapd 0.8.13

I tried to reproduce the problem on CentOS 6, but on this nss-pam-ldapd has dependencies to pam_ldap which has its config file in /etc/pam_ldap.conf and seems to not use /etc/nslcd.conf in the way it works on CentOS 7.


text:
Q: how to call dealloc method I am new to iPhone development.
I am calling one viewController on my button click event. But when I come back, my -dealloc method is not called. Here is my code of button click event:
-(IBAction)btnAddPressed:(id)sender
{
    FriendsTableListViewController *viewController = [[FriendsTableListViewController alloc] initWithNibName:@"FriendsTableListViewController" bundle:nil];
    [self.navigationController pushViewController:viewController animated:YES];
    [viewController release];
}

Here is my dealloc method of viewController where i was after clicked on button:
-(void)dealloc{
    [super dealloc];
}

I don't know why dealloc method is not working properly. Please help me. Thanking you...

A: The navigationController is holding on to your controller (it will take ownership when you push your view controller), so it will not be deallocated.
If you want to remove the view controller, pop it out of the navigation controller.


text:
Q: How to get row number via LINQ using Entity framework? Hope someone can help me out here as I'm a little stuck.
I'm building a service in front of a hiscore database for a game.
The database have the following two tables:
CREATE TABLE [dbo].[PB_HiscoreEntry] (
    [Id]          UNIQUEIDENTIFIER NOT NULL,
    [PlayerId]    UNIQUEIDENTIFIER NOT NULL,
    [Score]       INT              NOT NULL,
    [DateCreated] DATETIME         NOT NULL
);

CREATE TABLE [dbo].[PB_Player] (
    [Id]             UNIQUEIDENTIFIER NOT NULL,
    [UniquePlayerId] NCHAR (32)       NOT NULL,
    [Name]           NVARCHAR (50)    NOT NULL,
    [DateCreated]    DATETIME         NOT NULL
);

The idea is of course to only have each player once in the database and let them have multiple hiscore entries. This table PB_HiscoreEntry will have a lot of scores, but by doing a simple OrderBy descending, I can create a real hiscore list where the one with highest score is at the top and the lowest at the bottom.
My problem here is that my database don't have any idea of the actual Rank of the score compared to the others. This is something I should do as I do the OrderBy query described above.
Here is some code to help illutrate what I want to archive:
var q = (
    from he in entities.PB_HiscoreEntry
    orderby he.Score descending
    select new HiscoreItem()
    {
        UserId = he.PB_Player.UniquePlayerId,
        Username = he.PB_Player.Name,
        Score = he.Score,
        //Put in the rank, relative to the other entires here
        Rank = 1
    });

HiscoreItem, is just my own DTO i need to send over the wire.
So anybody have an idea of how I can do this or am I on a totally wrong path here?

A: You're on the right track, you just need to use the Queryable.Select overload that takes an extra index. Take a look at this:
var entries =
    from entry in entities.PB_HiscoreEntry
    orderby entry.Score descending
    select entry;

// Note the (entry, index) lambda here.
var hiscores = entries.Select((entry, index) => new HiscoreItem()
{
    UserId = entry.PB_Player.UniquePlayerId,
    Username = entry.PB_Player.Name,
    Score = entry.Score,
    Rank = index + 1
});

I'm not 100% sure if Entity Framework knows how to work with the
Select<TSource, TResult>(this IQueryable<TSource>, Expression<Func<TSource, int, TResult>>) overload. If that's the case, just use the equivalent method of the static Enumerable class:
// Note the .AsEnumerable() here.
var hiscores = entries.AsEnumerable()
    .Select((entry, index) => new HiscoreItem()
{
    UserId = entry.PB_Player.UniquePlayerId,
    Username = entry.PB_Player.Name,
    Score = entry.Score,
    Rank = index + 1
});

I hope this helps.


text:
Q: MaterialTapTargetPrompt: Way to have skip button to skip tutorial I have a tutorial demo app from here https://github.com/sjwall/MaterialTapTargetPrompt and I've successfully implemented it for my app. but is there a way to have a skip button on the prompt to skip that tutorial?
I was just wondering if someone here found a way to do that I'd really appreciate some help.


text:
Q: Nginx rewrite %20 I'm trying to add a rewrite rule to fix the %20 issue in urls and replace it by a '-' AND replace any capital letter by a lower case letter at the same time.
Example:

www.mysite.com/channels/channelidnumber/Funny%20Videos/ to
  www.mysite.com/channels/channelidnumber/funny-videos/

I tried the following but this only removed the %20 without replacing it and nothing else.
rewrite ^(.*)(\s|%20)(.*)$ $1$3 permanent;


text:
Q: Does Minimum Description Length apply for noisy communication? Rissanen's Minimum Description Length principle shows that, for a set alphabet $A$ of $n$ symbols with probabilities $\{p_1, ..., p_n\}$, one can construct a set of $n$ prefix binary codewords, using the shorter codewords for more frequent symbols in such a way that, for a randomly chosen sequence of these symbols, one can encode them with an expected per-symbol length
$L(A) \le -\sum_{i}{p_i log(p_i)}$
But, suppose that we want to allow, for each timestep in the sequence, not just the $n$ individual symbols, but also ambiguous communication?  For instance, "at timestep t, we send 'either symbol 3, 5, or 6'".  The total probability of that would be $p_{amb} = p_3 + p_5 + p_6$.  And, intuitively, the "information content" in such a communication ought to be equal to that of communicating a single symbol with that same probability, $p_{amb}$.
However, there doesn't seem any way to actually construct a code which allows for ambiguous combinations of more than one symbol.  But, is the construction of a code just a semantic device to help make the concept of information more concrete?  Or, is it necessary for the theory?

A: If a random variable $X$ picks symbols randomly and uniformly from an alphabet $\mathcal{X}$ then the entropy per symbol is $\log_2(|\mathcal{X}|)$ where $|\mathcal{X}|$ denotes the number of symbols in the set $\mathcal{X}$.
If another random variable $Y$ consists of noisy observations of the random variable $X$ then the random variable $Y$ is said to be observing the variable $X$ through a noisy channel. The average number of information bits that are being transmitted from $X$ to $Y$ per symbol is called the mutual information and is denoted $I(X;Y)$. It depends on both the distribution of the noisy channel and the input distribution $X$.
\begin{align}
I(X;Y) &= (\text{Entropy of X}) - (\text{Entropy of X given Y}) \\
&= H(X) - H(X|Y)\\
\end{align}
Now if X is uniformly distributed then
$$
I(X;Y) = \log_2|\mathcal{X}| - (\text{Entropy of X given Y})
$$
The entropy of $X$ given $Y$ is the amount of information bits you still do not know about $X$ after receiving the noisy symbol $Y$. Let $\mathcal{X}_s$ be some subset of the set $\mathcal{X}$. If after receiving the noisy observation $y$ the receiver now knows that the symbol $x$ is a member of some subset $\mathcal{X}_s$ and the receiver also knows that for each symbol $x_s$ in $\mathcal{X}_s$ the probability that the observed symbol was $x$ is $p(x_s = x)$, then the entropy of $X$ given $Y$ can be shown to be the entropy of $\mathcal{X}_s$ over the distribution $p_{X_s}$.
If you only had access a noisy observation $y$, and another receiver had access to both the same noisy observation you had and also had access to the true observed value $x$, then all that receiver needs to send you for you to be able to resolve $x$ is the information about the symbol $x_s$ in $\mathcal{X}_s$ such that $x = x_s$. The minimum number of bits needed for this is by definition the entropy of the set $\mathcal{X}_s$ over the distribution $p_{X_s}$.
If $x_s$ is uniformly distributed in $\mathcal{X}_s$ then it is clear that the entropy of $X_s$ will be $\log |\mathcal{X}_s|$, but if the distribution over $\mathcal{X}_s$ is not uniform then the entropy of $X_s$ will be less than $\log |\mathcal{X}_s|$. This is because the uniform distribution maximises entropy.
\begin{align}
 (\text{Entropy of X given Y}) &= (\text{Entropy of } X_s) \\
&\leq \log_2 |\mathcal{X_s}|
\end{align}
We can thus deduce that for uniformly distributed $X$ we have
\begin{align}
I(X;Y) &= (\text{Entropy of X}) - (\text{Entropy of X given Y}) \\
&= H(X) - H(X | Y) \\
&= \log |\mathcal{X}| - H(X | Y) \\
&\geq \log |\mathcal{X}| - log |\mathcal{X_s}|
\end{align}
In the 8 sided die case you outlined in the comments you have $X$ uniformly distributed in the set $\mathcal{X}$ with $|\mathcal{X}| = 8$. After the reception of the noisy variable $Y$ you now know that $x$ belongs to a subset $\mathcal{X}_s$ of $\mathcal{X}$ with $|\mathcal{X}_s| = 2$ so $I(X;Y) \geq (\log 8 - \log 2) = 2$.
Examples:
i) If after receiving the noisy variable Y, you will know that the observed symbol $x$ was equal to one of N symbols, with the probability of x being either one of those N symbols being equal then $I(X;Y) = \log |\mathcal{X}| - H(\mathcal{X_s}) = \log |\mathcal{X}| - log |\mathcal{X_s}| = \log 8 - \log N$.
ii) If after receiving the noisy variable Y, you will know that the observed symbol $x$ was equal to one of N symbols, with the probability of x being the $i^{th}$ of the N symbols being $p_i$ then $I(X;Y) = \log |\mathcal{X}| - H(\mathcal{X_s}) = \log |\mathcal{X}| - \sum _{i \in [1, N]} p_i\log \frac{1}{p_i}$ .
iii) If after receiving the noisy variable Y, you will know that the observed symbol was exactly $x$. $I(X;Y) = \log |\mathcal{X}| - H(\mathcal{X_s}) = \log |\mathcal{X}| - \log |\mathcal{X_s}| = \log 8 - \log 1 = 3$.


text:
Q: siteminder sso and spring security testing I am making a Java portal application that will be accessed via a Siteminder single sign on.
I have the application currently rejecting any requests without the SM_USERID using the following beans:
<bean id="siteminderFilter" class="org.springframework.security.web.authentication.preauth.RequestHeaderAuthenticationFilter">
    <property name="principalRequestHeader" value="SM_USERID"/>
    <property name="authenticationManager" ref="authenticationManager" />
</bean>

<bean id="preauthAuthProvider" class="org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationProvider">
    <property name="preAuthenticatedUserDetailsService">
        <bean id="userDetailsServiceWrapper"  class="org.springframework.security.core.userdetails.UserDetailsByNameServiceWrapper">
            <property name="userDetailsService" ref="ssoUserDetailsService"/>
        </bean>
    </property>
</bean>

My SSOUserDetailsService finds a user based on the SM_USERID header and returns it as a spring User.
My problem is that I cannot make this work locally.  It would need to be deployed so I can get the Siteminder header.
Is there any workaround to be able to submit a local test user's username in a mock Siteminder header to my Siteminder filter?
I was thinking of a page with each user as a button.  Clicking the button would send a request with a SM_USER header.
The problem with that is the filter doesn't allow access to the site at all without a SM_USER header so I couldn't get to that page!
What do I do?

A: Make a filter which injects the property SM_USERID in the header and place this fitler before your FilterChainProxy declaration in web.xml.

A: try to update the host file with the following value
http://www.xyz.com 127.0.0.1:8080/yourappName


text:
Q: como separar correctamente cada token y hacer las operaciones Desarrolle un programa que calcule una operación matemática introducida en una maquina pero divididas las operaciones entre dos equipos de computo.

st= new StringTokenizer(ecuacion," ");
while(st.hasMoreTokens()){
    this.muestra.append(st.nextToken()+"\n");
}
JOptionPane.showMessageDialog(null,"operadores 1 inicial :" + ecuacion);
while (ecuacion.contains("*") || ecuacion.contains("/")) {
    JOptionPane.showMessageDialog(null,"operadores * / " + ecuacion);
    operador = st.nextToken().charAt(0);//obtenemos el operador
    JOptionPane.showMessageDialog(null,"operadores 2 " + operador);
    op2 = Double.parseDouble(st.nextToken());//obtenemos el segundo operador
    JOptionPane.showMessageDialog(null,"operadores 3 " + operador);
    String operacion = op1 + " " + operador + " " + op2;//construimos la operacion
    JOptionPane.showMessageDialog(null,"operadores 4 " + operacion);
    if (operador == '*') {//si es multiplicacion la resuleve el server
        JOptionPane.showMessageDialog(null,"operadores 5 " + operador);
        resultado = op1 * op2;//guardamos el resultado
        JOptionPane.showMessageDialog(null,"resultado de server " + resultado);
        //sustituimos la operacion por el resultado
        ecuacion = ecuacion.replace(operacion, resultado + "");
        mostrar(ecuacion + "\n"); //mostramos la ecuacion simplificada
        JOptionPane.showMessageDialog(null,"resultado ecua " + ecuacion);
    } else if (operador == '/') {//si es divicion la resuelve el cliente
        //enviamos al cliente la operacion y le indicamos que es divicion
        //enviarDatos(operacion + "|/");
        //guardamos el resultado que se reciba del cliente
        //resultado = Double.parseDouble(entrada.readUTF());
        //sustituimos la operacion por el resultado
        ecuacion = ecuacion.replace(operacion, resultado + "");
        mostrar(ecuacion + "\n"); //mostramos la ecuacion simplificada
    }
    op1 = op2;//ahora el segundo operando sera el primer operando para despues buscar el operador
}


text:
Q: Ansible escape * in regex I'm trying to use Ansible's lineinfile module to ensure that a line beginning with a * is present in a file. However, the task fails every time with the following error
TASK: [nginx | Persist soft ulimit] *******************************************
failed: [aa.bb.cc.dd] => {"failed": true, "parsed": false}
BECOME-SUCCESS-xbfifannrufpkcmmfmtdigorggzvhzsx
Traceback (most recent call last):
  File "/home/ubuntu/.ansible/tmp/ansible-tmp-1442590356.11-253796220854159/lineinfile", line 2210, in <module>
    main()
  File "/home/ubuntu/.ansible/tmp/ansible-tmp-1442590356.11-253796220854159/lineinfile", line 394, in main
    ins_aft, ins_bef, create, backup, backrefs)
  File "/home/ubuntu/.ansible/tmp/ansible-tmp-1442590356.11-253796220854159/lineinfile", line 208, in present
    mre = re.compile(regexp)
  File "/usr/lib/python2.7/re.py", line 190, in compile
    return _compile(pattern, flags)
  File "/usr/lib/python2.7/re.py", line 244, in _compile
    raise error, v # invalid expression
sre_constants.error: nothing to repeat
OpenSSH_6.2p2, OSSLShim 0.9.8r 8 Dec 2011
debug1: Reading configuration data /Users/xyz/.ssh/config
debug1: Reading configuration data /etc/ssh_config
debug1: /etc/ssh_config line 20: Applying options for *
debug1: auto-mux: Trying existing master
debug1: mux_client_request_session: master session id: 2
Shared connection to aa.bb.cc.dd closed.

The task is as follows
- name: Persist soft ulimit
  lineinfile:
    dest: /etc/security/limits.conf
    regexp: "^\* soft nofile"
    line: "* soft nofile 9000"

Given typical escaping of regex, I'd assumed that it'd be escaped with \, but I just get the above error.
Ansible is 1.9.2
$ ansible --version
$ ansible 1.9.2

A: One sure-fire way of escaping (most) characters is to wrap it in a character class:
regexp: "^[*] soft nofile"


text:
Q: Integral that is continuous and looks like it converges to a geometric series
I think the key word is continous. the RHS totally looks like a sum from a geometric series but I dont see a trick when I think there is one .

A: Hint: Let $g(x) = (x+1)^{2017}$. Let $h = f-g$. By the mean value theorem, there exists $a$ such that
$$h(a) = \int_0^1 h(x) \, dx.$$


text:
Q: ASP.NET MVC: convention for organizing ViewModels As discussed throughout the various MVC questions and blogposts, we know that the ASP.NET MVC project layout is heavy on convention.
I blindly made a sub-directory in the Controllers folder.
This doesn't feel right.
alt text http://www.imagechicken.com/uploads/1252003002097179400.png
Question: What's the common accepted convention on which directory to store your ViewModels? What are your suggestions or what is the established convention?

A: I typically create a model for every view.  Even if it is just an exact map of some other object in my project that I could be using.  This way my view and it's required model is decoupled from the rest of the application.  It also makes adding data to the view in the future very easy by just extending your view's model.
It takes a little more work up front and sometimes seems like your duplicating objects but I just prefer the seperation.
I store all my view models in the models directory created in an MVC project.  Those 'models' map one to one to my views.  I use subfolders within the Models folder if the view models become more than just basic data holders.  The subfolders would contain all the bits and pieces required to represent that view.

A: I think the idea is that (View)Models should go in the Models directory (which is empty when you create a new ASP.NET MVC project).
Personally, it makes more sense for me to arrange namespaces around features instead of mechanics, but while this is of no consequence with regards to Models, it would have some implications when it comes to Controllers and Views.

A: I use a "Models" folder alongside Controllers and Views. The same one which is empty in your project (I don't use Areas).
The "M" in "MVC" model goes in a separate assembly. The only models in the web assembly are presentation/edit models.
Inside the Models folder, there are subfolders by namespace as usual. So I have:

Vertex.Data (Assembly with repositories, etc.)
Vertex.Web

Controllers
  BarController
  FooController
Models
  Bar
    BarListItem
  Foo
    FooDetail
    FooListItem
Views
  Bar
  Foo
  Shared

...etc.


text:
Q: VueJS transition slider I have a form with three steps.
And each step should transition from side to side on click of prey/next.
The problem is, that the transitions aren't being applied correctly after a direction change.
Does anyone know why vue isn't adding the correct class to the displayed element after the change in direction?
I have been racking my head as to why can't find a solution.
here's a pen:
https://codepen.io/cjfradley/pen/YgvJxe
the transition blocks look like this:
<transition :name="transition">

    Step 1

    <button @click.prevent="next()">Vorwärts</button>

</transition>

and the name of the transition is changed depending on which of the two buttons 'prev' or 'next' is clicked.
I was under the impression, that that would change the transition name for all transitions. But somehow the name lags behind one step.
Thanx for you your help
Chris

A: The transition musst be applied before using it.
You could do that by waiting for the next Tick.
  methods: {
    prev () {
      this.transition = "slide-prev"
      Vue.nextTick(_ => {
         this.step--
      })
    },
    next () {
      this.transition = "slide-next"
      Vue.nextTick(_ => {
        this.step++
      })
    },
  }

https://codepen.io/anon/pen/WmyYpx


text:
Q: typescript Object is possibly null when getting files from event I am trying to make a typescript + react fileinput component.
However I'm getting typescript error 'Object is possibly null'.
I have googled but couldn't find solution for this problem.
How can I fix this problem without disabling typescript null check.
I'm getting errors on e.target.files[0]!
Here is the code below
import React from 'react';

    export default function ImageUpload() {
      const [selectedFile, setSelectedFile] = React.useState<File | string>('fileurl');
      const [imagePreviewUrl, setImagePreviewUrl] = React.useState<string | undefined | ArrayBuffer | null>();

      const fileChangedHandler = (e : React.ChangeEvent<HTMLInputElement>) => {
        setSelectedFile(e.target.files[0]!);

        const reader = new FileReader();

        reader.onloadend = () => {
          setImagePreviewUrl(reader.result);
        };

        reader.readAsDataURL(e.target.files[0]!);
      };

      const submit = () => {
        const fd = new FormData();

        fd.append('file', selectedFile);
      };

      let imagePreview = (
Please select an Image for Preview
);
      if (imagePreviewUrl) {
        imagePreview = (

            {' '}

        );
      }

      return (

          <input type="file" name="avatar" onChange={fileChangedHandler} />
          <button type="button" onClick={submit}> Upload </button>
          { imagePreview }

      );
    }

A: Guys this is the proper way of handling this issue:
            e.target.files instanceof FileList
              ? reader.readAsDataURL(e.target.files[0]) : 'handle exception'

Hope this helps. Cheers!

A: From the code, I suspect that e.target is nullable. You could modify e.target.files[0]! to e.target!.files[0]!, which will make error go away because you will essentially tell the Typescript compiler that "it will not be null, trust me". But instead, I would advise to handle the null case properly - check for null or undefined and do something appropriate, depending on your app logic.

A: HTMLInputElement has a built-in property files that is typeof FileList | null.

files: FileList | null;

Simply secure the possibility that files is null.
if (!e.target.files) return;

At the beginning of the function.

A: if (!e.target.files || e.target.files.length === 0) {
      // you can display the error to the user
      console.error("Select a file");
      return;
    }

A: In my code it worked like this: I created a variable that received the HTML event, then created a variable that received all the event files and used the 'item' functionality at index 0, and then I was able to access the file
const handleSetFileName = (event: ChangeEvent<HTMLInputElement>) => {
  const files = event.target.files;
  setFileName(files?.item(0)?.name);
};


text:
Q: Distutils error when installing pyperclip into Mu editor on Windows 10 I'm trying to install the pyperclip module for the Mu editor and running into this pile of errors when I run it through the command line:
C:\Users\Torthew>pip install pyperclip --target C:\Users\Torthew\AppData\Local\Mu\pkgs
Collecting pyperclip
  Using cached pyperclip-1.7.0.tar.gz (15 kB)
Installing collected packages: pyperclip
ERROR: Exception:
Traceback (most recent call last):
  File "C:\Users\Torthew\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\pip\_internal\cli\base_command.py", line 186, in _main
    status = self.run(options, args)
  File "C:\Users\Torthew\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\pip\_internal\commands\install.py", line 395, in run
    installed = install_given_reqs(
  File "C:\Users\Torthew\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\pip\_internal\req\__init__.py", line 67, in install_given_reqs
    requirement.install(
  File "C:\Users\Torthew\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\pip\_internal\req\req_install.py", line 781, in install
    scheme = get_scheme(
  File "C:\Users\Torthew\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\pip\_internal\locations.py", line 185, in get_scheme
    scheme = distutils_scheme(
  File "C:\Users\Torthew\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\pip\_internal\locations.py", line 125, in distutils_scheme
    i.finalize_options()
  File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.8_3.8.496.0_x64__qbz5n2kfra8p0\lib\distutils\command\install.py", line 252, in finalize_options
    raise DistutilsOptionError("can't combine user with prefix, "
distutils.errors.DistutilsOptionError: can't combine user with prefix, exec_prefix/home, or install_(plat)base

How can I fix this?


text:
Q: Live file syncronization across multiple Linux servers with millions of files and directories What is the best way to synchronize huge data of a running production server?
Our server has over 20 million files (small files with 10k and bigger files up to 50MB) stored in 1 millon directories. The size of all data is about 5 TB (steadily increasing).
Is it possible to synchronize the data with lsyncd and what are the limits (especially of inotify)? How much additional space does lsyncd need? What about the load (cpu and memory) and the live time?
Another solution would be GlusterFS. Is it possible to use GlusterFS on a production with none or minimal downtime? GlusterFS stores a lot of magic data in x-attributes files and the storage volume is about 15 to 20% bigger than systems with non GlusterFS. Seems like a huge amount of waste...? What about the load?
And at least rsync and cronjobs could do the job. rsync would only run on the slave... So no additional space is needed on the primary server, but rsync must read the full directory tree every time the cron runs...

A: I'd seriously recommend using something like ZFS for the filesystem.
Built-in tools like the ZFS snapshot and ZFS send/receive allow you to take block-level snaps of the filesystem and ship it to a second server.
Some third party tools like sanoid/syncoid can set automatic management/pruning and synchronization of your filesystem from one host to another.
This is done at the block device level, so you avoid the rsync checksum/inventory process.

A: If you cannot change the filesystem on the production server, I would put the files on another server and mount them with NFS. I would use Linux and ZFS if man-hours are inexpensive, maybe some kind of home NAS distribution or maybe even a home NAS (both probably ZFS-based) if everything is expensive and you can find one that does professional-level redundancy, or a NetApp or an IBM Spectrum Scale if money is not a problem compared to reliability and support.
Once you have the files on a real full-featured file server with professional-level redundancy, you point your backup server either directly to the primary NFS IP if you configured failover, or to the backup NFS server.


text:
Q: How to find memory leaks for native code in post Android 18? I am trying to find a way to find memory leaks in native code on Android apps. I have found others answers like How to Find memory leaks from native code in android, but these solutions aren't applicable post Android 18 as the DDMS no longer supports the "Native Heap" tab.
So if anyone can suggest a solution, it will be great help!

A: https://github.com/android/ndk/issues/431 tracks LSan support for the NDK, which will be the best option when that's done. It's not currently being worked on, but will probably be picked up once TSan is done.

A: https://android-arsenal.com/details/1/1775
here you go. I use this. Installation is already inside the link.
Sometimes it is freezing when dumping information but still good I think.


text:
Q: Xamarin.Auth AccountStore - KeyStore was not initialized I've had this Xamarin.Auth AccountStore working in my app for a while, but then decided to do some updates to some Nuget Packages and Target Android versions >_<
I now have no idea what went wrong and how to get it working again, here is the exception:
Java.Security.KeyStoreException: KeyStore was not initialized

The code is pretty simple and looks like this:
var accountStore = AccountStore.Create(Android.App.Application.Context);
var accounts = accountStore.FindAccountsForService(providerName);

The 2nd line is throwing the exception.
This is in the Android project, being called from a PCL DependencyService.
It has been working this way for a while, I guess something changed in a version update in one of the packages but I don't know what, any ideas?

A: try to repair your visual studio installation.
This made the trick for our project. We had the same problems like you.


text:
Q: Downsides of using Java var keyword A presenter just cited that changing to var is useful syntactic-sugar (aligning variable names). I thought I'd check and found...
    List<String> list = new ArrayList<>(); // IMO this is safer future-proof coding
    list.add("HELLO WORLD");

... generates bytecode with an invokeinterface dispatch ...
 11: invokeinterface #12,  2           // InterfaceMethod java/util/List.add:(Ljava/lang/Object;)Z

Converting to Java 10+ var ...
    var list = new ArrayList<>();
    list.add("HELLO WORLD");

... generates bytecode with an invokevirtual dispatch ...
 11: invokevirtual #12                 // Method java/util/ArrayList.add:(Ljava/lang/Object;)Z

Should I be concerned with, say, bulk upgrading a whole application's sourcecode with var? E.g. Will sensitive sections be slower (or faster?! given invokeinterface involves more steps?) Aside from that, are there other non-technical impacts (I saw an interesting comment about the clarity of offline code review for example)

A: The reason the bytecode differs is because the var declaration infers the type ArrayList rather than List. It's equivalent to you writing ArrayList<String> list = new ArrayList<>(); explicitly. So if you wouldn't worry about changing List to ArrayList in your variable declaration, you shouldn't worry about changing it to var either.

A: This is java, not PHP :) So, I wouldn't worry if I were you. The only thing that could happen is that it will not compile and you need to 'revert' the var to typed variable.
The only issue var creates is a headache during code review.
IMHO, at least.


text:
Q: impression tracking for dynamic content I want to track the clicks and the sends done on the basis of the dynamic content used in the email.
I have already got the impression tracking report activated but in the report not getting details on the dynamic content.
Do I need to do some setting in the emails also to get the reports?

A: You need to ensure you have named and added "Begin impression region" and "End impression region" amp script to the beginning and end of each block you wish to track.
I am not sure how you are creating your dynamic content blocks, but if you are creating them 'manually' this can be done quite easily with ampscript:
https://help.marketingcloud.com/en/documentation/exacttarget/tracking/impression_tracking/impression_region_using_ampscript/
If you are using Content Builder to create your dynamic content this should be done automatically for you:
https://help.marketingcloud.com/en/documentation/exacttarget/tracking/impression_tracking/impression_region_using_dynamic_content/
You can sometimes check this by looking at the plain text version of your email created by the content builder, you might be able to see the rules for dynamic content tracking in there:
Example:
{{#=if (([Attribute] == "Some Value"))}}
{{= BeginImpressionRegion("01__Rule_1__An_Image.png")}}{{= EndImpressionRegion()}}
{{.else}}
{{= BeginImpressionRegion("01__Default_Content__Other_image.png")}}{{= EndImpressionRegion()}}
{{/if}}


text:
Q: JQuery datepicker default date and multiple datepickers Im using this datepicker
https://jqueryui.com/datepicker/
I have 2 date fields in the same html form.
I need the first field to load today as default date.
Second one as todays date -7 (1 week ago.)
Cant get this working for some reason.
I can get both fields working but they wont load any default dates.
Any help is appreciated.

 $(function() {
       $( "#from" ).datepicker({
      defaultDate: "+1w",
      changeMonth: true,
      numberOfMonths: 1,
      onClose: function( selectedDate ) {
        $( "#to" ).datepicker( "option", "minDate", selectedDate );
      }
    });
    $( "#to" ).datepicker({
      defaultDate: "+1w",
      changeMonth: true,
      numberOfMonths: 1,
      onClose: function( selectedDate ) {
        $( "#from" ).datepicker( "option", "maxDate", selectedDate );
      }
    });
  });

Start date: <input type="text" id="from" name="from">
End date: <input type="text" id="to" name = "to">

A: You will need to make use of the setDate method. See More: https://api.jqueryui.com/datepicker/#method-setDate

Sets the date for the datepicker. The new date may be a Date object or a string in the current date format (e.g., "01/26/2009"), a number of days from today (e.g., +7) or a string of values and periods ("y" for years, "m" for months, "w" for weeks, "d" for days, e.g., "+1m +7d"), or null to clear the selected date.

$(function() {
  // Initialize Date Fields
  var from = $("#from").datepicker({
    changeMonth: true,
    numberOfMonths: 1,
    onClose: function(selectedDate) {
      $("#to").datepicker("option", "minDate", selectedDate);
    }
  });
  var to = $("#to").datepicker({
    changeMonth: true,
    numberOfMonths: 1,
    onClose: function(selectedDate) {
      $("#from").datepicker("option", "maxDate", selectedDate);
    }
  });
  // Set Dates
  from.datepicker("setDate", "+0d");
  to.datepicker("setDate", "-7d");
});
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>

Start date: <input type="text" id="from" name="from"> End date: <input type="text" id="to" name="to">


text:
Q: Can't pull metadata for a term in my theme's function.php I have a strange issue where I've attached custom metadata to a Woocommerce product category using the KC Settings plugin and for some reason, I can access the data just fine in a separate plugin that I wrote as well as Debug Bar's console but not in my functions.php
Here's what the working code (in its most basic form) in the console and plugin looks like:
global $woocommerce;
echo (float) get_metadata( 'term', 14, 'latitude', true );

Unfortunately, it just returns a '0' instead of the actual value when executed from functions.php. I typecast it since I need it to return a number but PHP interprets the value of the metadata as a string.
Why will this work in a plugin as well as in the console, but not in the functions.php?
EDIT: using get_metadata() on a post works just fine.  Why is it the terms object that causing the issue?
EDIT 2: Even more confusing is the fact that I've written out a wpdb query to manually pull it and I just get a white page when I try to add an item to the cart.  This query works perfectly in the console however.
$wpdb->get_var( "SELECT meta_value FROM $wpdb->wp_termmeta WHERE term_id = 14 AND meta_key = 'latitude'" );

A: woocommerce_add_to_cart_validation is a filter that is run in the add_to_cart_action method of the WC_Form_Handler class.
This method is attached to the init hook.
add_action( 'init', array( $this, 'add_to_cart_action' ) );
Your taxonomy is quite probably also registered at the init hook.  The WooCommerce action has no priority set, so the default would be 10.  I would try to register your taxonomy with a higher priority (lower number), so that the taxonomy is definitely registered before the add_to_cart_action is run. (Just a guess, and not verified)


text:
Q: basic javascript issue I have a webpage form with a checkbox on it.  I am trying to set the box to checked clicking an  that exists on another part of the webpage using the onclick.
NONE of these seem to work (form and checkbox ID/NAME are all set properly):
  test

  test

  test

 test

 test

  test

A: You should use the  element instead:
Test

Clicking this  will automatically toggle the checkbox with ID active.  (If it's a textbox, it will focus the textbox)

To answer the question, TRUE should be lowercase.  (Javascript is case-sensitive)

A: You should use  for the job:
Name
...
<input type="checkbox" id="name" name="name" />

Or
<input type="checkbox" id="name" name="name" /> Name

Edit
If you really want to use Javascript to do something special, you need to add return false; to the onclick event, to prevent the browser from changing page. Here is a Javascript example (I never use inline Javascript):
document.getElementById('somelink').onclick = function(){
    document.getElementById('somecheckbox').checked = false; // Unchecks the checkbox
    return false; // Prevents the browser from changing page
};

A: This works fine: (http://jsfiddle.net/NQ5Rm/4/)
<input type="checkbox" id="active" >

 test

A: JavaScript is case-sensitive, and its boolean literals are lower-case. Try obj.checked=true instead. In addition, in some browsers (e.g. Chrome) getElementById() means no more than what it says: It gets element by ID, not by name. Set the id property as well as the name property.
The following works fine for me in IE and Chrome:

   test
  <form>
    <input type="checkbox" name="active" id="active" value="Car" />
  </form>

Some or all of your other versions will probably work equally well, if you fix the capitalization and (if you're not using IE) set id="foo" as well as name="foo" (and if you ARE using IE, bear in mind that most of us aren't).
Lastly, the  thing suggested by other commenters is worth knowing, and will probably solve your problem better than the JavaScript.


text:
Q: Functions with 3 positional arguments but a list were given I was having an issue with a program I created to integrate and finding the value of a function using a trapezoidal method and exact integration, then the value of trapezoidal method will be compared with the exact integration using a graph.
Here's the code that I write:
import numpy.polynomial.polynomial as ply
import matplotlib.pyplot as plt
import numpy as np

#Integration, Trapezoidal Method

# Define function to integrate
def f(x):
    return 2+5*x**7+4*x**2+2*x**5

def polynom():
    return [2, 0, 4, 0, 0, 2, 0, 5]

# Implementing trapezoidal method
def trapezoidal (x0,xn,n):
    # calculating step size
    h = (xn - x0) / n

    # Finding sum
    integration = f(x0) + f(xn)

    for i in range(1,n):
        k = x0 + i*h
        integration = integration + 2 * f(k)

    # Finding final integration value
    integration = integration * h/2

    return integration

#Exact integration

# Find Indefinite integral
I = ply.polyint(polynom())

# Find Definite integral
a = lower_limit
b = upper_limit
A = ply.polyval(b, I) - ply.polyval(a, I)

# Input section
lower_limit = float(input("Enter lower limit of integration: "))
upper_limit = float(input("Enter upper limit of integration: "))
elements = int(input("Enter number of elements : "))

#Sub_interval list
n_interval = []

# iterating till the range
for val in range(0, elements):
    sub_interval = int(input("Enter number of sub intervals: "))

    n_interval.append(sub_interval) # adding the element

# Call trapezoidal() method and get result
result = trapezoidal(lower_limit, upper_limit, *n_interval) #The *n_interval is used to unpack the list.
print("Indefinite integral's constant of exact integration is: ", I)
print("Definite integral of the exact integration is: ", A)
print("Integration result by Trapezoidal method is: ", result)
print("Error value is: ", (((result-A)/A)*100))

# Plotting the error and with respects to "N"
xValue = [sub_interval, 0]
yValue = [0, ((result-A)/A)*100]

plt.plot(xValue, yValue)
plt.title("Comparison of 'N' to Error Values" )
plt.xlabel("N value")
plt.ylabel("Error value")
plt.show()

The program gave an error:
trapezoidal() takes 3 positional arguments but 4 were given.

The problem is that I don't know how to change the functions arguments while at the same time still uses lists as the parameters.

A: If you want to pass lists as parameters, you don't need the asterisk (*).
Just do:
result = trapezoidal(lower_limit, upper_limit, n_interval)

It will pass the n_interval list as a parameter for trapezoidal.
For example:
def trapezoidal(x0, xn, n):
    print(x0, xn, n)

trapezoidal(1, 10, [1, 2, 3, 4])
# n is a list

will print
1 10 [1, 2, 3, 4]