text:
Q: C# Rijndael encryption puts extra bytes in front of the decrypted files I'm trying to encrypt image files using Rijndael encryption and I must be doing something wrong because the decrypted files are coming out with extra data at the front of the file any maybe a little extra at the end. I'm fairly new to this encryption algorithm so I'm pretty sure I'm just missing something simple.
Examples using text files
Input file
"the quick brown fox jumped over the lazy yellow dog"

Output file when I try to put a generated IV at the front of the file(\0=null)
"ÚñjÐæƒÊW®ï¡_Ü&ßthe\0 quick brown fox jumped over the lazy yellow dog"

Output file when I try to put an IV that is equal to my Key at front
"\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0the\0\0\0\0\0\0 quick brown fox jumped over the lazy yellow dog"

Output file when I use an IV that is equal to my Key and put nothing at  front of file
"\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0the\0\0\0\0\0\0 quick brown fox jumped over the lazy yellow dog"

CODE
private RijndaelManaged GetCipher(byte[] key, bool forEncrypt)
{
    RijndaelManaged rijndaelCipher;

    rijndaelCipher = new RijndaelManaged();
    rijndaelCipher.Mode = CipherMode.CBC;
    rijndaelCipher.Padding = PaddingMode.PKCS7;
    rijndaelCipher.KeySize = 0x80;
    rijndaelCipher.BlockSize = 0x80;
    rijndaelCipher.Key = key;

   /* if (forEncrypt)
        rijndaelCipher.GenerateIV();
    else
    rijndaelCipher.IV = new byte[16];*/
    rijndaelCipher.IV = _imageKey;

    return rijndaelCipher;
}

public void DecryptStamp(Stamp stampToDecrypt, string decrpytedStampFilePath)
{
    RijndaelManaged rijndaelCipher;
    FileStream inputStream = null;
    FileStream outputStream = null;
    CryptoStream encryptSteam = null;
    byte[] block;
    int numberRead;
    ICryptoTransform transform;

    if (!File.Exists(stampToDecrypt.Path))
        throw new FileNotFoundException(stampToDecrypt.Path + " does not exist");

    rijndaelCipher = this.GetCipher(_imageKey, false);
    block = new byte[16];

    try
    {
        inputStream = File.Open(stampToDecrypt.Path, FileMode.Open, FileAccess.Read);
        outputStream = File.Open(decrpytedStampFilePath, FileMode.Create, FileAccess.Write);

        //inputStream.Read(rijndaelCipher.IV, 0, rijndaelCipher.IV.Length);
        transform = rijndaelCipher.CreateDecryptor();
        encryptSteam = new CryptoStream(outputStream, transform, CryptoStreamMode.Write);

        while ((numberRead = inputStream.Read(block, 0, block.Length)) > 0)
        {
            Console.WriteLine(numberRead.ToString());
            encryptSteam.Write(block, 0, numberRead);
        }
    }
    finally
    {
        rijndaelCipher.Clear();
        rijndaelCipher.Dispose();
        if (encryptSteam != null)
            encryptSteam.Dispose();
        if (outputStream != null)
            outputStream.Dispose();
        if (inputStream != null)
            inputStream.Dispose();
    }
}

public Stamp EncryptStampToStampFolder(string stampFileToEncrpyt)
{
    Configuration config;
    Stamp stampToEncrypt;
    RijndaelManaged rijndaelCipher;
    string encryptedFilePath;

    if (!File.Exists(stampFileToEncrpyt))
        throw new FileNotFoundException(stampFileToEncrpyt + " does not exist");

    config = Configuration.GetProgramInstance();
    encryptedFilePath = Path.Combine(config.StampFolder, Path.GetFileNameWithoutExtension(stampFileToEncrpyt) + ".stmp");

    stampToEncrypt = new Stamp(Path.GetFileNameWithoutExtension(stampFileToEncrpyt), encryptedFilePath);

    rijndaelCipher = this.GetCipher(_imageKey, true);
    ICryptoTransform transform = rijndaelCipher.CreateEncryptor();

    FileStream inputStream = null;
    FileStream outputStream = null;
    CryptoStream encryptSteam = null;
    byte[] block = new byte[16];
    int numberRead;

    try
    {
        inputStream = File.Open(stampFileToEncrpyt, FileMode.Open, FileAccess.Read);
        outputStream = File.Open(encryptedFilePath, FileMode.Create, FileAccess.Write);

        //outputStream.Write(rijndaelCipher.IV, 0, 16);
        encryptSteam = new CryptoStream(outputStream, transform, CryptoStreamMode.Write);

        encryptSteam.Write(block, 0, block.Length);

        while ((numberRead = inputStream.Read(block, 0, block.Length)) > 0)
        {
            encryptSteam.Write(block, 0, numberRead);
        }
    }
    finally
    {
        rijndaelCipher.Clear();
        rijndaelCipher.Dispose();
        if (encryptSteam != null)
            encryptSteam.Dispose();
        if (outputStream != null)
            outputStream.Dispose();
        if (inputStream != null)
            inputStream.Dispose();
    }

    return stampToEncrypt;
}

public struct Stamp
{
    public string Name,
        Path;

    public Stamp(string StampName, string StampPath)
    {
        Name = StampName;
        Path = StampPath;
    }
}

CODE post fix
private RijndaelManaged GetCipher(byte[] key, bool forEncrypt)
{
    RijndaelManaged rijndaelCipher;

    rijndaelCipher = new RijndaelManaged();
    rijndaelCipher.Mode = CipherMode.CBC;
    rijndaelCipher.Padding = PaddingMode.PKCS7;
    rijndaelCipher.KeySize = 0x80;
    rijndaelCipher.BlockSize = 0x80;
    rijndaelCipher.Key = key;

    if (forEncrypt)
        rijndaelCipher.GenerateIV();
    else
        rijndaelCipher.IV = new byte[16];
    //rijndaelCipher.IV = _imageKey;

    return rijndaelCipher;
}

public void DecryptStamp(Stamp stampToDecrypt, string decrpytedStampFilePath)
{
    RijndaelManaged rijndaelCipher;
    FileStream inputStream = null;
    FileStream outputStream = null;
    CryptoStream encryptSteam = null;
    byte[] block;
    int numberRead;
    ICryptoTransform transform;

    if (!File.Exists(stampToDecrypt.Path))
        throw new FileNotFoundException(stampToDecrypt.Path + " does not exist");

    rijndaelCipher = this.GetCipher(_imageKey, false);
    block = new byte[16];

    try
    {
        inputStream = File.Open(stampToDecrypt.Path, FileMode.Open, FileAccess.Read);
        outputStream = File.Open(decrpytedStampFilePath, FileMode.Create, FileAccess.Write);

        inputStream.Read(rijndaelCipher.IV, 0, rijndaelCipher.IV.Length);
        transform = rijndaelCipher.CreateDecryptor();
        encryptSteam = new CryptoStream(outputStream, transform, CryptoStreamMode.Write);

        while ((numberRead = inputStream.Read(block, 0, block.Length)) > 0)
        {
            encryptSteam.Write(block, 0, numberRead);
        }
    }
    finally
    {
        rijndaelCipher.Clear();
        rijndaelCipher.Dispose();
        if (encryptSteam != null)
            encryptSteam.Dispose();
        if (outputStream != null)
            outputStream.Dispose();
        if (inputStream != null)
            inputStream.Dispose();
    }
}

public Stamp EncryptStampToStampFolder(string stampFileToEncrpyt)
{
    Configuration config;
    Stamp stampToEncrypt;
    RijndaelManaged rijndaelCipher;
    string encryptedFilePath;

    if (!File.Exists(stampFileToEncrpyt))
        throw new FileNotFoundException(stampFileToEncrpyt + " does not exist");

    config = Configuration.GetProgramInstance();
    encryptedFilePath = Path.Combine(config.StampFolder, Path.GetFileNameWithoutExtension(stampFileToEncrpyt) + ".stmp");

    stampToEncrypt = new Stamp(Path.GetFileNameWithoutExtension(stampFileToEncrpyt), encryptedFilePath);

    rijndaelCipher = this.GetCipher(_imageKey, true);
    ICryptoTransform transform = rijndaelCipher.CreateEncryptor();

    FileStream inputStream = null;
    FileStream outputStream = null;
    CryptoStream encryptSteam = null;
    byte[] block = new byte[16];
    int numberRead;

    try
    {
        inputStream = File.Open(stampFileToEncrpyt, FileMode.Open, FileAccess.Read);
        outputStream = File.Open(encryptedFilePath, FileMode.Create, FileAccess.Write);

        outputStream.Write(rijndaelCipher.IV, 0, 16);
        encryptSteam = new CryptoStream(outputStream, transform, CryptoStreamMode.Write);

        //encryptSteam.Write(block, 0, block.Length); this line was the problem in the orginal code

        while ((numberRead = inputStream.Read(block, 0, block.Length)) > 0)
        {
            encryptSteam.Write(block, 0, numberRead);
        }
    }
    finally
    {
        rijndaelCipher.Clear();
        rijndaelCipher.Dispose();
        if (encryptSteam != null)
            encryptSteam.Dispose();
        if (outputStream != null)
            outputStream.Dispose();
        if (inputStream != null)
            inputStream.Dispose();
    }

    return stampToEncrypt;
}

public struct Stamp
{
    public string Name,
        Path;

    public Stamp(string StampName, string StampPath)
    {
        Name = StampName;
        Path = StampPath;
    }
}

New Code's output
"7p¶¼oò¾½G€¢9±hfox\0\0 jumped over the lazy yellow dog"

A: The problem was three fold.
1)Extra data being written during encryption
2)The IV at the beginning of the file was being overwritten
3)The IV was not being read properly on decryption
CODE Fixed
private RijndaelManaged GetCipher(byte[] key, bool forEncrypt)
{
    RijndaelManaged rijndaelCipher;

    rijndaelCipher = new RijndaelManaged();
    rijndaelCipher.Mode = CipherMode.CBC;
    rijndaelCipher.Padding = PaddingMode.PKCS7;
    rijndaelCipher.KeySize = 0x80;
    rijndaelCipher.BlockSize = 0x80;
    rijndaelCipher.Key = key;

    if (forEncrypt)
        rijndaelCipher.GenerateIV();
    else
        rijndaelCipher.IV = new byte[16];
    //rijndaelCipher.IV = _imageKey;

    return rijndaelCipher;
}

public void DecryptStamp(Stamp stampToDecrypt, string decrpytedStampFilePath)
{
    RijndaelManaged rijndaelCipher;
    FileStream inputStream = null;
    FileStream outputStream = null;
    CryptoStream encryptSteam = null;
    byte[] block;
    int numberRead;
    ICryptoTransform transform;

    if (!File.Exists(stampToDecrypt.Path))
        throw new FileNotFoundException(stampToDecrypt.Path + " does not exist");

    rijndaelCipher = this.GetCipher(_imageKey, false);
    block = new byte[16];

    try
    {
        inputStream = File.Open(stampToDecrypt.Path, FileMode.Open, FileAccess.Read);
        outputStream = File.Open(decrpytedStampFilePath, FileMode.Create, FileAccess.Write);

        //This line was wrong because rijndaelCipher.IV never filled
        //inputStream.Read(rijndaelCipher.IV, 0, rijndaelCipher.IV.Length);

        inputStream.Read(block, 0, block.Length);
        rijndaelCipher.IV = block;
        block = new byte[16];
        transform = rijndaelCipher.CreateDecryptor();
        encryptSteam = new CryptoStream(outputStream, transform, CryptoStreamMode.Write);

        while ((numberRead = inputStream.Read(block, 0, block.Length)) > 0)
        {
            encryptSteam.Write(block, 0, numberRead);
        }
    }
    finally
    {
        rijndaelCipher.Clear();
        rijndaelCipher.Dispose();
        if (encryptSteam != null)
            encryptSteam.Dispose();
        if (outputStream != null)
            outputStream.Dispose();
        if (inputStream != null)
            inputStream.Dispose();
    }
}

public Stamp EncryptStampToStampFolder(string stampFileToEncrpyt)
{
    Configuration config;
    Stamp stampToEncrypt;
    RijndaelManaged rijndaelCipher;
    string encryptedFilePath;

    if (!File.Exists(stampFileToEncrpyt))
        throw new FileNotFoundException(stampFileToEncrpyt + " does not exist");

    config = Configuration.GetProgramInstance();
    encryptedFilePath = Path.Combine(config.StampFolder, Path.GetFileNameWithoutExtension(stampFileToEncrpyt) + ".stmp");

    stampToEncrypt = new Stamp(Path.GetFileNameWithoutExtension(stampFileToEncrpyt), encryptedFilePath);

    rijndaelCipher = this.GetCipher(_imageKey, true);
    ICryptoTransform transform = rijndaelCipher.CreateEncryptor();

    FileStream inputStream = null;
    FileStream outputStream = null;
    CryptoStream encryptSteam = null;
    byte[] block = new byte[16];
    int numberRead;

    try
    {
        inputStream = File.Open(stampFileToEncrpyt, FileMode.Open, FileAccess.Read);
        outputStream = File.Open(encryptedFilePath, FileMode.Create, FileAccess.Write);

        outputStream.Write(rijndaelCipher.IV, 0, IV.Length);
        //This had to be changed so that the IV was not overwitten
        //encryptSteam = new CryptoStream(outputStream, transform, CryptoStreamMode.Write);
        encryptSteam = new CryptoStream(inputStream, transform, CryptoStreamMode.Read);

        //this line was a problem in the orginal code that caused extra data to be added to the encrypted file
        //encryptSteam.Write(block, 0, block.Length);

        while ((numberRead = encryptSteam.Read(block, 0, block.Length)) > 0)
        {
            outputStream.Write(block, 0, numberRead);
        }
    }
    finally
    {
        rijndaelCipher.Clear();
        rijndaelCipher.Dispose();
        if (encryptSteam != null)
            encryptSteam.Dispose();
        if (outputStream != null)
            outputStream.Dispose();
        if (inputStream != null)
            inputStream.Dispose();
    }

    return stampToEncrypt;
}

public struct Stamp
{
    public string Name,
        Path;

    public Stamp(string StampName, string StampPath)
    {
        Name = StampName;
        Path = StampPath;
    }
}

A: Here's what I do to decrypt:
    private RijndaelManaged GetAesProvider(Stream stm, bool isEncryption)
    {
        byte[] finalKey = GetFinalKey();
        // GetIV either gets salt on encryption and writes it into stm
        // or reads it from stm if it's decryption
        byte[] iv = GetIV(stm, isEncryption);
        RijndaelManaged aes = new RijndaelManaged();
        aes.BlockSize = kAesBlockSizeInBytes * 8;
        aes.IV = iv;
        aes.Key = finalKey;
        aes.Mode = CipherMode.CBC;
        return aes;
    }

    public override Stream GetDecryptionStream(Stream source)
    {
        if (source.Length <= kIVSize)
        {
            return new EmptyStream();
        }
        RijndaelManaged aes = GetAesProvider(source, false);
        ICryptoTransform xform = aes.CreateDecryptor(aes.Key, aes.IV);
        return new CryptoStream(source, xform, CryptoStreamMode.Read);
    }


text:
Q: Windows file path length restriction while migrating users from Mac to Windows We are in the process of migrating users from OSX to Windows 10. On Mac, users never had restrictions with theirs paths lengths, so over time, they created many files/directories structures that exceeds the maximum authorized on Windows.
For the future, users will have to deal with this (stupid) restriction that Windows is still imposing in 2017. But the big issues for the moment is when I have to move their data from the old Mac to the new PC. I get errors when Windows finds a file with a too long file path.
I enabled the GPO policy enable win32 long paths, but this doesn't help. I think Microsoft fixed the Windows API, but not theirs apps like Windows Explorer.
I found the TLPD utility. It scan a file tree and reports files that exceeds the maximum allowed length. Then the user have to rename or trash theirs files. Very time consuming!
I also found Long Path Fixer utility. This is supposed to allow to copy files with a too long path length, but I failed to use it. It's slow and at the end it just crash.
Do you have better solutions?

A: I would try using robocopy to transfer, it's generally pretty good at getting around that limitation. Look through when you're done though to see if it auto truncated any names.
https://technet.microsoft.com/en-us/library/cc733145(v=ws.11).aspx
You will also want to verify that Explorer and apps are able to reach those longer file lengths okay before nuking it on the mac.
Edit: As far as accessing those files once they're copied... that's the Windows API limitation kicking in. If they're relatively uncommon, you can use extended-length prefix or substitute to jump into those paths...
https://msdn.microsoft.com/en-us/library/aa365247(v=vs.85).aspx#maxpath
https://technet.microsoft.com/en-us/library/bb491006.aspx
If they're common enough that manual workarounds are a pain, then I would suggest trying the /FAT parameter on the Robocopy job. I've never used it, but it appears to use the 8.3 naming scheme which might auto-truncate those paths for you; not sure if this would cause other issues though. Another option is if these machines are Windows 10, you can enable a registry key to get around the limitation in Explorer (see above MSDN article).

redpajama_set_name: RedPajamaStackExchange


text:
Q: RecyclerView does not display any data I've been struggling with this issue for a while. I have an activity (SerieActivity) where I allow the user to select various items and give them values. The items are stored in an ArrayList<Variable>, where Variable is a class that I've defined. The items are displayed in a RecyclerView. This works just fine. Upon clicking a button in that activity, the user is sent to another activity (Result) that displays the exact same items from the ArrayList in SerieActivity, with the respective values that the user has input.
In my Result activity I have created an instance of the SerieActivity class and then made an ArrayList to store the values of the original ArrayList from SerieActivity. However it seems like the RecyclerView from my Result class doesn't get populated with data. What could be going wrong?
Here's my code:
Variable class
public class Variable {

    boolean known;
    String unit, name;
    double value;
}

RVAdapterSerie - the adapter for the RecyclerView used in the SerieActivity class
public class RVAdapterSerie extends RecyclerView.Adapter<RVAdapterSerie.ViewHolder> {

    private Context context;
    private ArrayList<Variable> variableList;

    public RVAdapterSerie(Context context, ArrayList<Variable> variableList) {
        this.context = context;
        this.variableList = variableList;
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(context).inflate(R.layout.recycler_item, parent, false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(RVAdapterSerie.ViewHolder holder, int position) {
        Variable v = variableList.get(position);
        holder.setItems(v);
    }

    @Override
    public int getItemCount() {
        return variableList.size();
    }

    public class ViewHolder extends RecyclerView.ViewHolder {
        private CheckBox checkBox;
        private EditText editText;
        private TextView textView;

        public ViewHolder(View itemView) {
            super(itemView);
            checkBox = itemView.findViewById(R.id.value_cb);
            editText = itemView.findViewById(R.id.value_et);
            textView = itemView.findViewById(R.id.value_tv);
        }

        public void setItems (Variable variable) {
            checkBox.setText(variable.getName());
            editText.setText(String.format("%.3f", variable.getValue()));
            textView.setText(variable.getUnit());
        }
    }
}

SerieActivity class
public class SerieActivity extends AppCompatActivity {

    public ArrayList<Variable> mList = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_serie);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        RecyclerView recyclerView = findViewById(R.id.serie_rv);
        RVAdapterSerie rvAdapterSerie = new RVAdapterSerie(this, mList);
        recyclerView.setAdapter(rvAdapterSerie);
        recyclerView.setHasFixedSize(true);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));

        populateList();
        rvAdapterSerie.notifyDataSetChanged();

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.serie_fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(SerieActivity.this, Result.class);
                intent.putExtra("tag", "serie");
                startActivity(intent);
            }
        });
    }

    public void populateList() {
        mList.add(new Variable(false, "dummyunit", "dummyname", 0));
        mList.add(new Variable(false, "diofishafuio", "ghfuef", 0));
        mList.add(new Variable(false, "diofishdfesffafuio", "ghfuef", 0));
        //add dummy items
    }
}

RVResultAdapter - adapter for the RecyclerView in Result class
public class RVResultAdapter extends RecyclerView.Adapter<RVResultAdapter.ViewHolder> {

    private Context context;
    private ArrayList<Variable> variableList;

    public RVResultAdapter(Context context, ArrayList<Variable> variableList) {
        this.context = context;
        this.variableList = variableList;
    }

    @Override
    public RVResultAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(context).inflate(R.layout.result_item, parent, false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(RVResultAdapter.ViewHolder holder, int position) {
        Variable v = variableList.get(position);
        holder.setItems(v);
    }

    @Override
    public int getItemCount() {
        return variableList.size();
    }

    public class ViewHolder extends RecyclerView.ViewHolder {

        TextView textView1;
        TextView textView2;
        TextView textView3;

        public ViewHolder(View itemView) {
            super(itemView);
            textView1 = itemView.findViewById(R.id.result_name_tv);
            textView2 = itemView.findViewById(R.id.result_value_tv);
            textView3 = itemView.findViewById(R.id.result_unit_tv);
        }

        public void setItems (Variable variable) {
            textView1.setText(variable.getName());
            textView2.setText(String.format("%.3f", variable.getValue()));
            textView3.setText(variable.getUnit());
        }
    }
}

Result class
public class Result extends AppCompatActivity {

    public ArrayList<Variable> rList = new ArrayList<>();

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

        Intent intent = getIntent();
        String tag = intent.getExtras().getString("tag");

        if (tag.equals("serie")) {
            SerieActivity serieActivity = new SerieActivity();
            rList = serieActivity.mList;
        }

        RecyclerView recyclerView = findViewById(R.id.result_rv);
        RVResultAdapter rvResultAdapter = new RVResultAdapter(this, rList);
        recyclerView.setAdapter(rvResultAdapter);
        recyclerView.setHasFixedSize(true);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        rvResultAdapter.notifyDataSetChanged();
    }
}

My problem is with the RecyclerView in Result. It shows the blue "end of content" things when I scroll up and down, so I guess the RecyclerView is there, but doesn't get any data. Any help is greatly appreciated. I am quite new to Android and Java programming, so I guess it must be a dumb thing that I just don't see.

A: What are you doing dude. How can you get list from a new object of SerieActivity.class?

    if (tag.equals("serie")) {
        SerieActivity serieActivity = new SerieActivity();
        rList = serieActivity.mList;
    }

This is totally wrong way. If you want to pass list between activities. You can use parcelable methods putExtra and getExtra.
Assuming that your List is a list of strings make data an ArrayList<String> and use intent.putStringArrayListExtra("data", data)
Here is a skeleton of the code you need:
First you need to create a Parcelable object class, see the example
public class Student implements Parcelable {

        int id;
        String name;

        public Student(int id, String name) {
            this.id = id;
            this.name = name;

        }

        public int getId() {
            return id;
        }

        public String getName() {
            return name;
        }

        @Override
        public int describeContents() {
            // TODO Auto-generated method stub
            return 0;
        }

        @Override
        public void writeToParcel(Parcel dest, int arg1) {
            // TODO Auto-generated method stub
            dest.writeInt(id);
            dest.writeString(name);
        }

        public Student(Parcel in) {
            id = in.readInt();
            name = in.readString();
        }

        public static final Parcelable.Creator<Student> CREATOR = new Parcelable.Creator<Student>() {
            public Student createFromParcel(Parcel in) {
                return new Student(in);
            }

            public Student[] newArray(int size) {
                return new Student[size];
            }
        };
    }

And the list
ArrayList<Student> arraylist = new ArrayList<Student>();

Code from Calling activity
Intent intent = new Intent(this, SecondActivity.class);
Bundle bundle = new Bundle();
bundle.putParcelableArrayList("mylist", arraylist);
intent.putExtras(bundle);
this.startActivity(intent);

Code on called activity
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_second);

    Bundle bundle = getIntent().getExtras();
    ArrayList<Student> arraylist = bundle.getParcelableArrayList("mylist");
}

A: So you calling SerieActivity constructor in Results activity and execute populateList() inside onCreate(). You shouldn't create activities in this way because onCreate() will be never called. Instead of this you should pass data using putExtra and use Parcelable interface.

A: just set the recyclerview code like this first initialize adapter then set layout manager and then set to adapter to recyclerview.
recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
    mAdapter = new MoviesAdapter(movieList);
    RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
    recyclerView.setLayoutManager(mLayoutManager);
    recyclerView.setItemAnimator(new DefaultItemAnimator());
    recyclerView.setAdapter(mAdapter);

    prepareMovieData();


text:
Q: Cant pass the argument for a constructor from a switch case statement I tried this:
class Quota{
    private:
        ....
    public:
        Quota(const int sizee): ID(sizee), percentage(sizee){
            quotaa = 100;
        }
        ....
};
int main(){
    int intake, choice;
    cin >> choice;
    Quota q;
    switch(choice){
        case 1:
        cin >> intake;
        q(intake);
        break;
        case 2:
        ...
        default:
    }
    q.xyz();
}

How can i make this work? i need to initialize an object of the Quota class and pass the argument for the constructor in the switch statement while still being able to access the same object anywhere else in the main function?

A: Move the line that constructs the object after the switch statement.
int intake, choice;
cin >> choice;
switch(choice){

    case 1:
    cin >> intake;

    // Don't do this.
    // q(intake);
    break;

    case 2:
    ...

    default:
}

// Now that you have intake, construct q.
Quota q(intake);

A: This has nothing to do with the switch: as it is, you wouldn't be able to write
Quota q; // default construct
q(intake);

The first statement Quota q constructs a Quota, and that's where you need to pass the intake parameter.
You can use the copy constructor to do
Quota q;
q = Quota(intake);

A: You can't call constructors after the value is declared.
Try this instead:
q = Quota(intake);

You'll also need to declare a default constructor for Quota initializing all members to "reasonable defaults"


text:
Q: Can I break out of a python generator? Consider the following string
long_string = '#' * 4 + 'a' * 10 + '#' * 4

print(long_string)

####aaaaaaaaaa####

I want to cycle through and get only the first several characters until the character is Not a '#'
I can iterate through and get at just the '#'
''.join(x for x in long_string if x.startswith('#'))

'########'

This is too many.
I want to do something like this
def gen_break(long_string, mychar):
    i = iter(long_string)
    s = next(i)
    while s == mychar:
        yield s
        s = next(i)

''.join(gen_break(long_string, '#'))

'####'

This stopped iterating when it encountered a condition for which to break.  Is there a way to do this more elegantly within the (this for this in that) syntax?

NOTE:
This was a contrived example in order to highlight the question I am asking.  I'm not looking for a way to parse this example string.  I'm looking for a way to break out of iteration in an elegant way, preferably using comprehension syntax.

A: You can use the itertools.takewhile function:
from itertools import takewhile

''.join(takewhile(lambda x:x == '#','#### foo bar ### qux'))

this then generates:
>>> ''.join(takewhile(lambda x:x == '#','#### foo bar ### qux'))
'####'

So as long as the predicate (the first argument) of takewhile is satisfied, it iterates through the iterable (the second argument). From the moment the predicate is not satisfied, takewhile will stop. It will not exhaust the remaining(s) of the iterable/iterator.
As far as I know you can not do this with list comprehension/generator/... syntax.


text:
Q: Integer part hack fro the Fast inverse square root Can someone explain the meaning of this line of code?
i  = * ( long * ) &y;

The code is from wikipedia, Fast inverse square root.
Is there a way to do the same with python?

A: In Python why not just do x**-1/2 or x**-.5


text:
Q: Call back not working when Link is clicked in react router I've been trying to send a call back to parent component C from child component A to set state in parent C! This state will be sent to another child component B. I have a link component in A which calls the component in B but the child component needs the state from parent component and when I click on the link in A the call Back is not being called but I want it to be called.
Class C extends react.Component
{
    constructor(props: any)
    {
        super(props);
        this.state={
        somestate: '',
        }
    }
    CallBack(somestate:string)
    {
        this.Setstate({somestate, somestate},()=>{console.log(this.state.somestate);});
    }
    render()
    {
        return(

            <Route path='/somestate' >

            </Route>

        )
    }
}
Class A extends React.Component
{
    constructor(props: any)
    {
        super(props);
    }
    callback()
    {
        this.props.CallBack();//causing errror when i click Link tag
    }
    render()
    {
        return(
        <Link to='/somestate'>
            <button onClick={this.callback()}>click me</button>
        </Link>
        )
    }
}
Class B extends React.Component
{
    constructor(props: any)
    {
        super(props);
    }
    render()
    {
        return(

            this.props.somestate;

        )
    }
}

I'm not able to call the call back in props. I'm guessing we cant use call back to parent and link at the same time. So how to actually use it.

A: According to the React Router documents you should pass others props like onClick as bellow:
<Link to="/somestate" onClick={this.callback} className="some-classname">Click me</Link>

Also you can pass className so to shape the link as you want.


text:
Q: Method for testing DOM selector efficiency Is there any straightforward way to evaluate DOM selector efficiency on a page? My curiosity comes from a page written with jQuery, but ideally I'm looking for something more generic (I appreciate the efficiency of selector may differ between approach used to locate it).
This came from a situation where I had a form, say #myForm which contained a <button class="button">
As a selector I was using #myForm button, but I could obviously use #myForm .button , #myForm button.button and a few other alternatives.
Whilst in this example the different is trivial, I wondered whether there is a general consensus as to best approach and further to that, whether there is an easy way to pop together a test page of sorts to experiment with combinations. This then made my realise I have not a clue how to performance test a selector, does anyone have any preferred routes to perform this type of action? Any thoughts appreciated.

A: The order of dom selectors according to this article:
http://csswizardry.com/2011/09/writing-efficient-css-selectors/

*

*ID, e.g. #header

*Class, e.g. .promo

*Type, e.g. div

*Adjacent sibling, e.g. h2 + p

*Child, e.g. li > ul

*Descendant, e.g. ul a

*Universal, i.e. *

*Attribute, e.g. [type="text"]

*Pseudo-classes/-elements, e.g. a:hover

I've created a jsperf text with some example selectors to show how you can test each one:
http://jsperf.com/dom-selector-testing
From those results the fastest to the slowest is:

*

*getElementById

*getElementsByTagName

*getElementsByClassName // ie8 does not support this

*querySelector


text:
Q: How to extract skin from an image using HSV thresholding and contouring in OpenCv? This is my code. Skin Detector is a separate class that does the HSV thresholding. I've got it covered.
`

using namespace std;
using namespace cv;

// Function Headers
void Display(String s);
void detectAndDisplay(Mat frame);

void drawStuff();
void showInputWindow();
void showCannyWindow();
void showContourWindow();
void FindContour(Mat skinMat);

// Global variables

 cv::Rect roi_b;
 cv::Rect roi_c;
 int thresh = 2;
 Mat img_rgb,img_gray,img_bw,canny_output,drawing;

// Copy this file from opencv/data/haarscascades to target folder

string face_cascade_name = "c:/haarcascade_frontalface_alt.xml";
CascadeClassifier face_cascade;
string window_name = "Capture - Face detection";
int filenumber; // Number of file to be saved
string filename;

// Function main

int main(void)
{

//  Display("3.jpg");

    // Load the cascade
    if (!face_cascade.load(face_cascade_name))
    {
        printf("--(!)Error loading\n");
        return (-1);
    };

    // Read the image file

    Mat frame = imread("c:/Emma.jpg");

 //   for (;;)
    {
        // Apply the classifier to the frame
        if (!frame.empty())
        {
            detectAndDisplay(frame);

            // detect skin
            SkinDetector mySkinDetector;
            Mat skinMat;
            skinMat= mySkinDetector.getSkin(frame);

            imshow("Skin Image",skinMat);

            // for contour detection

    img_rgb  = skinMat;
    blur( img_rgb, img_rgb, Size(3,3) );
    cvtColor(img_rgb,img_gray,CV_RGB2HSV);
  //  showInputWindow();

    drawStuff();
    cv::waitKey(0);

    }

        else
        {
            printf(" --(!) No captured frame -- Break!");
           // break;
        }

        int c = waitKey(10);

        if (27 == char(c))
        {
           // break;
        }

    /*for (int s=3 ; s>=0 ; s-- )
    {
        Display(+s+".jpg");
    }*/

    getchar();
    //waitKey(10);
    return 0;
}

}

// Function detectAndDisplay
void detectAndDisplay(Mat frame)

{
    std::vector<Rect> faces;
    Mat frame_gray;
    Mat crop;
    Mat res;
    Mat gray;
    string text;
    stringstream sstm;
    Mat Test1 = frame;

    cvtColor(frame, frame_gray, COLOR_BGR2GRAY);
    equalizeHist(frame_gray, frame_gray);

    // Detect faces
    face_cascade.detectMultiScale(frame_gray, faces, 1.1, 2, 0 | CASCADE_SCALE_IMAGE, Size(30, 30));

    // Set Region of Interest
   /* cv::Rect roi_b;  we need them global
    cv::Rect roi_c;*/

    size_t ic = 0; // ic is index of current element
    int ac = 0; // ac is area of current element

    size_t ib = 0; // ib is index of biggest element
    int ab = 0; // ab is area of biggest element

    for (ic = 0; ic < faces.size(); ic++) // Iterate through all current elements (detected faces)

    {
        roi_c.x = faces[ic].x;
        cout<<roi_c.x<<"/n";;
        roi_c.y = faces[ic].y;
        cout<<roi_c.y<<"/n";
        roi_c.width = (faces[ic].width);
        roi_c.height = (faces[ic].height);

        ac = roi_c.width * roi_c.height; // Get the area of current element (detected face)

        roi_b.x = faces[ib].x;
        roi_b.y = faces[ib].y;
        roi_b.width = (faces[ib].width);
        roi_b.height = (faces[ib].height);

        ab = roi_b.width * roi_b.height; // Get the area of biggest element, at beginning it is same as "current" element

        //if (ac > ab)
        //{
        //    ib = ic;
        //    roi_b.x = faces[ib].x;
        //    roi_b.y = faces[ib].y;
        //    roi_b.width = (faces[ib].width);
        //    roi_b.height = (faces[ib].height);
        //}

        crop = frame(roi_b);
      //  resize(crop, res, Size(128, 128), 0, 0, INTER_LINEAR); // This will be needed later while saving images
      //  cvtColor(crop, gray, CV_BGR2HSV); // Convert cropped image to Grayscale

        // Form a filename
        filename = "";
        stringstream ssfn;
        ssfn << filenumber << ".jpg";
        filename = ssfn.str();
        filenumber++;

    //  Mat ArrayDetectedFaces []

        imwrite(filename, crop);

        Point pt1(faces[ic].x, faces[ic].y); // Display detected faces on main window - live stream from camera
        Point pt2((faces[ic].x + faces[ic].height), (faces[ic].y + faces[ic].width));
        rectangle(frame, pt1, pt2, Scalar(255, 0, 0), 2, 1, 0);

        FindContour(frame(roi_c));

    }

    // Show image
    sstm << "Crop area size: " << roi_b.width << "x" << roi_b.height << " Filename: " << filename;
    text = sstm.str();

    putText(frame, text, cvPoint(30, 30), FONT_HERSHEY_COMPLEX_SMALL, 0.8, cvScalar(0, 0, 255), 1, CV_AA);
    imshow("original", frame);

    Mat ccc = frame (roi_c);
    Mat bbb = frame (roi_b);
    Mat Img = frame;
    Mat destinationROI = frame( roi_c );

Size size(roi_c.width , roi_c.height);//the dst image size,e.g.100x100

Mat dst = bbb;//dst image
Mat src = ccc;//src image

cout<< dst.cols<<"\n";
cout<< dst.rows<<"\n";

resize(src,dst,size);//resize image

cout<< dst.cols<<"\n";
cout<< dst.rows<<"\n";

cout<< src.cols<<"\n";
cout<< src.rows<<"\n";

cout<< roi_b.width<<"\n";
cout<< roi_b.height<<"\n";

cout<< roi_c.width<<"\n";
cout<< roi_c.height<<"\n";

dst.copyTo(Img( roi_c ));

Mat FML;

//compare(dst,  Img(roi_c), FML , CMP_EQ );
    //cout<<FML;

    if (!crop.empty())
    {
    //  imshow("c", Test1(roi_c));

    //    imshow("b", bbb);
    //  imshow("result", Img(roi_c));
    }
    else
        destroyWindow("detected");
}

void Display(String s)

{
    Mat I = imread(s);
if (I.empty())
{
    std::cout << "!!! Failed imread(): image not found" << std::endl;
    // don't let the execution continue, else imshow() will crash.
}

namedWindow( "Display window", CV_WINDOW_AUTOSIZE );// Create a window for display.
imshow( "Display window", I );

}

void drawStuff(){
    vector<vector<Point> > contours;
    vector<Vec4i> hierarchy;

    Canny( img_gray, canny_output, thresh, thresh*2, 3 );
    cv::dilate(canny_output, canny_output, cv::Mat(), cv::Point(-1,-1));
  //  showCannyWindow();

    findContours( canny_output, contours, hierarchy, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_SIMPLE, Point(0, 0) );
    drawing = Mat::zeros( canny_output.size(), CV_8UC3 );

    vector<Point> approxShape;
    for(size_t i = 0; i < contours.size(); i++){
        approxPolyDP(contours[i], approxShape, arcLength(Mat(contours[i]), true)*0.04, true);
        drawContours(drawing, contours, i, Scalar(255, 255, 255), CV_FILLED);   // fill BLUE
    }

    showContourWindow();
}

void showContourWindow()
{
    cv::namedWindow("Fill");
    cv::imshow("Fill",drawing);
}

void FindContour(Mat skinMat)

{
img_rgb  = skinMat;
    blur( img_rgb, img_rgb, Size(3,3) );
    cvtColor(img_rgb,img_gray,CV_RGB2HSV);
  //  showInputWindow();

    drawStuff();
    cv::waitKey(0);
}`

After thresholding and contouring, the output is soemthing like this.!
  http://postimg.org/image/5ri87c2r5/

My question is, How can use this image to extract out only the features of the face (skin, eyes, nose, lips) and place it on another image. Will it work? Is there any easier way to do it?
If there is an easier way, please explain.
Its very important so please help me.
Moreover when I use copyto function, It doesn't give me an error but it also doesn't show any change in the picture.
Please don't mind excessive variables and bad programming. Its a test version.

A: As far as, i understand that you use cascade and contour to get face.
Then try these steps,

*

*detect biggest contour, which represent as face and remove all other small contours.

*overlap your binary face image with original image to get your real face and then use some other threshold like Ostu Method.

*For eyes detection: use circle detection method to get eye ball, which will represent your eyes.

*For skin detection: Use only hue because color is represented by hue and refer my paper for detecting skin.

*And for other face features such as nose, try other threshold methods.

Hope this helps.
Cheers :)


text:
Q: Поиск минимальной разницы элементов двух списков Имеется два списка чисел:
s1 = [1, 10, 20, 30, 40, 50, 60, 70, 80, 90]
s2 = [2, 12, 22, 32, 42, 52, 62, 72, 82, 92]

необходимо найти разницу для каждого элемента первого списка с каждым элементом второго, после чего вывести результат в файл.

A: In [12]: s1 = [1,10,20]

In [13]: s2 = [2, 12, 22]

In [14]: min(x-y for x in s1 for y in s2)
Out[14]: -21

A: Вот:
l1 = [1, 10, 20, 30, 40, 50, 60, 70, 80, 90]
l2 = [2, 12, 22, 32, 42, 52, 62, 72, 82, 92]

open(FILENAME, 'w').write(' '.join(map(lambda t: str(t[0] - t[1]), zip(l1, l2))))

A: itertools.product
# product('ABCD', 'xy') --> Ax Ay Bx By Cx Cy Dx Dy
# product(range(2), repeat=3) --> 000 001 010 011 100 101 110 111

import itertools
with open('file.txt', 'w') as file:
    for a, b in itertools.product(s1, s2):
        file.write('{r}={a}-{b}\n'.format(r=a-b, a=a, b=b))


text:
Q: My controllers doesn't work I'm running a Zend Framework app on my.phpcloud.com (so server configs should be ok...)
The index page works fine, I modified application/controllers/IndexController.php like this:
class IndexController extends Zend_Controller_Action
{
    public function indexAction()
    {
        $this->view->assign('hello', 'hello world!');
    }
}

in application/views/scripts/index/index.phtml I print $this->hello and everything works fine.
But if I create a new controller like application/controllers/UserController.php
class UserController extends Zend_Controller_Action
{
    public function indexAction()
    {
        $this->view->assign('name', 'Albert');
    }
}

I created the view in application/views/scripts/user/index.phtml and I print $this->name as I did in the index's view.
But when i visit http://myapp/user I get a Not Found error...what's the problem?

A: 1) Check that the file name for user controller contains first uppercase letter UserController.php (not userController.php)
2) Check .htaccess file for proper rewrite rulles
3) Try http://myapp/User (User uppercase first letter)
4) Check that default routing is enabled.
5) Do you have error controller created and enabled?
I think that there is some problem in configuration, maybe in your bootstrap or in config.ini


text:
Q: How to fix Java rxtxSerial.dll or jSSC-2.7_x86_64.dll Serial Port Error in Windows 10? UPDATE:  I have found a solution by using the jSerialComm library. (see code at the bottom)
I have a program that we have been running for quite a while on windows 7 machines, but now are starting to introduce machines with Windows 10, and the program crashes.  So i need to find a solution.
The error is an EXCEPTION_ACCESS_VIOLATION error. (See below)
The first block of code below is my own code which uses the rxtxSerial.dll library.  It will open and set the port parameters, but crashes as soon as data is received from the port.
I have also tried the jssc.jar library with the same EXCEPTION_ACCESS_VIOLATION error.
The second block of code is straight from the JSSC samples WIKI.  It crashes as soon as it tries to open the port.
I am the using IntelliJ IDE.
The rxtxSerial.dll error:
#
# A fatal error has been detected by the Java Runtime Environment:
#
# EXCEPTION_ACCESS_VIOLATION (0xc0000005) at pc=0x0000000180005b00, pid=12340, tid=6016
#
# JRE version: Java(TM) SE Runtime Environment (10.0.1+10) (build 10.0.1+10)
# Java VM: Java HotSpot(TM) 64-Bit Server VM (10.0.1+10, mixed mode, tiered, compressed oops, g1 gc, windows-amd64)
# Problematic frame:
# C  [rxtxSerial.dll+0x5b00]
#
# No core dump will be written. Minidumps are not enabled by default on client versions of Windows
#
# An error report file with more information is saved as:
# C:\Users\jochu\IdeaProjects\WITSReader\hs_err_pid12340.log
#
# If you would like to submit a bug report, please visit:
#  http://bugreport.java.com/bugreport/crash.jsp
# The crash happened outside the Java Virtual Machine in native code.
# See problematic frame for where to report the bug.
#

I have tried several versions of rxtxSerial.dll and RXTXcomm.jar
At this point I am thinking it is not an issue with my code as much as in issue with a library or maybe even the java SDK 10.0.1.
Update:  I also have the same issue in Java SDK 11.0.1 with Javafx SDK 11.0.1
Below is the code I use which causes the error. (only when run on windows 10)
rxtxSerial.dll and RXTXcomm.jar need to be linked libraries.
import gnu.io.*;
import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.TooManyListenersException;

public class Main {

    static CommPortIdentifier[] portId = new CommPortIdentifier[10];
    static Enumeration portList;
    static InputStream inputStream;
    static SerialPort serialPort;
    static String stringBuffer = "";

    public static void main(String[] args) {

        //manually change for comport selection to keep code simple
        int selectedPort = 0;

        // Checking for ports
        portList = CommPortIdentifier.getPortIdentifiers();
        System.out.println("portList... " + portList);
        int comPortCounter = 0;
        while (portList.hasMoreElements()) {
            portId[comPortCounter] = (CommPortIdentifier) portList.nextElement();
            System.out.println(portId[comPortCounter].getName());
            System.out.println("port identified is Serial.. " + portId[comPortCounter].getPortType());
            comPortCounter++;
            if (comPortCounter > 9){
                comPortCounter = 9;
            }
        }

        // opening the port
        try{
            serialPort = (SerialPort) portId[selectedPort].open("SerialTest",500);
            System.out.println("Serial port open: " + portId[selectedPort].getName());
        } catch (PortInUseException e){
            System.out.println("Port in use error");
            return;
        }

        // initiate listening on the port
        try {
            inputStream = serialPort.getInputStream();
            System.out.println("Input Stream... " + inputStream);
        } catch (IOException e) {
            System.out.println("IO Exception");
            return;
        }

        // create the listener
        try {
            serialPort.addEventListener(new ListenerTest());
        } catch (TooManyListenersException e) {
            System.out.println("Too many Listener exception");
            return;
        }
        serialPort.notifyOnDataAvailable(true);

        // set COM port parameters (default 9600, 8, 1 , NONE)
        try {
            serialPort.setSerialPortParams(9600, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);

            // no handshaking or other flow control
            serialPort.setFlowControlMode(SerialPort.FLOWCONTROL_NONE);

            // timer on any read of the serial port
            serialPort.enableReceiveTimeout(500);

            System.out.println("Serial port parameters have been set");
        } catch (UnsupportedCommOperationException e) {
            System.out.println("UnSupported comm operation");
            return;
        }
    }

    //Listener Class for the serial port.
    static public class ListenerTest implements SerialPortEventListener {

        @Override
        public void serialEvent(SerialPortEvent event) {

            switch (event.getEventType()) {
                case SerialPortEvent.DATA_AVAILABLE:

                    System.out.println("In SerialEvent");

                    // Wets Serial Port Read
                    try {
                        while (inputStream.available() > 0) {
                            byte[] byteBuffer = new byte[1024];
                            int length = -1;
                            length = inputStream.read(byteBuffer);
                            stringBuffer += new String(byteBuffer, 0, length);
                        }

                        System.out.println(stringBuffer);

                    } catch (IOException e) {
                        System.out.println("IO Exception in SerialEvent()");
                    }

                    break;
            }
        }
    }

}

I have also tried the jSSC.jar libraray with the following code.  This code is straight from the jssc sample WIKI with the exception of the extra System.out.println commands to track where the code was crashing.
import jssc.SerialPort;
import jssc.SerialPortEvent;
import jssc.SerialPortEventListener;
import jssc.SerialPortException;

public class Main {

    static SerialPort serialPort;

    public static void main(String[] args) {
        serialPort = new SerialPort("COM14");
        try {
            System.out.println("Before openPort command.");
            serialPort.openPort();//Open port
            System.out.println("Port is open.");
            serialPort.setParams(9600, 8, 1, 0);//Set params
            System.out.println("Port Parameters are set.");
            int mask = SerialPort.MASK_RXCHAR + SerialPort.MASK_CTS + SerialPort.MASK_DSR;//Prepare mask
            serialPort.setEventsMask(mask);//Set mask
            System.out.println("Mask is set.");
            serialPort.addEventListener(new SerialPortReader());//Add SerialPortEventListener
            System.out.println("Listener has started.");
        }
        catch (SerialPortException ex) {
            System.out.println(ex);
        }
    }

    /*
     * In this class must implement the method serialEvent, through it we learn about
     * events that happened to our port. But we will not report on all events but only
     * those that we put in the mask. In this case the arrival of the data and change the
     * status lines CTS and DSR
     */
    static class SerialPortReader implements SerialPortEventListener {

        public void serialEvent(SerialPortEvent event) {
            System.out.println("In Listener Event.");
            if(event.isRXCHAR()){//If data is available
                if(event.getEventValue() == 10){//Check bytes count in the input buffer
                    //Read data, if 10 bytes available
                    try {
                        byte buffer[] = serialPort.readBytes(10);
                    }
                    catch (SerialPortException ex) {
                        System.out.println(ex);
                    }
                }
            }
            else if(event.isCTS()){//If CTS line has changed state
                if(event.getEventValue() == 1){//If line is ON
                    System.out.println("CTS - ON");
                }
                else {
                    System.out.println("CTS - OFF");
                }
            }
            else if(event.isDSR()){///If DSR line has changed state
                if(event.getEventValue() == 1){//If line is ON
                    System.out.println("DSR - ON");
                }
                else {
                    System.out.println("DSR - OFF");
                }
            }
        }
    }
}

And it generates the following error on the openPort command.
#
# A fatal error has been detected by the Java Runtime Environment:
#
#  EXCEPTION_ACCESS_VIOLATION (0xc0000005) at pc=0x0000000000aeb5bb, pid=12216, tid=16084
#
# JRE version: Java(TM) SE Runtime Environment (10.0.1+10) (build 10.0.1+10)
# Java VM: Java HotSpot(TM) 64-Bit Server VM (10.0.1+10, mixed mode, tiered, compressed oops, g1 gc, windows-amd64)
# Problematic frame:
# C  [jSSC-2.7_x86_64.dll+0xb5bb]
#
# No core dump will be written. Minidumps are not enabled by default on client versions of Windows
#
# An error report file with more information is saved as:
# C:\Users\jochu\IdeaProjects\jsscTest\hs_err_pid12216.log
#
# If you would like to submit a bug report, please visit:
#   http://bugreport.java.com/bugreport/crash.jsp
# The crash happened outside the Java Virtual Machine in native code.
# See problematic frame for where to report the bug.
#

I am hoping someone may have run into this error before me, and found a solution.
I just need to read serial data through a listener on windows 10.
Any help will be very much appreciated!
The code below works on windows 10 with the jSerialComm-2.4.0.jar library.
import com.fazecast.jSerialComm.SerialPort;
import com.fazecast.jSerialComm.SerialPortDataListener;
import com.fazecast.jSerialComm.SerialPortEvent;

public class Main {

    static SerialPort comPort;
    static String stringBuffer;

    private static final class DataListener implements SerialPortDataListener
    {
        @Override
        public int getListeningEvents() { return SerialPort.LISTENING_EVENT_DATA_AVAILABLE; }

        @Override
        public void serialEvent(SerialPortEvent event)
        {
            //System.out.println("In event listener.");
            if (event.getEventType() != SerialPort.LISTENING_EVENT_DATA_AVAILABLE)
                return;
            //System.out.println("Past event type check.");
            byte[] newData = new byte[comPort.bytesAvailable()];
            int numRead = comPort.readBytes(newData, newData.length);
            stringBuffer = new String(newData,0,numRead);
            //System.out.println("Read " + numRead + " bytes.");
            System.out.println(stringBuffer);

        }
    }

    static public void main(String[] args)
    {
        comPort = SerialPort.getCommPorts()[0];
        comPort.openPort();
        System.out.println("COM port open: " + comPort.getDescriptivePortName());
        DataListener listener = new DataListener();
        comPort.addDataListener(listener);
        System.out.println("Event Listener open.");
    }
}

A: I had a similar problem with jRxTx which uses rxtx. My program would run fine for 2 minutes and then crash with the same error message.
The problem with my implementation was that I added the same serialEventListener twice to the serialPort.
serialPort.addEventListener(eventListener);

A: I have solved it installing a previous Java version. Exactly the JDK_7u80. However, I have selected an old version to be sure because this was the last version in which I had tried my programme before. When you try to do the same with the latest Java versions, you receive that error. However, in the Java Bug System, they answered that is not a Java issue (serial and driver).
This happens with RXTX, jSSC, Fazecast/jSSC, and PanamaHitek. I have tested the four. The problem is that Fazecast and Panama are based on jSSC.

A: I am using jmod that points to rxtx and I get the same results with jdk8 build 321, 311. But when I was testing build 251 it went well. I use as well a serial cable connected to an USB adapter.


text:
Q: Rotating image by Jquery I am testing image rotating by jquery. Reference is here (Example 5).
What is it missing in my code, image does not rotate when I click?

        <title>Rotate Image</title>

package :

A: You missed to include jQuery core

Also the closing tags for the script tag should be </script>

        <title>Rotate Image</title>


text:
Q: Google Cloud Bigtable Update or Insert with Versioning I'm wondering if I should use a update query to update my row data or use maxversions and enable the versioning and just insert.
I do understand it may depend on what kind of data I need to store, but just wanted to know if there is a performance difference between querying (selecting) a data witch has versioning or non-versioning. Or has a performance difference between insert and update.

A: Performance is impacted by the size of the row and the amount of data returned from the server.
Bigtable has to read an entire row for every request.  That will be a limiting factor on reads.  At some size (100s+ of MB), systemic performance will degrade any time the tablet with that row is loaded.  When the row size reaches GBs, you'll have major problems.
At query time, performance is also impacted by how much data is returned from the server.  You can still get decent performance lower range of "large rows" if you limit your Get or Scan to a small subset of the row.  Limits like cells per row, and/or retrieving only a few qualifiers would help with the network costs.
In general, it's better to keep your rows smaller, if you can.  That is generally done with a combination of "insert" and some sort of age/version restriction on the column family.


text:
Q: Undefined method `has_attached_file' with paperclip 2.3.8 gem for Rails 2 using Ruby 1.8.7 I am trying to use the paperclip plugin in my rails app to upload images for posts. I am using Rails 2.0.2 and ruby 1.8.7 on Ubuntu 10.04 os for project specific purposes.
I am referring to the following tutorials for this :-

*

*http://railscasts.com/episodes/134-paperclip?view=comments

*http://jimneath.org/2008/04/17/paperclip-attaching-files-in-rails.html
I did a git clone on the paperclip plugin via:- https://github.com/thoughtbot/paperclip , but the command like ruby script/generate paperclip group_post photo didn't generate a migration for it. I then created a migration for the same through ruby script/generate and uploaded the appropriate columns of my table group_posts.
I then tried to install the gem and since I am using activerecord and activesupport 2.0.2 I used paperclip 2.3.8 gem from rubygems.org.The undefined method error still persisted, I really couldn't figure out why.
Now here.. the command  ruby script/generate paperclip group_post photo worked perfectly fine for me.
The current error I am getting exactly looks like this:-
undefined method `has_attached_file' for #<Class:0xb67119f0>

A funny thing that I observed wrt this behavior was when I made use of IRB, require 'paperclip' returned true but I wonder why they can't detect the method that comes along with the plugin in my rails app.
The Application Trace for the same is:-
/home/mohnish/.rvm/gems/ruby-1.8.7-p334/gems/activerecord-2.0.2/lib/active_record/base.rb:1532:in `method_missing_without_paginate'
vendor/plugins/will_paginate/lib/will_paginate/finder.rb:170:in `method_missing'
app/models/group_post.rb:9
app/controllers/groups_controller.rb:27:in `show'

The Full Trace for this just in case is:-
/home/mohnish/.rvm/gems/ruby-1.8.7-p334/gems/activerecord-2.0.2/lib/active_record/base.rb:1532:in `method_missing_without_paginate'
vendor/plugins/will_paginate/lib/will_paginate/finder.rb:170:in `method_missing'
app/models/group_post.rb:9
/home/mohnish/.rvm/gems/ruby-1.8.7-p334/gems/activesupport-2.0.2/lib/active_support/dependencies.rb:203:in `load_without_new_constant_marking'
/home/mohnish/.rvm/gems/ruby-1.8.7-p334/gems/activesupport-2.0.2/lib/active_support/dependencies.rb:203:in `load_file'
/home/mohnish/.rvm/gems/ruby-1.8.7-p334/gems/activesupport-2.0.2/lib/active_support/dependencies.rb:342:in `new_constants_in'
/home/mohnish/.rvm/gems/ruby-1.8.7-p334/gems/activesupport-2.0.2/lib/active_support/dependencies.rb:202:in `load_file'
/home/mohnish/.rvm/gems/ruby-1.8.7-p334/gems/activesupport-2.0.2/lib/active_support/dependencies.rb:94:in `require_or_load'
/home/mohnish/.rvm/gems/ruby-1.8.7-p334/gems/activesupport-2.0.2/lib/active_support/dependencies.rb:248:in `load_missing_constant'
/home/mohnish/.rvm/gems/ruby-1.8.7-p334/gems/activesupport-2.0.2/lib/active_support/dependencies.rb:453:in `const_missing_not_from_s3_library'
/home/mohnish/.rvm/gems/ruby-1.8.7-p334/gems/aws-s3-0.6.2/lib/aws/s3/extensions.rb:206:in `const_missing'
/home/mohnish/.rvm/gems/ruby-1.8.7-p334/gems/activesupport-2.0.2/lib/active_support/dependencies.rb:465:in `const_missing'
/home/mohnish/.rvm/gems/ruby-1.8.7-p334/gems/activesupport-2.0.2/lib/active_support/dependencies.rb:471:in `send'
/home/mohnish/.rvm/gems/ruby-1.8.7-p334/gems/activesupport-2.0.2/lib/active_support/dependencies.rb:471:in `const_missing'
app/controllers/groups_controller.rb:27:in `show'
/home/mohnish/.rvm/gems/ruby-1.8.7-p334/gems/actionpack-2.0.2/lib/action_controller/base.rb:1158:in `send'
/home/mohnish/.rvm/gems/ruby-1.8.7-p334/gems/actionpack-2.0.2/lib/action_controller/base.rb:1158:in `perform_action_without_filters'
/home/mohnish/.rvm/gems/ruby-1.8.7-p334/gems/actionpack-2.0.2/lib/action_controller/filters.rb:697:in `call_filters'
/home/mohnish/.rvm/gems/ruby-1.8.7-p334/gems/actionpack-2.0.2/lib/action_controller/filters.rb:689:in `perform_action_without_benchmark'
/home/mohnish/.rvm/gems/ruby-1.8.7-p334/gems/actionpack-2.0.2/lib/action_controller/benchmarking.rb:68:in `perform_action_without_rescue'
/home/mohnish/.rvm/rubies/ruby-1.8.7-p334/lib/ruby/1.8/benchmark.rb:293:in `measure'
/home/mohnish/.rvm/gems/ruby-1.8.7-p334/gems/actionpack-2.0.2/lib/action_controller/benchmarking.rb:68:in `perform_action_without_rescue'
/home/mohnish/.rvm/gems/ruby-1.8.7-p334/gems/actionpack-2.0.2/lib/action_controller/rescue.rb:199:in `perform_action_without_caching'
/home/mohnish/.rvm/gems/ruby-1.8.7-p334/gems/actionpack-2.0.2/lib/action_controller/caching.rb:678:in `perform_action'
/home/mohnish/.rvm/gems/ruby-1.8.7-p334/gems/activerecord-2.0.2/lib/active_record/connection_adapters/abstract/query_cache.rb:33:in `cache'
/home/mohnish/.rvm/gems/ruby-1.8.7-p334/gems/activerecord-2.0.2/lib/active_record/query_cache.rb:8:in `cache'
/home/mohnish/.rvm/gems/ruby-1.8.7-p334/gems/actionpack-2.0.2/lib/action_controller/caching.rb:677:in `perform_action'
/home/mohnish/.rvm/gems/ruby-1.8.7-p334/gems/actionpack-2.0.2/lib/action_controller/base.rb:524:in `send'
/home/mohnish/.rvm/gems/ruby-1.8.7-p334/gems/actionpack-2.0.2/lib/action_controller/base.rb:524:in `process_without_filters'
/home/mohnish/.rvm/gems/ruby-1.8.7-p334/gems/actionpack-2.0.2/lib/action_controller/filters.rb:685:in `process_without_session_management_support'
/home/mohnish/.rvm/gems/ruby-1.8.7-p334/gems/actionpack-2.0.2/lib/action_controller/session_management.rb:123:in `process_without_test'
/home/mohnish/.rvm/gems/ruby-1.8.7-p334/gems/actionpack-2.0.2/lib/action_controller/test_process.rb:15:in `process'
/home/mohnish/.rvm/gems/ruby-1.8.7-p334/gems/actionpack-2.0.2/lib/action_controller/base.rb:388:in `process'
/home/mohnish/.rvm/gems/ruby-1.8.7-p334/gems/actionpack-2.0.2/lib/action_controller/dispatcher.rb:171:in `handle_request'
/home/mohnish/.rvm/gems/ruby-1.8.7-p334/gems/actionpack-2.0.2/lib/action_controller/dispatcher.rb:115:in `dispatch'
/home/mohnish/.rvm/gems/ruby-1.8.7-p334/gems/actionpack-2.0.2/lib/action_controller/dispatcher.rb:126:in `dispatch_cgi'
/home/mohnish/.rvm/gems/ruby-1.8.7-p334/gems/actionpack-2.0.2/lib/action_controller/dispatcher.rb:9:in `dispatch'
/home/mohnish/.rvm/gems/ruby-1.8.7-p334/gems/mongrel-1.1.5/lib/mongrel/rails.rb:76:in `process'
/home/mohnish/.rvm/gems/ruby-1.8.7-p334/gems/mongrel-1.1.5/lib/mongrel/rails.rb:74:in `synchronize'
/home/mohnish/.rvm/gems/ruby-1.8.7-p334/gems/mongrel-1.1.5/lib/mongrel/rails.rb:74:in `process'
/home/mohnish/.rvm/gems/ruby-1.8.7-p334/gems/mongrel-1.1.5/lib/mongrel.rb:159:in `process_client'
/home/mohnish/.rvm/gems/ruby-1.8.7-p334/gems/mongrel-1.1.5/lib/mongrel.rb:158:in `each'
/home/mohnish/.rvm/gems/ruby-1.8.7-p334/gems/mongrel-1.1.5/lib/mongrel.rb:158:in `process_client'
/home/mohnish/.rvm/gems/ruby-1.8.7-p334/gems/mongrel-1.1.5/lib/mongrel.rb:285:in `run'
/home/mohnish/.rvm/gems/ruby-1.8.7-p334/gems/mongrel-1.1.5/lib/mongrel.rb:285:in `initialize'
/home/mohnish/.rvm/gems/ruby-1.8.7-p334/gems/mongrel-1.1.5/lib/mongrel.rb:285:in `new'
/home/mohnish/.rvm/gems/ruby-1.8.7-p334/gems/mongrel-1.1.5/lib/mongrel.rb:285:in `run'
/home/mohnish/.rvm/gems/ruby-1.8.7-p334/gems/mongrel-1.1.5/lib/mongrel.rb:268:in `initialize'
/home/mohnish/.rvm/gems/ruby-1.8.7-p334/gems/mongrel-1.1.5/lib/mongrel.rb:268:in `new'
/home/mohnish/.rvm/gems/ruby-1.8.7-p334/gems/mongrel-1.1.5/lib/mongrel.rb:268:in `run'
/home/mohnish/.rvm/gems/ruby-1.8.7-p334/gems/mongrel-1.1.5/lib/mongrel/configurator.rb:282:in `run'
/home/mohnish/.rvm/gems/ruby-1.8.7-p334/gems/mongrel-1.1.5/lib/mongrel/configurator.rb:281:in `each'
/home/mohnish/.rvm/gems/ruby-1.8.7-p334/gems/mongrel-1.1.5/lib/mongrel/configurator.rb:281:in `run'
/home/mohnish/.rvm/gems/ruby-1.8.7-p334/gems/mongrel-1.1.5/bin/mongrel_rails:128:in `run'
/home/mohnish/.rvm/gems/ruby-1.8.7-p334/gems/mongrel-1.1.5/lib/mongrel/command.rb:212:in `run'
/home/mohnish/.rvm/gems/ruby-1.8.7-p334/gems/mongrel-1.1.5/bin/mongrel_rails:281
/home/mohnish/.rvm/gems/ruby-1.8.7-p334/gems/activesupport-2.0.2/lib/active_support/dependencies.rb:489:in `load'
/home/mohnish/.rvm/gems/ruby-1.8.7-p334/gems/activesupport-2.0.2/lib/active_support/dependencies.rb:489:in `load'
/home/mohnish/.rvm/gems/ruby-1.8.7-p334/gems/activesupport-2.0.2/lib/active_support/dependencies.rb:342:in `new_constants_in'
/home/mohnish/.rvm/gems/ruby-1.8.7-p334/gems/activesupport-2.0.2/lib/active_support/dependencies.rb:489:in `load'
/home/mohnish/.rvm/gems/ruby-1.8.7-p334/gems/rails-2.0.2/lib/commands/servers/mongrel.rb:64
/home/mohnish/.rvm/rubies/ruby-1.8.7-p334/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:31:in `gem_original_require'
/home/mohnish/.rvm/rubies/ruby-1.8.7-p334/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:31:in `require'
/home/mohnish/.rvm/gems/ruby-1.8.7-p334/gems/activesupport-2.0.2/lib/active_support/dependencies.rb:496:in `require'
/home/mohnish/.rvm/gems/ruby-1.8.7-p334/gems/activesupport-2.0.2/lib/active_support/dependencies.rb:342:in `new_constants_in'
/home/mohnish/.rvm/gems/ruby-1.8.7-p334/gems/activesupport-2.0.2/lib/active_support/dependencies.rb:496:in `require'
/home/mohnish/.rvm/gems/ruby-1.8.7-p334/gems/rails-2.0.2/lib/commands/server.rb:39
/home/mohnish/.rvm/rubies/ruby-1.8.7-p334/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:31:in `gem_original_require'
/home/mohnish/.rvm/rubies/ruby-1.8.7-p334/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:31:in `require'
script/server:3

My groups_controller.rb show method looks like this, here line 27 is @group_post = GroupPost.new(params[:group_post]) :-
  def show
    @investor_group = InvestorGroup.find(params[:id])
    @members = @investor_group.activated_members
    # code taken from discuss method
    investor_id = session['investor_id']
    @investor = Investor.find(investor_id)

    @members = @investor_group.activated_members

    unless @current_user.is_an_existing_member_of_group(@investor_group)
        flash[:notice] = "Please join this group to participate in discussions"
        redirect_to :action => :show, :id => @investor_group and return
    else
       @group_post = GroupPost.new(params[:group_post]) # line 27, tried GroupPost.create also.. seems to be of no avail..
    end
    #@group_post = GroupPost.new(params[:group_post])
      @group_post.investor_group_id = @investor_group.id
      @group_post.post_by = investor_id
    unless @group_post.message.blank?
      if @group_post.save
        flash[:notice] = 'Post was successfull'
     else
        flash[:notice] = 'Post was not successfull'
      end
       #redirect_to :action => :show, :id => @investor_group and return to change.. appropriately....
    end
    #if @group_post.message.blank?
    #  flash[:notice] = 'Post can\'t be blank.'
    #end
    @group_all_posts  = GroupPost.find(:all, :conditions => [ 'investor_group_id = ?', "#{@investor_group.id}" ], :order => 'created_at DESC')
    # code taken from discuss method
  end

The group_post model looks like this with line 9 having the following code has_attached_file :photo :-
class GroupPost < ActiveRecord::Base
  has_many :group_comments
  belongs_to :investor_group
  validates_presence_of :message
#include Paperclip
  require "paperclip"
   # Paperclip
  has_attached_file :photo # line 9
end
Part of my view file where I am trying to upload the picture along with a post looks like this:-
<%form_for  :group_post, @group_post, :url => {:action => :show},:html => {:multipart => 'true'},:id => 'new_post' do |f| -%>

Start Discussion:
<%=f.text_field :message%>

   <%=f.file_field :photo%>

<%=submit_tag "Post"%>

  <%end%>

I tried what was given in:-

*

*Why do I get an "undefined method for `has_attached_file` when installing PaperClip?
This option didn't seem applicable to my case as it seems to be using a
   higher Rails version

*

*Undefined method has_attached_file after Paperclip installation?
I tried restarting my server, but it didn't solve my problem;

*https://github.com/thoughtbot/paperclip/issues/192
I tried the include Paperclip - but it really didn't seem to help my case...
I have added a require in my group_post.rb and in my environment.rb file as require "paperclip". I still get an undefined method error. I don't know why..

*

*NoMethodError: undefined method `has_attached_file'
On referring to this I tried Imumar's fork of paperclip, I manually pasted it in my vendor/plugins directory after git cloning it.. I got the following error( I have a feeling there surely would have been a dependency issue as his version might be compatible only with a higher rails version:
mohnish@mohnish-desktop:~/UP/dev$ ruby script/server -p 4000
=> Booting Mongrel (use 'script/server webrick' to force WEBrick)
=> Rails application starting on http://0.0.0.0:4000
=> Call with -d to detach
=> Ctrl-C to shutdown server
** Starting Mongrel listening at 0.0.0.0:4000
** Starting Rails with development environment...
Exiting
/home/mohnish/.rvm/gems/ruby-1.8.7-p334/gems/activesupport-2.0.2/lib/active_support/dependencies.rb:263:in `load_missing_constant': uninitialized constant Paperclip::CallbackCompatability::Rails20 (NameError)
    from /home/mohnish/.rvm/gems/ruby-1.8.7-p334/gems/activesupport-2.0.2/lib/active_support/dependencies.rb:453:in `const_missing'
    from /home/mohnish/UP/dev/vendor/plugins/paperclip/lib/paperclip.rb:118:in `included'
    from /home/mohnish/UP/dev/vendor/plugins/paperclip/lib/paperclip.rb:364:in `include'
    from /home/mohnish/UP/dev/vendor/plugins/paperclip/lib/paperclip.rb:364:in `send'
    from /home/mohnish/UP/dev/vendor/plugins/paperclip/lib/paperclip.rb:364
    from /home/mohnish/.rvm/rubies/ruby-1.8.7-p334/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:31:in `gem_original_require'
    from /home/mohnish/.rvm/rubies/ruby-1.8.7-p334/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:31:in `require'
    from /home/mohnish/.rvm/gems/ruby-1.8.7-p334/gems/activesupport-2.0.2/lib/active_support/dependencies.rb:496:in `require'
    from /home/mohnish/.rvm/gems/ruby-1.8.7-p334/gems/activesupport-2.0.2/lib/active_support/dependencies.rb:342:in `new_constants_in'
    from /home/mohnish/.rvm/gems/ruby-1.8.7-p334/gems/activesupport-2.0.2/lib/active_support/dependencies.rb:496:in `require'
    from /home/mohnish/UP/dev/vendor/plugins/paperclip/init.rb:1:in `evaluate_init_rb'
    from /home/mohnish/.rvm/gems/ruby-1.8.7-p334/gems/rails-2.0.2/lib/rails/plugin.rb:79:in `evaluate_init_rb'
    from /home/mohnish/.rvm/gems/ruby-1.8.7-p334/gems/activesupport-2.0.2/lib/active_support/core_ext/kernel/reporting.rb:11:in `silence_warnings'
    from /home/mohnish/.rvm/gems/ruby-1.8.7-p334/gems/rails-2.0.2/lib/rails/plugin.rb:75:in `evaluate_init_rb'
    from /home/mohnish/.rvm/gems/ruby-1.8.7-p334/gems/rails-2.0.2/lib/rails/plugin.rb:39:in `load'
    from /home/mohnish/.rvm/gems/ruby-1.8.7-p334/gems/rails-2.0.2/lib/rails/plugin/loader.rb:33:in `load_plugins'
    from /home/mohnish/.rvm/gems/ruby-1.8.7-p334/gems/rails-2.0.2/lib/rails/plugin/loader.rb:32:in `each'
    from /home/mohnish/.rvm/gems/ruby-1.8.7-p334/gems/rails-2.0.2/lib/rails/plugin/loader.rb:32:in `load_plugins'
    from /home/mohnish/.rvm/gems/ruby-1.8.7-p334/gems/rails-2.0.2/lib/initializer.rb:189:in `load_plugins'
    from /home/mohnish/.rvm/gems/ruby-1.8.7-p334/gems/rails-2.0.2/lib/initializer.rb:105:in `process'
    from /home/mohnish/.rvm/gems/ruby-1.8.7-p334/gems/rails-2.0.2/lib/initializer.rb:49:in `send'
    from /home/mohnish/.rvm/gems/ruby-1.8.7-p334/gems/rails-2.0.2/lib/initializer.rb:49:in `run'
    from /home/mohnish/UP/dev/config/environment.rb:16
    from /home/mohnish/.rvm/rubies/ruby-1.8.7-p334/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:31:in `gem_original_require'
    from /home/mohnish/.rvm/rubies/ruby-1.8.7-p334/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:31:in `require'
    from /home/mohnish/.rvm/gems/ruby-1.8.7-p334/gems/activesupport-2.0.2/lib/active_support/dependencies.rb:496:in `require'
    from /home/mohnish/.rvm/gems/ruby-1.8.7-p334/gems/activesupport-2.0.2/lib/active_support/dependencies.rb:342:in `new_constants_in'
    from /home/mohnish/.rvm/gems/ruby-1.8.7-p334/gems/activesupport-2.0.2/lib/active_support/dependencies.rb:496:in `require'
    from /home/mohnish/.rvm/gems/ruby-1.8.7-p334/gems/mongrel-1.1.5/bin/../lib/mongrel/rails.rb:147:in `rails'
    from /home/mohnish/.rvm/gems/ruby-1.8.7-p334/gems/mongrel-1.1.5/bin/mongrel_rails:113:in `cloaker_'
    from /home/mohnish/.rvm/gems/ruby-1.8.7-p334/gems/mongrel-1.1.5/lib/mongrel/configurator.rb:149:in `call'
    from /home/mohnish/.rvm/gems/ruby-1.8.7-p334/gems/mongrel-1.1.5/lib/mongrel/configurator.rb:149:in `listener'
    from /home/mohnish/.rvm/gems/ruby-1.8.7-p334/gems/mongrel-1.1.5/bin/mongrel_rails:99:in `cloaker_'
    from /home/mohnish/.rvm/gems/ruby-1.8.7-p334/gems/mongrel-1.1.5/lib/mongrel/configurator.rb:50:in `call'
    from /home/mohnish/.rvm/gems/ruby-1.8.7-p334/gems/mongrel-1.1.5/lib/mongrel/configurator.rb:50:in `initialize'
    from /home/mohnish/.rvm/gems/ruby-1.8.7-p334/gems/mongrel-1.1.5/bin/mongrel_rails:84:in `new'
    from /home/mohnish/.rvm/gems/ruby-1.8.7-p334/gems/mongrel-1.1.5/bin/mongrel_rails:84:in `run'
    from /home/mohnish/.rvm/gems/ruby-1.8.7-p334/gems/mongrel-1.1.5/lib/mongrel/command.rb:212:in `run'
    from /home/mohnish/.rvm/gems/ruby-1.8.7-p334/gems/mongrel-1.1.5/bin/mongrel_rails:281
    from /home/mohnish/.rvm/gems/ruby-1.8.7-p334/gems/activesupport-2.0.2/lib/active_support/dependencies.rb:489:in `load'
    from /home/mohnish/.rvm/gems/ruby-1.8.7-p334/gems/activesupport-2.0.2/lib/active_support/dependencies.rb:489:in `load'
    from /home/mohnish/.rvm/gems/ruby-1.8.7-p334/gems/activesupport-2.0.2/lib/active_support/dependencies.rb:342:in `new_constants_in'
    from /home/mohnish/.rvm/gems/ruby-1.8.7-p334/gems/activesupport-2.0.2/lib/active_support/dependencies.rb:489:in `load'
    from /home/mohnish/.rvm/gems/ruby-1.8.7-p334/gems/rails-2.0.2/lib/commands/servers/mongrel.rb:64
    from /home/mohnish/.rvm/rubies/ruby-1.8.7-p334/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:31:in `gem_original_require'
    from /home/mohnish/.rvm/rubies/ruby-1.8.7-p334/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:31:in `require'
    from /home/mohnish/.rvm/gems/ruby-1.8.7-p334/gems/activesupport-2.0.2/lib/active_support/dependencies.rb:496:in `require'
    from /home/mohnish/.rvm/gems/ruby-1.8.7-p334/gems/activesupport-2.0.2/lib/active_support/dependencies.rb:342:in `new_constants_in'
    from /home/mohnish/.rvm/gems/ruby-1.8.7-p334/gems/activesupport-2.0.2/lib/active_support/dependencies.rb:496:in `require'
    from /home/mohnish/.rvm/gems/ruby-1.8.7-p334/gems/rails-2.0.2/lib/commands/server.rb:39
    from /home/mohnish/.rvm/rubies/ruby-1.8.7-p334/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:31:in `gem_original_require'
    from /home/mohnish/.rvm/rubies/ruby-1.8.7-p334/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:31:in `require'
    from script/server:3
mohnish@mohnish-desktop:~/UP/dev$

I really wonder where I am going wrong..
Any suggestions/insights would be highly appreciated. This is urgent for me as I have a deployment due, I would be really glad to get prompt answers/responses..
Thanks a lot..

A: Ok, firstly, just to cover the "obvious" base: do "ls vendor/plugins" just to make sure that some version of paperclip is actually in your plugins directory and is therefore reachable by your application.
Secondly - the "require paperclip" in the model seems wrong to me. I'm guessing that require should go in your environment instead. Try putting it at the end of config/environments.rb instead.
Thirdly (and maybe unrelated to your specific problem) - 2.0.2 is a really old version of rails. If you can I'd upgrade to 2.3.5, or at the very least, 2.2.x. For all we know - you could have a problem because you've got a new version of paperclip and an old version of rails... this does sometimes make a difference.
A lot of the other links you posted are referring to installations up to Rails3 - the solutions to their problems will be different to yours for that reason.

A: Slightly related, decided to put this here for future googlers.
Using Rails 2.3.14 on Ruby 1.8.7 with bundler. As suggested by thoughtbot I'm using paperclip 2.7, i.e. my gemfile contains:
gem "paperclip", "~> 2.7.0"

I was also receiving the "undefined method" error. What fixed it for me was to drop a paperclip.rbfile into config/initializerscontaining the following:
require "paperclip/railtie"
Paperclip::Railtie.insert

Hopefully this will save someone a bit of headache.


text:
Q: Textmate: source R script to iTerm This is a Mac specific question. I would like to source a script that I'm editing on Textmate2, e.g. mycode.R, and make it run in iTerm (terminal would do as well). I do not need to start R, I have the top window of iTerm already running it.
So in the iTerm tab should appear the line:
> source("[path]/mycode.R", chdir = TRUE)
 What I needs equivalent to what you have on Rstudio with the key combination Cmd + Shift+S. I found this answer How can I send selected text (or a line) in TextMate to R running on Terminal, but this is about sending a line, or echo the entire code, while what I need should be easier. I succeeded in sourcing to R.app using the following code
#!/bin/bash

osascript -e 'tell application "R.app" to activate'
osascript -e "tell application \"R.app\" to cmd \"source(file='"$TM_FILEPATH"',print.eval=TRUE, chdir=TRUE)\"" \
osascript -e 'tell application "TextMate" to activate'

But if I replace "R.app" by "iTerm", "iTerm2" or "Terminal", the script fails.

A: This does what I was looking for. I'm really not proficient with scripting, this is just result of (a lot of) trial and error. I'm sure there exists a more correct
or elegant solution. Here is the code.
#!/usr/bin/env bash
[[ -f "${TM_SUPPORT_PATH}/lib/bash_init.sh" ]] && . "${TM_SUPPORT_PATH}/lib/bash_init.sh"

curDir=''
if [[ ${#TM_DIRECTORY} -gt 0 ]]; then
    curDir="$TM_DIRECTORY"
fi

osascript \
    -e 'on run(theCode)' \
        -e 'tell application "iTerm2"' \
            -e 'tell current window' \
                -e 'tell current tab' \
                    -e 'tell current session' \
                        -e 'write text (item 1 of theCode)' \
                    -e 'end tell' \
                -e 'end tell' \
            -e 'end tell' \
        -e 'end tell' \
    -e 'end run' -- "source(\"$TM_FILEPATH\",print.eval=TRUE, chdir=TRUE)"


text:
Q: How to save input value to database magento2 I am absolutely new in magento. I have made new input called 'name' under email input in app/design/frontend/NewVendor/NewTheme/Magento_Newsletter/templates/subscribe.phtml

<?= $block->escapeHtml(__('Newsletter')) ?>

    <form class="form subscribe"
        novalidate
        action="<?= $block->escapeUrl($block->getFormActionUrl()) ?>"
        method="post"
        data-mage-init='{"validation": {"errorClass": "mage-error"}}'
        id="newsletter-validate-detail">

            <?= $block->escapeHtml(__('Sign Up for Our Newsletter:')) ?>

                <input name="email" type="email" id="newsletter"
                       placeholder="<?= $block->escapeHtml(__('Enter your email address')) ?>"
                       data-mage-init='{"mage/trim-input":{}}'
                       data-validate="{required:true, 'validate-email':true}"/>
                <input name="name" placeholder="Name"/>

            <button class="action subscribe primary" title="<?= $block->escapeHtmlAttr(__('Subscribe')) ?>" type="submit">
                <?= $block->escapeHtml(__('Subscribe')) ?>
            </button>

    </form>

I have made a new column in newsletter_subscriber table in app/code/Mag/Newsletter/Setup/UpgradeSchema.php
class UpgradeSchema implements UpgradeSchemaInterface

{
public function upgrade(SchemaSetupInterface $setup, ModuleContextInterface $context)
{
    $setup->startSetup();
    if (version_compare($context->getVersion(), '0.0.2', '<')) {
        $setup->getConnection()->addColumn(
            $setup->getTable('newsletter_subscriber'),
            'name',
            [
                'type' => \Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
                'length' => 50,
                'nullable' => false,
                'default' => '',
                'comment' => 'Name'
            ]
        );
    }
    $setup->endSetup();
}

}
And this is my controller in app/code/Mag/Newsletter/Controller/Subscriber/NewAction.php
<?php
namespace Magebit\Newsletter\Controller\Subscriber;

class NewAction extends
\Magento\Newsletter\Controller\Subscriber\NewAction
{
    public function execute() {
        $name = $this->getRequest()->getPost();
        var_dump($name);exit;
    }
}

For now controller var_dump's input value.
What I want to achieve is to save input value into "name" column in 'newsletter_subscriber' table.
Can't get it right.
What should I do next?

A: You have to get the instance of the Subscriber model and then use native method for example
->setName('NAME')

and then
->save();

A: Please use below event to save your custom field data.
Step 1: Please create file events.xml in path Vendor/Module/etc/

A: Please use below event to save your custom field data.
Step 1: Please create file events.xml in path Vendor/Module/etc/
Step 2: Please create file newsletterSubscriberSave.php under path Vendor/Module/Observer/
_request = $request;
    }

    public function execute(Observer $observer)
    {
        $subscriber = $observer->getEvent()->getSubscriber();
        $params = $this->_request->getParams();

        if(isset($params['subscriber_name'])) {
            $name = $params['subscriber_name'];
            $subscriber->setSubscriberName($name);
        }

        return $this;
    }
}

A: First inject the \Magento\Newsletter\Model\Subscriber class in your constructor:
protected $_subscriber;

public function __construct(
    ...
    \Magento\Newsletter\Model\Subscriber $subscriber
    ...
){
    ...
    $this->_subscriber= $subscriber;
    ...
}

Then you have two possible cases
Assuming your have the customer email
Then in your code you can call the following code to check whether or not the customer is subscribed to the newsletter:
    $checkSubscriber = $this->_subscriber->loadByEmail($customerEmail);

        if ($checkSubscriber->isSubscribed()) {
            // Customer is subscribed
            $checkSubscriber->setName($name);
        } else {
            // Customer is not subscribed
        }

       $checkSubscriber->save();

Assuming you have the customer id
You can call the following code:
    $checkSubscriber = $this->_subscriber->loadByCustomerId($customerId);

    if ($checkSubscriber->isSubscribed()) {
        // Customer is subscribed
        $checkSubscriber->setName($name);
    } else {
        // Customer is not subscribed
    }
$checkSubscriber->save();


text:
Q: Server returned: EXPECTED_CRLF error when using pybeanstalk I am using pybeanstalk. When I try and produce a message to the tube, I get this error:
beanstalk.errors.ExpectedCrlf: Server returned: EXPECTED_CRLF

Here is the code I am executing:
message = str(message) + '\r\n'
data = job.Job(data=message, conn=self.beanstalk_connection)
data.Queue()

What is going on here? Thanks!


text:
Q: Using jquery .on to attach custom plugins Let's say I've defined a custom plugin in a separate js file as follows:
;(function($) {
$.fn.AjaxImgUpload = function() {

In another file I am able to call that function as such:
$('#div').AjaxImgUpload({});

No problems there, but I need to immediately remove the function call after it's finished. I have the "after" part set up, but I know I have not appropriately attached the function to be removed in the first place. I am thinking there is some way to use .on and .off to do this, like:
$('#div').on(AjaxImgUpload({}));

Then
$('#div').off(AjaxImgUpload({}));

This obviously does not work because the function is not an event handler. Is there some way to make it so?

A: I guess this will not workout with on and off API .There is better option like :
Make two Plugin methods

*

*AjaxImgUpld() to get your functionality done.

*AjaxOffimg() where you put your code that you needed to apply after AjaxImgupld

So first call AjaxImgUpld and then when you want to off it then simply call AjaxOffimg


text:
Q: C++ circular dependency on public aliases (typdef/using) defined inside a class/struct Is there a way to break circular dependencies like the following without moving both using/typedef aliases outside classes?
// header A.h
#ifdef A
#define A
#include "B.h"
class A {
  using ID = uint32_t;
  void some_func(B::ID id);
};
#endif A

// header B.h
#ifdef B
#define B
#include "A.h"
class B {
  using ID = uint64_t;
  void some_func(A::ID id);
};
#endif B

// main.cpp
#include "A.h"
int main() {...}

Assume guard #ifdefs are present and ID can be a more complex type (a struct etc.).
Edit: a bit of clarification: alias names are not necessarily the same (i.e. not ID).
Modified example:
// header A.h
#ifdef A
#define A
#include "B.h"
class A {
  using SomeAliasInA = uint32_t;
  void some_func(B::SomeAliasInB id);
};
#endif A

// header B.h
#ifdef B
#define B
#include "A.h"
class B {
  using SomeAliasInB = std::string;
  void some_func(A::SomeAliasInA id);
};
#endif B

A: Create an external file for type definitions:
template<typename T>
struct types{};

class A;
class B;

template<>
struct types<A>{
    using alias = std::string;
};

template<>
struct types<B>{
    using ID = bool;
    using alias_2 = int;
    using alias_3 = short;
};

You can then use it like so:
class A{
    void foo(types<B>::ID id);
};
class B{
    void foo(types<A>::alias id);
};


text:
Q: How to convert Image3D object into Graphics3D object and vice versa? There are some rendering options (for example, Lighting) which are associated with the Graphics3D objects. I cannot apply these options for an Image3D object (for example, ExampleData[{"TestImage3D", "MRknee"}]).
Is there any way to convert an Image3D object into Graphics3D object, apply some lighting options and convert back to Image3D object?

A: Simply use Show.  This creates a Graphics3D containing a Raster3D.
In general, expressions convertible to Graphics are converted with Show.  This works for images, 3D images, graphs, and possibly other things I've forgotten about.
But I'm not sure Lighting is ever used in the rendering of 3D images, regardless of whether they are contained in an Image3D or a Graphics3D through Raster3D ...
As for the reverse conversion, that is not possible for arbitrary Graphics3D.  But you can always extract a Raster3D and transplant its contents into an Image3D.
For 2D images, just use Image[Graphics[...]].

A: For Graphics3D -> Image3D:
This answer: https://mathematica.stackexchange.com/a/33277/6804 gives an approach that rasterizes individual 2D slices at different heights and stacks them into a 3d image.
Of course you need to select a resolution, the conversion will not be lossless in general (and I don't know what would happen when the Graphics3D object is a Show@Image3D... maybe you get a resampling, or nothing).


text:
Q: Meshlab perimeter measurements of a STL file I have a relatively simple question. I am using Meshlab to record simple linear (point-to-point) measurements on a 3D scan of a dental arch. I wish to take multiple measurements on a stl file to record the perimeter of a dental arch, this would require multiple linear measurements linked together. Is this possible on Meshlab? It sounds relatively simple to do however I am not sure if Meshlab or any other stl software can do it? I am willing to consider an alternative software if this is not possible on MeshLab.

A: It is possible to get the perimeter of a selection.
After you have selected the FACES you need, use:
filters->Quality Measures and Computations->Compute Area/Perimeter of Selection.
the result will be printed in the LOG AREA of the layer panel.


text:
Q: Is there a way to tell mypy to ignore checks on overridden functions? I changed a function in a specific library by monkey patching it with a different function.
Library's send function
def send(content: str):
  ...

Monkey patch
def new(content: Union[str, dict[str, str]]):
  return send(content)

library.send = new

But using that function results in a mypy error:
Code that resulted in an error
library.send(
  {"ja": "Japanese text", "en": "English text"}
)

Error text
Argument 1 to "send" has incompatible type "Dict[str, str]"; expected "str"

Is it possible to make exceptions for certain functions to avoid this?


text:
Q: Responsive images for a mobile website that scales with the same width and height I am a bit stuck with my meager css skills. I have a bootstrap panel and a grid layout that contains 3 images in a single row.
My problem is that the images that I get from the webservice are all very different in size. some are HD quality and others are 80 X 80 pixels. I want to use css and make all three images appear the same size. The images must also be responsive since this is a mobile website. I found a solution that does what I want, but the stock browser on android does not support vw and vh. My current solution is as follows.

Photo Gallery

Is there a easy css cross browser solution that will allow me to get all three images to be the same size, whilst also being responsive ?
Thank you in advance for your help.

A: try to add this class on your img tag
.img-responsive

Boostrap 3 - Responsive images

Images in Bootstrap 3 can be made responsive-friendly via the addition of the .img-responsive class. This applies max-width: 100%; and height: auto; to the image so that it scales nicely to the parent element.

A: Is is almost important (but not fundamental) that aspect ratio of different images is the same.
Anyway, use % instead of "vw", setting width to '100%' and height to 'auto' for IMG tags. They will be contain inside 'col-xs-4' containers.

A: I ran into this problem with twitter bootstrap not to long ago. I used this method as supplied by another users jsfiddle. It centers images of different sizes in a responsive container. I would still try to use PHP or some other server side code to resize images to a smaller size so you are not resizing a 3000px image down to 80px for example.
JSfiddle
.html

.css
.dummy {
    padding-top: 100%; /* forces 1:1 aspect ratio */
}

.img-container {
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;

    text-align:center; /* Align center inline elements */
    font: 0/0 a;
}

.img-container .centerer {
    display: inline-block;
    vertical-align: middle;
    height: 100%;
}

.img-container img {
    vertical-align: middle;
    display: inline-block;
    max-height: 100%;  /* <-- Set maximum height to 100% of its parent */
    max-width: 100%;   /* <-- Set maximum width to 100% of its parent */
}


text:
Q: Conditionally render elements in React JS? I have a child component which i am looping over array to print out title and values. I have an event listener which renders a new row of title and values. I have a button in child component which i want do not want to be displayed by default but rendered only when i add new rows. So every 2 rows, there will be one button, for every 3, there will be 2 and so on.
This is my app.js file
import React, {Component} from 'react';
import './App.css';
import Child from './Child.js'

class App extends Component {
   state = {
      myArray: [
       { title: 'Hello', value: 'hello' }
     ]
   }

 addNewField = () => {
    const myArray = [...this.state.myArray, { title: 'Hello', value: 'hello' }]
     this.setState ({
    myArray
  })
}

render() {
  return (

   {
    this.state.myArray.map ( (val,idx) => {
      return (
        <Child
        key = {idx}
        title = {val.title}
        animal = { val.value }
        />
      )
    })
  }
  <button onClick = {this.addNewField}>Add Me</button>

   )
 }
}
export default App;

This is the setup for my Child Component:-
import React from 'react'

const Child = (props) => {
  return (

{props.title}

{props.value}

        <button>New Block!!</button>

   )
}

 export default Child

So basically the button in the Child component named new block should not be displayed by default but only after every click there after. Thank you.

A: Add a prop to the parent with the index of the map loop. Then add a flag so only children rendered after the first get the "New Block!!" button:
render() {
  return (

   {
    this.state.myArray.map ( (val,idx) => {
      return (
        <Child
        key = {idx}
        title = {val.title}
        animal = { val.value }
        renderIndex = {idx}
        />
      )
    })
  }
  <button onClick = {this.addNewField}>Add Me</button>

   )
 }
}

import React from 'react'

const Child = (props) => {
  return (

{props.title}

{props.value}

        {props.renderIndex > 0 && <button>New Block!!</button>}

   )
}
export default Child


text:
Q: How can I convert ViewGroup into white background Bitmap?         view.measure(MeasureSpec.makeMeasureSpec(view.layoutParams.width, MeasureSpec.EXACTLY),
                MeasureSpec.makeMeasureSpec(view.layoutParams.height, MeasureSpec.EXACTLY))
        view.layout(0, 0, view.measuredWidth, view.measuredHeight)
        return Bitmap.createBitmap(view.width, view.height, Bitmap.Config.RGB_565)

And I got
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.graphics.Bitmap.setHasAlpha(boolean)' on a null object reference

The part that I want to convert is rl_logo_name
       <RelativeLayout
            android:id="@+id/rl_logo_name"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="42px"
            android:layout_marginRight="30px"
            android:layout_marginTop="35px">

            <!-- The source file is vector(xml) file -->
            <ImageView
                android:id="@+id/iv_logo"
                android:layout_width="81px"
                android:layout_height="42px"
                android:layout_marginTop="29px"
                android:background="@drawable/ico_logo"
                android:textStyle="bold" />

            <RelativeLayout
                android:id="@+id/rl_name"
                android:layout_width="wrap_content"
                android:layout_height="72px"
                android:layout_marginLeft="3px"
                android:layout_toRightOf="@id/iv_logo">

                <TextView
                    android:id="@+id/tv_name"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="John"
                    android:textSize="72px"
                    android:textColor="#323232"
                    android:paddingLeft="51px"
                    android:paddingRight="51px"/>
            </RelativeLayout>
        </RelativeLayout>

rl_logo_name's parent view is RelativeLayout.
I want them to be converted to a one bitmap with a white background. How can I achieve that?

A: Add these to your code:
val c = Canvas(bitmap)
v.draw(c)
return bitmap


text:
Q: Execute a SQL String and insert result into table I have a table
DECLARE @Results TABLE(QueryIndex smallint, FieldValue nvarchar(50))

QueryIndex is a loop counter, it will get value from @QueryIndex.
FieldValue will get value from another SQL String. For some reason, I need to execute SQL string dynamically.
SET @SQL = "SELECT " + @FieldName + " FROM MyView"
            + " WHERE Condition1='" + @Value1 + "'"
            + " AND Condition2=" + CONVERT(nvarchar(12),@Value2)

Now I try to insert data into @Results
NSERT INTO @Results(QueryIndex, FieldValue)
SELECT @QueryIndex, EXEC (@SQL)

No surprise, this code won't work. Please provide me solution to insert data into my table. Any methods will be worth trying.
The result in table should like this:
QueryIndex   FieldName
  1            First
  2            Second
  3            Third

Thanks.

A: You need to combine the retrieval of @QueryIndex with the select then you can simply
SET @SQL = 'SELECT ' + cast(@QueryIndex as varchar(16)) + ',' + @FieldName + ...
INSERT INTO @Results(QueryIndex, FieldValue)
   EXEC (@SQL)

A: you should create the structure of the containing table - before !
 CREATE TABLE #tmp  // or @tbl... doesnt really matter...
      (
        ...
      )

    INSERT INTO #tmp  -- if we use exec we  must have the pre-Structure of the table
    EXEC (@sql)

now  , Do waht ever you want to do with #tmp....