text:
Q: My mouse is becoming locked for a few seconds Using Windows 7, my mouse locks up several times per hour for about three seconds. Then I hear an error sound and it frees itself.
This has been happening for three weeks. I have checked the error logs and there's nothing in them that points to this.
Has anyone experienced this? What is wrong?

A: There are several things you should do:

*

*First of all, check your mouse cable, try it on another computer, and
try another mouse on your computer. Does the problem still exist?

*When it repeats, remember the exact time and check the Event Viewer logs. Is there an event/error which occured at that time? If yes, post it here. For opening the Event Viewer, do this: press Win+R, type eventvwr, press Enter.

*There is a type of malware which blocks the mouse cursor for a few seconds, sends a certain pre-programmed malicious mouse input, and then unlocks the user mouse input again. Consider scanning your computer for viruses with a reputable antivirus. Also, check your autoruns and services (Sysinternal's Autoruns is here to help you), and remove odd/suspicious things from the Windows startup.


text:
Q: How to know if node is installed with homebrew or nvm? I had installed & uninstalled node on Mac OS with multiple ways using homebrew, nvm etc
Now I don't remember which technique I had used last time to install.
Is there a way to find our how node was installed or which tool is used to install node ?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Do weapons requiring higher strength also require higher skill? Observation on bows. Efficacy greatly varies with bow
I have three bows. Villager's hazel bow, requiring (Strength, Agility)  > (4,3) then Villager's yew bow, requiring (6,4) and some hunting bow I don't have on me, with strength requirement 8. My strength and agility both equal 12 my bow skill 4.
With the first bow I quite easily win the advanced archery contest. With the second, I struggle to win the beginner contest. With the third I hardly hit anything on purpose.
So, do better weapons require higher skill to use effectively, apart from strength and agility?
Maces
I now have the money and strength to buy the bailiff's mace. My mace skill is 6.93.  Will I use the bailiff's mace less effectively than a common mace up to a certain mace skill? (irrespective of strength and agility)?

A: From what I recall, the only requirements to use weapons efficiently are the ones on the item's description. If you don't meet the requirements, you'll deal less damage/swing slower, and may even be unable to draw your bow's string. If there's no skill requirement, then your skill level gives no extra (dis)advantage.
Also regarding bows, keep in mind that they shoot more or less flat, and that also depends on draw time (bows requiring more strength take longer to fully draw).


text:
Q: How to upload multiple images in php and store it as blob mysql Here is my current code and can anyone help me how i can upload multiple images with a text in category? i have to store the images as blob in database.
<?php
    if(count($_FILES) > 0) {
        if(is_uploaded_file($_FILES['userImage']['tmp_name'])) {
            mysql_connect("localhost", "root", "");
            mysql_select_db ("au");
            $cat = $_POST['cat'];
            $imgData =addslashes(file_get_contents($_FILES['userImage']['tmp_name']));
            $imageProperties = getimageSize($_FILES['userImage']['tmp_name']);
            $sql = "INSERT INTO output_images(imageType ,imageData, category)
            VALUES('{$imageProperties['mime']}', '{$imgData}', '$cat')";
            $current_id = mysql_query($sql) or die("Error: Problem on Image Insert
" . mysql_error());
            if(isset($current_id)) {
                header("Location: listImages.php");
            }
        }
    }
?>

        <TITLE>Upload Image to MySQL BLOB</TITLE>
        <link href="imageStyles.css" rel="stylesheet" type="text/css" />

        <form name="frmImage" enctype="multipart/form-data" action="" method="post" class="frmImageUpload">
            Upload Image File:

            <input type="text" name="cat">
            <input name="userImage" type="file" class="inputFile" />
            <input type="submit" value="Submit" class="btnSubmit" />
        </form>

A: I have two articles in my blog refer to multiple files uploading and storing images in MySQL database.

*

*Multiple files uploading

upload.html
<form action="product.php" method="post" enctype="multipart/form-data">
  <input type="file" class="form-control-file" name="prod_pic[]" id="prod_pic[]">
  <input type="file" class="form-control-file" name="prod_pic[]" id="prod_pic[]">
             :
  <button type="submit" class="btn btn-primary">Save Prodcut Info</button>
</form>

Note that the 'name' property of the <input> tag should be added an array tag '[]'. In addition, enctype="multipart/form-data" should be added in the tag in order to enable the file uploading function. Thus, the $_FILES variable can be an array to carry multiple files information.
Then, the product.php converts $_FILE variable and save files to the destination path.
product.php
<?php
  if (isset($_FILES['prod_pic'])) {
    $pics = convert_upload_file_array($_FILES['prod_pic']);

    foreach ($pics as $key => $pic) {
      $target = "images/{$pic['name']}";
      move_uploaded_file($pic['tmp_name'], $target);
    }
  }
?>

$_FILES variable as an array is not as a usual form as we think. It is formed by using file's attribute as the key, not the index number. Therefore, we need a converting function convert_upload_file_array().
function convert_upload_file_array($upload_files) {
  $converted = array();

  foreach ($upload_files as $attribute => $val_array) {
    foreach ($val_array as $index => $value) {
      $converted[$index][$attribute] = $value;
    }
  }
  return $converted;
}

Read more: How to Upload Multiple Files in PHP

*

*Regarding storing images in MySQL database

Please refer to the following code:
$prod_pic = $mysqli->real_escape_string(file_get_contents($_FILES['prod_pic']['tmp_name']));
$prod_pic_type = $_FILES['prod_pic']['type'];
 :
 :
$sql = "UPDATE products
        SET prod_pic      = '{$prod_pic}',
            prod_pic_type = '{$prod_pic_type}'
        WHERE prod_id = {$prod_id}";
$mysqli->query($sql) or die($mysqli->connect_error);
$mysqli->close();

The key part is As you can see, the key part is:
file_get_contents($_FILES['prod_pic']['tmp_name'])

and
$mysqli->real_escape_string(......)

Read more: Insert and Update An Image to MySQL Server Field with Blob Data Type in PHP
By using the key ideas above, your goal should be easily achieved.


text:
Q: Xcode Beginner: how link UITableView in Xcode story.boared to UITableView.h & .m code impelmantion class I built a table view using Xcode interface buidler. In this table there is a textfield which users could edit. I would need to know when user edited the textfield to save these changes.
I know in order to get the event, I might need to use UITableViewControler. So I created UITableViewControler .h & .m file, and in the identity inspector I set the class to my UITableViewControler, however, when I ran my application, table where blank. it lost all the changes that I made using interface builder.
hence, how would I link my table to my .h .m UITableViewControler.

A: I found it:
go to identity inspector -> set class.


text:
Q: TensorFlow: Ran out of memory trying to allocate 16.0KiB Running a training script results in a memory error on a GPU-optimized Ubuntu machine. The error looks suspicious, as the machine has enough memory to run the algorithm.
Here is the error:

TensorFlow: Ran out of memory trying to allocate 16.0KiB

Memory status:
$ free -m
              total        used        free      shared  buff/cache   available
Mem:          15038         190        6580           8        8267       14670
Swap:             0           0           0

Console with error:
$ python ./train.py --run --continue
Using TensorFlow backend.
I tensorflow/stream_executor/dso_loader.cc:108] successfully opened CUDA library libcublas.so locally
I tensorflow/stream_executor/dso_loader.cc:108] successfully opened CUDA library libcudnn.so locally
I tensorflow/stream_executor/dso_loader.cc:108] successfully opened CUDA library libcufft.so locally
I tensorflow/stream_executor/dso_loader.cc:108] successfully opened CUDA library libcuda.so.1 locally
I tensorflow/stream_executor/dso_loader.cc:108] successfully opened CUDA library libcurand.so locally
Loading data..
Number of categories: 2
Number of samples 425
/home/ubuntu/DeepClassificationBot-master/data.py:134: VisibleDeprecationWarning: using a non-integer number instead of an integer will result in an error in the future
  val = np.random.choice(dataset_indx, size=number_of_samples)
/home/ubuntu/DeepClassificationBot-master/data.py:127: VisibleDeprecationWarning: using a non-integer number instead of an integer will result in an error in the future
  train = np.random.choice(dataset_indx, size=number_of_samples)
Building and Compiling model..
I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:925] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero
I tensorflow/core/common_runtime/gpu/gpu_init.cc:102] Found device 0 with properties:
name: GRID K520
major: 3 minor: 0 memoryClockRate (GHz) 0.797
pciBusID 0000:00:03.0
Total memory: 3.94GiB
Free memory: 3.91GiB
I tensorflow/core/common_runtime/gpu/gpu_init.cc:126] DMA: 0
I tensorflow/core/common_runtime/gpu/gpu_init.cc:136] 0:   Y
I tensorflow/core/common_runtime/gpu/gpu_device.cc:838] Creating TensorFlow device (/gpu:0) -> (device: 0, name: GRID K520, pci bus id: 0000:00:03.0)
Training..
I tensorflow/core/common_runtime/bfc_allocator.cc:639] Bin (256):   Total Chunks: 0, Chunks in use: 0 0B allocated for chunks. 0B client-requested for chunks. 0B in use in bin. 0B client-requested in use in bin.
I tensorflow/core/common_runtime/bfc_allocator.cc:639] Bin (512):   Total Chunks: 0, Chunks in use: 0 0B allocated for chunks. 0B client-requested for chunks. 0B in use in bin. 0B client-requested in use in bin.
I tensorflow/core/common_runtime/bfc_allocator.cc:639] Bin (1024):  Total Chunks: 0, Chunks in use: 0 0B allocated for chunks. 0B client-requested for chunks. 0B in use in bin. 0B client-requested in use in bin.
I tensorflow/core/common_runtime/bfc_allocator.cc:639] Bin (2048):  Total Chunks: 0, Chunks in use: 0 0B allocated for chunks. 0B client-requested for chunks. 0B in use in bin. 0B client-requested in use in bin.
I tensorflow/core/common_runtime/bfc_allocator.cc:639] Bin (4096):  Total Chunks: 0, Chunks in use: 0 0B allocated for chunks. 0B client-requested for chunks. 0B in use in bin. 0B client-requested in use in bin.
I tensorflow/core/common_runtime/bfc_allocator.cc:639] Bin (8192):  Total Chunks: 0, Chunks in use: 0 0B allocated for chunks. 0B client-requested for chunks. 0B in use in bin. 0B client-requested in use in bin.
I tensorflow/core/common_runtime/bfc_allocator.cc:639] Bin (16384):     Total Chunks: 0, Chunks in use: 0 0B allocated for chunks. 0B client-requested for chunks. 0B in use in bin. 0B client-requested in use in bin.
I tensorflow/core/common_runtime/bfc_allocator.cc:639] Bin (32768):     Total Chunks: 0, Chunks in use: 0 0B allocated for chunks. 0B client-requested for chunks. 0B in use in bin. 0B client-requested in use in bin.
I tensorflow/core/common_runtime/bfc_allocator.cc:639] Bin (65536):     Total Chunks: 0, Chunks in use: 0 0B allocated for chunks. 0B client-requested for chunks. 0B in use in bin. 0B client-requested in use in bin.
I tensorflow/core/common_runtime/bfc_allocator.cc:639] Bin (131072):    Total Chunks: 0, Chunks in use: 0 0B allocated for chunks. 0B client-requested for chunks. 0B in use in bin. 0B client-requested in use in bin.
I tensorflow/core/common_runtime/bfc_allocator.cc:639] Bin (262144):    Total Chunks: 0, Chunks in use: 0 0B allocated for chunks. 0B client-requested for chunks. 0B in use in bin. 0B client-requested in use in bin.
I tensorflow/core/common_runtime/bfc_allocator.cc:639] Bin (524288):    Total Chunks: 0, Chunks in use: 0 0B allocated for chunks. 0B client-requested for chunks. 0B in use in bin. 0B client-requested in use in bin.
I tensorflow/core/common_runtime/bfc_allocator.cc:639] Bin (1048576):   Total Chunks: 0, Chunks in use: 0 0B allocated for chunks. 0B client-requested for chunks. 0B in use in bin. 0B client-requested in use in bin.
I tensorflow/core/common_runtime/bfc_allocator.cc:639] Bin (2097152):   Total Chunks: 0, Chunks in use: 0 0B allocated for chunks. 0B client-requested for chunks. 0B in use in bin. 0B client-requested in use in bin.
I tensorflow/core/common_runtime/bfc_allocator.cc:639] Bin (4194304):   Total Chunks: 0, Chunks in use: 0 0B allocated for chunks. 0B client-requested for chunks. 0B in use in bin. 0B client-requested in use in bin.
I tensorflow/core/common_runtime/bfc_allocator.cc:639] Bin (8388608):   Total Chunks: 0, Chunks in use: 0 0B allocated for chunks. 0B client-requested for chunks. 0B in use in bin. 0B client-requested in use in bin.
I tensorflow/core/common_runtime/bfc_allocator.cc:639] Bin (16777216):  Total Chunks: 0, Chunks in use: 0 0B allocated for chunks. 0B client-requested for chunks. 0B in use in bin. 0B client-requested in use in bin.
I tensorflow/core/common_runtime/bfc_allocator.cc:639] Bin (33554432):  Total Chunks: 0, Chunks in use: 0 0B allocated for chunks. 0B client-requested for chunks. 0B in use in bin. 0B client-requested in use in bin.
I tensorflow/core/common_runtime/bfc_allocator.cc:639] Bin (67108864):  Total Chunks: 0, Chunks in use: 0 0B allocated for chunks. 0B client-requested for chunks. 0B in use in bin. 0B client-requested in use in bin.
I tensorflow/core/common_runtime/bfc_allocator.cc:639] Bin (134217728):     Total Chunks: 0, Chunks in use: 0 0B allocated for chunks. 0B client-requested for chunks. 0B in use in bin. 0B client-requested in use in bin.
I tensorflow/core/common_runtime/bfc_allocator.cc:639] Bin (268435456):     Total Chunks: 0, Chunks in use: 0 0B allocated for chunks. 0B client-requested for chunks. 0B in use in bin. 0B client-requested in use in bin.
I tensorflow/core/common_runtime/bfc_allocator.cc:656] Bin for 16.0KiB was 16.0KiB, Chunk State:
I tensorflow/core/common_runtime/bfc_allocator.cc:674] Chunk at 0x702580000 of size 6912
I tensorflow/core/common_runtime/bfc_allocator.cc:674] Chunk at 0x702581b00 of size 6912
I tensorflow/core/common_runtime/bfc_allocator.cc:674] Chunk at 0x702583600 of size 256
I tensorflow/core/common_runtime/bfc_allocator.cc:674] Chunk at 0x702583700 of size 256
I tensorflow/core/common_runtime/bfc_allocator.cc:674] Chunk at 0x702583800 of size 147456
I tensorflow/core/common_runtime/bfc_allocator.cc:674] Chunk at 0x7025a7800 of size 147456
I tensorflow/core/common_runtime/bfc_allocator.cc:674] Chunk at 0x7025cb800 of size 256
....... Very long list of chunks
I tensorflow/core/common_runtime/bfc_allocator.cc:689]      Summary of in-use Chunks by size:
I tensorflow/core/common_runtime/bfc_allocator.cc:692] 115 Chunks of size 256 totalling 28.8KiB
I tensorflow/core/common_runtime/bfc_allocator.cc:692] 34 Chunks of size 512 totalling 17.0KiB
I tensorflow/core/common_runtime/bfc_allocator.cc:692] 21 Chunks of size 1024 totalling 21.0KiB
I tensorflow/core/common_runtime/bfc_allocator.cc:692] 42 Chunks of size 2048 totalling 84.0KiB
I tensorflow/core/common_runtime/bfc_allocator.cc:692] 7 Chunks of size 6912 totalling 47.2KiB
I tensorflow/core/common_runtime/bfc_allocator.cc:692] 42 Chunks of size 16384 totalling 672.0KiB
I tensorflow/core/common_runtime/bfc_allocator.cc:692] 5 Chunks of size 32768 totalling 160.0KiB
I tensorflow/core/common_runtime/bfc_allocator.cc:692] 7 Chunks of size 147456 totalling 1008.0KiB
I tensorflow/core/common_runtime/bfc_allocator.cc:692] 7 Chunks of size 294912 totalling 1.97MiB
I tensorflow/core/common_runtime/bfc_allocator.cc:692] 7 Chunks of size 589824 totalling 3.94MiB
I tensorflow/core/common_runtime/bfc_allocator.cc:692] 7 Chunks of size 1179648 totalling 7.88MiB
I tensorflow/core/common_runtime/bfc_allocator.cc:692] 14 Chunks of size 2359296 totalling 31.50MiB
I tensorflow/core/common_runtime/bfc_allocator.cc:692] 7 Chunks of size 4718592 totalling 31.50MiB
I tensorflow/core/common_runtime/bfc_allocator.cc:692] 35 Chunks of size 9437184 totalling 315.00MiB
I tensorflow/core/common_runtime/bfc_allocator.cc:692] 5 Chunks of size 67108864 totalling 320.00MiB
I tensorflow/core/common_runtime/bfc_allocator.cc:692] 6 Chunks of size 411041792 totalling 2.30GiB
I tensorflow/core/common_runtime/bfc_allocator.cc:692] 1 Chunks of size 663988224 totalling 633.23MiB
I tensorflow/core/common_runtime/bfc_allocator.cc:696] Sum Total of in-use chunks: 3.61GiB
I tensorflow/core/common_runtime/bfc_allocator.cc:698] Stats:
Limit:                  3878682624
InUse:                  3878682624
MaxInUse:               3878682624
NumAllocs:                     362
MaxAllocSize:            663988224

W tensorflow/core/common_runtime/bfc_allocator.cc:270] **********************************************************************************************xxxxxx
W tensorflow/core/common_runtime/bfc_allocator.cc:271] Ran out of memory trying to allocate 16.0KiB.  See logs for memory state.
W tensorflow/core/framework/op_kernel.cc:930] Internal: Dst tensor is not initialized.
E tensorflow/core/common_runtime/executor.cc:334] Executor failed to create kernel. Internal: Dst tensor is not initialized.
     [[Node: Variable_91/initial_value = Const[dtype=DT_FLOAT, value=Tensor<type: float shape: [4096] values: 0 0 0...>, _device="/job:localhost/replica:0/task:0/gpu:0"]()]]
Traceback (most recent call last):
  File "./train.py", line 154, in <module>
    run(extract=extract_mode, cont=continue_)
  File "./train.py", line 104, in run
    sample_weight=None)
  File "/usr/local/lib/python2.7/dist-packages/keras/models.py", line 405, in fit
    sample_weight=sample_weight)
  File "/usr/local/lib/python2.7/dist-packages/keras/engine/training.py", line 1031, in fit
    self._make_train_function()
  File "/usr/local/lib/python2.7/dist-packages/keras/engine/training.py", line 658, in _make_train_function
    training_updates = self.optimizer.get_updates(trainable_weights, self.constraints, self.total_loss)
  File "/usr/local/lib/python2.7/dist-packages/keras/optimizers.py", line 314, in get_updates
    vs = [K.variable(np.zeros(K.get_value(p).shape)) for p in params]
  File "/usr/local/lib/python2.7/dist-packages/keras/backend/tensorflow_backend.py", line 78, in variable
    get_session().run(v.initializer)
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/client/session.py", line 710, in run
    run_metadata_ptr)
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/client/session.py", line 908, in _run
    feed_dict_string, options, run_metadata)
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/client/session.py", line 958, in _do_run
    target_list, options, run_metadata)
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/client/session.py", line 978, in _do_call
    raise type(e)(node_def, op, message)
tensorflow.python.framework.errors.InternalError: Dst tensor is not initialized.
     [[Node: Variable_91/initial_value = Const[dtype=DT_FLOAT, value=Tensor<type: float shape: [4096] values: 0 0 0...>, _device="/job:localhost/replica:0/task:0/gpu:0"]()]]
Caused by op u'Variable_91/initial_value', defined at:
  File "./train.py", line 154, in <module>
    run(extract=extract_mode, cont=continue_)
  File "./train.py", line 104, in run
    sample_weight=None)
  File "/usr/local/lib/python2.7/dist-packages/keras/models.py", line 405, in fit
    sample_weight=sample_weight)
  File "/usr/local/lib/python2.7/dist-packages/keras/engine/training.py", line 1031, in fit
    self._make_train_function()
  File "/usr/local/lib/python2.7/dist-packages/keras/engine/training.py", line 658, in _make_train_function
    training_updates = self.optimizer.get_updates(trainable_weights, self.constraints, self.total_loss)
  File "/usr/local/lib/python2.7/dist-packages/keras/optimizers.py", line 314, in get_updates
    vs = [K.variable(np.zeros(K.get_value(p).shape)) for p in params]
  File "/usr/local/lib/python2.7/dist-packages/keras/backend/tensorflow_backend.py", line 75, in variable
    v = tf.Variable(np.asarray(value, dtype=dtype), name=name)
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/ops/variables.py", line 211, in __init__
    dtype=dtype)
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/ops/variables.py", line 289, in _init_from_args
    dtype=dtype)
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/framework/ops.py", line 628, in convert_to_tensor
    ret = conversion_func(value, dtype=dtype, name=name, as_ref=as_ref)
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/framework/constant_op.py", line 180, in _constant_tensor_conversion_function
    return constant(v, dtype=dtype, name=name)
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/framework/constant_op.py", line 167, in constant
    attrs={"value": tensor_value, "dtype": dtype_value}, name=name).outputs[0]
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/framework/ops.py", line 2317, in create_op
    original_op=self._default_original_op, op_def=op_def)
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/framework/ops.py", line 1239, in __init__
    self._traceback = _extract_stack()

This works, but still issues memory warning:
$ python deploy.py --URL http://www.example.com/image.jpg
Using TensorFlow backend.
I tensorflow/stream_executor/dso_loader.cc:108] successfully opened CUDA library libcublas.so locally
I tensorflow/stream_executor/dso_loader.cc:108] successfully opened CUDA library libcudnn.so locally
I tensorflow/stream_executor/dso_loader.cc:108] successfully opened CUDA library libcufft.so locally
I tensorflow/stream_executor/dso_loader.cc:108] successfully opened CUDA library libcuda.so.1 locally
I tensorflow/stream_executor/dso_loader.cc:108] successfully opened CUDA library libcurand.so locally
I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:925] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero
I tensorflow/core/common_runtime/gpu/gpu_init.cc:102] Found device 0 with properties:
name: GRID K520
major: 3 minor: 0 memoryClockRate (GHz) 0.797
pciBusID 0000:00:03.0
Total memory: 3.94GiB
Free memory: 3.91GiB
I tensorflow/core/common_runtime/gpu/gpu_init.cc:126] DMA: 0
I tensorflow/core/common_runtime/gpu/gpu_init.cc:136] 0:   Y
I tensorflow/core/common_runtime/gpu/gpu_device.cc:838] Creating TensorFlow device (/gpu:0) -> (device: 0, name: GRID K520, pci bus id: 0000:00:03.0)
W tensorflow/core/common_runtime/bfc_allocator.cc:213] Ran out of memory trying to allocate 2.05GiB. The caller indicates that this is not a failure, but may mean that there could be performance gains if more memory is available.
W tensorflow/core/common_runtime/bfc_allocator.cc:213] Ran out of memory trying to allocate 2.14GiB. The caller indicates that this is not a failure, but may mean that there could be performance gains if more memory is available.
W tensorflow/core/common_runtime/bfc_allocator.cc:213] Ran out of memory trying to allocate 2.14GiB. The caller indicates that this is not a failure, but may mean that there could be performance gains if more memory is available.
W tensorflow/core/common_runtime/bfc_allocator.cc:213] Ran out of memory trying to allocate 2.14GiB. The caller indicates that this is not a failure, but may mean that there could be performance gains if more memory is available.
1/1 [==============================] - 2s
______________________________________________
Image Name: image.jpg
Categories:
1. shrek 100.00%
2. darth vader 0.00%


text:
Q: How to use atomselect to specify atomNumbers/Index position in a pdb file for MDAnalysis? After reading through the documentation I still have not been able to figure out a way to select one specific atom in my pdb file with MDAnalysis.
For my project I am essentially pulling a chloride through a membrane channel in an applied electric field. I want to use MDAnalysis to specifically select this one chloride that is being pushed through the channel. Unfortunately this is not the only chloride in the same system or even segment so selecting a resname or segment isn't going to be useful in identifying which chloride I would like to track. Essentially with MDAnalysis I am going to be running a calculation that uses the trajectory of that one specific chloride to calculate the displacement charge function. I am having difficulty writing code to tell MDAnalysis that I want that specific chloride.
The way I have distinguished this in NAMD was by using an index number but I cannot find a way in their documentation to use this number within MDAnalysis and would really appreciate if someone has experience using the pdb index number rather than segnames and ids, or linking the relevant page to the documentation if it exists.
Thanks!

A: Unfortunately this is not yet documented, but as of 2.0.0dev0 you can also use the id keyword in addition to index and bynum. This might be more straightforward, as id corresponds directly to the number in the "serial" column in the PDB format. For example:
import MDAnalysis as mda
from MDAnalysis.tests.datafiles import PDB
u = mda.Universe(PDB)
atom_with_serial_10_in_pdb = u.select_atoms("id 10")[0]

or
atom_with_serial_10_in_pdb = u.atoms[u.atoms.ids == 10][0]

A: bynum 7:10 which is a 1-based inclusive index
index 7 which is a 0-based index
For example, atomi7 = universe.select_atoms("index 7")
Relevant documentation:


text:
Q: HTML5: Set input pattern to fixed value What regular expression should I use if I want the input to be equivalent to a specific value? For example, the input field must be "100". What would be the expression for this?
I've already tried:
<input type="text" pattern="[1-1][0-0][0-0]" maxlength="3" disabled required/>

The above attribute would work without disabled but doesn't work if the input is disabled.
What I'm trying to do is to offer the user the ability to insert total marks allotted to 2 exams (mids and finals). And the total's input is done by jquery and should be hundred. I'm looking for a simple solution using HTML5 that if the total's input is not equal to hundred, it would give a validation error.
Thanks.

A: <input type="number" name="foo" pattern="100" required>

Should do it.

A: you can use jquery to check the input's value.
for that you don't need to use regular expression.
var inputvalue = $("input").val();
if(inputvalue == '100'){
 alert('value == 100');
}


text:
Q: jQuery Functions not applying to dynamically generated content I've been trying to apply my jQuery functions to dynamically generated content by using the .on API from jQuery, but it's not working as it's suppose to. The purpose of the code is to display a set of options only when a user hovers over the div ".feed_post_full", and it does. Although it doesn't apply to content that is dynamically generated.
Here is my code here:
$(".feed_post_full" ).on({
mouseenter: function() {
    var id = (this.id);
    $('#post_options'+id).show();
}, mouseleave: function() {
    var id = (this.id);
    $('#post_options'+id).hide();
}});

What should I do to fix it?

A: You need to use the delegated form of .on() for it to work with dynamically create elements.  You want this form:
$('#static_parent').on(events, ".dynamic_child", function() {});

See these other posts for more explanation:
jQuery .live() vs .on() method for adding a click event after loading dynamic html
Does jQuery.on() work for elements that are added after the event handler is created?
Does jQuery.on() work for elements that are added after the event handler is created?
Your code would look like this:
$(parent selector).on({
    mouseenter: function () {
        var id = (this.id);
        $('#post_options' + id).show();
    },
    mouseleave: function () {
        var id = (this.id);
        $('#post_options' + id).hide();
    }
}, ".feed_post_full");

Where the parent selector is a selector of the closest parent to your dynamic content that is not itself dynamic.

A: Try this:
$(document).on({
    mouseenter: function() {
    var id = (this.id);
    $('#post_options'+id).show();
}, mouseleave: function() {
    var id = (this.id);
    $('#post_options'+id).hide();
}
}, ".feed_post_full");

Best way to improve performance:
 $("FEED_POST_FULL_PARENT_ELEMENT_AVAILABLE_ON_DOM_READY").on({
        mouseenter: function() {
        var id = (this.id);
        $('#post_options'+id).show();
    }, mouseleave: function() {
        var id = (this.id);
        $('#post_options'+id).hide();
    }
    }, ".feed_post_full");


text:
Q: Programmer new to Apple - How to efficiently switch between files in XCode? I'm a programmer that's pretty much brand new to Apple software, and everthing is all weird and different and scary :P, so I'm trying to figure out some workflow stuff:
I'm used to having a Visual Studio / Notepad++ style "tab bar" that has all the open documents so that I can have a group of files open to quickly switch between. The XCode navigator works for switching, but it lists all files, which in large projects makes it difficult to quickly work on a set of related files.
I can tell that Apple eschews the "single containing window" thing, so I'm not looking for the same thing in XCode, but asking what's the Apple way of doing document switching?
I can double click to open several windows, but I can't seem to find a way to "list" all open windows, and even though I was able to discover Command-Tab (or WindowsKey-Tab on my keyboard :) it only seems to switch between applications and not files.

A: Xcode does support tabs. You can add a new one by pressing Command ⌘+T, or go to View > Show Tab Bar to keep the bar open always so you can press the + button there. With multiple tabs, you can use Command ⌘+{ and Command ⌘+} to cycle through them.
As mentioned by bassplayer7 in the comments, you can also use multiple windows and cycle through them with Command ⌘+`(backtick) or Command ⌘+~(tilde).
Additionally, you can have multiple documents open in one window using Assistant editors. Either use Navigate > Open in Assistant Editor, or click the icon which looks like a shirt and bow tie in your toolbar to bring the editor up. Then, you can use the little + in the upper-right corner of the editor to add more.
The Navigate menu has several other useful options too, such as going through an editor's history, various counterparts to a file (headers, implementations, interfaces, ...), and switching focus between various portions of the window.
As for the navigator, use groups to combine related files for easier access. Use File > New > Group or File > New > Group From Selection to add a group and rearrange things however you want. You can completely remove the original groups created in the original project if you want, since they are just for navigation and have no affect on the actual project.

A:
I can double click to open several windows, but I can't seem to find a
  way to "list" all open windows, and even though I was able to discover
  Command-Tab (or WindowsKey-Tab on my keyboard :) it only seems to
  switch between applications and not files.

As @bassplayer7 said, command-` cycles between all open windows in an app. You might also want to use Mission Control – I believe the default keyboard shortcut for showing all windows of the current app is fn-F10 (you can double-check this by going to the Apple menu > System Preferences > Mission Control).


text:
Q: How to set a favicon for Doxygen output I am automating documentation generation using Doxygen.  How can I specify a favicon (URL icon) for the output?

A: In doxygen one has the possibility to define his own HTML header file, best based on the default HTML header file.
To obtain the default HTML header file, syntax:
doxygen -w html headerFile footerFile styleSheetFile [configFile]

in the headerFile insert in the head part a line like:
<link rel="shortcut icon" href="$relpath^my_icon.ico" type="image/x-icon" />

Note: that the $relpath^ part is necessary especially in case of CREATE_SUBDIRS is set.
Furthermore in the configuration file (Doxyfile) you have to set:
HTML_HEADER            = headerFile
HTML_EXTRA_FILES       += my_icon.ico

Of course the standard restrictions regarding favicons still apply (regarding support by browsers etc.).


text:
Q: Testing Redux combined reducers Say I have several reducer functions and I combine them all into one reducer using combineReducers(...), is there a way of testing what reducers the combined reducer actually contains?
For example, if I have this:
import { combineReducers } from 'redux'

const reducer1 = (state, action) => {...}
... (more reducers, etc)

const rootReducer = combineReducers({
    reducer1,
    reducer2,
    reducer3
})

export default rootReducer

Can I write a test with Mocha and Expect.js that will enable me to check if the rootReducer contains say reducer2? Is this even possible?
The way I currently have my project set up is that each reducer is in a separate file and is then imported into the file where the combineReducers(...) function is used to combine them all. I am testing all the individual reducers to check that they do what they should, but I also thought it would be a good idea to test the combined reducer to make sure that it contains all the other reducers that it should (in case I forget to add one for example).
Thanks

A: You are testing the wrong thing IMO. You should trust that the combineReducers() function does what it should (it should be tested in Redux distrubution tests). But you can create a method that will return the object with reducers to combine to pass as the parameter to combineReducers(). That method can and should be tested.


text:
Q: Java: java.util.NoSuchElementException: No line found I have a problem and don't know what to do. Here's the exception:
Exception in thread "main" java.util.NoSuchElementException: No line found
    at java.util.Scanner.nextLine(Unknown Source)
    at Auto.<init>(Auto.java:32)
    at Auto.main(Auto.java:22)

And that's my Code:
import java.util.Scanner;

public class Auto {
    private String Marke1;
    String Modell1;
    String Farbe1;
    double Höhe;
    double Breite;
    double Länge;
    int Tueren = 4;

    public static void main(String[] args) {
        System.out.println("Hello Auto!");

        Auto myFerrari = new Auto();
        myFerrari.einfacheNachricht();
        Auto myOpel = new Auto();
        myOpel.einfacheNachricht();
    }

    public Auto() {
        Scanner r = new Scanner(System.in);
        System.out.println("Bitte geben Sie die Marke ihres Autos an");
        Marke1 = r.nextLine()
        System.out.println("Bitte geben Sie das Modell ihres Autos an");
        Modell1 = r.nextLine();
        System.out.println("Bitte geben Sie die Farbe ihres Autos an");
        Farbe1 = r.nextLine();
        System.out.println("Bitte geben Sie an, wiehoch ihr Auto ist");
        Höhe = r.nextDouble();
        System.out.println("Bitte geben Sie an, wie breit ihr Auto ist");
        Breite = r.nextDouble();
        System.out.println("Bitte geben Sie an, wie lang ihr Auto ist");
        Länge = r.nextDouble();
        r.close();
    }

    public Auto(String aMarke1, String aModell1, String aFarbe1, double aHöhe, double aBreite, double aLänge) {
        Marke1 = aMarke1;
        Modell1 = aModell1;
        Farbe1 = aFarbe1;
        Höhe = aHöhe;
        Breite = aBreite;
        Länge = aLänge;
    }

    public int getSitzreihen() {
        return Tueren = 2;
    }

    public void einfacheNachricht() {
        System.out.println("------------------------------------------");
        System.out.println("Automarke: " + Marke1);
        System.out.println("Modell: " + Modell1);
        System.out.println("Farbe: " + Farbe1);
        System.out.println("Sitzreihen: " + getSitzreihen());
        System.out.println("Volumen: " +(Höhe * Breite * Länge) +"m²" ) ;
        System.out.println("Ihr " + Farbe1 + "er " + Marke1 + " " + Modell1 + " hat ein Volumen von "+(Höhe * Breite * Länge) +"m²");
        System.out.println("------------------------------------------\n");
    }
}

A: Closing a Scanner causes the underlying InputStream to be closed also. As there is only one System.in, any newly created Scanner objects will not be able to read from the same stream:
r.close();

This line should be removed
See: Do not create multiple buffered wrappers on a single InputStream

A: You need to check if the next line exists before, use hasNextLine() before calling nextLine()


text:
Q: Node modules cache in deployment of angular cli app I am using Jenkins for deployment, now on every deployment I need to clone the app and run npm install every time.
Is there any way to cache or something so that data downloading should be save.
I am asking this for Angular CLI app on a ubuntu server.

A: Following issue was resolved with making a symbolic link to node_modules outside the directory.
So it doesn't make installation again of node modules.


text:
Q: Stopping Save/Send document when user exits Spell Check Dialog I have a form that has a basic save button.  In the save button is some code to launch the spell check Dialog.
Call uidoc.SpellCheck

Is there a way that I can trap return codes from the dialog?  Specifically, I would like the save to stop if the user uses the X in the upper right hand corner to 'Exit' the spell check dialog.
What I am looking for is what type of exits codes the dialog could provide me to stop the save with.  I didn't see anything in the documentation and online help for LotusScript is harder to come by than with other languages.
Thanks for the help.

A: From my experience the SpellCheck method is too high level to offer any useful return codes you can program against.  It'll simply run the operation and then return.
Here's a post that might help.  Instead of using the uidoc.SpellCheck method, you could optionally enable the "Automatically check mail for misspelling" option which provides the "Cancel Send" button.  Then just a call to save/send the document should trigger the spell check to occur, and allow the user to cancel sending if there are spelling errors.  That is assuming that's the behavior you're after.


text:
Q: How to handle null dates value using object How handle null value using object in C# ASP.NET C#.
Below I am doing visible true and false base on condition using hyperlink.
<asp:Label ID="Label3" runat="server"  Text="Date not confirm"
     Visible='<%#GetVisible2(Eval("DateofEvent").ToString()=="")%>'></asp:Label>

below is my c# code.
public bool GetVisible2(object value)
{
    if (value=="")
    {
        //return value.ToString() == "Visible";
        return true;
    }
    return false;
}

Every time returning false only. I dont know if condition is correct or wrong.

A: By default DateTime variable takes DateTime.MinValue so you should compare it with this as below:
<asp:Label ID="Label3" runat="server"  Text="Date not confirm"
         Visible='<%#GetVisible2(Eval("DateofEvent"))%>'></asp:Label>

    public bool GetVisible2(DateTime? value)
    {
        if (value == null || value == DateTime.MinValue)
        {
            return true;
        }
        return false;
    }

A: Because you passing your function a boolean value which never equals to empty string:
Eval("DateofEvent").ToString()=="" // this will generate true or false

this will pass boolean to GetVisible2. Try this:
<asp:Label ID="Label3" runat="server"  Text="Date not confirm"
     Visible='<%#GetVisible2(Eval("DateofEvent").ToString())%>'></asp:Label>

and you can change function as:
public bool GetVisible2(string value)
{
   return String.IsNullOrEmpty(value);
}

or much cleaner approach as suggested by Tim Schmelter, without any validation method:
<asp:Label ID="Label3" runat="server"  Text="Date not confirm"
     Visible='<%#String.IsNullOrEmpty(Eval("DateofEvent").ToString())%>'></asp:Label>

A: You are evaluating a function inside ASPX page and passing a Boolean value to your GetVisible2 function.
This is why you are returning false everytime, since the object value is never a string, but a boolean.
Should be
Eval("DateofEvent")

insteadof
Eval("DateofEvent").ToString() == ""

And the function will be
public bool GetVisible2(object value)
{
    return value!=null;
}

Or, if you want to consider empty strings "null" also, you can do the following
public bool GetVisible2(object value)
{
    var s = value as string;
    return value!=null || (s is string && !string.IsNullOrEmpty(value as string));
}

gettting error: object doest not contain a definiation for to string and no extension method tostring acception a first argument of type object could be found. @OrcusZ

It's not
toString()

but it's
ToString()

C# is case sensitive.

A: I think its better to pass the DateofEvent before converting it to string, because; if DateofEvent is null then the .ToString() will raise NullReference, So the changes would be like the following:
 <asp:Label ID="Label3" runat="server"  Text="Date not confirm"
 Visible='<%#IsVisible(Eval("DateofEvent"))%>'></asp:Label>

So the parameter passed to the method will be an object, we have to check for null and then for Empty string, So the method will be like this:
public bool IsVisible(object value)
{
   return value != null && String.IsNullOrEmpty(value.ToString());
}

Or even something like this: return value != null && value.ToString()!="";

A: A method exist to check is a string is null :
  if (String.IsNullOrEmpty(value))
    {
        return true;
    }
    return false;


text:
Q: Make autocomplete on text Input field using django-autocomplete-light 3.2.10 I have integrate django-autocomplete-light 3.2.10 successfully and it is working fine the issue is with its UI
In template it renders with <select> <option> html, after clicking on it a span get attached to it with input text field inside.

In form i am using ModelSelect2 as widget.
widget=autocomplete.ModelSelect2(url='discovery:city-autocomplete')

TextWidget is not supported in latest version 3.2.10

I just want the input text field directly visible to user. is there any possible way to achieve it with same library. May be i can create my own CustomTextWidget, or use some javascript to customize its UI


text:
Q: How can I fetch the parent directory of the current symlinked directory? I would like to get an absolute path of the current script which is actually symlinked.
The __FILE__ always points to the real file and not the symlink, while $_SERVER['SCRIPT_FILENAME'] points to the symlink.
I would like to go up the directory tree of the $_SERVER['SCRIPT_FILENAME'] but appending the /.. and invoking realpath navigates up the directory tree of the actual file.
Here's the code I'm running:
print dirname(__FILE__);
print '
';
print realpath(dirname(__FILE__) . '/..');
print '
';
print $_SERVER['SCRIPT_FILENAME'];
print '
';
print realpath(dirname($_SERVER['SCRIPT_FILENAME']) . '/..');

The code above outputs:
/Users/mridang/Hello/Application
/Users/mridang/Hello
/Applications/MAMP/htdocs/1609/modules/mymodule/ctrl.php
/Users/mridang/Hello

How can I navigate up the directory of the symlink without resolving the symlink?

A: From what I know you can use the native PHP function readlink. This should resolve symlinks.
You can also check this answer from StackOverflow.

A: Use readlink($path) to read the target of symbolic link. You can check if it is a symbolic link with is_link:
Examples:
<?php
    if (is_link($link)) {
       echo(readlink($link));
    }

    echo readlink(dirname(__FILE__));
?>


text:
Q: How can I find the intersection of the sets in these tables? For example how do I find the number of Males that are Students and that are born Local? So essentially I want to find the number of Males that are Students and that are Local born from these tables (please see link there's more information than what I work with below). I thought this was a situation where I could use unions and intersections so I tried thinking along the lines of:
There are 37 Males in total.
There are 12 that are Students.
There are 26 that are local.
So I thought 37 is the union of the 12 and the 26, and the intersection formula would be
37=12+26-x
x=1
but then I realized 37 isn't the union as it includes males that are neither students nor locals...
So is it possible to get what I want? Any help appreciated!
2-way tables

A: I won't solve it, but will tell you how I would try it. [Up to you to do the attempt.]
It looks by the table that: 1) some are students, some are not. 2) some are male, some are not [=female] 3) some are local, some are not [= overseas]. You could set up a Venn diagram with three circles, one labelled S for students, one labelled M for male, one labelled L for local. Put a single letter in each region, to represent how many are in that region. (Don't forget to put a letter in the region outside all three circles which is nonstudent female overseas. So eight letters in all.
) Then the data in the table will give you 12 equations each having two of the letters added to a specific number read from the table. Next job is to try to solve the equations and see what total end up in the category you want the total for.
I made an error in previous update, now it may be there is only one answer. Will get back later.


text:
Q: Is there a way to access WPF control properties (specifically a button's IsDefault) if I only have an AutomationElement? I have an AutomationElement for a particular WPF Button in an external application from the WPF application that I am try to access. Is there a way to find out the button's IsDefault property?
I have tried to access the button's window's control through its handle, using (Window)HwndSource.FromHwnd(hWnd).RootVisual,where hWnd is the button's window's NativeWindowHandle, but FromHwnd returns null.

A: Normally, you can't access a WPF control object in another process. You might be able to do something with a tool like Snoop. In this particular case, I see that when I set IsDefault to true, the AccessKey property on the button's automation element is "\r". Otherwise it is empty ("").


text:
Q: How to insert a new node at any given position in linked list? Kindly check my code below. I am not getting the actual output when I run this program.
What I want to do is to insert a new node at the position entered by the user. I have tested this code by entering 5 values for 5 nodes i.e 1,2,3,4,5 and then I entered position 2 to insert a value 8, but when I display it, it gives all other values except the value that I entered at the specific position.
#include<iostream>
using namespace std;

class Node
{
    public:
        int data;
        Node* next;
};

int main()
{
    int choice, pos, count = 0, i = 1;
    Node* head, *newnode, *temp;
    head = 0;

    do
    {
        count++;
        newnode=new Node();
        cout<<"Enter data:";
        cin>>newnode->data;
        newnode->next=0;
        if(head==0)
            head=temp=newnode;
        else
        {
            temp->next=newnode;
            temp=newnode;
        }
        cout<<"Do you want to create a new node... press 0 for no and 1 yes:";
        cin>>choice;
    }while(choice==1);

    cout<<"Enter position:";
    cin>>pos;
    if(pos>count)
    {
        cout<<"Invalid position\n";
    }
    else
    {
        temp=head;
        while(i<pos)
        {
            temp=temp->next;
            i++;
        }
        cout<<"Enter data you want to insert:";
        newnode=new Node();
        cin>>newnode->data;
        newnode=temp->next;
        temp->next=newnode;
    }

    temp=head;

    while(temp!=0)
    {
        cout<<temp->data;
        temp=temp->next;
    }
}

A: Your problem is here:
cout<<"Enter data you want to insert:";
newnode=new Node();
cin>>newnode->data;
newnode=temp->next;
temp->next=newnode;

newnode=temp->next makes newnode equal to 0, then temp->next=newnode makes temp->next equal to zero.
Perhaps you meant to write newnode->next = temp->next instead?


text:
Q: Markup a citation (\citep) with pdfcomment's \pdfmarkupcomment When I try to mark-up text that contains a citation, I have trouble. Here's an attempt at a minimal working example called mwe-pdfcomment.tex
\documentclass[11pt]{article}
\usepackage[square,sort,comma,numbers]{natbib}
%pdfcomment stuff below:
\usepackage[opacity=1.0,version=1]{pdfcomment}
\usepackage{tikz}
\usetikzlibrary{calc}
\pdfcommentsetup{color=yellow,opacity=1.0}
%pdfcomment stuff above
\author{John Doe} \title{Sample Document}
\begin{document}

\maketitle

\section{Introduction}

According to a handbook \pdfmarkupcomment[color=yellow,opacity=1.0,markup=Highlight]{
   {\citep{texbook}}  %commenting this line out works
Blah
}{Why do you think this citation is important?},
this paragraph---and certainly this
section---should be longer than one sentence.

\bibliographystyle{plain}   % (uses file "plain.bst")
\bibliography{mwe}      % expects file "mwe.bib"
\end{document}

and the corresponding mwe.bib
@BOOK{texbook,
   author = "Donald E. Knuth",
   title= "The {{\TeX}book}",
   publisher = "Addison-Wesley",
   year = 1984
}

Initially, I got the error
! Argument of \@citex has an extra }.

which is why I put an extra set of {} around the \citep stuff. However, that leads to the following error:
! Package soul Error: Reconstruction failed.

Does \pdfcomment allow for citations inside the markup? If so, how?
There are related questions Problem when using pdfcomment in figure captions and then referencing and possibly Conflict between amsmath and pdfcomment

A: The error here is coming from the soul package, which is being used by pdfcomment to do the highlighting. If you read the soul docs, you'll find that there are cases where it can't operate successfully. I suspect what you are seeing here is the case of a hyphenation point inside a group. What you do find is that if you keep going past the error, run BibTeX then run LaTeX again twice, on the final run everything is OK. That's presumably because the \citep now produces text that soul can handle.
I'm not sure there is much you can do about this: it's a known limitation of soul and you'll just have to put up with it.


text:
Q: Setting up a subdomain to use both www and non-www I have www.mydomain.com and mydomain.com both working. Now, the subdomain sub.mydomain.com also works well; but not www.sub.mydomain.com.

*

*I've tried adding A records for for www.app; but not working.

*I've also tried creating a CNAME record "www.app" for mydomain.com; but also not working.

Browser throws a NET::ERR_CERT_COMMON_NAME_INVALID for both.
Any suggestions?


text:
Q: Java - Issues with reading a file into an array and using the array afterwards I made a class that reads a text file into an integer array, which I believe I've done correctly. Then I wanted to make a method (getInt();) within that to get the the first index of the array, and then each time it gets called get the following index element.
I had the idea to increment it every time it gets called to get the following index element, but the main problem I am having is that I cannot access my list outside of the try statement and I am therefore unable to make a method for it.
Can anyone suggest a piece of code or any advice on how to create this method?
import java.io.*;
import java.util.*;

public class ScannerIntegerList {

   public static void main(String[] args) {
      try {
         FileReader file = new FileReader("file.txt");
         BufferedReader input = new BufferedReader(file);

         List<Integer> list = new ArrayList<Integer>();

         String temp = "";

         while ((temp = input.readLine()) != null)
            if (!temp.trim().equals("0"))
               list.add(new Integer(temp));

         input.close();

         int i = 0;
         System.out.println(list.get(i));
         i++;

      } catch (IOException ie) {
         System.out.println(ie);
      }
   }

}

Also as a side note I am using eclipse and whenever I try and remove public static void main( String [] args) it tells me I need it, can anyone explain why this happens and how I can get around it, specifically with this bit of code?
When this class is finished the filename will also come from the command line so any advice on this would be greatly appreciated.
Many thanks in advance

A: If you want to use list outside the try block, declare and initialize it outside.
Also, use try-with-resources when working with closeable resources, like this:
List<Integer> list = new ArrayList<>();

try (BufferedReader input = new BufferedReader(new FileReader("file.txt"))) {
    String temp = "";
    while ((temp = input.readLine()) != null) {
        if (!temp.trim().equals("0")) {
            list.add(new Integer(temp));
        }
    }
} catch (IOException e) {
    e.printStackTrace();
}

// you can use list here, knock yourself out

If the filename will come from the command line,
then you really need the public static void main(String[] args) method.
Your program will receive command line arguments in the args array.
If the filename is the first command line argument,
you can use it via args[0].


text:
Q: How to make a loop without stopping the code execution I was making a discord bot and wanted to make a timer, but without using a loop.  The problem with a loop is that it would stop the rest of the circuit until it's done executing the loop. Is there a way to get around this? I did search how to do it, but all of them used while x > 60 which would not work in this case.

A: You need to use threads, and that would look something like this:
import threading

def func():
    times = 0
    while times < 10:
        print(times)
        times += 1;

x = threading.Thread(target=func)
x.start()

n = 100

while n < 110:
    n += 1
    print(n)

Here both while loops run at the same time


text:
Q: What are some ways to check for data leaks on a server I have a site that is being protected by Cloudflare and recently, Cloudflare has been blocking requests being made to the admin panel from another country where no one should have access to the admin. The admin URLs contain security keys that can be linked back to numerous workers who do have admin access to the site, so these are not random attempts to connect to the admin, they are targeted requests. They are somehow getting these URLs, but I can't figure out where the leak is coming from. I have logged all requests made to the site using NGINX logging as well as logging any outbound traffic using tcpdump, but none of them have logged any traffic coming from or going to any of the IP addresses that are being blocked that are trying to make these illegitimate requests, though for tcpdump at least, a lot of the traffic is encrypted, so I'm not 100% sure of that.
I've also scanned the site for malware using clamav and sitelock, neither of which have logged any malware.
The admin panel is whitelisted, so only a handful of sites can access the admin, mainly the main office and the owner's house. The office itself has pretty strong security in place, including scanning for viruses and malware daily along with a firewall appliance, so I'm not convinced the leak is coming from any of the computers at the office, I'm pretty sure it's coming from the server, but I can't figure out where it could be coming from.
Is there anything else I can try to figure out where this leak is coming from? No data has been changed on the admin panel, but I still don't like that there is a leak somewhere on the site with no apparent source.


text:
Q: C# Creating A Error Checking Class? I'm very new to OOP, and in the program I'm working on, I have an Utilities class that contains some general methods.  Should I include my error checking in the Utilities class or should I create a new class just for error checking?

A: "Utilities" classes tend have a nasty habit of becoming monstrosities -- keep the error checking code separate.

A: I don't know exactly what you want to do, but it is a safe bet that error checking class(es) should not be in your Utilities class.   Error Handling is a class of functionality that warrents it's own class(es).
Also, remember OOP is not putting your functions and routines in classes.  OOP is making classes that represent things.  Avoid "Utilities" classes as much as possible.

A: Generally speaking, I either handle errors where I am writing the code, or let the caller handle errors (i.e. let exceptions pass up the call stack).  It doesn't matter whether it is a utility function or not.
public static class Utility
{
    public static string GetSomeString(string someOtherString)
    {
        try
        {
            // something
        }
        catch (exception ex)
        {
            // handle error
        }
        return result;
    }
}

A: I think neither. Errors are usually Exceptions, which are classes themselfes and handled exactly on spot where you know how to deal with them.
If you're looking for logging or similar tasks, you should use a finished framework for that, such as Log4Net, or use AOP such as provided by PostSharp.

A: Error checking, such an input validation should go along with what needs to be checked - unless it's rather complex, in which case it should be moved to separate methods in the class of the thing being checked. If it's still too complex for that, a separate class that's devoted just to validation should be made. The validation class should be nested inside your main class, or it should be marked internal.

A: What about using the Application_Error event in the Global.asax file?  This gets fired when any unhandled error occurs int he application.

A: There are different forms of error checking
If you mean error checking in the sense of validity id jsut do it in code ... when you find that you have common tests EG string has length, maybe  a regex ... ints have a range ... i end up with a static class with these tests in however that is simply a refactoring.  I end up with a static class with sub static classes to get to the methods ...
Unit testing
These would be in different project to the main code again simply to define to scope of methods.
Error Checking.
I tend to use debug.assert statements all over the shop for general error checking in my methods and functions to test assumptions whilst debugging - I tend to use these as a weak form of unit testing.
Exception Management
This depends on the area you are working in. Exceptions in the backend have very different management scenarios than the front end.
for iinstance WCF has a interface for exceptions. IErrorHandler iirc correctly, but as far as anything connecting to it there are just a few faults that can be fired accross. At the backend these faults could caused by exceptions that are many exceptions deep with data attached to them at all levels.  You don't want that data to hit the front end - but you need to record it. As a result the exceptions at the front end are simply the husks of the real exceptions ... my point is that by the time you have sorted that out your utility class will be huge and you will want to start re factoring it into several classes.
But this is why exceptions need to be in a seperate project - you can then reference them from all over and reuse them.
I have a project that i tend to include for handling errors.
I also have a WCF service set up that i can fire exceptions at in order to record them for if we ned them (think about targetted bug fixing).
An example of how things grow is that part of this requires being able to serialise the error and all its data.
So I would shy away from a single utility class ... things that start off as a single method generally grow at an alarming rate once scope creep starts.
This kind of goes beyond OOP into more architectural questions - you need to know why you want to move the code into a utilities class and ytou then need to decide if simply putting it there is enough ... I'd suggest that moving it out is good but you should go further and think of error management as an entire solution in its own right. Its begging for a SOA style solution (or at least project) imo .... its one of those things that is not only common accross applications but is also invariant ....


text:
Q: Programming language that supports inheriting value types I develop in C++, and sometimes I wish I could say something like this:
class Heading : public float    // this line won't compile
{
public:
  Heading( float const value_ )
  : float(value_)               // this line won't compile
  {
    assert( value_ >= 0.0f );
    assert( value_ <= 360.0f );
  }
};

Instead, I have to do something like:
class Heading : public float
{
public:
  Heading( float const value_ )
  : value(value_)
  {
    assert( value >= 0.0f );
    assert( value <= 360.0f );
  }
private:
  float value;
};

Are there any programming languages out there that allow you to extend value types?

A: Python.
Everything's an object.  So extending float is simple.
class Heading( float ):
   def __init__( self, value ):
       assert 0.0 <= value <= 360.0
       super( Heading, self ).__init__( value )

And yes, 0.0 <= value <= 360.0 is legal syntax.

A: In ruby you can go a step further.  You can actually modify built in types.
class Float
  class self.heading(val)
    raise RangeError unless (0.0...360.0) === val
    val
  end
end

A: Ada allows this to a limited extent: specifically, your example can be expressed in Ada as
type Heading is digits 10
    range 0.0..360.0;

Pascal had a similar feature that was, IIRC, restricted to integers.
I don't know of any languages that allow unrestricted inheritance from primitive types like float.  Object-oriented inheritance by definition involves inheriting from a class, which something like C++'s float by definition is not.

A: D, java, and Objective-C allow deriving from built-in types.  In fact most object-oriented languages with built-in types defined to inherit from Object permit inheritance from the built-in types.  (I'm sure there's a counterexample and we're about to find out about it in the comments...)


text:
Q: Does android kill singleton in order to free memory? I've got a very weird problem and is difficult to describe so please read carefully the assumptions before the answer to avoid jumping into something I already know isn't
1 - I've got an android app which login from my server
2 - after a successful login I instantiate a Singleton API which will be shared across the activities in order to make the requests to the server
3 - Isn't possible to use the app without login
4 - in my login activity I have a very clean condition
if(APIFacade.getInstance() != null){
startActivity(new Intent(this,MainActivity.class));
                        finish();

}else {/*error handling*/}

5 - there is just one call to startActivity method in the whole LoginActivityclass so isn't possible to start MainActivity without check if the facade is null
6 - it isn't possible to set APIFacade.INSTANCE to null after instantiating it
But even with all these conditions sometimes users get NullPointerException on MainActivity when the app tries to make the first call to API after login
String url = APIFacade.getInstance().getProfilePicUrl(); //throws nullpointerexception on 5% of the times
APIFacade class is like this:
public class APIFacade {
 private static APIFacade INSTANCE = null;

  @WorkerThread
    public APIFacade(Object i, final boolean preLoad) {
        INSTANCE = this;
//other stuff
}

  public static APIFacade getInstance() {
        return INSTANCE;
    }
}

I'm not able to reproduce the problem in the development environment so I just know it happens due to the crashlytics dashboard on firebase...
I believe my code has no leak to lead this situation, so the only theory I got is: Android is cleaning some variables from memory when my app goes background...
I know android naturally does it for activities, but singletons?
and if yes what can I do to solve it?

A: Well I found the answer myself thanks to a great article: https://medium.com/@davethomas_9528/please-dont-use-singletons-to-persist-state-on-android-7bac9bc78b29
Briefly:
Everybody says that singleston on android are attached to the application life, so will only be released if the application is killed
THIS IS TRUE
what you dont hear, is that the application can be killed by the SO without user interaction (to release memory for foreground apps) and in this scenario when the user tries to come back to your app it will restart from the last used activity and not from the launcher activity.


text:
Q: C# Generated CSV changes the format of the data retrieved from a SQL database protected void ExportCSV(object sender, EventArgs e)
{

DataTable ds = new DataTable();
ds.Columns.AddRange(new DataColumn[1] { new DataColumn("Name") });
foreach (GridViewRow roww in GridView1.Rows)

{
    if (roww.RowType == DataControlRowType.DataRow)
    {
        CheckBox chkRow = (roww.Cells[0].FindControl("chkRow") as CheckBox);

        if (chkRow.Checked)
        {
            string name = roww.Cells[1].Text;
            string DefaultConnection = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
            using (SqlConnection con = new SqlConnection(DefaultConnection))

            {
                SqlCommand command = new SqlCommand();

                using (SqlCommand cmd = new SqlCommand("Select AssignNumber, Stage.StageName,Stage.StationName,AspNetUsers.UserName,RecordedDateTime,StartTime,EndTime,Duration,PauseCount,PauseTotalTime,StageRecord.Count, StageRecord.Notes,Location,VarName,DropOut From TimingProfile Inner Join StudyRecord ON TimingProfile.TimingProfileID = StudyRecord.TimingProfileID Inner Join StageRecord ON StudyRecord.StudyRecordID = StageRecord.StudyRecordID Left Join Stage ON StageRecord.StageID = Stage.StageID Left Join VarAffect ON StageRecord.VarID = VarAffect.VarID Left Join MultiNameValue ON StudyRecord.StudyRecordID = MultiNameValue.StudyRecordID Left Join UserStage ON UserStage.StageID = Stage.StageID Left Join AspNetUsers ON UserStage.UserID = AspNetUsers.Id Where TimingProfile.Name = " + "'"+name+"'"))

                    using (SqlDataAdapter sda = new SqlDataAdapter())
                    {
                        cmd.Connection = con;
                        sda.SelectCommand = cmd;
                        using (DataTable dt = new DataTable())
                        {
                            sda.Fill(dt);

                            //Build the CSV file data as a Comma separated string.
                            string csv = string.Empty;

                            foreach (DataColumn column
                            in dt.Columns)
                            {
                                //Add the Header row for CSV file.
                                csv += column.ColumnName + ',';
                            }

                            //Add new line.
                            csv += "\r\n";

                            foreach (DataRow row in dt.Rows)
                            {
                                foreach (DataColumn column in dt.Columns)
                                {
                                    //Add the Data rows.
                                    csv += row[column.ColumnName].ToString().Replace(",", ";") + ',';
                                }

                                //Add new line.
                                csv += "\r\n";
                            }
                            DateTime localdate = DateTime.Now;
                        //Download the CSV file.

                        Response.Clear();
                            Response.Buffer = true;
                            Response.AddHeader("content-disposition", "attachment;filename=MultiStation" + "" + name + " " + localdate + ".csv");

                        Response.Charset = "";
                            Response.ContentType = "application/text";
                            Response.Output.Write(csv);

                        Response.Flush();
                        Response.End();

                    }
                }

            }
            }

        }
    }
}

When I used the query in SQL management studio the duration is shown as :00:32:39 but it appears in the generated CSV as 0.0226736111111111 instead. Is there a way to rectify this?

A: Someone needs to say it. This code shows loadsa enthusiasm and not much sophistication. You've mixed up UI (checkbox), business logic, data access, serialization and HTTP in one method ! And, predictably, there are problems. Your SQL is in string literals with concatenation, and hidden at the end is a glowing SQL injection vulnerability. Your serialization code, converting commas to semicolons, loses data and will produce invalid CSV (double quotes not doubled). Not using stringbuilder to construct the CSV will very likely cause performance issues. All these traps would be avoided by using libraries, Dapper or QueryFirst (disclaimer: which I wrote) for data access, servicestack for serialization.
Understanding how your data is stored, and how and when to format it, is really a core competence for a programmer. Often it's good to format at the last moment. If you were reusing sql requests, you might want to format in C#. Since this request is only used in this one place, you might want to format directly in the SQL. The downside is that the C# will not treat your duration as a duration. Try and use built-in date time formats before building your own.


text:
Q: Secure a url that has a cname record I have a site that has subdomains for each user and a wildcard SSL Cert
https://user1.mysite.com
https://user2.mysite.com
The question is can someone set a cname record such as user1.theirsite.com -> user1.mysite.com and have it still use https?
Will it work if they install a SSL Cert on their server to secure the connection?
Thanks

A: The best way for this to work is if they arrange with you to have your SSL certificate include their "alias" as a Subject Alternate Name extension in your X.509 certificate.
This is the approach used by some CDNs when they host https sites for clients - they put all of the known site names that are hosted on one server in one large SSL certificate, and then the clients use CNAMEs to point their domain at the right CDN server.

A: The host name and certificate verification (and in fact, checking that SSL is used at all) are solely the responsibility of the client.
The host name verification will be done by the client, as specified in RFC 2818, based on the host name they request in their URL. Whether the host name DNS resolution is based on a CNAME entry or anything else is irrelevant.
If users are typing https://user1.theirsite.com/ in their browser, the certificate on the target site should be valid for user1.theirsite.com.
If they have their own server for user1.theirsite.com, different to user1.mysite.com, a DNS CNAME entry wouldn't make sense. Assuming the two hosts are effectively distinct, they could have their own valid certificate for user1.theirsite.com and make a redirection to https://user1.theirsite.com/. The redirection would also be visible in the address bar.
If you really wanted to have a CNAME from user1.theirsite.com to user1.mysite.com, they might be able to give you their certificate and private key so that you host it on your site too, using Server Name Indication (assuming same port, and of course same IP address since you're using a CNAME). This would work for clients that support SNI. There would however be a certain risk to them in giving you their private keys (which isn't generally recommended).

A: The following is set up and working:
DNS entry for a.corp.com -> CNAME b.corp2.com -> A 1.2.3.4
The haproxy at 1.2.3.4 will serve up the cert for a.corp.com and the site loads fine from a webserver backend.
So, on your server you will need user1.theirsite.com cert and it will work.


text:
Q: ERROR 2: Internalize failed ERROR 1: GetBlockRef failed at X block offset 0, Y block offset 0 I used GDAL RasterIO to read multi-band geotiff, when I apply it to the same band, it is ok, but when I appply it to tow different bands, the error occurs.
GDALRasterBand *tmpBand1 = img_sar->GetRasterBand(1);
GDALRasterBand *tmpBand2 = img_sar->GetRasterBand(2);
int cols = img_sar->GetRasterXSize();
int ligs = img_sar->GetRasterYSize();
tmpBand1->RasterIO(GF_Read,0,0,cols,1,tmp,cols,1,GDT_Float32,0,0);//it is ok
tmpBand2->RasterIO(GF_Read,0,0,cols,1,tmp,cols,1,GDT_Float32,0,0);//the error occurs this line


text:
Q: How do I migrate part of a business process to DDD? I am quite new to DDD, but I am currently working on a system which has a payroll element to it. I have a requirement to send payslips to an external system when they are created. Currently the payslip process is all in the existing legacy code, but I was thinking that it might be a good chance to move some code into a bounded context that has recently been created for payroll to slowly migrate the legacy code to. The system isn't distributed so everything all runs in one process.
My thoughts were to make an application service which would orchestrate calling an infrastructure service to send the data to the external system and then update the status of the payslip. This would be called from the legacy code. Is an infrastructure service the right thing for this integration, or is the whole thing a design smell?

A: This is more of an architecture question than DDD.  DDD can be implemented with 2 tier, 3 tier, Clean, Hexagonal, etc.  It appears from the terms you used in the question that you are using something similar to Clean Architecture, so I'll make that assumption.
An infrastructure service is where you would implement the service to make the eventual call to the external message broker, but getting the message to be sent from the domain model and into that infrastructure service seems to be where you're stuck.
In the domain model, declare an interface for a messaging service that is generic (i.e. does not use anything declared by the messaging service you end up using).  Implement the service that calls the external message broker in the infrastructure layer, and make it implement the interface in the domain layer.  Now you can either inject that service into your domain objects, or pass it in from the outside if it's not used often.  This sidesteps the need for the application service which would do nothing but pass the message on.
BTW, even if all the code is running in the same address space, you should use a message broker.  This creates a seam to allow breaking off that domain in the future into a microservice of its own when your app becomes unexpectedly successful.


text:
Q: Javac producing error with no origin I am using javac in ant to compile a project and I am getting an compilation error message without the file or line number. Why is this and how can i find where in the (large) project the problem is?
build.xml

make_folders:

compile:
[javac] Compiling 33 source files to *project root*/bin/classes
[javac] error: incompatible types: String cannot be converted to Integer
[javac] Note: Some messages have been simplified; recompile with -Xdiags:verbose to get full output
[javac] 1 error

BUILD FAILED
*project root*/build.xml:33: Compile failed; see the compiler error output for details.

And heres the relevant lines with verbose set to true:
[javac] [loading ZipFileIndexFileObject[/Library/Java/JavaVirtualMachines/jdk1.8.0_20.jdk/Contents/Home/lib/ct.sym(META-INF/sym/rt.jar/java/util/Date.class)]]
[javac] error: incompatible types: String cannot be converted to Integer

UPDATE:
So I managed to figure out that the error it was originating from calling a function in a class from within an inner class in said outer class. I'm not sure why this produced an error or why it was presented with such little information so any help would still be appreciated.


text:
Q: Unable to export data to an excel file using interop open library in C# after deploying the application I am working on a C# windows application in Visual Studio 2013 which has a feature to export data to an excel file using interop excel open library.
It works fine when used on my development machine but fails when I deploy it on a user machine which has Office 2013 I get the following error

Not sure why it threw me that error and details are as follows
I tried many ways but failed to solve this
Also, my code to export data is as follows
 // creating Excel Application
            Microsoft.Office.Interop.Excel._Application app = new Microsoft.Office.Interop.Excel.Application();

            // creating new WorkBook within Excel application
            Microsoft.Office.Interop.Excel._Workbook workbook = app.Workbooks.Add(Type.Missing);

            // creating new Excelsheet in workbook
            Microsoft.Office.Interop.Excel._Worksheet indexWorkSheet = null;
            indexWorkSheet = workbook.Sheets[1];
            // changing the name of active sheet
            indexWorkSheet.Name = "Index Summary";

            indexWorkSheet.get_Range("A1").Style.HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignCenter;
            indexWorkSheet.get_Range("A10", "A30").Style.HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignCenter;
            string filelocation;
            SaveFileDialog SaveFile = new SaveFileDialog();
            if (SaveFile.ShowDialog() == DialogResult.OK)
            {
                filelocation = SaveFile.FileName;

                // storing header part in Excel
               indexWorkSheet.Shapes.AddPicture(@"C:\Atlas Applications\AtlasPetroleumIndex\CLPetroleumIndex\Images\logo.jpg", MsoTriState.msoFalse, MsoTriState.msoCTrue, 155, 20, 180, 65).LockAspectRatio = MsoTriState.msoCTrue;
            // indexWorkSheet

                for (int i = 1; i < dataGridViewIndex.Columns.Count + 1; i++)
                {
                    indexWorkSheet.Cells[9, i + 3] = dataGridViewIndex.Columns[i - 1].HeaderCell.Value;
                }

                for (int i = 1; i < dataGridViewIndex.Rows.Count + 1; i++)
                {
                    indexWorkSheet.Cells[i + 9, 3] = dataGridViewIndex.Rows[i - 1].HeaderCell.Value;
                    //worksheet2.Cells[i + 1, 1] = dataGridViewPaymentsReceived.Rows[i - 1].HeaderCell.Value;
                }

                for (int i = 0; i < dataGridViewIndex.Rows.Count; i++)
                {
                    for (int j = 0; j < dataGridViewIndex.Columns.Count; j++)
                    {

                        indexWorkSheet.Cells[i + 10, j + 4] = dataGridViewIndex.Rows[i].Cells[j].Value.ToString();
                    }
                }

                indexWorkSheet.Cells[7, 2] = lblIndexSummary.Text;

                indexWorkSheet.Range[indexWorkSheet.Cells[6, 2], indexWorkSheet.Cells[1, 9]].Merge();
                indexWorkSheet.Range[indexWorkSheet.Cells[7, 2], indexWorkSheet.Cells[7, 9]].Merge();
                indexWorkSheet.Cells[9, 3].EntireRow.Font.Bold = true;
                indexWorkSheet.Cells[7, 3].EntireRow.Font.Bold = true;

                for (int i = 1; i < dataGridViewIndex.Rows.Count + 9; i++)
                {
                    indexWorkSheet.Cells[i + 9, 3].Font.Bold = true;
                }

                string colIndex = "I" + (dataGridViewIndex.Rows.Count + 9).ToString();
                Microsoft.Office.Interop.Excel.Range formatRange;
                formatRange = indexWorkSheet.get_Range("B8", colIndex);

                formatRange.BorderAround(Microsoft.Office.Interop.Excel.XlLineStyle.xlContinuous,
                Microsoft.Office.Interop.Excel.XlBorderWeight.xlMedium, Microsoft.Office.Interop.Excel.XlColorIndex.xlColorIndexAutomatic,
                Microsoft.Office.Interop.Excel.XlColorIndex.xlColorIndexAutomatic);

                string volumeIndex = "H" + (dataGridViewIndex.Rows.Count + 9).ToString();
                Microsoft.Office.Interop.Excel.Range numberFormatRange;
                numberFormatRange = indexWorkSheet.get_Range("H10", volumeIndex);
                numberFormatRange.NumberFormat="N3";

                string alignIndex = "H" + (dataGridViewIndex.Rows.Count + 9).ToString();
                Microsoft.Office.Interop.Excel.Range alignRange;
                alignRange = indexWorkSheet.get_Range("E9", alignIndex);
                alignRange.HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignRight;

                workbook.SaveAs(filelocation, Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookNormal, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive, Type.Missing, Type.Missing, Type.Missing, Type.Missing);

                workbook.ExportAsFixedFormat(Microsoft.Office.Interop.Excel.XlFixedFormatType.xlTypePDF, filelocation);

                workbook.Close(true, Type.Missing, Type.Missing);
                app.Quit();

May I know a way to fix it?

A:
You are using 3rd party software like AddinExpress and OffiSync which
  are probably incompatible with Office 2013 or out of date. (Source)

Have the user remove the incompatible addin from Excel.


text:
Q: Regular expression for ignoring an optional comma I have a text:
$test = <<<START
 DOTHIS themsp1
  @theint =    431,
  @theText = "%dumdum%",
  @operator = 'ANY',
  @crossCheck = 'PLUS'

START;

The filter:
$regEx = '/@(.*)=(.*)[,]*?/';
preg_match_all($regEx,$test,$vars,PREG_SET_ORDER);
print_r($vars);

The Output:
Array
(
    [0] => Array
        (
            [0] => @theint =  431,
            [1] => theint
            [2] =>   431,
        )

    [1] => Array
        (
            [0] => @theText = "%dumdum%",
            [1] => theText
            [2] =>  "%dumdum%",
        )

    [2] => Array
        (
            [0] => @operator = 'ANY',
            [1] => operator
            [2] =>  'ANY',
        )

    [3] => Array
        (
            [0] => @crossCheck = 'PLUS'
            [1] => crossCheck
            [2] =>  'PLUS'
        )

)

I don't want commas OR the whitespace in the output :( .. The problem is that the commas are optional;

A: /@(.*?)\s*=\s*(.*?),?/

Add \s* in the appropriate places to match whitespace. Use a question mark for .*? to match non-greedily. A non-greedy match matches as short a match as possible, so (.*?),? will let the comma on the right match a comma rather than the .* capturing the comma.

A: In your regex $regEx = '/@(.*)=(.*)[,]*?/'; the 2nd (.*) is greedy and will match the comma, since the comma as you wrote it is optional.
Untested, this regex will allow optional spaces around the equal sign but not include them in the capture '/@([^\s=]+)\s*=\s*([^\s,]+)\s*,?/'  It also allows space between the value and the comma.

A: You should be more specific than just using ., for example:
/@([a-zA-Z]+)[ \t]*=[ \t]*([0-9]+|"(?:[^\\"]|\\.)*"|'(?:[^\\']|\\.)*')[ \t]*,?/

Here [a-zA-Z]+ specified the name as a sequence of alphabetic characters. That is then followed by the = that may be surrounded by spaces or tabs. And then the value is either a number ([0-9]+, sequence of one or more digits) or a quoted string that may contain escape sequences ("(?:[^\\"]|\\.)*"|'(?:[^\\']|\\.)*'), followed by optional spaces or tabs.


text:
Q: calling C++ from C# cross platform Hi I'm looking for an example of how to call a simple C++ function or class from C# that works cross platform i.e. visual studios and mono, most of the stuff i've found on the web seem to only work via visual studios.

A: You can use SWIG for calling C++ code from C#. It seems to work equally well with mono see http://www.swig.org/Doc1.3/CSharp.html

A: You can't call C++ functions, because of the name mangling, but you can call extern "C" functions via P/Invoke.
This might be a good read: http://msdn.microsoft.com/en-us/library/42b9ea93.aspx
Google would of course be valuable too.
I'd say it's unlikely that you will be able to write completely cross-platform P/Invoke code, since so many things are different across platforms.


text:
Q: Resize images to store in drawable folder I'm having some troubles with display of images, someone can help me?
- I've a listView and I wanna show one different image in each item of this list (in background), all right, my images has the resolution so much large (for example 6016x2188px), then I have to resize them, by:
public static int getInSampleSize(BitmapFactory.Options opt, int reqWidth, int reqHeight) {

        final int imgWidth = opt.outWidth;//rec a larg orig da img
        final int imgHeight = opt.outHeight;//rec a alt orig da img
        int inSampleSize = 1;

        LogUtil.logD(LogUtil.LOG_TAG, "Img Alt -> %s | Img Larg -> %s", String.valueOf(imgHeight), String.valueOf(imgWidth));

        if (imgWidth > reqWidth || imgHeight > reqHeight) {
            final int halfHeight = imgHeight / 2;
            final int halfWidth = imgWidth / 2;

            while ((halfHeight / inSampleSize) > reqHeight &&
                    (halfWidth / inSampleSize) > reqWidth) {

                inSampleSize *= 2;
            }

            long totalPixels = imgWidth * imgHeight / inSampleSize;

            final long totalReqPixelsCap = reqWidth * reqHeight * 2;

            while (totalPixels > totalReqPixelsCap) {
                inSampleSize *= 2;
                totalPixels /= 2;
            }
        }

        LogUtil.logD(LogUtil.LOG_TAG, "Img inSampleSize -> %s", String.valueOf(inSampleSize));
        return inSampleSize;
    }

public static Bitmap getSampleBitmap(Context ctx, int imgId, int reqWidth, int reqHeight) {

        final BitmapFactory.Options opt = new BitmapFactory.Options();
        opt.inJustDecodeBounds = true;

        Resources res = ctx.getResources();

        BitmapFactory.decodeResource(res, imgId, opt);

        opt.inSampleSize = getInSampleSize(opt, reqWidth, reqHeight);

        opt.inJustDecodeBounds = false;

        LogUtil.logD(LogUtil.LOG_TAG, "Decode bitmap...");
        return BitmapFactory.decodeResource(res, imgId, opt);
    }

//each row in adapter
txtview.setBackgroundDrawable(new BitmapDrawable(ctx.getResources(), getSampleBitmap(ctx, R.drawable.img, txtview.getWidth(), txtview.getHeight())));

Ok, it works, but my app is displaying this images with a time gap, and this makes the app very strange.
Then some people had said that I have to store the images already resized in drawable folder, but how I'll know how many pixels I have to resize if the android deals with dp and this dp can become different amount of pixel depending on of resolution of each device? (I wanna store just a xxdpi to that the app do not be so many large)
If I resize them to 800px of width (the best quality for tablets 10"), this will work properly to all other resolution?
By the way, the .setBackgroundDrawable() is deprecated, so any other idea to set a bitmap like background?
Thanks

A: You can use this asset studio to generate the complete set of properly sized images organized into the correct Drawable folders.  After generation, you just download the zip, extract the folders and place them in your app hierarchy.
https://romannurik.github.io/AndroidAssetStudio/icons-generic.html#source.space.trim=1&source.space.pad=0&size=24&padding=8&color=33b5e5%2C100&name=ic_example


text:
Q: Cannot debug on Z10, STL100-3 I am developing an app on Momentics.
The app runs fine on my STL100-3 model Z10 but I cannot debug the app. When I launch the debug process, it continually terminates.
I get the following error from the console
Timed out.
MsgNak received - resending

Eventually, this times out. The debug session never starts.
How can I go around this?

A: I had problems like this when using wireless to debug my apps. When I switched to debugging via USB everything worked much much better.


text:
Q: Cloudformation - Route table has a conflicting association with the gateway I'm trying to deploy EC2 instance using cloudformation, It's giving the following error when i try to execute the stack.
Route table has a conflicting association with the gateway igw-0d7bbb47c8b4e8875 (Service: AmazonEC2; Status Code: 400; Error Code: RouteConflict; Request ID: 0ca161d0-b58d-4f95-a2f1-01038ccc4cae; Proxy: null)
Parameters:
  InstanceType:
    Type: "String"
    Default: t2.micro
  Image:
    Type: "String"
    Default: ami-0aab712d6363da7f9

Resources:
  WebServer:
    Type: AWS::EC2::Instance
    Properties:
      AvailabilityZone: ap-southeast-2a
      KeyName: poweruser-keypair
      InstanceType: !Ref InstanceType
      ImageId: !Ref Image
      SubnetId: !Ref SubNet
  VPC:
    Type: AWS::EC2::VPC
    Properties:
      CidrBlock: "10.0.0.0/16"
      InstanceTenancy: default

  SubNet:
    Type: AWS::EC2::Subnet
    Properties:
      AvailabilityZone: ap-southeast-2a
      MapPublicIpOnLaunch: true
      CidrBlock: "10.0.0.0/24"
      VpcId: !Ref VPC

  InternetGateway:
    Type: AWS::EC2::InternetGateway

  IgwAttachment:
    Type: AWS::EC2::VPCGatewayAttachment
    Properties:
      InternetGatewayId: !Ref InternetGateway
      VpcId: !Ref VPC

  RouteTable:
    Type: AWS::EC2::RouteTable
    Properties:
      VpcId: !Ref VPC

  RoutingToInternet:
    Type: AWS::EC2::Route
    DependsOn: IgwAttachment
    Properties:
       RouteTableId: !Ref RouteTable
       DestinationCidrBlock: 0.0.0.0/0
       GatewayId: !Ref InternetGateway

  SubnetRouteTableAssociation:
    Type: AWS::EC2::SubnetRouteTableAssociation
    Properties:
      RouteTableId: !Ref RouteTable
      SubnetId: !Ref SubNet

  SubnetNetworkAclAssociation:
    Type: AWS::EC2::SubnetNetworkAclAssociation
    Properties:
      SubnetId:
        Ref: SubNet
      NetworkAclId:
        Ref: NetworkACL

  NetworkACL:
    Type: AWS::EC2::NetworkAcl
    Properties:
      VpcId: !Ref VPC

  NACLEntry:
    Type: AWS::EC2::NetworkAclEntry
    Properties:
      CidrBlock: "10.0.0.0/16"
      Egress: true
      NetworkAclId: !Ref NetworkACL
      Protocol: -1
      RuleAction: "allow"
      RuleNumber: 100

A: There is nothing wrong with your cloudformation template. This means that the code that you used in the question is not fully representative of your actual template that you use.


text:
Q: Using exec while redirecting the output to a text file seems to lock said file On a WAMP configuration, I am executing a shell command with exec and redirecting the output with >> log.txt. The commando is called many times in the script. The first time, the file is created, and the first output is written on it, but it seems the file stream is not closed (I can't delete the file, and Windows tells me that the file is opened by somebody else), and as such the script try to continue loading but do nothing else, and is still try after the 5 minutes limit I set for this script.
Am I doing something wrong? If yes why? Otherwise where does the problem lies?
EDIT: I've confirmed that by commenting the code line that it is the source of my problem. Furthermore, although I interrupted the script, the file remained locked to any change (edit/move/delete).
EDIT 2: Using pclose(popen("start /B ". $cmd, "r")) instead, as suggested in this comment doesn't seems to bring anything, regardless If I use >> log.txt or not.
EDIT 3: After a forced unwanted reboot of the server, the issue isn't there anymore.
I've talked with some colleague which encountered a similar problem with their application, and they said that rebooting their server always "solved" the problem. But I don't call that a solution if the problem comes again sooner or later. So it seems that the "silent update" scenario is the more possible.
In the meantime the server will be migrated to a machine with a newer OS (Windows 2008 Server). I'll wait and see if the problem comes again, but if possible I would like to takes measures so I don't have to deal with it in the future.

A: why dont you exec($cmd, $output, $result) ? this will return the output in the $output variable. you can then do a file_put_contents($file, implode("\r\n", $output), FILE_APPEND)
this will let you append the output of the command right into the log file in pure php way


text:
Q: InfoBarMessage set to none in viewmodel I've used so far some Catel DataWindow specifing in the constructor
public class MyViewModel: base(Catel.Windows.DataWindowMode.OkCancel, null, Catel.Windows.DataWindowDefaultButton.None, true, Catel.Windows.InfoBarMessageControlGenerationMode.None)

in order to not have the InfoBarMessage and it works perfectly
Now I've a catel:UserControl how can I disable that InfoBarMessage? since I've a Model that validates some filters and I want to have validation on UIElements
Thanks

A: User controls don't create an InfoBarMessageControl in Catel. If you disable it for all windows, you should set UserControl.DefaultskipSearchingForInfoBarMessageControl = true;.
You should also look into ApiCop. It will inform you about best practices based on the actual code you are using at runtime, for example:
================================================================
DATAWINDOWTEST.VIEWS.AVIEW
================================================================

Cop TargetType: Catel.Windows.Controls.MVVMProviders.Logic.UserControlLogic
Rule: UserControlLogic.InfoBarMessageControl (Error)
For more information about this rule, visit https://catelproject.atlassian.net/wiki/display/CTL/Performance+considerations

[DataWindowTest.Views.AView] Feature used '0' of '2' times, consider turning it off by default

----------------------------------------------------------------

Cop TargetType: Catel.Windows.Controls.MVVMProviders.Logic.UserControlLogic
Rule: UserControlLogic.CreateWarningAndErrorValidator (Error)
For more information about this rule, visit https://catelproject.atlassian.net/wiki/display/CTL/Performance+considerations

[DataWindowTest.Views.AView] Feature used '0' of '2' times, consider turning it off by default

----------------------------------------------------------------


text:
Q: iOS 6 - Error in sending data in HTTPBody with POST method Till last night the code was working perfectly, but today i am facing a weird problem.
NSString *hostStr = [@"My API string" stringByAppendingString: @"/users/login"];

NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:hostStr]];
[request setHTTPMethod:@"POST"];

NSString *boundary = @"-----FOO";
NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",boundary];
[request addValue:contentType forHTTPHeaderField:@"Content-Type"];

NSData *usernameData = [username dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:NO];
NSData *passwordData = [password dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:NO];

NSMutableData *body = [NSMutableData data];

[body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[@"Content-Disposition: form-data; name=\"data[login_name]\"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[@"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[NSData dataWithData:usernameData]];

[body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[@"Content-Disposition: form-data; name=\"data[password]\"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[@"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[NSData dataWithData:passwordData]];

[body appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPBody:body];

NSError *error;
NSURLResponse *response;
NSData *urlData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSString *serverOutput = [[NSString alloc] initWithData:urlData encoding:NSUTF8StringEncoding];
NSLog(@"%@",serverOutput);

Above code gives me following response
<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">

<title>400 Bad Request</title>

Bad Request

Your browser sent a request that this server could not understand.

Additionally, a 404 Not Found
error was encountered while trying to use an ErrorDocument to handle the request.

<address>Apache Server at MY API URL Port 80</address>

But for the same lines of code when i comment this part
[body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n", boundary]  dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[@"Content-Disposition: form-data; name=\"data[login_name]\"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[@"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[NSData dataWithData:usernameData]];

[body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[@"Content-Disposition: form-data; name=\"data[password]\"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[@"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[NSData dataWithData:passwordData]];

[body appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];

It gives me following request response
{"login_name":"Username or Password is not valid","responseCode":"0"}

Means when i am not sending any data in HTTPBody, API call gives me desire response.
I have no any idea what is going wrong here. Many Thanks in advance.

A: Well. This is something that I never realized could be a problem.
As I more and more check my code, I found that there isn't any problem with my code up "there". But the problem was server side.
I contacted the server people and they said that they have enabled some ModSecurity so a multipart form data was not able to be sent in the HTTPBody.
This cost me two whole days to figure out. Hope it saves some one's time.


text:
Q: Online check for staff discord.py Basically I want to make it so that if someone calls command ?server ("There is raid going on!" - for example), people with role "Staff" that also have status "online" would receive dm with message in command
I tried to do it for like an hour but didn't come up with anything working.

A: First, we'll get the role itself, then filter out all of the staff and send each a message.  I'm using asyncio.gather to send the messages simultaneously, but you can also send them sequentially.
from discord.ext import commands
from discord.utils import get
from discord import Status
from asyncio import gather

bot = commands.Bot("?")

@bot.command()
async def server(ctx, *, text="There is raid going on!"):
    staff = get(ctx.guild.roles, name="Staff")
    online = (member for member in staff.members if member.status == Status.online)
    messages = (member.send(text) for member in online)  # You could also send the messages sequentially
    await gather(messages)

bot.run("token")