text:
Q: Sequentially arranged and add placeholders in text file I have a text file which contains data. There are 3 columns, each column starts at a specific location and ends a specific location in the file. The first column which is (300, 301, 302, 304...) is always number based. the second column is a string, and the last column is currency.
The current .txt file is missing numbers which is (303, 305).
I was able to find the missing numbers and add it to an array then write it to the file.
My goal is to write all the columns data sequentially to the text file even the missing ones. As for column 2 and 3, I want 0 to be the placeholder for the missing data and aligned with its own column.
I'm close but need help
   //read file
   string[] lines = File.ReadAllLines(FilePath);
   var Numbers = new List<int>();
   int i = 0;
   foreach (var line in lines)
   {
       //get value of first column
       var FirstColumn = line.Substring(0, 3);
       //add it to array
       Numbers.Add(Convert.ToInt32(FirstColumn));
       ++i;
   }
   //find missing numbers add to array
   var result = Enumerable.Range(Numbers.Min(), Numbers.Count);

   //write to file
   using (StreamWriter file = new StreamWriter(OutPutFile, true))
   {
       foreach (var item in result.ToArray())
       {
           file.WriteLine(item);
       }
   }

   Console.ReadKey();

Current .txt file
300     Family Guy      1,123
301     Dexters Lab     456
302     Rugrats         1,789.52
304     Scooby-Doo      321
306     Recess          2,654
307     Popeye          1,987.02

GOAL: Desired Output .txt file
300     Family Guy      1,123
301     Dexters Lab     456
302     Rugrats         1,789.52
303     0               0
304     Scooby-Doo      321
305     0               0
306     Recess          2,654
307     Popeye          1,987.02

A: You are reading the first column, but not the rest.  What I do is create a dictionary, using the first number as the index, and stuffing the other two fields into a System.ValueTuple (you need to include the ValueTyple Nuget package to get this to work).
First I set some stuff up:
 const int column1Start = 0;
 const int column1Length = 3;
 const int column2Start = 8;
 const int column2Length = 15;
 const int column3Start = 24;

 int indexMin = int.MaxValue;     //calculated during the first
 int indexMax = int.MinValue;     //pass through the file

Then I create my dictionary.  That (string, decimal) syntax describes a 2-tuple that contains a string and a decimal number (kind of like the ordered-pairs you were taught about in high school).
 Dictionary<int, (string, decimal)> data = new Dictionary<int, (string, decimal)>();

Then I make a pass through the file's lines, reading through the data, and stuffing the results in my dictionary (and calculating the max and min values for that first column):
 var lines = File.ReadAllLines(fileName);
 foreach (var line in lines) {
     //no error checking
     var indexString = line.Substring(column1Start, column1Length);
     var cartoon = line.Substring(column2Start, column2Length).TrimEnd();
     var numberString = line.Substring(column3Start);

     if (int.TryParse(indexString, out var index)) {
         //I have to parse the first number - otherwise there's nothing to index on
         if (!decimal.TryParse(numberString, out var number)){
             number = 0.0M;
         }
         data.Add(index, (cartoon, number));

         if (index < indexMin) {
             indexMin = index;
         }
         if (index > indexMax) {
             indexMax = index;
         }
     }
 }

Finally, with all my data in hand, I iterate from the min value to the max value, fetching the other two columns out of my dictionary:
 for (int i = indexMin; i <= indexMax; ++i) {
     if (!data.TryGetValue(i, out var val)){
         val = ("0", 0.0M);
     }
     Console.WriteLine($"{i,5}  {val.Item1,-column2Length - 2}  {val.Item2, 10:N}");
 }

My formatting isn't quite the same as yours (I cleaned it up a bit).  You can do what you want.  My results look like:
  300  Family Guy           1,123.00
  301  Dexters Lab            456.00
  302  Rugrats              1,789.52
  303  0                        0.00
  304  Scooby-Doo             321.00
  305  0                        0.00
  306  Recess               2,654.00
  307  Popeye               1,987.02


text:
Q: How to determine which logical cores share the same physical core? I am working on a tool to allow students to self-evaluate their programming assignment's performance. In particular, the program they're writing is multi-threaded and I have no direct way of influencing the number of threads created. I would like to compare the performance of their programs given a different number of cores (and ideally, their programs should speed up roughly proportionally to how many cores it is allowed to use).
We can pass a bitmask to Process.SetAffinity to control which cores the program uses.
This is problematic on i5 and i7 machines that use hyper-threading and split each physical core in to two logical ones. I want the program to run on two/four distinct physical cores. On my i7 machine, a process with affinity set to 3 (cores 0&1) will run roughly as fast as the program on a single core (indicating these logical cores share the same physical core), but with affinity set to 5 (cores 0&3) it will run much faster (indicating these cores are using different physical cores). However, I haven't found a reliable way (other than trial-and-error) to determine this.
How can I (without experimentation) determine which logical cores share the same physical core?
(/proc/cpuinfo has the information I need but that is not available on Windows machines.)

A: Based on comments to your question (thanks to all, especially to @RLH) I made this class for you:
/// <summary>
/// Provides CPU information
/// </summary>
public static class Processor
{
    private static IHardwareCore[] cores;
    private static int[] logicalCores;

    /// <summary>
    /// Hardware core
    /// </summary>
    public interface IHardwareCore
    {
        /// <summary>
        /// Logical core IDs
        /// </summary>
        int[] LogicalCores { get; }
    }

    /// <summary>
    /// Hardware cores
    /// </summary>
    public static IHardwareCore[] HardwareCores
    {
        get
        {
            return cores ?? (cores = GetLogicalProcessorInformation()
                .Where(x => x.Relationship == LOGICAL_PROCESSOR_RELATIONSHIP.RelationProcessorCore)
                .Select(x => new HardwareCore((UInt64)x.ProcessorMask))
                .ToArray<IHardwareCore>());
        }
    }

    /// <summary>
    /// All logical core IDs
    /// </summary>
    public static int[] LogicalCores
    {
        get
        {
            return logicalCores ?? (logicalCores = HardwareCores
                .SelectMany(x => x.LogicalCores)
                .ToArray());
        }
    }

    /// <summary>
    /// Current logical core ID
    /// </summary>
    public static int CurrentLogicalCore
    {
        get { return GetCurrentProcessorNumber(); }
    }

    private class HardwareCore : IHardwareCore
    {
        public HardwareCore(UInt64 logicalCoresMask)
        {
            var logicalCores = new List<int>();

            for (var i = 0; i < 64; ++i)
            {
                if (((logicalCoresMask >> i) & 0x1) == 0) continue;
                logicalCores.Add(i);
            }

            LogicalCores = logicalCores.ToArray();
        }

        public int[] LogicalCores { get; private set; }
    }

    #region Exports

    [StructLayout(LayoutKind.Sequential)]
    private struct PROCESSORCORE
    {
        public byte Flags;
    };

    [StructLayout(LayoutKind.Sequential)]
    private struct NUMANODE
    {
        public uint NodeNumber;
    }

    private enum PROCESSOR_CACHE_TYPE
    {
        CacheUnified,
        CacheInstruction,
        CacheData,
        CacheTrace
    }

    [StructLayout(LayoutKind.Sequential)]
    private struct CACHE_DESCRIPTOR
    {
        public byte Level;
        public byte Associativity;
        public ushort LineSize;
        public uint Size;
        public PROCESSOR_CACHE_TYPE Type;
    }

    [StructLayout(LayoutKind.Explicit)]
    private struct SYSTEM_LOGICAL_PROCESSOR_INFORMATION_UNION
    {
        [FieldOffset(0)]
        public PROCESSORCORE ProcessorCore;
        [FieldOffset(0)]
        public NUMANODE NumaNode;
        [FieldOffset(0)]
        public CACHE_DESCRIPTOR Cache;
        [FieldOffset(0)]
        private UInt64 Reserved1;
        [FieldOffset(8)]
        private UInt64 Reserved2;
    }

    private enum LOGICAL_PROCESSOR_RELATIONSHIP
    {
        RelationProcessorCore,
        RelationNumaNode,
        RelationCache,
        RelationProcessorPackage,
        RelationGroup,
        RelationAll = 0xffff
    }

    private struct SYSTEM_LOGICAL_PROCESSOR_INFORMATION
    {
        public UIntPtr ProcessorMask;
        public LOGICAL_PROCESSOR_RELATIONSHIP Relationship;
        public SYSTEM_LOGICAL_PROCESSOR_INFORMATION_UNION ProcessorInformation;
    }

    [DllImport(@"kernel32.dll", SetLastError = true)]
    private static extern bool GetLogicalProcessorInformation(
        IntPtr Buffer,
        ref uint ReturnLength
    );

    private const int ERROR_INSUFFICIENT_BUFFER = 122;

    private static SYSTEM_LOGICAL_PROCESSOR_INFORMATION[] GetLogicalProcessorInformation()
    {
        uint ReturnLength = 0;
        GetLogicalProcessorInformation(IntPtr.Zero, ref ReturnLength);
        if (Marshal.GetLastWin32Error() == ERROR_INSUFFICIENT_BUFFER)
        {
            IntPtr Ptr = Marshal.AllocHGlobal((int)ReturnLength);
            try
            {
                if (GetLogicalProcessorInformation(Ptr, ref ReturnLength))
                {
                    int size = Marshal.SizeOf(typeof(SYSTEM_LOGICAL_PROCESSOR_INFORMATION));
                    int len = (int)ReturnLength / size;
                    SYSTEM_LOGICAL_PROCESSOR_INFORMATION[] Buffer = new SYSTEM_LOGICAL_PROCESSOR_INFORMATION[len];
                    IntPtr Item = Ptr;
                    for (int i = 0; i < len; i++)
                    {
                        Buffer[i] = (SYSTEM_LOGICAL_PROCESSOR_INFORMATION)Marshal.PtrToStructure(Item, typeof(SYSTEM_LOGICAL_PROCESSOR_INFORMATION));
                        Item += size;
                    }
                    return Buffer;
                }
            }
            finally
            {
                Marshal.FreeHGlobal(Ptr);
            }
        }
        return null;
    }

    [DllImport(@"kernel32.dll", SetLastError = true)]
    private static extern int GetCurrentProcessorNumber();

    #endregion
}

Usage example:
for (var i = 0; i < Processor.HardwareCores.Length; ++i)
{
    Console.WriteLine("Hardware Core {0} has logical cores {1}", i,
        string.Join(", ", Processor.HardwareCores[i].LogicalCores));
}
Console.WriteLine("All logical cores: " + string.Join(", ", Processor.LogicalCores));
Console.WriteLine("Current Logical Core is " + Processor.CurrentLogicalCore);

Example outputs for Intel Core i5:
Hardware Core 0 has logical cores 0, 1
Hardware Core 1 has logical cores 2, 3
All logical cores: 0, 1, 2, 3
Current Logical Core is 2

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to get the highest accuracy with low number of selected features using xgboost? I have been looking for several feature selection methods and found about the feature selection with help of XGBoost from the following link (XGBoost feature importance and selection). I implemented the method for my case, and results were the following:

*

*Thresh= 0.000, n= 11, Accuracy: 55.56%

*Thresh= 0.000, n= 11, Accuracy: 55.56%

*Thresh= 0.000, n= 11, Accuracy: 55.56%

*Thresh= 0.000, n= 11, Accuracy: 55.56%

*Thresh= 0.097, n= 7, Accuracy: 55.56%

*Thresh= 0.105, n= 6, Accuracy: 55.56%

*Thresh= 0.110, n= 5, Accuracy: 50.00%

*Thresh= 0.114, n= 4, Accuracy: 50.00%

*Thresh= 0.169, n= 3, Accuracy: 44.44%

*Thresh= 0.177, n= 2, Accuracy: 38.89%

*Thresh= 0.228, n= 1, Accuracy: 33.33%

So, my question is the following, for this case how can I select the highest accuracy with a low number of features [n]? [The code can be found in the link]
Edit 1:
Thanks to @Mihai Petre, I managed to get it to work with code in his answer. I have another question, say I ran the code from the link and got the following:
Feature Importance results = [29.205832   5.0182242  0.         0.         0. 6.7736177 16.704327  18.75632    9.529003  14.012676   0.       ]
Features = [ 0  7  6  9  8  5  1 10  4  3  2]

*

*Thresh= 0.000, n= 11, Accuracy: 38.89%

*Thresh= 0.000, n= 11, Accuracy: 38.89%

*Thresh= 0.000, n= 11, Accuracy: 38.89%

*Thresh= 0.000, n= 11, Accuracy: 38.89%

*Thresh= 0.050, n= 7, Accuracy: 38.89%

*Thresh= 0.068, n= 6, Accuracy: 38.89%

*Thresh= 0.095, n= 5, Accuracy: 33.33%

*Thresh= 0.140, n= 4, Accuracy: 38.89%

*Thresh= 0.167, n= 3, Accuracy: 33.33%

*Thresh= 0.188, n= 2, Accuracy: 38.89%

*Thresh= 0.292, n= 1, Accuracy: 38.89%

How can I remove the features that gave out zero feature importance and get the features with feature importance values?
Side Questions:

*

*I am trying to find the best feature selection that involves using
specific classification model and best features that help to give
high accuracy, say, for example, using KNN classifier and would like
to find the best features that give out high accuracy. What feature
selection would be appropriate to use?

*When Implementing multiple classification models, is it best to do feature selection for each classification model or you need to do feature selection once and then use the selected features to multiple classification models?

A: Ok, so what the guy in your link is doing with
thresholds = sort(model.feature_importances_)
for thresh in thresholds:
    # select features using threshold
    selection = SelectFromModel(model, threshold=thresh, prefit=True)
    select_X_train = selection.transform(X_train)
    # train model
    selection_model = XGBClassifier()
    selection_model.fit(select_X_train, y_train)
    # eval model
    select_X_test = selection.transform(X_test)
    predictions = selection_model.predict(select_X_test)
    accuracy = accuracy_score(y_test, predictions)
    print("Thresh=%.3f, n=%d, Accuracy: %.2f%%" % (thresh, select_X_train.shape[1], accuracy*100.0))

is to create a sorted array of thresholds and then he trains the XGBoost for every element of the thresholds array.
From your question, I'm thinking you want to only select the 6th case, the one with the lowest number of features and highest accuracy. For this case, you'd want to do something like this:
selection = SelectFromModel(model, threshold=threshold[5], prefit=True)
select_X_train = selection.transform(X_train)
selection_model = XGBClassifier()
selection_model.fit(select_X_train, y_train)
select_X_test = selection.transform(X_test)
predictions = selection_model.predict(select_X_test)
accuracy = accuracy_score(y_test, predictions)
print("Thresh=%.3f, n=%d, Accuracy: %.2f%%" % (threshold[5], select_X_train.shape[1], accuracy*100.0))

If you want to automate the whole thing, then you'd want to calculate the minimum n for which the accuracy is at its maximum inside that for loop, and it would look more or less like this:
n_min = *your maximum number of used features*
acc_max = 0
thresholds = sort(model.feature_importances_)
obj_thresh = thresholds[0]
for thresh in thresholds:
    selection = SelectFromModel(model, threshold=thresh, prefit=True)
    select_X_train = selection.transform(X_train)
    selection_model = XGBClassifier()
    selection_model.fit(select_X_train, y_train)
    select_X_test = selection.transform(X_test)
    predictions = selection_model.predict(select_X_test)
    accuracy = accuracy_score(y_test, predictions)
    if(select_X_train.shape[1] < n_min) and (accuracy > acc_max):
        n_min = select_X_train.shape[1]
        acc_max = accuracy
        obj_thresh = thresh

selection = SelectFromModel(model, threshold=obj_thresh, prefit=True)
select_X_train = selection.transform(X_train)
selection_model = XGBClassifier()
selection_model.fit(select_X_train, y_train)
select_X_test = selection.transform(X_test)
predictions = selection_model.predict(select_X_test)
accuracy = accuracy_score(y_test, predictions)
print("Thresh=%.3f, n=%d, Accuracy: %.2f%%" % (obj_thresh, select_X_train.shape[1], accuracy*100.0))

A: I managed to sort it out. Please find the code below:
To get the lowest number of features with the highest accuracy:
# Fit the model:
f_max = 8
f_min = 2
acc_max = accuracy
thresholds = np.sort(model_FS.feature_importances_)
obj_thresh = thresholds[0]
accuracy_list = []
for thresh in thresholds:
    # select features using threshold:
    selection = SelectFromModel(model_FS, threshold=thresh, prefit=True)
    select_X_train = selection.transform(X_train)
    # train model:
    selection_model = xgb.XGBClassifier()
    selection_model.fit(select_X_train, y_train)
    # eval model:
    select_X_test = selection.transform(X_test)
    selection_model_pred = selection_model.predict(select_X_test)
    selection_predictions = [round(value) for value in selection_model_pred]
    accuracy = accuracy_score(y_true=y_test, y_pred=selection_predictions)
    accuracy = accuracy * 100
    print('Thresh= %.3f, n= %d, Accuracy: %.2f%%' % (thresh, select_X_train.shape[1], accuracy))
    accuracy_list.append(accuracy)
    if(select_X_train.shape[1] < f_max) and (select_X_train.shape[1] >= f_min) and (accuracy >= acc_max):
        n_min = select_X_train.shape[1]
        acc_max = accuracy
        obj_thresh = thresh
# select features using threshold:
selection = SelectFromModel(model_FS, threshold=obj_thresh, prefit=True)
select_X_train = selection.transform(X_train)
# train model:
selection_model = xgb.XGBClassifier()
selection_model.fit(select_X_train, y_train)
# eval model:
select_X_test = selection.transform(X_test)
selection_model_pred = selection_model.predict(select_X_test)
accuracy = accuracy_score(y_test, predictions)
selection_predictions = [round(value) for value in selection_model_pred]
accuracy = accuracy_score(y_true=y_test, y_pred=selection_predictions)
print("Selected: Thresh=%.3f, n=%d, Accuracy: %.2f%%" % (obj_thresh, select_X_train.shape[1], accuracy*100.0))
key_list = list(range(X_train.shape[1], 0, -1))
accuracy_dict = dict(zip(key_list, accuracy_list))
optimum_num_feat = n_min
print(optimum_num_feat)

# Printing out the features:
X_train = X_train.iloc[:, optimum_number_features]
X_test = X_test.iloc[:, optimum_number_features]

print('X Train FI: ')
print(X_train)
print('X Test FI: ')
print(X_test)

To get the features with importance values without zero importance values:
# Calculate feature importances
importances = model_FS.feature_importances_
print((model_FS.feature_importances_) * 100)

# Organising the feature importance in dictionary:
## The key value depends on your maximum number of features:
key_list = range(0, 11, 1)
feature_importance_dict = dict(zip(key_list, importances))
sort_feature_importance_dict = dict(sorted(feature_importance_dict.items(), key=lambda x: x[1], reverse=True))
print('Feature Importnace Dictionary (Sorted): ', sort_feature_importance_dict)

# Removing the features that have value zero in feature importance:
filtered_feature_importance_dict = {x:y for x,y in sort_feature_importance_dict.items() if y!=0}
print('Filtered Feature Importnace Dictionary: ', filtered_feature_importance_dict)
f_indices = list(filtered_feature_importance_dict.keys())
f_indices = np.asarray(f_indices)
print(f_indices)

X_train = X_train.loc[:, f_indices]
X_test = X_test.loc[:, f_indices]

print('X Train FI: ')
print(X_train)
print('X Test FI: ')
print(X_test)


text:
Q: HP 255 G3 running Ubuntu 12.04 LTS I can't seem to get my Atheros wireless card to connect. I plugged in an Ethernet cable and applies my updates and checked driver updates but I can't get this laptop to connect wirelessly. What am I missing please help.
sudo lspci just states I have a Qualcomm Atheros QCA9565 card it won't let me post images
$ sudo rfkill list
Soft blocked: no
Hard blocked: no

A: I had an hp laptop, and suffered with similar problems, you can try these things:

*

*if you are dual booting, restart from windows rather than shut down. This works in most cases, if its showing wifi disabled by hardware switch

*Plugin your Ethernet cable. Go to settings -> software and updates -> additional drives, there you might find needed driver to download and install.

*Sometimes there is a firmware missing. When you boot up ubuntu, after showing ubuntu logo, some text lines appear quoting firmware/driver missing. Search for that firmware online. My broadcam firmware was missing and downloading one fixed it.
These steps helped me, if they don't work for you, i will try finding some other ways.

A: You can get your wifi working using backports
wget https://www.kernel.org/pub/linux/kernel/projects/backports/2015/09/03/backports-20150903.tar.gz
tar -zxvf backports-20150903.tar.gz
cd backports-20150903
make defconfig-wifi
make
sudo make install
Reboot
After a kernel update the backports will need to be reinstalled with

cd backports-20150903
make clean
make defconfig-wifi
make
sudo make install
And reboot


text:
Q: RabbitMQ does not load the advanced.config file We are looking to upgrade to the latest version of RabbitMQ so I have installed Erlang 24.0 and RabbitMQ 3.8.16 onto a Windows 10 PC for testing. I have the two RabbitMQ configuration files (rabbitmq.conf and advanced.config) stored in a folder called C:\RabbitMQ. The advanced.config contains static shovel configuration. I cannot get RabbitMQ to recognise the advanced.config file. Has anyone encountered this problem before?
We have earlier installs of RabbitMQ (i.e. Erlang 22.1 an RabbitMQ 3.8.2) running on Windows Server 2019 and these earlier versions load both config files with no issues.
All of our RabbitMQ installations store the config files in a folder called C:\RabbitMQ. We then set three environment variables to ensure that RabbitMQ recognises the folder and files:

*

*RABBITMQ_ADVANCED_CONFIG_FILE - C:\RabbitMQ\advanced

*RABBITMQ_BASE - C:\RabbitMQ

*RABBITMQ_CONFIG_FILE - C:\RabbitMQ\rabbitmq

I have followed the advice on the RabbitMQ config page https://www.rabbitmq.com/configure.html with regard to verifying the config file location.
I have also run the rabbitmq-diagnostics command which shows that only one config file is being loaded:

If I run the same command on our earlier installation then I can see that both files are being loaded:

A: We tested it internally and everything works as expected.
Note that:
RABBITMQ_ADVANCED_CONFIG_FILE=/path/to/a/custom/location/advanced.config

you need to add .config
see:
RABBITMQ_CONFIG_FILE=/path/to/a/custom/location/rabbitmq.conf

# overrides advanced config file location
RABBITMQ_ADVANCED_CONFIG_FILE=/path/to/a/custom/location/advanced.config

here: https://www.rabbitmq.com/configure.html


text:
Q: How to create post comment from different domain Using an API plugin i have been able to build a site that combines content from multiple Wordpress websites. I want to give users the ability to quickly leave a comment for one of these posts without having to navigate to the source website. I was able to copy the comment code from the source site, but the form redirects to the source website.
I was thinking the easiest way around all of this would be to just directly insert the comment into wp_comments. The table structure is very simple and shouldnt cause any trouble. Is this the best solution or is there something i am unaware of that could solve this problem.

A: This quite rare setup so it is hard to recommend one way or another.
Having worked with comments before I would recommend to stick with WordPress API functions (wp_insert_comment() and so on) for manipulating them. While DB structure is indeed simple you don't account for all the hooks firing and other things that might be happening.
For example once in the past I had been deleting comments from database directly for reasons... And then one day found years worth of orphan metadata for them that had been left behind. :)


text:
Q: OpenPGP Signature Packet hashed data RFC 4880 describes the version 4 signature packet, tag 2, as
- One-octet signature type.
- One-octet public-key algorithm.
- One-octet hash algorithm.
- Two-octet scalar octet count for following hashed subpacket data.
Note that this is the length in octets of all of the hashed
subpackets; a pointer incremented by this number will skip over
the hashed subpackets.
- Hashed subpacket data set (zero or more subpackets).
- Two-octet scalar octet count for the following unhashed subpacket
data. Note that this is the length in octets of all of the
unhashed subpackets; a pointer incremented by this number will
skip over the unhashed subpackets.
- Unhashed subpacket data set (zero or more subpackets).
- Two-octet field holding the left 16 bits of the signed hash
value.
- One or more multiprecision integers comprising the signature.

and i assume that the second to last line means just take the string of the hashed subpacket and hash it with the hash algorithm and take its first 2 bytes. however, no matter what i do, i cannot seem to get it.
I generated this fake key a long time ago
-----BEGIN PGP PUBLIC KEY BLOCK-----
Version: BCPG v1.39

mQGiBE5B0h8RBAD533Z5bK1IpBx02QyQL0QoJE4uFRIMGDiwXuwmZzVl+R7Vlurd
GRLsCCbE6vOOh7XQVZGzLEBy9WNzZ9m+EbCfSVAYkjS6FhLws6hG6irrnS+b3JBf
gFJ8vNGF9Z7bhx+7y7NBk0IMyWkGnUkcnav73t5FQUI2faEBN4c/yAGJZwCgjcB7
3akWk9XVWvTCsiMXxpyvkukEALXsvB6cOoFEtQq9cQHjP63fBlvD94dhhMiM0cH6
hW9JotxdK+cxFGG9ZIWgoN2PWbMJka/H4W5EL6tS+YiNAR7I1Ozkt6X16GjnQUzZ
MlSpleK+KiKVN2anRaPEoOIinHrE3ZXd6QlJ/4+OJn4IVWmSEaJpFf4QNgvEu4rh
xinyBAD2RNzREOA+wpnFZ4lDt9NZXmXdxQME/l0J9XcvWhpGsxA/MATQKImy7N49
7GT/M38F+TrpBobag1O3buE99fOLyws4Tbc+sZMdHxoiGZDAIRNQS2rv475E6ktj
7vd5CYvOkA6+8sX1+hPcNlkHtHB1OFkJRsYp6k0zkyC9adjBM7QTYWJjIDxtYWtj
bUBhYWEuY29tPohGBBMRAgAGBQJOQdIfAAoJEDBSJUXPd92GRSQAoItbtbToOg7a
/hcg2sA/aBEQNwuxAKCGR69vmSoCWoBP5waPk0UsjM3BSbjMBE5B0h8QAgCUlP7A
lfO4XuKGVCs4NvyBpd0KA0m0wjndOHRNSIz44x24vLfTO0GrueWjPMqRRLHO8zLJ
S/BXO/BHo6ypjN87Af0VPV1hcq20MEW2iujh3hBwthNwBWhtKdPXOndJGZaB7lsh
LJuWv9z6WyDNXj/SBEiV1gnPm0ELeg8Syhy5pCjMAf9QHehP2eCFqfEwTAnaOlA6
CU+rYHKPZaI9NUwCA7qD2d93/l08/+ZtFvejZW1RWrJ8qfLDRtlPgRzigoF/CXbR
iEYEGBECAAYFAk5B0h8ACgkQMFIlRc933YZRrACfUnWTjHHN+QsEEoJrwRvFmvzj
bR4An24pTpeeN+I6R59O/sdmYsAhjULX
=sStS
-----END PGP PUBLIC KEY BLOCK-----

what i think im supposed to do:
sha1("\x05\x02\x4e\x41\xd2\x1f") = "52f07613cfd61c80d2343566a8f3f487a0975b80"

\x05 - length of subpacket
\x02 - subpacket type
\x4e\x41\d2\x1f - creation time

From pgpdump.net, i see that the left 2 bytes of the hash (SHA 1) value is 45 24 for the first signature packet and 51 ac for the second one. i am getting 52 f0 for both. obviously, im not including some information, but what is it? the hashed subpackets are identical, and all of the data before the hashed data are the same as well except they are different types of signature packets (0x13 / 0x18). i have been unable to get either of the correct hash values even when i add/take characters from the data packet. the key im generating is exactly the same as the key shown here except for the hash values.
what is the data that i should be hashing??
edit: if found this a little later on:
The concatenation of the data being signed and the signature data
from the version number through the hashed subpacket data (inclusive)
is hashed. The resulting hash value is what is signed. The left 16
bits of the hash are included in the Signature packet to provide a
quick test to reject some invalid signatures.

but what is the data being signed? all packets before the signature? just the packet before the current signature packet?
the key example up there is made up of packet 6 + packet 13 + packet 2 + packet 14 + packet 2. i have tried all sorts of combinations of packet 6, packet 13, and packet 2 (from version number to hashed data inclusive), but still cannot find the string that hashes to the correct values

A: When you generate a signature packet, it's always a signature of something by someone. That is, there's some blob of data being signed, and a public key, and the point of a signature is that it's something that's only supposed to be able to be made by someone who has that exact data and the corresponding private key.
So "the data being signed" will be whatever that blob of data happens to be. See section 5.2.1 of RFC4880 for some examples. In the present case, presumably you're interested in the signature packets inside your public key block.
The first one is a "Positive certification of a User ID and Public Key packet(0x13)". This is described in section 5.2.4 of RFC4880.
The second one is a "subkey binding signature", whereby the primary key (the DSA one) guarantees that the subkey (ElGamal encrypt-only) belongs to it. The way this works is also described in section 5.2.4 of RFC4880.
Here's the relevant text from 5.2.4:

When a signature is made over a key, the hash data starts with the
  octet 0x99, followed by a two-octet length of the key, and then body
  of the key packet.  (Note that this is an old-style packet header for
  a key packet with two-octet length.)  A subkey binding signature (type
  0x18) or primary key binding signature (type 0x19) then hashes the
  subkey using the same format as the main key (also using 0x99 as the
  first octet).  Key revocation signatures (types 0x20 and 0x28) hash
  only the key being revoked.

and then

A certification signature (type 0x10 through 0x13) hashes the User ID
  being bound to the key into the hash context after the above data.  A
  V3 certification hashes the contents of the User ID or attribute
  packet packet, without any header.  A V4 certification hashes the
  constant 0xB4 for User ID certifications or the constant 0xD1 for User
  Attribute certifications, followed by a four-octet number giving the
  length of the User ID or User Attribute data, and then the User ID or
  User Attribute data.


text:
Q: How to prevent pip install the latest version package if the package has installed For example, currently my env is pytorch 1.10.1+cuda102, then i want to install yolov5(https://pypi.org/project/yolov5/) by pip install yolov5, but when i execute this command, pip will uninstall pytorch1.10.1+cuda102, and install pytorch 1.11.0 cpu, this is not what i want, i want to keep pytorch at 1.10(1.11 has some bug) and keep it with gpu version.
So when i am executiing pip install somepackage or pip install -r requirements.txt, how to make pip not to install the latest version if the package has already installed and satisfy the version requirement , while if the package not installed, then just install its latest version ?


text:
Q: Python 3 POST request to handle form data I can't figure out how to correctly set up a POST request with the following data:
General
Request URL: https://myurl.com/install/index.cgi
Request Method: POST

Request Headers
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en
Cache-Control: max-age=0
Connection: keep-alive
Content-Length: 48
Content-Type: application/x-www-form-urlencoded
Host: myurl.com
Origin: https://myurl.com
Referer: https://myurl.com/install/
Upgrade-Insecure-Requests: 1
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64)

Form Data
page: install
state: STATUS

I can do the following:
import requests

headers = {"Accept":"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8",
    "Accept-Encoding":"gzip,deflate,br",
    "Accept-Language":"en-US,en;q=0.8",
    "Cache-Control":"max-age=0",
    "Connection":"keep-alive",
    "Content-Length":"48",
    "Content-Type":"application/x-www-form-urlencoded",
    "Host":"myurl.com",
    "Origin":"https://myurl.com",
    "Referer":"https://myurl.com/install/?s=ROM",
    "User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/537.36"}

f = requests.put(path, headers=headers)

But how do I handle the form data? Under the form data there is a page: install and a state: STATUS.
How do I include this on my POST request?

A: Just add data= to your request:
import requests

path = ...
headers = ...
form_data = {
    "page": "install",
    "state": "STATUS",
}

f = requests.put(path, headers=headers, data=form_data)

A: I presume you know how to use the developer tools on the browser of your choice. The following is a template I follow:
Load the page (GET)
Use XPATH to find_element_by_id I'm targeting, i.e. username
Set XPATH to SetValue of such element
Post the page (POST)


text:
Q: AVMutableCompositionTrack - insertTimeRange - insertEmptyTimeRange issue I have a strange problem: I want to generate a new sound file out of two soundfiles and silence.
sound1: 2 seconds long
+
silence: 2 seconds silence
+
sound2: 2 seconds long
When I try the code below, I get a 6 seconds long soundfile with all the parts, but in a different order! The order is: sound1, sound2, silence
I am not able to put this silence in the middle of this composition (also not at the beginning). Is this a typical behavior or do I something wrong?
Here is the code for putting the segments together:
[compositionAudioTrack insertTimeRange:CMTimeRangeMake(kCMTimeZero, [audio1 duration])  ofTrack:clipAudioTrack1 atTime:kCMTimeZero error:nil];
[compositionAudioTrack insertEmptyTimeRange:CMTimeRangeMake(kCMTimeZero, CMTimeMake(2, 1))];
[compositionAudioTrack insertTimeRange:CMTimeRangeMake(kCMTimeZero, [audio2 duration])  ofTrack:clipAudioTrack2 atTime:CMTimeMake(4, 1) error:nil];

Perhaps someone has an idea? Thank you in advance!
By the way: following code without the insertEmptyTimeRange-line doesn't work either, it just generates 4 seconds of sound and sound2 slides to the end of sound1:
    [compositionAudioTrack insertTimeRange:CMTimeRangeMake(kCMTimeZero, [audio1 duration])  ofTrack:clipAudioTrack1 atTime:kCMTimeZero error:nil];
[compositionAudioTrack insertTimeRange:CMTimeRangeMake(kCMTimeZero, [audio2 duration])  ofTrack:clipAudioTrack2 atTime:CMTimeMake(4, 1) error:nil];

It seems that it is not allowed that there is "nothing" between segments!?

A: Still don't know what this "insertEmptyTimeRange" means. I made a work around with a "silence"-audio file which has nothing in it. I put this empty audio file between the two sound files and this does it for me. Question closed ;)
(But if someone could explain this "insertEmptyTimeRange" this would be still interesting...)

A: I got it working as follows:
[compositionAudioTrack insertTimeRange:CMTimeRangeMake(kCMTimeZero, CMTimeMake(2,1))
                               ofTrack:audioTrack
                                atTime:kCMTimeZero
                                error:nil];
[compositionAudioTrack insertEmptyTimeRange:CMTimeRangeMake(CMTimeMake(2, 1), CMTimeMake(4, 1))];
[compositionAudioTrack insertTimeRange:CMTimeRangeMake(kCMTimeZero, CMTimeMake(2,1))
                               ofTrack:audioTrack
                                atTime:CMTimeMake(4, 1)
                                 error:nil];

The "empty time range" needs to be (2,4) if your sounds are from (0,2) and (4,6).

A: Not sure if its late,
insertEmptyTimeRange : If you insert an empty time range into the track, any media that was presented during that interval prior to the insertion will be presented instead immediately afterward.
So all you have to do is add both the clips first and then add the emptytime range at time 2.
This should work
insertTimeRange(0 to 2)
insertTimeRange(2 to 4)
insertEmptyTimeRange(2 to 4)


text: Q: Mockito - Mocking a Selenium WebElement object in Java? I'm writing a screen-scraper that scrapes items off a specific ecommerce cite. I have been thinking about a possible way to write unit tests for this code. This would involve mocking external dependencies (in my case the website I happen to be scraping from). How would I use mockito to mock the return of a Selenium WebElement object? The language I'm using in this case is Java.


text:
Q: pitfalls with mixing storage engines in mysql with django? I'm running a django system over mysql in amazon's cloud, and the database default is innodb. But now I want to put a fulltext index on a couple of tables for searching, which evidently requires myisam.
The obvious solution is to just tell mysql to ALTER TABLE to myisam, but are there going to be any issues with that?
One that comes to mind is that I'll have to remember to do that any time I build a new version of the database, which should theoretically be rare, but there doesn't seem to be a way to tell django to please set the storage engine at the table level. I guess I could write a migration (we use south).
Any other things I might be missing? What could possibly go wrong?

A: Will the application notice?  Probably not.
Will it cause problems?  Only when things go wrong.  MyISAM is not a transactional storage engine.  If you change the data in a MyISAM table while inside of a transaction, then have to roll back changes, the changes in that table won't be rolled back.  It's been a while since I tried to break it horribly, but I'm willing to wager that MySQL won't even issue a warning when this happens.  This will lead to data consistency issues.
You should seriously consider external search software instead of a fulltext index, like ElasticSearch (integrates at the application level), or Sphinx (integrates at the MySQL level, though if you're using RDS instead of MySQL directly, I don't think you'll be able to use it).

A: the following may be of help:

use a myisam fulltext table to index back into your innodb tables for example:
  Build your system using innodb:...

Any way to achieve fulltext-like search on InnoDB


text:
Q: Jframe.setContentPane(new JLabel([image])); background image not loading after built .jar I am having a problem with loading images, as I am trying to load a background for my launcher. It works when I run it in Eclipse, but when I export it to a jar file, it doesn't. I have paged through the already asked questions, No luck.
Here is my code:
public void initializeJFrame(){

    ImageIcon bg = new ImageIcon("src/background.png");

    jb.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            if (jta.getText().length() < 3 || jta.getText().length() > 16) {
                System.exit(-1);
            } else {
                try {
                    Runtime.getRuntime().exec(cmd, null, dir);
                } catch (IOException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }
                System.exit(0);
            }
        }

    });
    jf.setSize(WIDTH,HEIGHT);
    jf.setTitle("Cracked Launcher");
    jf.setLayout(null);
    jf.setContentPane(new JLabel(bg));
    jf.setResizable(false);
    jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    t.start();

My image is in the src folder, nothing else. I cannot find what the problem is.
Thanks for your support.

A: ImageIcon bg = new ImageIcon("src/background.png");

This constructor takes a filename; it will not load resources from a jar. You want to pass a URL generated by a classloader, like so:
ImageIcon bg = new ImageIcon(getClass().retResource("background.png"));


text:
Q: Flutter- per my code how to make material button invisible on swiping left and re-appear on swiping right I am creating  an APP which has a lot of emphasis on the image in the background as such, their is text in arabic on that image per line and I want to add "material buttons" on top of this text. I was able to do this ...but then I want the button to be invisible once I swipe left, and re-appear when I swipe to the right, I did use gesture Detector and it does print on the screen if  I swipe right or swipe left ..I was trying to input the gesture detector within the material button but everytime  I try this it sends an error that's why I have the gesture detector on the bottom of the whole code please help ...
please help
import 'dart:io';
import 'package:Quran_highlighter/main.dart';
import 'package:flutter/rendering.dart';
import 'package:system_shortcuts/system_shortcuts.dart';
import 'package:Quran_highlighter/Widgets/NavDrawer.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:zoom_widget/zoom_widget.dart';
import 'package:flutter/gestures.dart';

class Aliflaammeem extends StatefulWidget {
  @override
  _AliflaammeemState createState() => _AliflaammeemState();
}

class _AliflaammeemState extends State<Aliflaammeem> {
  var nameList = new List<String>();
    final items = List<String>.generate(20, (i) => "Item ${i + 1}");

  List<MaterialButton> buttonsList = new List<MaterialButton>();

  @override
  void initState(){
    super.initState();
    nameList.add("I love");
    nameList.add("my ALLAH");
    nameList.add("SWT Very Much");

List<Widget> buildButtonswithName(){
  int length = nameList.length;
  for (int i=0; i<length; i++){
    buttonsList.add(new MaterialButton(
      height:40.0,
      minWidth: 300.0,
      color: Colors.blue,
      textColor: Colors.white,

  ));
  }
}  }

List<String> labels = ['apple', 'banana', 'pineapple', 'kiwi'];
// List<VoidCallback> actions = [_buyApple, _doSomething, _downloadData, () => print('Hi')
// ];
   bool _visible = true;
  int _counter = 0;
  double _initial = 0.0;

  var textHolder = "";

  changeTextEnglish() {
    setState(() {
      bool _visible = true;
         _visible =  _visible;
      textHolder = "All Praise and Thanks is to Allah the lord of the worlds";
    });
  }

  changeTextArabic() {
    bool _visible = true;
    setState(() {
      _visible =  _visible;
    });
  }

  @override
  Widget build(BuildContext context) {
    final title = 'Dismissing Items';
    // appBar: AppBar(
    //   title: Text('Para 1, Pg2'),
    //   backgroundColor: Colors.teal[400],

    // SystemChrome.setPreferredOrientations(
    //     [DeviceOrientation.landscapeLeft, DeviceOrientation.landscapeRight]);
    return Scaffold(
        body: Center(
            child: Stack(fit: StackFit.expand, children: <Widget>[
      Stack(
        children: <Widget>[
          SingleChildScrollView(
            scrollDirection: Axis.vertical,
            child: SafeArea(
              top: true,
              bottom: true,
              right: true,
              left: true,
              child: Image(
                  image: AssetImage('test/assets/quranpg0.png'),
                  fit: BoxFit.cover
              ),
            ),
          ),
        ],
          ),

      Stack(
        children: <Widget>[
        // for(int i = 0; i< labels.length; i++)
        // weather_app/lib/page/settings_page.dart -- line ~81
    // ListView.builder(
    //       itemCount: items.length,
    //       itemBuilder: (context, index) {
    //         final item = items[index];

    //         return Dismissible(
    //           // Each Dismissible must contain a Key. Keys allow Flutter to
    //           // uniquely identify widgets.
    //           key: Key(item),
    //           // Provide a function that tells the app
    //           // what to do after an item has been swiped away.
    //           onDismissed: (direction) {
    //             // Remove the item from the data source.
    //             setState(() {
    //               items.removeAt(index);
    //             });
    //         // Then show a snackbar.
    //             Scaffold.of(context)
    //                 .showSnackBar(SnackBar(content: Text("$item dismissed")));
    //           },
    //           // Show a red background as the item is swiped away.
    //           background: Container(color: Colors.green),
    //           secondaryBackground: Container(color: Colors.red),
    //           child: ListTile(title: Text('$item'))

    //         );
    //           },
    //         ),

        Container(
          child: Align(
            alignment: Alignment(.27, 0.1
            ),
          //   child: Visibility(
          // visible: _visible,
          // maintainSize: true,
          // maintainAnimation: true,
          // maintainState: true,
              child: MaterialButton(
              height: 70.0,
              // minWidth: 36.5,
              minWidth: 85.0,
              onPressed: () => changeTextArabic(),
              onLongPress: () => changeTextEnglish(),
              // child: Text(labels[i]),
              child: Text('$textHolder'),
              color: Colors.cyan[400],
              // color: Colors.purple[300],
              highlightColor: Colors.blue,
              textColor: Colors.white,
              padding: EdgeInsets.only(left: 10, top: 2, right: -1, bottom: 5
              ),
              ),
            ),
            ),
            for(int i = 0; i< labels.length; i++)
               Container(
          child: Align(
            alignment: Alignment(-.5, 0.1
            ),
//  child: Text("The Most Loving",
//  style: TextStyle(
//    fontSize: 15.0,
//    backgroundColor: Colors.cyan,
//    height: 1.0,
//    fontWeight: FontWeight.bold
//    ),
            child: MaterialButton(
              height: 70.0,
              minWidth: 36.5,
              onPressed: () => changeTextArabic(),
              onLongPress: () => changeTextEnglish(),
              // Positioned(
              // top: 21,
              child: Text(labels[i]),
              disabledTextColor: Colors.transparent,
              color: Colors.cyan[300],
              // color: Colors.purple[300],
              highlightColor: Colors.blue,
              textColor: Colors.white,
              padding: EdgeInsets.only(left: 46, top: 2, right: -20, bottom: 5),
            ),
//  ),
          ),
        )
      ],
      ),
        GestureDetector(onPanUpdate: (DragUpdateDetails details) {
        if (details.delta.dx > 0) {
          print("right swipe english");
          changeTextEnglish();
          setState(() {

          });
        } else if (details.delta.dx < 0) {
          print("left swipe arabic");
          changeTextArabic();
          setState(() {
          });
        }
      })
    ])));
  }
}

A: I think I got want you want.
First I added a condition to display the MaterialButton like so:
(_visible) ? MaterialButton(...) : Container()

Then inside "changeTextEnglish" and "changeTextArabic":

*

*I changed _visible to absolute value

*I deleted your lines "bool _visible = ..." because here you where creating local variable inside the function and therefore could no longer access _visible as the attribute of _AliflaammeemState.

So "changeTextEnglish" and "changeTextArabic" became:
changeTextEnglish() {
    setState(() {
      _visible = true;
      textHolder = "All Praise and Thanks is to Allah the lord of the worlds";
    });
  }

changeTextArabic() {
    setState(() {
      _visible = false;
    });
  }

Which fives me the following working code (I deleted your comment to be able to see the issue so maybe don't copy paste the entire code.
class Aliflaammeem extends StatefulWidget {
  @override
  _AliflaammeemState createState() => _AliflaammeemState();
}

class _AliflaammeemState extends State<Aliflaammeem> {
  var nameList = new List<String>();
  final items = List<String>.generate(20, (i) => "Item ${i + 1}");

  List<MaterialButton> buttonsList = new List<MaterialButton>();

  @override
  void initState() {
    super.initState();
    nameList.add("I love");
    nameList.add("my ALLAH");
    nameList.add("SWT Very Much");
  }

  List<String> labels = ['apple', 'banana', 'pineapple', 'kiwi'];
  bool _visible = true;
  int _counter = 0;
  double _initial = 0.0;

  var textHolder = "";

  changeTextEnglish() {
    setState(() {
      _visible = true;
      textHolder = "All Praise and Thanks is to Allah the lord of the worlds";
    });
  }

  changeTextArabic() {
    setState(() {
      _visible = false;
    });
  }

  @override
  Widget build(BuildContext context) {
    final title = 'Dismissing Items';
    return Scaffold(
        body: Center(
            child: Stack(fit: StackFit.expand, children: <Widget>[
      Stack(
        children: <Widget>[
          SingleChildScrollView(
            scrollDirection: Axis.vertical,
            child: SafeArea(
              top: true,
              bottom: true,
              right: true,
              left: true,
              child: Image(image: AssetImage('test/assets/quranpg0.png'), fit: BoxFit.cover),
            ),
          ),
        ],
      ),
      Stack(
        children: <Widget>[
          Container(
            child: Align(
              alignment: Alignment(.27, 0.1),
              child: _visible
                  ? MaterialButton(
                      height: 70.0,
                      minWidth: 85.0,
                      onPressed: () => changeTextArabic(),
                      onLongPress: () => changeTextEnglish(),
                      child: Text('$textHolder'),
                      color: Colors.cyan[400],
                      highlightColor: Colors.blue,
                      textColor: Colors.white,
                      padding: EdgeInsets.only(left: 10, top: 2, right: -1, bottom: 5),
                    )
                  : Container(),
            ),
          ),
          for (int i = 0; i < labels.length; i++)
            Container(
              child: Align(
                alignment: Alignment(-.5, 0.1),
                child: MaterialButton(
                  height: 70.0,
                  minWidth: 36.5,
                  onPressed: () => changeTextArabic(),
                  onLongPress: () => changeTextEnglish(),
                  child: Text(labels[i]),
                  disabledTextColor: Colors.transparent,
                  color: Colors.cyan[300],
                  highlightColor: Colors.blue,
                  textColor: Colors.white,
                  padding: EdgeInsets.only(left: 46, top: 2, right: -20, bottom: 5),
                ),
//  ),
              ),
            )
        ],
      ),
      GestureDetector(onPanUpdate: (DragUpdateDetails details) {
        if (details.delta.dx > 0) {
          print("right swipe english");
          changeTextEnglish();
          setState(() {});
        } else if (details.delta.dx < 0) {
          print("left swipe arabic");
          changeTextArabic();
          setState(() {});
        }
      })
    ])));
  }
}


text:
Q: Integrating Azure Services with Route53 Hosted Domain I have a domain hosted on AWS Route53, but would like to enable Azure services such as Azure AD and 365 to be addressable on the same domain name.
Notably, I would like to keep the main domain under route53 control rather than delegating the entire address to Azure.
What would be the recommended method for integrating the 2 public cloud services, I am unsure if I should manually add CNAME records etc for the required Azure services or if I should look to delegate a subdomain to Azure's domain services directly (such as azure.example.com, while keeping example.com on route53).
Alternateively, should I register an entirely new domain (msexample.com) on azure, and if so how would I make these integrate email etc.
Thank you very much for any advice or direction on best-practices you can provide.


text:
Q: Xcode system clear and "expression result unused" error using C++ While attempting to code a Tic Tac Toe game in Xcode to practice C++, I'm running into all sorts of issues which I have mostly fixed but I'm still having trouble understanding why I'm getting the following errors and how to properly fix them/avoid them.
Problem 1:
I've linked the curses library but I still get this error:conversion from string literal to 'char*' is deprecated.
#include <unistd.h>
#include <term.h>
void ClearScreen()
{
if (!cur_term)
{
    int result;
    setupterm( NULL, STDOUT_FILENO, &result );
    if (result <= 0) return;
}
putp( tigetstr( "clear" ) );
}

Problem 2:
I keep getting an Unused Entity Issue (Expression result unused).
(gridBox is a 2-d array of type char and player is type char as well, both global variables.)
    if (gridBox[0,0] == gridBox[1,0] && gridBox[1,0] == gridBox[2,0]) {

    if (player == 'X') {
        return 'X';
    }
    if (player == 'O') {
        return 'O';
    }
}

Problem 3:
When I try changing the if statement in the last problem to...
    if (gridBox[0,0] == 'X' && gridBox[1,0] == 'X' && gridBox[2,0] == 'X') {
    return 'X';
}

I get this error:Comparison between pointer and integer ('char*' and 'int').
This is driving me completely insane, please help.
Thank you all in advance!

A: *

*Is just that: implicit conversion from a string literal, such as "clear", to a pointer to non-const char, char*, used to be allowed for historical reasons but has been deprecated because it's very unsafe.
This can cause some issues when interfacing with C libraries or old code, but is usually easily worked around.
Replace it with a non-const array:
char clear[] = "clear";
 putp(tigetstr(clear));

*Is caused by indexing the wrong way; a 2-D array is an array of arrays, and it is indexed like this:
gridBox[0][0]
The comma operator is used in some contexts if you want to evaluate two expressions in sequence and throw away the result of the first - a, b returns the value of b, so gridBox[0,0] is equivalent to gridBox[0].
It's quite rare in practice - so rare that compilers have started issuing warnings because it's almost never what you intend.

*Since gridBox is an array of arrays of char, and since because of point 2) gridBox[0,0] is  equivalent to gridBox[0], gridBox[0] is an array of char.
You can't compare arrays with ==. Instead, they are implicitly converted to pointers to the array's first element, which are then used for comparison.
Thus, the left hand side is a char*, and the right hand side is promoted to an int for comparison purposes, and those two can't be compared.
If you fix your indexing problem, this problem will disappear at the same time.


text:
Q: Find the leading order behavior of this coupled pair of ODE's The system of equations is $x^2y''=(x+1)y+xz$ and $x^2z''=-(x+1)z-xy$
I don't want the full answer, I just have no idea how to start. The techniques we were given were all for second order things and I'm not sure how to extend it to systems. If there is some trick with the equations let me know.
Also, the books says very explicitly not to approximate x+1 by x

A: You make a system of four equations out of your two equations.
$u_1=y, u_2=y', u_3=z, u_4=z'$
The system would be in terms of $u$ and $u'$ so you can linearize it.


text:
Q: Can you control the speed of a video clip playing in Quartz Composer? Is there a way to manipulate the speed of the video playback? I'm especially interested in a way to slow down with frame blending, exactly like the function in Final Cut Pro.

A: Currently it's not possible to do frame-blending using the built-in Movie Loader patch.
You can arbitrarily control the playback head, though.

*

*Insert a Movie Loader patch, and set the Movie Location.

*Connect it to a Billboard.  The movie should play at normal speed.

*Right-click on the patch, select Timebase, and then select External.  This gives the Movie Loader patch a Patch Time input, and freezes it at the first frame.

*

*The value you enter for Patch Time is the time offset, in seconds, at which the Movie Loader should render.

*Insert a Patch Time patch, and connect its output to the Movie Loader's Patch Time input.  The movie should again play at normal speed.

Now comes the fun part:

*

*Insert a Mathematical Expression patch and enter t/2 for the equation.

*Connect the Patch Time patch to the input of the Mathematical Expression, and the output of the Mathematical Expression to the Patch Time input of the Movie Loader patch --- the movie now plays at half speed.

You can alter the equation to change the playback rate --- t/3 will play at 1/3 speed, t*2 will play at double speed, and so forth.
However, if you change the playback rate equation while the movie's playing, you'll notice that the playback head jumps to a new position rather than continuing on from the previous time.
To solve this, you'll want to use the Integrator patch.

*

*Create an Integrator, set the Value to 1, and connect the Integrator's output to the Movie Loader's Patch Time input.  The movie should play from the beginning at normal speed.

*Change the Integrator's Value to 0.5.  The movie should play at half speed, continuing from the current position.

You can even play movies backwards using this technique (though, depending on what codec you use, it may severely impact performance).

A: Interpolation should be able to help you. There's an example included with Quartz Composer (Interpolation Modes.qtz) and a beginning tutorial here that breifly mentions it (step 5).
this wiki article also discusses it and talks about the different types.
Note: I don't actually have a Mac that can run QC, so this is just what I've been able to find through Google, but it sounds like it should get you on the right track.

A: v002 Movie Player (Beta) as a replacement for the built-in Movie Loader patch provides a Rate input. I have gotten very smooth video speed changes with that.

(I added the Playhead Seconds input; if anybody else would find that useful I'll post it.)


text:
Q: How to pass the data to vue from node.js, in nuxt.js ssr? I want to pass the firestore data to vue files from Node.js (Express). Because I must use firestore's getCollections() method. It cannot run in client side.
I build nuxt-ssr to deploy google-cloud-functions and cloud-hosting. I
 refer to this article.(https://itnext.io/how-to-create-a-ssr-serverless-app-with-firebase-nuxt-js-in-an-hour-6e6e03d0b3b8)
This directory structure is like below.
---public (deploy to cloud-hosting)
|
|-src (nuxt build to functions directory)
|
|-functions (have Node.js and deploy to cloud-functions)
|
|-firebase.json
:
I guess my purpose can achieved by index.js in functions dir. It looks like below.
const functions = require('firebase-functions')
const express = require('express')
const { Nuxt } = require('nuxt')

const app = express()

const config = {
  dev: false,
  buildDir: 'nuxt',
  build: {
    publicPath: '/'
  }
}
const nuxt = new Nuxt(config)

function handleRequest(req, res) {
  res.set('Cache-Control', 'public, max-age=600, s-maxage=1200')
  nuxt.renderRoute('/').then(result => {
    res.send(result.html)
  }).catch(e => {
    res.send(e)
  })
}

app.get('*', handleRequest)
exports.nuxtApp = functions.https.onRequest(app)

How I should change this code? Please give me your wisdom.

A: I had answer.
nuxt.renderRoute()can pass the data in argument as optional. (https://nuxtjs.org/api/nuxt-render-route)
So in functions dir, I should change the code like below.
  :
function handleRequest(req, res) {
  res.set('Cache-Control', 'public, max-age=600, s-maxage=1200')
  **req.data = "some data from firestore"**
  nuxt.renderRoute('/', **{ req }** ).then(result => {
    res.send(result.html)
  }).catch(e => {
    res.send(e)
  })
}
  :

And in src dir, vue.js file looks like below.
<template>
    <p>{{ apiResult }}</p>
</template>

<script>
export default {
  asyncData(context) {
    return { apiResult: context.req.data };
  }
}
</script>

<template>
</template>

It will view the req.data like some data from firestore.
I could achieve my purpose. Thank you guys!


text:
Q: FastCGI, SCGI,  I'm writing a web server in C, and I need to figure out a way to use CGI to execute dynamic content server-side.
I'm looking at the FastCGI protocol and it looks annoying. It reminds me of the bit twiddling I had to do in a class when I was converting ASCII to UTF-8 and back (that seemed useless then, but maybe it wasn't...)
I found a great library written in PHP where I could just start up php-cgi -b localhost:8888 and start communicating with it. Obviously, I'd like that in C.
I'd appreciate it if someone could find a library (for FastCGI clients!). If not, then I'm fine with contributing to the open source community by writing one.
Also, how exactly do I use SCGI? There's barely any documentation on it (that I can find, anyway). What socket do I connect to? Where do I send the requests?

Also, php-cgi is only for PHP, so how do things work for Perl, Python, etc?
Thanks again.

A: mario said (in the question comments):

*

*There are a few libraries mentioned on the FastCGI homepage. http://fastcgi.com/drupal/node/5. The development kit should include the server.

*The client implementation is included there for, too. http://fastcgi.com/devkit/doc/fcgi-devel-kit.htm

*SCGI http://python.ca/scgi/protocol.txt is extremely simple to implement even without reference code.

*You need an SCGI client that runs as deamon, and that accepts socket connections on an agreed port (4000 or 5000 seem common).

*SCGI is no different than FastCGI. Each language would require its own daemon, you can run multiple. And accepting CGI requests is pretty much what they do. The only difference is the socket and the header format instead of a CGI stdin pipe and env variables.

To this I'd like to add: CGI (which is exactly what the question asks for) is different from FCGI and SCGI in their working models. It's quite easy to mistake one for others. Luckily, it seems like Preetam asked for FCGI and SCGI.


text:
Q: estou tendo problemas em meu angular angular , quando vou da um npm start ele da essa mensagem
This likely means that the library (@angular/material/snack-bar) which declares MatSnackBar has not been processed correctly by ngcc, or is not compatible with Angular Ivy. Check if a newer version of the library is
available, and update if so. Also consider checking with the library's authors to see if the library is expected to be compatible with Ivy.

esta assim meus imports

app.module.ts

import { NgModule } from '@angular/core';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { HeaderComponent } from './components/template/header/header.component';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';

import { FooterComponent } from './components/template/footer/footer.component';
import { NavComponent } from './components/template/nav/nav.component'

import { MatToolbarModule } from '@angular/material/toolbar';
import { MatSidenavModule } from '@angular/material/sidenav'
import { MatCardModule } from '@angular/material/card'
import { MatListModule } from '@angular/material/list';
import { MatButtonModule } from '@angular/material/button';
import { MatSnackBar } from '@angular/material/snack-bar'
import { ProductCrudComponent } from './views/product-crud/product-crud.component';
import { ProductCreateComponent } from './components/products/product-create/product-create.component';
import { HomeComponent } from './views/home/home.component'

@NgModule({
  declarations: [
    AppComponent,
    HeaderComponent,
    FooterComponent,
    NavComponent,
    ProductCrudComponent,
    ProductCreateComponent,
    HomeComponent,
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    BrowserAnimationsModule,
    MatToolbarModule,
    MatSidenavModule,
    MatListModule,
    MatCardModule,
    MatButtonModule,
    MatSnackBar
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }```

A: Tente adicionar em package.json
"scripts": {
"postinstall": "ngcc"
}

A: Tente colocar Module após a MatSnackBar (isso no app.module.ts), como está abaixo:
import { MatSnackBarModule } from '@angular/material/snack-bar';

@NgModule({
  declarations: [
   ...
  ],
  imports: [
    MatSnackBarModule
  ],


text:
Q: I am building DSpace repository on Ubuntu 16.04 LTS I am building a DSpace repository on Ubuntu 16.04 LTS. I have installed all the prerequisite softwares according to the manual over here: https://wiki.duraspace.org/display/DSDOC5x/Installing+DSpace.
The build is successful, I can deploy the webapps. But when I try to add[screen after clicking search link][1]
[1]: https://i.stack.imgur.com/nlDDT.png click the search link this error comes up.
Bellow is the error details

Expected mime type application/octet-stream but got text/html.
  Apache Tomcat/8.0.39 - Error
  reportH1
  {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:22px;}
  H2
  {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:16px;}
  H3
  {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:14px;}
  BODY
  {font-family:Tahoma,Arial,sans-serif;color:black;background-color:white;}
  B
  {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;} P
  {font-family:Tahoma,Arial,sans-serif;background:white;color:black;font-size:12px;}A
  {color : black;}A.name {color : black;}.line {height: 1px;
  background-color: #525D76; border: none;}
  HTTP Status 403 - type Status reportmessage
description Access to the specified resource
  has been forbidden.Apache
  Tomcat/8.0.39

How can I bypass through this error. Please help.

A: It sounds like your Solr webapp is rejecting the HTTP request from the DSpace Discovery module. By default, the 'solr' WAR comes configured with a LocalHostRestrictionFilter which ensures that only the local machine can communicate directly with the solr cores like search, statistics, etc.
Make sure that in your $dspace/config/dspace.cfg configuration, your "solr.server" parameter is set correctly. If you're running everything on the same machine with default values, this should be something like
solr.server = http://localhost:8080/solr

And your $dspace/config/modules/discovery.cfg should say
discovery.search.server = ${solr.server}/search

If your solr instance is deployed to a different machine than the one running your XMLUI application / main DSpace instance, this would be expected behaviour. Even if it's all running on the same machine, perhaps solr is seeing an IP other than '127.0.0.1' (eg. ipv6 local address, or an address changed by SNAT, proxy address).
Your Tomcat access logs should give you an idea of which IP it's seeing (search for the entries with a 403 HTTP response code). If the IP you looks good but just happens not to match 127.0.0.1 (ipv6, a rewritten or proxied address) then you can alter the LocalHostRestrictionFilter valve to also allow that address. (just be careful not to open up access to more than you want!)
There is a guide on how to do this at https://wiki.duraspace.org/display/DSPACE/Solr#Solr-Bypassinglocalhostrestrictionpermanently


text:
Q: Android Studio can't sync project's gradle I can't build my project, I'm getting this error :
Gradle 'test' project refresh failed
Error:Cause: org/gradle/internal/typeconversion/TypeFilteringNotationConverter

with this stack trace in the IDE :
2015-10-08 08:09:23,172 [1172468]   WARN - nal.AbstractExternalSystemTask - Cause: org/gradle/internal/typeconversion/TypeFilteringNotationConverter
com.intellij.openapi.externalSystem.model.ExternalSystemException: Cause: org/gradle/internal/typeconversion/TypeFilteringNotationConverter
    at org.jetbrains.plugins.gradle.service.project.AbstractProjectImportErrorHandler.createUserFriendlyError(AbstractProjectImportErrorHandler.java:106)
    at org.jetbrains.plugins.gradle.service.project.BaseProjectImportErrorHandler.getUserFriendlyError(BaseProjectImportErrorHandler.java:158)
    at org.jetbrains.plugins.gradle.service.project.BaseGradleProjectResolverExtension.getUserFriendlyError(BaseGradleProjectResolverExtension.java:438)
    at com.android.tools.idea.gradle.project.AndroidGradleProjectResolver.getUserFriendlyError(AndroidGradleProjectResolver.java:348)
    at org.jetbrains.plugins.gradle.service.project.AbstractProjectResolverExtension.getUserFriendlyError(AbstractProjectResolverExtension.java:164)
    at org.jetbrains.plugins.gradle.service.project.GradleProjectResolver$ProjectConnectionDataNodeFunction.fun(GradleProjectResolver.java:366)
    at org.jetbrains.plugins.gradle.service.project.GradleProjectResolver$ProjectConnectionDataNodeFunction.fun(GradleProjectResolver.java:332)
    at org.jetbrains.plugins.gradle.service.project.GradleExecutionHelper.execute(GradleExecutionHelper.java:225)
    at org.jetbrains.plugins.gradle.service.project.GradleProjectResolver.resolveProjectInfo(GradleProjectResolver.java:97)
    at org.jetbrains.plugins.gradle.service.project.GradleProjectResolver.resolveProjectInfo(GradleProjectResolver.java:65)
    at com.intellij.openapi.externalSystem.service.remote.RemoteExternalSystemProjectResolverImpl$1.produce(RemoteExternalSystemProjectResolverImpl.java:41)
    at com.intellij.openapi.externalSystem.service.remote.RemoteExternalSystemProjectResolverImpl$1.produce(RemoteExternalSystemProjectResolverImpl.java:37)
    at com.intellij.openapi.externalSystem.service.remote.AbstractRemoteExternalSystemService.execute(AbstractRemoteExternalSystemService.java:59)
    at com.intellij.openapi.externalSystem.service.remote.RemoteExternalSystemProjectResolverImpl.resolveProjectInfo(RemoteExternalSystemProjectResolverImpl.java:37)
    at com.intellij.openapi.externalSystem.service.remote.wrapper.ExternalSystemProjectResolverWrapper.resolveProjectInfo(ExternalSystemProjectResolverWrapper.java:49)
    at com.intellij.openapi.externalSystem.service.internal.ExternalSystemResolveProjectTask.doExecute(ExternalSystemResolveProjectTask.java:51)
    at com.intellij.openapi.externalSystem.service.internal.AbstractExternalSystemTask.execute(AbstractExternalSystemTask.java:138)
    at com.intellij.openapi.externalSystem.service.internal.AbstractExternalSystemTask.execute(AbstractExternalSystemTask.java:124)
    at com.intellij.openapi.externalSystem.util.ExternalSystemUtil$4.execute(ExternalSystemUtil.java:540)
    at com.intellij.openapi.externalSystem.util.ExternalSystemUtil$5$2.run(ExternalSystemUtil.java:621)
    at com.intellij.openapi.progress.impl.CoreProgressManager$TaskRunnable.run(CoreProgressManager.java:563)
    at com.intellij.openapi.progress.impl.CoreProgressManager$2.run(CoreProgressManager.java:152)
    at com.intellij.openapi.progress.impl.CoreProgressManager.registerIndicatorAndRun(CoreProgressManager.java:452)
    at com.intellij.openapi.progress.impl.CoreProgressManager.executeProcessUnderProgress(CoreProgressManager.java:402)
    at com.intellij.openapi.progress.impl.ProgressManagerImpl.executeProcessUnderProgress(ProgressManagerImpl.java:54)
    at com.intellij.openapi.progress.impl.CoreProgressManager.runProcess(CoreProgressManager.java:137)
    at com.intellij.openapi.progress.impl.ProgressManagerImpl$1.run(ProgressManagerImpl.java:126)
    at com.intellij.openapi.application.impl.ApplicationImpl$8.run(ApplicationImpl.java:400)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)
    at org.jetbrains.ide.PooledThreadExecutor$1$1.run(PooledThreadExecutor.java:56)

How to fix that?

A: I had to re-install android studio to solve this...


text:
Q: How to make a toast message in Honeycomb? I know this might seem quite trivial, however, I've been tackling with it for quite some time.
I'm trying to simply display an error message through a TOAST in honeycomb. However, if I use the traditional Toast method, the app crashes.
From what I found (not very clear) the TOAST method must be in its own thread (?)?
Any help would be greatly appreciated and sorry if this is a really noob question...
        public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    setContentView(R.layout.hseactivity);

    Toast.makeText(getApplicationContext(), "Sorry, an error occurred...", Toast.LENGTH_LONG).show();

A: I would try cleaning the project and then rebuild it. It happens quite often that android breaks the code and you end up with this kind of odd errors.


text:
Q: How can I pass some values from gsp to controller in a g:form? I know there are some questions like mine, but I'm hoping to get an explanation of how to do it in Grails.
What I want to do is pass values from a gsp datepicker and textfield to the controller when upon Submit button press.
My thanks in advance
GSP:
<g:form action="generateReport">

                    <g:message code="Data" default="Data"/>
                    *
                    <g:datePicker id="data" name="datapicker" precision="day"></g:datePicker>

                    <g:message code="Time" default="Time"/>
                    <g:textField name="minutes"/>

        <g:submitButton value="search" name="button"/>

</g:form>

Controller:
def generateReport(){
    log.info("Button pressed")
    redirect(action: "list")
}

A: I just found the answer:
the view:
<g:textField name="name" />
the controller:

Controller:
  class SomeController {
      def someAction() {
        def name = params.name
        // do something with name
      }
    }


text:
Q: Flutte error android\gradlew.bat" exited abnormally I am getting below error on android studio.
ProcessException: ProcessException: Process "F:\Flutter Projects\Flutter\login_signup_flutter_test\android\gradlew.bat" exited abnormally:
Exception in thread "main" java.lang.NullPointerException
    at org.gradle.wrapper.BootstrapMainStarter.findLauncherJar(BootstrapMainStarter.java:34)
    at org.gradle.wrapper.BootstrapMainStarter.start(BootstrapMainStarter.java:25)
    at org.gradle.wrapper.WrapperExecutor.execute(WrapperExecutor.java:129)
    at org.gradle.wrapper.GradleWrapperMain.main(GradleWrapperMain.java:61)
  Command: F:\Flutter Projects\Flutter\login_signup_flutter_test\android\gradlew.bat -v

A: Delete '.gradle' folder in C:\Users***.gradle, connect to internet, rebuild project to download latest Gradle.


text:
Q: Cannot apply '&' operator for generic Enum parameters I'm trying to write some generic extension methods for flag-style enums. As of C# 7.3, the TFlag type argument can be marked as Enum, but the compiler throws an error for the expression flags & flagToTest, it says that "Operator '&' cannot be applied for type TFlag and TFlag". Since TFlag is an Enum, the '&' operator should work fine.
public static bool IsSet<TFlag>(this TFlag flags, TFlag flagToTest) where TFlag : Enum
{
    if (!Attribute.IsDefined(typeof(TFlag), typeof(FlagsAttribute)))
        throw new InvalidOperationException("The given enum type is not decorated with Flag attribute.");

    if (flagToTest.Equals(0))
        throw new ArgumentOutOfRangeException(nameof(flagToTest), "Value must not be 0");

    return (flags & flagToTest) == flagToTest;
}

A: First of all, take a look at this answer https://stackoverflow.com/a/50219294/6064728.
You can write your function in this way or something like this:
public static bool IsSet<TFlag>(this TFlag flags, TFlag flagToTest) where TFlag : Enum
{
    if (!Attribute.IsDefined(typeof(TFlag), typeof(FlagsAttribute)))
        throw new InvalidOperationException("The given enum type is not decorated with Flag attribute.");

    if (flagToTest.Equals(0)) throw new ArgumentOutOfRangeException(nameof(flagToTest), "Value must not be 0");
    int a = Convert.ToInt32(flags);
    int b = Convert.ToInt32(flagToTest);
    return (a & b) == b;
}


text:
Q: Page URL and database organization I want that its name would be the page address. For example, if page has heading "Some Page", than its address should be http://somesite/some_page/.
"some_page"-name generated by system automatically. "some_page" - is the unique identifier of page. The problem in that the user in the future can enter a name which already exists that will cause an error.
It is necessary to find an optimum variant of the decision of a problem for great volumes of the data.
I have solved a problem as follows:
The page identifier in a database is the name of page and a suffix which is by default equal to zero. At page addition there is a check on existence. If such page does not exist, the suffix is equal 0 and its name is "some_page", if page is exist, than - search for the maximum number of a suffix and suffix=suffix+1 and page name become "some_page_1".
For this I create in a database the compound key from fields "suffix" and "pageName":
Table Pages

suffix|pageName  |pageTitle
0     |some_page |Some Page
1     |some_page |Some Page
0     |other_page|Other Page

Addition of pages occurs through stored procedure:
CREATE PROCEDURE addPage (pageNameVal VARCHAR(100), pageTitleVal VARCHAR(100))

BEGIN

    DECLARE v INT DEFAULT 0;

    SELECT MAX(suffix) FROM pages WHERE pageName=pageNameVal INTO v;

    IF v >= 0 THEN

        SET v = v + 1;

    ELSE

        SET v = 0;

    END IF;

    INSERT INTO pages (suffix, pageName) VALUES (pageNameVal, v, pageTitleVal);

END;

Whether there are more the best decisions?

A: I think this should be okay - it would keep multiple instances of the key distinct. However, why not use a generated key instead of something provided by the user? If you maintain control over the page's lookup ID, you'll ensure no duplicates. Your current setup shouldn't cause any trouble, though.
The only problem (though it seems highly unlikely), is that your SP has a chance to duplicate the suffix for a particular key if two callers try to save the same key at the same time - ie, two simultaniousrequests with the same brand new pagename could both end up trying to use suffix 0. If you don't care about the result of your insert statement (and your current SP doesn't return it), then just do it in a single statement inside your SP:
CREATE PROCEDURE addPage (pageNameVal VARCHAR(100), pageTitleVal VARCHAR(100))
BEGIN

    INSERT INTO pages (pageName, suffix, pageTitle)
    SELECT n.pageNameVal, ISNULL(NextValue, 0), n.pageTitleVal
      FROM (SELECT pageNameVal, pageTitleVal) n
      LEFT
      JOIN (SELECT MAX(suffix+1) as NextValue FROM pages WHERE pageName=pageNameVal) m

END


text:
Q: Dynamic creation of beans in Spring Is there a way in spring wherein we can read the fields of a bean from the DB table and create a complete bean class - with getters and setters on server startup????
I require this to make my application completely configurable...as in if I have to add a new field in future , all I would require would be adding a field in the db and the bean setters and getters would be available to me.
Thanks

A: You could try approaches for dynamically registering beans . You could use the BeanDefinitionBuilder for this purpose . See a sample here . But as @Darren says , It's not a wise idea to creak a bean via DB lookup .

A: 1: Improve your accept-rate
2: You might benefit from something like an ORM approach (Hibernate or JPA). Another slightly different approach that might suite you is the Active Record pattern as implemented in, forinstance, ActiveJDBC.
Spring does not, in itself, offer anything like what you are after, but using spring-jpa together with Hibernate might get you a bit closer towards your goal. If, OTOH, you want auto-generated code you could also look at something like Spring-Roo

A: You might want to think about this a little more. Even if you made your fields totally configurable, you will still have to write the code that accesses them. And given that you are going to have to write code anyway, might as well keep everything in code. It's much simpler that way.


text:
Q: How to empty the uploaded file list? I am using the jQuery file upload plugin. Everything is fine, except I am not able to empty the uploaded file list.
I found someone suggested using $("table#img tbody.files").empty();. I downloaded the Basic Plus UI demo to test this solution. It could temporally clear the list, but when I refreshed my page, the file list came back again.
I am wondering whether there is a way to clear the list. Thanks

A: I think I solved my problem, comment out the following codes in "UploadHandler.php".
protected function get_file_objects($iteration_method = 'get_file_object') {
    $upload_dir = $this->get_upload_path();
    if (!is_dir($upload_dir)) {
        return array();
    }
    return array_values(array_filter(array_map(
        array($this, $iteration_method),
        scandir($upload_dir)
    )));
}

By doing this, you won't get any file lists after refreshing the page or running $("table tbody.files").empty(); manually.


text:
Q: Gridview Changes Page Title Does anyone know why or how a gridview in Visual Studio would change a page title on a web page.  When the page is first opened, the title is fine.  When you start scrolling the grid, the title changes to a number that appears to be the number of pixels moved.  Numbers are 0, 14, 28, 42, etc.
I am trying to help a coworker fix the issue, but looking for a good starting point.  I've never seen this and my google searches are turning up empty.
Thanks in Advance,
Randy

A: After some debugging of the code, we found that he was updating the field himself.  It was a coding error.
Thanks,
Randy


text:
Q: Definition of Poincare Section Def: Let $X\subset Y$ with $\phi_t:Y\to Y$ a semiflow. $X$ is called a Poincaré section of $\phi_t$ if the first return time $\tau(x):=$inf$\{t>0:\phi_t(x)\in X\}\in\mathbb{R}^+$ for every $x\in X$, with the convention inf$\{\}=+\infty$.
We then define a discrete dynamical system from the map $f:X\to X$ by $f(x)=\phi_{\tau(x)}(x)$.
Questions:
1.) I take this definition of a Poincaré section to mean that every point of $X$ eventually returns to $X$ (infinitely often) and the flow must not be parallel along $X$ (otherwise, $\tau(x)=0\notin\mathbb{R}^+$ for every $x\in X$). In another text I have (Strogatz), it says that if $Y$ has dimension $n$, then the Poincaré section $X$ has dimension $n-1$. I'm not sure why this is the true though. Does this follow from the definition above, or is it an extra condition? Why, for example, couldn't you have a line in $\mathbb{R}^3$ be a Poincaré section?
2.) I'm not sure why $\phi_{\tau(x)}(x)\in X$. $\tau(x)$ is the greatest lower bound of all times $t$ such that $\phi_t(x)\in X$, but why does this mean that $\tau(x)$ is also such a time? It would seem to me that $\tau$ would have to be defined in terms of a strict minimum instead of an infimum.


text:
Q: JQuery syntax for finding if an element exists I am trying to find a form inside of a div on a webpage using JQuery. I have the following:
alert('in');
alert($('#prodForm').length == 0);
alert('made it past');

When the script executes, I see the 'in' printed out, but I never see the 'made it past' get printed, leading me to believe there is a problem with my 2nd line, where I am trying to determine if the form exists. The form has an id of prodForm.
Am I missing something syntactically?

A: alert($('div').has('#prodForm').length != 0); // the form exists

A: Apparently JQuery wasn't loaded, I am building a chrome plugin, and I had to list jquery BEFORE my javascript file

A: alert('in');
alert($('#prodForm').size() == 0);
alert('made it past');


text:
Q: Django how to send an email with the user link? Hi i am newbie in Django just learning from the documentation.I just used django send an email https://docs.djangoproject.com/en/2.1/topics/email/.
i want to send an email in join message want to send an a url with its driver ID in it for book a car . how do i send an url with his id . for example i am having 4 user in my employe site . our company employe hit the link send an email to the user which is registered . after click on send an email how do i get the driver id in my url and send him as in join message a link where his id in the url .
Views.py
def rentacar_carapp_approve(request):
    if request.POST:
        try:
            args['driver'] = driver = Driver.objects.get(id=request.POST.get('driver_id'))
            subject = "Please Register Your Car"
            from_email = settings.EMAIL_HOST_USER
            to_email = driver_email
            if to_email is not None:
                join_message = """Please hit the link and book a car "url with his id " """
                send_mail(subject=subject, from_email=from_email, recipient_list=[to_email], message=join_message,
                          fail_silently=False)
                print("email sent")
        except Driver.DoesNotExist:
            print("Driver doesn't exists")
        return HttpResponseRedirect('/mega-admin/rentacar/carapp-manager/')

Url.py
url(r'^drivers/(?P<driver_id>\d+)/$',rent_views.book,name='book'),

A: You can try this way:
if request.is_secure():
   protocol = 'https://'
else:
   protocol = 'http://'

host = request.get_host()

url = protocol + host + reverse('url_name', kwargs={user_id: user_id})

*

*kwargs may be null if there is no arguements with the url pattern.

Then concatenate the url with your message body in send email().


text:
Q: Text shaking when using css transition and scale() I have searched everywhere, including SO, but no one seems to find an answer. My issue is that when I hover an element using transform: scale(1.2) and opacity, the element grows, which is fine, but the text/content shakes or wiggles as it appears and scales.
Is there a way to stop the text from shaking/wiggling/flickering, as it's annoying and not UX friendly?
You can see an example here: http://jsfiddle.net/dv78etsv/
Many Thanks

A: You run a couple transitions at the same time, simply remove all the transitions and decide on one - for specific css property transition: opacity 1s
remove changing font-size on hover, and don't over-use transitions, those two should be enough:
.carte-sample {
    transition: transform 1s;
}
.carte-inner {
    transition: opacity 1s;
}

working example
http://jsfiddle.net/dv78etsv/2/


text:
Q: MediaStreamRecorder can't record more than an hour? I am creating a video conference which takes 1 hour. And it can't save because Payload Too Large
Here is my code:
const data = [];
multiStreamRecorder.ondataavailable = function (blob) {
    data.push(blob);

    var fileName = getFileName('webm');
    var scheduleId = $('#stop-recording').data('id');
    var fileObject = new File([data[0]], fileName, {
        type: data[0].type
    });
    var objectUrl = URL.createObjectURL(data[0]);

    var formData = new FormData();
        formData.append('video_blob', fileObject);
        formData.append('video_filename', fileObject.name);
        formData.append('schedule_id', scheduleId);

    $.ajax({
        url: '{{ url('/') }}/store',
        data: formData,
        cache: false,
        contentType: false,
        processData: false,
        type: 'POST',
        success: function(response) {
            //
        }
    });
};
multiMediaRecorder.start();

I need to record the entire conference.

A: The "payload too large" error comes from your server, not from the MediaRecorder API.
You probably have ways to raise that limit in your server's configs.
Alternatively, you could send the final file by chunks, but that's probably sub-optimal.
Unrelated note:
sending the blobURI is useless, this URI will only be valid for the context that did create it.


text:
Q: Problems with TCP in VACaMobil I am having some problems with TCP in VACaMobil.
I am using two TCP modules built up in Inet: TCPBasicClientApp and TCPEchoApp.
The former works as a client and the former works as a server.
The number of cars (the module name is "coche") in the simulation is 100, and there are five concurrent transmissions:
CLIENT    SERVER
Car 0 --> Car 99
Car 1 --> Car 98
Car 2 --> Car 97
Car 3 --> Car 96
Car 4 --> Car 95

I am also using three routing protocols: AODV, DYMO and OLSR.
However, regardless of the configuration that I run, errors like this ocurr in the simulation:
Error in module (TCPBasicClientApp) Highway.coche[*].tcpApp[0] (id = 35) at event #49519, t = 166: IPvXAddressResolver: module 'coche[98]' not found.

In this case, using AODV, the car 1 cannot communicate with the car 98. I learned that VACaMobil, after a time, deletes some cars while it is creating others beyond 100,
such as  "coche[110]", "coche[115]", etc.
I don't understand why it keeps deleting and creating nodes; I thought that VACaMobil really generated a constant number of vehicles.
How can I fix this? Any help is appreciated.
Here is the omnetpp.ini:
[General]

network = Highway

debug-on-errors = false

cmdenv-express-mode = true
cmdenv-autoflush = true
cmdenv-status-frequency = 10000000s
#repeat = 10
tkenv-plugin-path = ../../../etc/plugins
tkenv-image-path = bitmaps

check-signals = true

**.manager.**.scalar-recording = true
**.manager.**.vector-recording = true
**.manetrouting.**.scalar-recording = true
**.movStats.**.scalar-recording = true
**.movStats.**.vector-recording = true
**.mac.**.scalar-recording = true
**.mac.**.vector-recording = true
**.scalar-recording = true
**.vector-recording = true

#ChannelControl
*.channelControl.carrierFrequency = 2.4GHz
*.channelControl.pMax = 2mW
*.channelControl.sat = -110dBm
*.channelControl.alpha = 2
*.channelControl.numChannels = 1

# TraCIScenarioManagerLaunchd
*.manager.updateInterval = 1s
*.manager.host = "localhost"
*.manager.port = 9999
*.manager.moduleType = "rcdp9.TAdhocHost"
*.manager.moduleName = "coche"
*.manager.moduleDisplayString = ""
*.manager.autoShutdown = true
*.manager.margin = 25
*.manager.warmUpSeconds = 0
*.manager.launchConfig = xmldoc("VACaMobil/Milan/downtown.launch.xml")
*.manager.getStatistics = true
*.manager.statFiles = "${resultdir}/${configname}-${runnumber}-"

# nic settings
**.wlan[*].bitrate = 24Mbps
**.wlan[*].opMode = "g"
**.wlan[*].mgmt.frameCapacity = 10
**.wlan[*].mgmtType = "Ieee80211MgmtAdhoc"
**.wlan[*].mac.basicBitrate = 24Mbps
**.wlan[*].mac.controlBitrate = 24Mbps
**.wlan[*].mac.address = "auto"
**.wlan[*].mac.maxQueueSize = 14
**.wlan[*].mac.rtsThresholdBytes = 3000B
**.wlan[*].mac.retryLimit = 7
**.wlan[*].mac.cwMinData = 7
**.wlan[*].radio.transmitterPower = 2mW
**.wlan[*].radio.thermalNoise = -110dBm
**.wlan[*].radio.sensitivity = -85dBm
**.wlan[*].radio.pathLossAlpha = 2
**.wlan[*].radio.snirThreshold = 4dB

**.channelNumber = 0

**.coche.networkLayer.configurator.networkConfiguratorModule = "configurator"

# manet routing
**.routingProtocol = ${"AODVUU", "DYMO", "OLSR"}

**.tcpAlgorithmClass = "TCPNewReno"

**.coche[0..4].numTcpApps = 1
**.coche[0..4].tcpApp[*].typename = "TCPBasicClientApp"
**.coche[0..4].tcpApp[*].localPort = -1
**.coche[0..4].tcpApp[*].connectPort = 1000
**.coche[0..4].tcpApp[*].dataTransferMode = "bytecount"
**.coche[0..4].tcpApp[*].startTime = 10s
**.coche[0..4].tcpApp[*].thinkTime = 1s
**.coche[0..4].tcpApp[*].idleInterval = 3s
**.coche[0..4].tcpApp[*].requestLength = 5000000B

**.coche[5..94].numTcpApps = 0

**.coche[95..99].numTcpApps = 1
**.coche[95..99].tcpApp[*].typename = "TCPEchoApp"
**.coche[95..99].tcpApp[*].localPort = 1000
**.coche[95..99].tcpApp[*].dataTransferMode = "bytecount"

**.coche[0].tcpApp[*].connectAddress = "coche[99]"
**.coche[1].tcpApp[*].connectAddress = "coche[98]"
**.coche[2].tcpApp[*].connectAddress = "coche[97]"
**.coche[3].tcpApp[*].connectAddress = "coche[96]"
**.coche[4].tcpApp[*].connectAddress = "coche[95]"

**.meanNumberOfCars = 100
**.autoShutdown = false

Here is TAdhocHost.ned:
package rcdp9;

import inet.networklayer.IManetRouting;
import inet.networklayer.autorouting.ipv4.HostAutoConfigurator2;
import inet.nodes.inet.AdhocHost;

module TAdhocHost extends AdhocHost
{
    parameters:
        @display("i=device/cellphone");
        mobilityType = default("TraCIMobility");
        IPForward = true;
    submodules:
        ac_wlan: HostAutoConfigurator2 {
          @display("p=127,240");
        }
    connections:
}

Here is Highway.ned:
package rcdp9;

import inet.world.VACaMobil.VACaMobil;
import inet.networklayer.autorouting.ipv4.IPv4NetworkConfigurator;
import inet.networklayer.autorouting.ipv4.HostAutoConfigurator;
import inet.nodes.inet.AdhocHost;
import inet.world.radio.ChannelControl;
import inet.world.traci.TraCIScenarioManagerLaunchd;

network Highway
{
    submodules:
        configurator: IPv4NetworkConfigurator {
            @display("p=396,221");
        }
        channelControl: ChannelControl {
            @display("p=396,310");
        }
        manager: VACaMobil {
            @display("p=322,405");
        }
    connections allowunconnected:
}

A: From what I understand, VACaMobil is built on Veins.
Veins creates a new network node for every vehicle that starts driving. When the corresponding vehicle stops driving (having arrived at its destination) Veins deletes the network node. It never re-uses the same node index.
Thus, in your example, the first vehicle that starts driving will be coche[0]. The next vehicle that starts driving will be coche[1] - independent of whether coche[0] already arrived or is still driving.