text:
Q: Cleanest way to copy a constant size array in c++11 I often find myself wanting to copy the contents of arrays that have a constant size, I usually just write something along the lines of:
float a[4] = {0,1,2,3};
float b[4];

for(int i=0; i<4; i++){
    b[i]=a[i];
}

As of lately, I am writing a linear calculus library for educational purposes, and I was wondering if there was a better way to do it.
The first thing that came to my mind, was using memcpy:
memcpy(b, a, sizeof(float) * 4);

But this seems very c-like and error prone to me. I like having my errors at compile time, and this can get ugly for data types with non-trivial copy constructors, or if I forget to multiply with sizeof(datatype).
Since I am writing a math library that I am going to use intensively, performance is very important to me. Are the compilers today smart enough to understand that the first example is just copying a chunk of memory and optimize it to be as efficient as the second solution?
Perhaps there is a function in the standard library that can help me? Something new in c++11? Or should I just create a macro or a template function?

A: If you use std::array instead of a built-in array (which you should), it becomes very simple.  Copying an array is then the same as copying any other object.
std::array<float,4> a = {0,1,2,3};
std::array<float,4> b = a;

A: The C++03 way
Use std::copy():
float a[4] = {0,1,2,3};
float b[4];

std::copy(a,a + 4, b);

That's about as clean as it gets.
The C++11 way
std::copy(std::begin(a), std::end(a), std::begin(b));

If you can use std::array
With std::array you just do simple assignment:
std::array<float,4> a = {0,1,2,3};
auto b = a;

A: Below method works for usual arrays as well std:array.
float a[4] = {0,1,2,3};
float b[4];

std::copy(std::begin(a), std::end(a), b);

A: #include <algorithm>
std::copy_n(a, 4, b)

A: For interested in C++03 (and also C) solution - always use struct containing an array instead of solely array:
struct s { float arr[5]; };

Structs are copyable by default.
Its equivalent in C++11 is,already mentioned, std::array<float,5>;


text:
Q: Writing a DataFrame to an excel file where items in a list are put into separate cells Consider a dataframe like pivoted, where replicates of some data are given as lists in a dataframe:

d = {'Compound': ['A', 'A', 'A', 'B', 'B', 'B', 'C', 'C', 'C', 'C'],
     'Conc': [1, 0.5, 0.1, 1, 0.5, 0.1, 2, 1, 0.5, 0.1],
     'Data': [[100, 90, 80], [50, 40, 30], [10, 9.7, 8],
              [20, 15, 10], [3, 4, 5, 6], [100, 110, 80],
              [30, 40, 50, 20], [10, 5, 9, 3], [2, 1, 2, 2], [1, 1, 0]]}

df = pd.DataFrame(data=d)
pivoted = df.pivot(index='Conc', columns='Compound', values='Data')

This df can be written to an excel file as such:
with pd.ExcelWriter('output.xlsx') as writer:
    pivoted.to_excel(writer, sheet_name='Sheet1', index_label='Conc')

How can this instead be written where replicate data are given in side-by-side cells? Desired excel file:

A: Then you need to pivot your data in a slightly different way, first explode the Data column, and deduplicate with groupby.cumcount:
(df.explode('Data')
   .assign(n=lambda d: d.groupby(level=0).cumcount())
   .pivot(index='Conc', columns=['Compound', 'n'], values='Data')
   .droplevel('n', axis=1).rename_axis(columns=None)
)

Output:
        A    A    A    B    B    B    B   C   C   C    C
Conc
0.1    10  9.7    8  100  110   80  NaN   1   1   0  NaN
0.5    50   40   30    3    4    5    6   2   1   2    2
1.0   100   90   80   20   15   10  NaN  10   5   9    3
2.0   NaN  NaN  NaN  NaN  NaN  NaN  NaN  30  40  50   20

A: Beside the @mozway's answer, just for formatting, you can use:
piv = (df.explode('Data').assign(col=lambda x: x.groupby(level=0).cumcount())
         .pivot(index='Conc', columns=['Compound', 'col'], values='Data')
         .rename_axis(None))
piv.columns = pd.Index([i if j == 0 else '' for i, j in piv.columns], name='Conc')
piv.to_excel('file.xlsx')

redpajama_set_name: RedPajamaStackExchange


text:
Q: android: add Tab bar to all activities in an application I have to add TabBar to each activities in my application. How do I do this?

A: You can use include tag or viewstub or even fragments
Here's how to use include to achieve what you want

*

*Create layout file that describes your toolbar, e.g. toolbar.xml

*In each XML layout file you want your toolbar to appear add include tag pointing to your toolbar.xml

Example:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_height="fill_parent" android:layout_width="fill_parent">
    <include android:id="@+id/titleBar" layout="@layout/title_bar"
        android:layout_width="fill_parent" android:layout_height="48dip" />
    <!-- All the rest of your activity layout below -->
</RelativeLayout>


text:
Q: How to make python code run faster? (For solving the Collatz Conjecture) def main_func():

    def infinity():
        n = 295147905179352825856
        while True:
            yield n
            n+=1

    i = 295147905179352825856
    data = 0

    def func(i, num, x, data):
        if x == True:
            print(i, num, "F", data)
            #F means the number that can't be reduced to 1 is found
            i = 0
        else:
            print("Not Successful")

    check = 0

    for i in infinity():
        i+=1
        data+=1
        num=i
        if i > 1:
            while i > 1:

                if i % 2 == 0:
                    i = int(i/2)

                    if i == 1:
                        #print(data, ".", i, num)
                        #print("T")
                        if data == 100000:
                            data = 0
                            check+=1
                            print (check, num)
                            #This is done to make the console print less numbers/text

                        #else:
                            #print ("Not reached 1 Lakh")

                        #T means the number can be reduced to 1

                else:
                    i = int(3*i + 1)

            if i != 1:
                x = bool(True)
                func (i, num, x, data)
                print(i, num, "Eureka!")

        else:
            print("Try Again")

main_func()

I have tried to make a solution for the Collatz Conjecture using Python. This code check all the numbers from 2^68 upto infinity (never ends) whether it can be converted to 1 by using either n/2 or 3n+1. How can I make the process of checking faster?


text:
Q: How to Convert String to array in js Actually, I'm making a day wise items like (item name,description,price) like this but now coming same line all the data like (Hot & Crisp - ItemChicken Snacker,description,$8-$5) i want like below that format.
name:"Hot & Crisp
description:
price:"$6"

name":"Chicken Snacker"
description":"A delicious chunk of chicken served in a soft sesame bun, with salad and Thousand Island sauce."
price:"$5"

BUT now my output is like this:(name:Hot & Crisp - ItemChicken Snacker,description:jjjdjdjdjdj,price:$8-$5)
Mycode:
var ItemsDetails = v.itemsArray;
var ItemsName = JSON.stringify(ItemsDetails);
                                lg(ItemsName);
                                var myObject = eval('(' + ItemsName + ')');
                                for (i in myObject)
                                {
                                    var itemname = myObject[i]["name"];
                                    html += ''+ itemname +'';
                                }

A: You can edit this line:
html += ''+ itemname +'';

to:
html += ''+ itemname +'
';

A: not really sure, but this may be similar to what you are looking for.

var ItemsDetails = [{
  name: "Hot & Crisp",
  description: "",
  price: "$6"
}, {
  name: "Chicken Snacker",
  description: "A delicious chunk of chicken served in a soft sesame bun, with salad and Thousand Island sauce.",
  price: "$5"
}];
//var ItemsName = JSON.stringify(ItemsDetails);

//var myObject = eval('(' + ItemsName + ')');
//for (i in myObject)
//{
//    var itemname = myObject[i]["name"];
//    html += ''+ itemname +'';
//}
var htmlOut = "";
for (var i = 0; i < ItemsDetails.length; i++) {
  htmlOut += '
';
  htmlOut += 'Name: ' + ItemsDetails[i].name + '
';
  htmlOut += 'Description: ' + ItemsDetails[i].description + '
';
  htmlOut += 'Price: ' + ItemsDetails[i].price;
  htmlOut += '
';
}

document.getElementById("sampleDiv").innerHTML = htmlOut;


text:
Q: Cordova requestFileSystem is no longer being loaded 3.4.1 I recently updated to Cordova 3.4.1 I then proceeded to build and test my project and found it had issues. I have spent that last day and a half trying to revert and rebuild the project so that it works. Nothing i have tried thus far has worked.
Error im getting:
Uncaught TypeError: Object [object DOMWindow] has no method 'requestFileSystem'

Code used to produce this error:
var app = {
    appRoot: 'cdvfile://localhost/persistent/',
    init: function(){
        this.bindEvents();
    },
    bindEvents: function(){
        document.addEventListener('deviceready', this.onDeviceReady(this), false);
    },
    onDeviceReady: function(that){
        //location.reload(true);
        console.log(Object.keys(window));
        console.log(Object.keys(cordova));
        window.requestFileSystem(window.PERSISTENT, 0, function(fs){
            console.log('we have a fs');
            fs.root.getFile(dir+file,{create:true, exclusive: false},function(fileEntry){
                console.log('we have a file entry');
                var reader = new FileReader();
                reader.onloadend = function(evt){
                    success(evt.target.result);
                };
                reader.readAsText(dir+file);
            },fail);
        },fail);
    }
};
function fail(e){
    var msg = '';

    switch (e.code) {
      case FileError.QUOTA_EXCEEDED_ERR:
        msg = 'QUOTA_EXCEEDED_ERR';
        break;
      case FileError.NOT_FOUND_ERR:
        msg = 'NOT_FOUND_ERR';
        break;
      case FileError.SECURITY_ERR:
        msg = 'SECURITY_ERR';
        break;
      case FileError.INVALID_MODIFICATION_ERR:
        msg = 'INVALID_MODIFICATION_ERR';
        break;
      case FileError.INVALID_STATE_ERR:
        msg = 'INVALID_STATE_ERR';
        break;
      default:
        msg = 'Unknown Error';
        break;
    };

    console.log('Error: ' + msg);
 }

 app.init();

What Ive tried:

*

*Ive tried using the following Cordova versions 3.3.1, 3.4.0, 3.4.1, 3.5.0

*Ive tried using older version of the file api 1.0.0, 1.0.1, 1.1.0

*I have tried creating a new project from scratch

*I have tried building using api version 17, 19

*I have tried testing on an android 4.2.2 and 4.4.2

I have verified that the plugin is loaded into the project, and that it gets built onto the device. Im using the monitor.bat that comes with the Android SDK to watch console events and errors and the requestFileSystem is just not being injected.
I have tried using( as suggested by here):
location.reload()

and
location.reload(true) //not from cache

to see if there was errors with the cordova plugin initialization but there was nothing.
Does anyone have any more suggestions on what could fix this issue?

A: You are actually calling deviceReady too soon. In this line:
document.addEventListener('deviceready', this.onDeviceReady(this), false);

the return result of onDeviceReady is being passed to addEventListener, which isn't your intent, and means it gets called well before any plugins are initialized.
Better to do this:
document.addEventListener('deviceready', this.onDeviceReady, false);

If you must pass this (or another parameter) along, do this:
document.addEventListener('deviceready', this.onDeviceReady.bind(this), false);

But you shouldn't really have to do that, assuming you're setting your object up correctly.


text:
Q: Datatable is not working after ajax call in Laravel DataTable is not working properly. Data is shown on the table but search, pagination is not working. I use ajax request to get data.
Here my controller code
 $products = FoodItemPrice::with('items')->get();

        if ($request->ajax()) {
            return response()->json($products);
        }

Here is my ajax call
function getData(){

 $.ajax({

        url: "{{url('admin/category/')}}",
        method:"GET",
        contentType:false,
        cache: false,
        processData:false,
        dataType:"json",

        success: function(response){
              var data = ""
              var i = 1;
              $.each(response, function(key, value){
                data = data + "
"
                data = data + ""+i+++"	"
                data = data + ""+value.name+"	"
                data = data + ""
                data = data + "<button type='button' class='ms-btn-icon btn-dark mr-3' onclick='editCategory("+value.id+")'> </button>"
                data = data + "<button type='button'class='ms-btn-icon btn-danger'  onclick='deleteData("+value.id+")'> </button>"
                data = data + "	"
                data = data + "
"
              });
               $('tbody').html(data);

          }
  });
}
getData();

Here is dataTable scripts

    $(document).ready(function()
    {
        $('#dataTable').DataTable();
    } );

Where is the problem? Can anyone tell me how to solve it?

A: I recommend you to use Laravel Yajra Datatable and use built in Datatable server side data load
https://github.com/yajra/laravel-datatables


text:
Q: How to generate a random DNA sequence in matlab I am new to Matlab and I am trying to create random DNA sequence generator and so far I only found a way in generating A, C, G, T with equal probabilities, how do I assign different probabilities to each letter? All probabilities must add up to 1.
total_bp=10;
%open file
SeqLength=100;
bases = repmat('ACGT', 1, SeqLength/4);
for i=1:total_bp
%random DNA sequence
SeqLength=100;
Seq = bases(randperm(SeqLength));
display(num2str(Seq))
end
fclose('all');

A: Define a cell-array of the bases
bases = {'A', 'C', 'G', 'T'};

And an array of probabilities;
probs = [0.1,0.5,0.3,0.1];

Then you can draw a uniform random number and bin it:
bin = discretize(rand,[0,cumsum(probs)]);

and then translate to a letter:
seq = bases(bin);

In total:
n = 10;
bases = {'A', 'C', 'G', 'T'};
probs = [0.1,0.5,0.3,0.1];
seq = bases(discretize(rand(1,n),[0,cumsum(probs)]));
disp(strjoin(seq)) %Join to single string.


text:
Q: How can I use python xlib to generate a single keypress? I want to make a very simple python 3 script that will generate a single keypress (F15). I don't want to use a bunch of libraries to do this as I only need one key to be pressed and don't need support for the whole keyboard. I know I need to use KeyPress and KeyRelease in order to generate a keyboard event. I'm just not sure where exactly to start and the documentation is a little confusing.
http://tronche.com/gui/x/xlib/events/keyboard-pointer/keyboard-pointer.html
http://python-xlib.sourceforge.net/?page=documentation

A: I'll use ctypes to show you how it could work, but porting it to python-xlib should be straightforward. So lets start with loading the library:
import ctypes
X11 = ctypes.CDLL("libX11.so")

and defining the structures needed:
class Display(ctypes.Structure):
    """ opaque struct """

class XKeyEvent(ctypes.Structure):
    _fields_ = [
            ('type', ctypes.c_int),
            ('serial', ctypes.c_ulong),
            ('send_event', ctypes.c_int),
            ('display', ctypes.POINTER(Display)),
            ('window', ctypes.c_ulong),
            ('root', ctypes.c_ulong),
            ('subwindow', ctypes.c_ulong),
            ('time', ctypes.c_ulong),
            ('x', ctypes.c_int),
            ('y', ctypes.c_int),
            ('x_root', ctypes.c_int),
            ('y_root', ctypes.c_int),
            ('state', ctypes.c_uint),
            ('keycode', ctypes.c_uint),
            ('same_screen', ctypes.c_int),
        ]

class XEvent(ctypes.Union):
    _fields_ = [
            ('type', ctypes.c_int),
            ('xkey', XKeyEvent),
            ('pad', ctypes.c_long*24),
        ]

X11.XOpenDisplay.restype = ctypes.POINTER(Display)

Now we just need to send the event to the root window:
display = X11.XOpenDisplay(None)
key = XEvent(type=2).xkey #KeyPress
key.keycode = X11.XKeysymToKeycode(display, 0xffcc) #F15
key.window = key.root = X11.XDefaultRootWindow(display)
X11.XSendEvent(display, key.window, True, 1, ctypes.byref(key))
X11.XCloseDisplay(display)

This minimal example worked well for me (just using F2 instead). The same can be done to send a KeyRelease event. If a special window is to be targeted, key.window should be set appropriately.
I'm not sure, if it's necessary to use the XEvent union, since it'd worked with the XKeyEvent all alone for me, but it's better to be safe.


text:
Q: UnicodeError 'idna' encoding when working with Heroku, Redis and Flask I have a Flask REST API hosted on Heroku with a Heroku-Redis server.
When code that tries to access the Redis server is executed I get the following error.
UnicodeError: encoding with 'idna' codec failed (UnicodeError: label empty or too long)
The code that seems to cause this error is,
revoked_store.set(access_jti, 'false', ACCESS_EXPIRES * 1.2)
revoked_store.set(refresh_jti, 'false', REFRESH_EXPIRES * 1.2)

The connection is set here:
revoked_store = redis.StrictRedis(host=os.environ.get('REDIS_URL'), port=6379, db=0, decode_responses=True)

From looking at various other posts I think this error is caused by the Redis URL being too long (>64 characters). See here.
I am not sure how to fix this effort so any help would be appreciated.
If you require more information, please let me know.
Thank you.

A: I had the same problem, then I just read the documentation on Heroku Redis.
For reference, I did the following, and it solved my issue:
import os
from urllib.parse import urlparse
import redis

url = urlparse(os.environ.get("REDIS_URL"))
r = redis.Redis(host=url.hostname, port=url.port, username=url.username, password=url.password, ssl=True, ssl_cert_reqs=None)


text:
Q: Update UI Thread from ViewModel I am trying to execute the simple action of updating a progress bar on my UI inside of a loop by using a BackgroundWorker. I don't know what I'm doing wrong.  Any help is greatly appreciated.
private void ProcessButtonClickAction(object param)
{
   BackgroundWorker BGWUpdateUi = new BackgroundWorker();

   BGWUpdateUi.ProgressChanged += (sender, args) =>
   {
       ProgressBarValue += args.ProgressPercentage;
       ((SelectedDwgFile)args.UserState).Status = "Completed";
   };

   BGWUpdateUi.WorkerReportsProgress = true;

    foreach(var obj in FileList)
    {
        Thread.Sleep(250);
        BGWUpdateUi.ReportProgress(pbvalueIncrement, obj);
    }
}

The collection is an ObservableCollection and ProgressBarValue is bound to the value of the progress bar.
I have looked at several of examples and no matter which one I try - BackgroundWorker, Dispatcher - they all update after the loop.

A: Put the part that you want to run in the background, into the DoWork method, and then call RunWorkerAsync:
private void ProcessButtonClickAction(object param)
{
   BackgroundWorker BGWUpdateUi = new BackgroundWorker()

   BGWUpdateUi.DoWork += (sender, args) =>
   {
       foreach (var obj in FileList)
       {
           Thread.Sleep(250);
           obj.Status = "Completed";
           ProgressBarValue += pbvalueIncrement;
       }
   };
   BGWUpdateUi.RunWorkerAsync();
}

Also, make sure to dispatch UI-related updates back to the UI thread (otherwise you will get a cross-thread access exception).


text:
Q: Cant see option of upload APK in my suspended android app Android team rejected my application due to some security reason and asked me to upload new APK.I resolved issues but I can't see option of upload APK in developer console if I select my suspended app. is there way to resubmit my APK again?

A: If your application is suspended, you cannot upload new apk or make changes to application. App will not be available to users to download either.

*

*You can appeal against the suspension if you have enough evidence to support your claim. Once suspension is removed you can upload new apk in same app.

*You need create completely new application to upload you apk ( name/title of new app cannot be similar to your existing app ).


text:
Q: Display JSON info in a PHP table I am trying to display JSON content in a PHP table but its not working. I  can't figure out what I should  change.
Here is my code:

<title>Download</title>

<?php
$myData = file_get_contents("https://youtubetoany.com/@api/json/videostreams/VEou0QBeHlk");
$myObject = json_decode($myData);
$myObjectMap = $myObject->vidInfo;
?>

        Url
        Size
        Quality
        Type

  <?php foreach($myObjectMap as $key => $item): ?>

      <?PHP echo $item->dloadUrl; ?>
      <?PHP echo $item->rSize; ?>
      <?PHP echo $item->round; ?>
      <?PHP echo $item->quality; ?>
      <?PHP echo $item->ftype; ?>

  <?php endforeach; ?>

This is what I get in my browser:

Url   Size    Quality     Type

A: I just found probably why its not working. The link returns a JavaScript attached to the bottom of the JSON. So here is my solution.

<title>Download</title>

<?php
$myData = file_get_contents("https://youtubetoany.com/@api/json/videostreams/VEou0QBeHlk");

// This up to the last occurrence of the "}"
$json_block = substr($myData, 0, strripos($myData, "}"));

$myObject = json_decode($json_block);
$myObjectMap = $myObject->vidInfo;
?>

        Url
        Size
        Quality
        Type

  <?php foreach($myObjectMap as $key => $item): ?>

      <?PHP echo $item->dloadUrl; ?>
      <?PHP echo $item->rSize; ?>
      <?PHP echo $item->round; ?>
      <?PHP echo $item->quality; ?>
      <?PHP echo $item->ftype; ?>

  <?php endforeach; ?>

A: Your source has some javascript attached. You need to get rid of that:
$myData = file_get_contents("https://youtubetoany.com/@api/json/videostreams/VEou0QBeHlk");

// get the substring from start til the first occurence of "


text:
Q: Bindable dynamic DataGrid Columns Here is my ViewModel class:
public class ColumnViewModel : ViewModelBase
{
    private string bindingPropName;
    public string BindingPropName
    {
        get { return bindingPropName; }

        set
        {
            if (bindingPropName != value)
            {
                bindingPropName = value;
                RaisePropertyChanged("BindingPropName");
            }
        }
    }

    private string header;
    public string Header
    {
        get { return header; }

        set
        {
            if (header != value)
            {
                header = value;
                RaisePropertyChanged("Header");
            }
        }
    }
}

DataGrid extension classes:
public static class DataGridColumns
{
    static DataGridColumns()
    {
        FrameworkElement.DataContextProperty.AddOwner(typeof(DataGridTextColumn));
    }

    private static readonly DependencyProperty DataGridColumnSettingsProperty = DependencyProperty.RegisterAttached(
        "DataGridColumnSettings",
        typeof(DataGridColumnSettings),
        typeof(DataGridColumn));
    private static void SetDataGridColumnSettings(DataGridColumn column, DataGridColumnSettings settings) { column.SetValue(DataGridColumnSettingsProperty, settings); }
    private static DataGridColumnSettings GetDataGridColumnSettings(DataGridColumn column) { return column.GetValue(DataGridColumnSettingsProperty) as DataGridColumnSettings; }

    public static readonly DependencyProperty DisplayColumnsProperty = DependencyProperty.RegisterAttached(
        "DisplayColumns",
        typeof(IList),
        typeof(DataGridColumns),
        new PropertyMetadata(null, DisplayColumnsPropertyChanged));

    public static void SetDisplayColumns(DataGrid dataGrid, IList columns) { dataGrid.SetValue(DisplayColumnsProperty, columns); }
    public static IList GetDisplayColumns(DataGrid dataGrid) { return dataGrid.GetValue(DisplayColumnsProperty) as IList; }
    private static void DisplayColumnsPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        var target = d as DataGrid;
        var columns = e.NewValue as IList;
        var template = GetColumnSettingsTemplate(target);

        CreateColumns(target, columns, template);
    }

    public static readonly DependencyProperty ColumnSettingsTemplateProperty = DependencyProperty.RegisterAttached(
        "ColumnSetupTemplate",
        typeof(DataTemplate),
        typeof(DataGridColumns),
        new PropertyMetadata(null, ColumnSettingsTemplateChanged));
    public static void SetColumnSettingsTemplate(DataGrid dataGrid, DataTemplate columnSetupTemplate) { dataGrid.SetValue(ColumnSettingsTemplateProperty, columnSetupTemplate); }
    public static DataTemplate GetColumnSettingsTemplate(DataGrid dataGrid) { return dataGrid.GetValue(ColumnSettingsTemplateProperty) as DataTemplate; }
    private static void ColumnSettingsTemplateChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        var target = d as DataGrid;
        var columns = GetDisplayColumns(target);
        var template = e.NewValue as DataTemplate;

        CreateColumns(target, columns, template);
    }

    private static void CreateColumns(DataGrid dataGrid, IList columnViewModels, DataTemplate columnSettings)
    {
        if (dataGrid == null)
            return;
        dataGrid.Columns.Clear();

        if (columnViewModels == null)
            return;

        foreach (var column in columnViewModels)
        {
            var newColumn = new DataGridTextColumn();
            newColumn.SetValue(FrameworkElement.DataContextProperty, column);
            if (columnSettings != null)
            {
                var settings = columnSettings.LoadContent() as DataGridColumnSettings;
                if (settings != null)
                {
                    settings.Setup(newColumn, column);
                    SetDataGridColumnSettings(newColumn, settings);
                }
            }
            dataGrid.Columns.Add(newColumn);
        }
    }
}

public class DataGridColumnSettings : FrameworkElement
{
    public static readonly DependencyProperty ColumnBindingPathProperty = DependencyProperty.Register(
        "ColumnBindingPath",
        typeof(string),
        typeof(DataGridColumnSettings),
        new PropertyMetadata(null, ColumnBindingPathChanged));
    public string ColumnBindingPath
    {
        get { return GetValue(ColumnBindingPathProperty) as string; }
        set { SetValue(ColumnBindingPathProperty, value); }
    }
    private static void ColumnBindingPathChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        var target = d as DataGridColumnSettings;
        if (target == null)
            return;
        target.column.Binding = new Binding(e.NewValue as string);
    }

    public static readonly DependencyProperty HeaderProperty = DependencyProperty.Register(
        "Header",
        typeof(object),
        typeof(DataGridColumnSettings));
    public object Header
    {
        get { return GetValue(HeaderProperty); }
        set { SetValue(HeaderProperty, value); }
    }

    private DataGridTextColumn column;
    private object viewModel;

    public void Setup(DataGridTextColumn column, object columnViewModel)
    {
        this.column = column;
        viewModel = columnViewModel;
        this.DataContext = columnViewModel;

        if (Header is FrameworkElement)
        {
            (Header as FrameworkElement).DataContext = columnViewModel;
            column.Header = Header;
        }
        else
            BindingOperations.SetBinding(column, DataGridColumn.HeaderProperty, new Binding("Header") { Source = this });
        column.Binding = new Binding(ColumnBindingPath);
    }
}

and my XAML code:
<DataGrid t:DataGridColumns.DisplayColumns="{Binding Columns}" ItemsSource="{Binding Rows}" AutoGenerateColumns="False">
    <t:DataGridColumns.ColumnSettingsTemplate>
        <DataTemplate>
            <t:DataGridColumnSettings ColumnBindingPath="{Binding BindingPropName}">
                <t:DataGridColumnSettings.Header>
                        <TextBlock Text="{Binding Header}"/>
                </t:DataGridColumnSettings.Header>
            </t:DataGridColumnSettings>
        </DataTemplate>
    </t:DataGridColumns.ColumnSettingsTemplate>
</DataGrid>

Everything what i'm trying to achieve is adding CellTemplate:
<DataGrid t:DataGridColumns.DisplayColumns="{Binding Columns}" ItemsSource="{Binding Rows}" AutoGenerateColumns="False">
    <t:DataGridColumns.ColumnSettingsTemplate>
        <DataTemplate>
            <t:DataGridColumnSettings ColumnBindingPath="{Binding BindingPropName}">
            <t:DataGridColumnSettings.Header>
                <TextBlock Text="{Binding Header}"/>
            </t:DataGridColumnSettings.Header>
            <t:DataGridColumnSettings.CellTemplate>
                <TextBlock Text="{Binding ColumnBindingPath}"/>
            </t:DataGridColumnSettings.CellTemplate>
            </t:DataGridColumnSettings>
        </DataTemplate>
    </t:DataGridColumns.ColumnSettingsTemplate>
</DataGrid>

I think the easiest approach would be to add one more dependency property to take a cell template. Then if this exist, create DataGridTemplateColumn instead of  DataGridTextColumn when filling the DataGrid, but i have a little problem with Binding my CellTemplate TextBlock to ColumnBindingPath dependency property. Please help ...

A: The syntax for binding to an attached property would be:
<TextBlock Text="{Binding Path=(t.DataGridColumns.ColumnBindingPath)}"/>

The Path= needs to be written explicitly when binding to attached properties. This has been fixed in WPF 4.5, so there it may be sufficient to write
<TextBlock Text="{Binding (t.DataGridColumns.ColumnBindingPath)}"/>

Note, that you still need parenthesis around the property. Does this answer your question already?


text:
Q: Is it stupid to calculate the mean of standard deviations I have several point on a chromosome that I am getting measurements from. Each point is measured 15 times. I want to demonstrate that the standard deviation across the whole chromosome for each point, for this measurement, is very low. I also want to show the median, upper and lower quartile for teh standard deviations across the whole chromosome. Is it too simple to just get standard deviations for the 15 measurements at each point within a chromosome and then average them (and get medians etc?

A: If you are repeating your experiment 15 times...
Then you may get 15 different standard deviations for each experiment....
I think it won't be stupid to go for mean of standard deviation of 15 experiments in this case....


text:
Q: Invoke-Command to Microsoft Exchange a recent patch of Microsoft Exchange changed the way people can use Invoke-Command to an Microsoft Exchange server.
Invoke-Command -Session $ExOSessionVariable -ScriptBlock {Get-RemoteMailbox -Identity UserName ; Get-User -Identity UserName}

is returning:
The syntax is not supported by this runspace. This can occur if the runspace is in no-language mode.

This behavior has changed since : https://techcommunity.microsoft.com/t5/exchange-team-blog/released-april-2021-exchange-server-security-updates
Microsoft advices to use .AddScript() or .AddCommand(). can someone tell me how to use this commands with invoke-Command ?
Any help is appreciated.
Michael

A: I think the semicolon is causing the problem in your example.
So this is a workaround rather than a direct answer to your question.
If you replace your script block, for example:
$Scriptblock = {
  Get-RemoteMailbox -Identity UserName
  Get-User -Identity UserName
}

Invoke-Command -Session $ExOSessionVariable -ScriptBlock $Scriptblock

It should work.


text:
Q: SQlite query for stop times in GTFS data I am working with GTFS data on Android (SQlite). And I would like to improve performance when I do select queries in my database filled with GTFS data.
The query below select the stop times associated to a route at a stop:
The first sub query gets the daily stop times on thursday.
The second gets all the exception stop times which are not valid for TODAY (2013-07-25).
The third one gets all the exception stop time which are only valid for TODAY (2013-07-25).
Then I remove the non-valid one and add the valid one to the first sub query.
select distinct stop_times_arrival_time
from stop_times, trips, calendar
where stop_times_trip_id=trip_id
and calendar_service_id=trip_service_id
and trip_route_id='11821949021891616'
and stop_times_stop_id='3377699721872252'
and calendar_start_date<='20130725'
and calendar_end_date>='20130725'
and calendar_thursday=1
and stop_times_arrival_time>='07:40'

except

select stop_times_arrival_time
from stop_times, trips, calendar, calendar_dates
where stop_times_trip_id=trip_id
and calendar_service_id=trip_service_id
and calendar_dates_service_id = trip_service_id
and trip_route_id='11821949021891694'
and stop_times_stop_id='3377699720880977'
and calendar_thursday=1
and calendar_dates_exception_type=2
and stop_times_arrival_time > '07:40'
and calendar_dates_date = 20130725

union

select stop_times_arrival_time
from stop_times, trips, calendar, calendar_dates
where stop_times_trip_id=trip_id
and calendar_service_id=trip_service_id
and calendar_dates_service_id = trip_service_id
and trip_route_id='11821949021891694'
and stop_times_stop_id='3377699720880977'
and calendar_thursday=1
and calendar_dates_exception_type=1
and stop_times_arrival_time > '07:40'
and calendar_dates_date = 20130725;

It took about 15 seconds to compute (which is very long).
I am sure there is a better to do this query since I do 3 different queries (almost the same by the way) which take time.
Any idea how to improve it?
EDIT:
Here is the schema:
table|calendar|calendar|2|CREATE TABLE calendar (
    calendar_service_id TEXT PRIMARY KEY,
    calendar_monday INTEGER,
    calendar_tuesday INTEGER,
    calendar_wednesday INTEGER,
    calendar_thursday INTEGER,
    calendar_friday INTEGER,
    calendar_saturday INTEGER,
    calendar_sunday INTEGER,
    calendar_start_date TEXT,
    calendar_end_date TEXT
)
index|sqlite_autoindex_calendar_1|calendar|3|
table|calendar_dates|calendar_dates|4|CREATE TABLE calendar_dates (
        calendar_dates_service_id TEXT,
        calendar_dates_date TEXT,
        calendar_dates_exception_type INTEGER
)
table|routes|routes|8|CREATE TABLE routes (
        route_id TEXT PRIMARY KEY,
        route_short_name TEXT,
        route_long_name TEXT,
        route_type INTEGER,
        route_color TEXT
)
index|sqlite_autoindex_routes_1|routes|9|
table|stop_times|stop_times|12|CREATE TABLE stop_times (
        stop_times_trip_id TEXT,
        stop_times_stop_id TEXT,
        stop_times_stop_sequence INTEGER,
        stop_times_arrival_time TEXT,
        stop_times_pickup_type INTEGER
)
table|stops|stops|13|CREATE TABLE stops (
        stop_id TEXT PRIMARY KEY,
        stop_name TEXT,
        stop_lat REAL,
        stop_lon REAL
)
index|sqlite_autoindex_stops_1|stops|14|
table|trips|trips|15|CREATE TABLE trips (
        trip_id TEXT PRIMARY KEY,
        trip_service_id TEXT,
        trip_route_id TEXT,
        trip_headsign TEXT,
        trip_direction_id INTEGER,
        trip_shape_id TEXT
)
index|sqlite_autoindex_trips_1|trips|16|

And here is the query plan:
2|0|0|SCAN TABLE stop_times (~33333 rows)
2|1|1|SEARCH TABLE trips USING INDEX sqlite_autoindex_trips_1 (trip_id=?) (~1 rows)
2|2|2|SEARCH TABLE calendar USING INDEX sqlite_autoindex_calendar_1 (calendar_service_id=?) (~1 rows)
3|0|3|SCAN TABLE calendar_dates (~10000 rows)
3|1|2|SEARCH TABLE calendar USING INDEX sqlite_autoindex_calendar_1 (calendar_service_id=?) (~1 rows)
3|2|0|SEARCH TABLE stop_times USING AUTOMATIC COVERING INDEX (stop_times_stop_id=?) (~7 rows)
3|3|1|SEARCH TABLE trips USING INDEX sqlite_autoindex_trips_1 (trip_id=?) (~1 rows)
1|0|0|COMPOUND SUBQUERIES 2 AND 3 USING TEMP B-TREE (EXCEPT)
4|0|3|SCAN TABLE calendar_dates (~10000 rows)
4|1|2|SEARCH TABLE calendar USING INDEX sqlite_autoindex_calendar_1 (calendar_service_id=?) (~1 rows)
4|2|0|SEARCH TABLE stop_times USING AUTOMATIC COVERING INDEX (stop_times_stop_id=?) (~7 rows)
4|3|1|SEARCH TABLE trips USING INDEX sqlite_autoindex_trips_1 (trip_id=?) (~1 rows)
0|0|0|COMPOUND SUBQUERIES 1 AND 4 USING TEMP B-TREE (UNION)

A: Columns that are used for lookups should be indexed, but for a single (sub)query, it is not possible to use more than one index per table.
For this particular query, the following additional indexes would help:
CREATE INDEX some_index ON stop_times(
    stop_times_stop_id,
    stop_times_arrival_time);
CREATE INDEX some_other_index ON calendar_dates(
    calendar_dates_service_id,
    calendar_dates_exception_type,
    calendar_dates_date);


text:
Q: Change $TMPDIR in a parallel processing I run a batch job on a high-performance computing system to sort aligned reads and used GNU parallel to speed up my work, but my job failed with the following reason:

parallel: Error: Output is incomplete. Cannot append to buffer file in
  $TMPDIR. Is the disk full? parallel: Error: Change $TMPDIR with
  --tmpdir or use --compress.

My job script looks like this:
module load samtools/1.2

export TMPDIR=/scratch/$SLURM_JOBID

cd /data
ls *sam* | parallel "samtools sort –T /scratch/$SLURM_JOBID/{.} -O bam -o {}.bam {}"

Does anyone know how to solve this problem?

A: I get the same message "parallel: Error: Change $TMPDIR with --tmpdir or use --compress"
I try adding "--tmpdir /home/mydirectory" to the script, but when I see the file "/home/mydirectory/" doesn't create anything, I see the default directory "/tmp/" and the temporally files (like /tmp/pAh6uWuQCg, /tmp/opjhZCzAX4, etc) are still created in that directory. For me it means that the parameter "--tmpdir /home/mydirectory" in the script does not work.
In my case I run the script of my app isolated and check the logs, and realize that my app was with error, for that the logs shows error messages and it was fill the file "/tmp/"
Maybe my experience will help you

A: Have you tried what GNU Parallel suggests?
parallel: Error: Change $TMPDIR with --tmpdir or use --compress.


text:
Q: Validating and Displaying database info from Xamarin.Forms I'm starting to learn how to use Xamarin.Forms for app development. I'm making a simple app that only consists of a sign up, sign in and a page displaying the corresponding info when you sign in.
However, I'm running into some issues so far, mainly data validation. Why is it so complex in XAML? in HTML, you can just set the property "required", whereas every solution I've seen for XF that even claims to be "simple" consists of sometimes hundreds of lines of code.
After, data validation, I also want to make sure that the app won't let me save information if there's already an user registered with that email address. Lastly, I want to output an user's information once they log in.
My app consists of 3 views: SignUpPage, LoginPage and HomePage. Upon successful authentication, the user is taken to HomePage.
I'm using SQLite to handle the DB, with a single table RegUserTable.cs
This is the RegistrationPage.xaml.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.IO;
using SQLite;
using System.Text;
using System.Threading.Tasks;
using UNEDProFinal.Tables;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;

namespace UNEDProFinal.Views
{
    [XamlCompilation(XamlCompilationOptions.Compile)]
    public partial class RegistrationPage : ContentPage
    {
        public RegistrationPage()
        {
            InitializeComponent();
        }

        void Handle_Clicked(object sender, EventArgs e)
        {
            var dbpath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "UserDatabase.db");
            var db = new SQLiteConnection(dbpath);
            db.CreateTable<RegUserTables>();

            var ChosenDate = EntryUserDOB.ToString();

            if (EntryUserPassword.Text != ConfirmEntryUserPassword.Text)
            {
                Device.BeginInvokeOnMainThread(async () =>
                {
                    var passError = await this.DisplayAlert("Las contraseñas no concuerdan", "Error", "Intentarlo de Nuevo", "Salir");
                    if (passError)
                        await Navigation.PushAsync(new RegistrationPage());
                    else
                    {
                        await Navigation.PushAsync(new LoginPage());
                    }
                });
            }

            else
            {

                var item = new RegUserTables()
                {
                    UserName = EntryUserName.Text,
                    Password = EntryUserPassword.Text,
                    Email = EntryUserEmail.Text,
                    PhoneNumber = EntryUserPhoneNumber.Text,
                    UserFirstSurname = EntryUserFirstSurname.Text,
                    UserLastSurname = EntryUserLastSurname.Text,
                    UserDOB = ChosenDate
                };

                db.Insert(item);
                Device.BeginInvokeOnMainThread(async () =>
                {
                    var result = await this.DisplayAlert("Felicidades", "Usuario Registrado", "Continuar", "Salir");
                    if (result)
                        await Navigation.PushAsync(new LoginPage());
                });
            }
        }
    }

}

And the RegistrationPage.Xaml
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:d="http://xamarin.com/schemas/2014/forms/design"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             mc:Ignorable="d"
             x:Class="UNEDProFinal.Views.RegistrationPage">
    <ContentPage.Content>
        <ScrollView>
            <StackLayout>
                <Grid Margin="20,0,0,0" VerticalOptions="CenterAndExpand">
                    <Grid.RowDefinitions>
                        <RowDefinition Height="Auto"/>
                        <RowDefinition Height="Auto"/>
                        <RowDefinition Height="Auto"/>
                        <RowDefinition Height="Auto"/>
                        <RowDefinition Height="Auto"/>
                        <RowDefinition Height="Auto"/>
                        <RowDefinition Height="Auto"/>
                        <RowDefinition Height="Auto"/>
                        <RowDefinition Height="Auto"/>
                    </Grid.RowDefinitions>

                    <StackLayout Grid.Row="0">
                        <Entry Placeholder="Nombre" FontSize="16" x:Name="EntryUserName"/>
                    </StackLayout>
                    <StackLayout Grid.Row="1">
                        <Entry Placeholder="Primer Apellido" FontSize="16" x:Name="EntryUserFirstSurname"/>
                    </StackLayout>
                    <StackLayout Grid.Row="2">
                        <Entry Placeholder="Segundo Apellido" FontSize="16" x:Name="EntryUserLastSurname"/>
                    </StackLayout>
                    <StackLayout Grid.Row="3">
                        <DatePicker  FontSize="16" Format="D" x:Name="EntryUserDOB"/>
                    </StackLayout>
                    <StackLayout Grid.Row="4">
                        <Entry Placeholder="Email" FontSize="16" x:Name="EntryUserEmail"/>
                    </StackLayout>
                    <StackLayout Grid.Row="5">
                        <Entry Placeholder="Número teléfonico" FontSize="16" x:Name="EntryUserPhoneNumber"/>
                    </StackLayout>
                    <StackLayout Grid.Row="6">
                        <Entry Placeholder="Password" IsPassword="True" FontSize="16" x:Name="EntryUserPassword"/>
                    </StackLayout>
                    <StackLayout Grid.Row="7">
                        <Entry Placeholder="Confirm Password" IsPassword="True" FontSize="16" x:Name="ConfirmEntryUserPassword"/>
                    </StackLayout>
                    <StackLayout Grid.Row="8">
                        <Button Text="Register" HorizontalOptions="CenterAndExpand" TextColor="White" BackgroundColor="Blue" Clicked="Handle_Clicked"/>
                    </StackLayout>

                </Grid>
            </StackLayout>
        </ScrollView>
    </ContentPage.Content>
</ContentPage>

And I want to output the information the user entered once he logs in on HomePage.Xaml, which hasn't got anything on it so far.
Lastly, here's the table
using System;
namespace UNEDProFinal.Tables
{
    public class RegUserTables
    {
        public Guid UserId { get; set; }
        public string UserName { get; set; }
        public string UserFirstSurname { get; set; }
        public string UserLastSurname { get; set; }
        public string Password { get; set; }
        public string Email { get; set; }
        public string PhoneNumber { get; set; }
        public string UserDOB { get; set; }

    }
}

I'd also like to know...with my current logic for saving information, is the database actually relating the entered information to a specific user? Or would it just be throwing random information?

A:
I'd like to find a simple way to validate information in
  xamarin.forms

You can write your own Validation by using behaviors in Xamarin.forms. For example:
public class PasswordValidationBehavior : Behavior<Entry>
{
    const string passwordRegex = @"^(?=.*[A-Za-z])(?=.*\d)(?=.*[$@$!%*#?&])[A-Za-z\d$@$!%*#?&]{8,}$";

    protected override void OnAttachedTo(Entry bindable)
    {
        bindable.TextChanged += HandleTextChanged;
        base.OnAttachedTo(bindable);
    }

    void HandleTextChanged(object sender, TextChangedEventArgs e)
    {
        bool IsValid = false;
        IsValid = (Regex.IsMatch(e.NewTextValue, passwordRegex));
        ((Entry)sender).TextColor = IsValid ? Color.Default : Color.Red;
    }

    protected override void OnDetachingFrom(Entry bindable)
    {
        bindable.TextChanged -= HandleTextChanged;
        base.OnDetachingFrom(bindable);
    }
}

You can also have e-mailValidationBehavior, PhoneNumberValidationBehavior and etc. Then add those Validations to Corresponding Entry and reuse these Validations in different Entry:
<Entry Placeholder="Enter a PassWord">
    <Entry.Behaviors>
        <local:PasswordValidationBehavior />
    </Entry.Behaviors>
</Entry>

Here are some blogs you can read: input-validation-in-xamarin-forms-behaviors and custom-entry-validation-in-xamarin-forms

I'd like to find a way to display that saved information in a page of
  the app.

Since you have saved information in the local DB, you can query personal info by specific UserId from DB and then show them in the Page with Data-binding or other ways you want. Feel free to ask me any question.
Refer : data-bindings-to-mvvm


text:
Q: How do I pull in the right number of dynamically generated variables using php and javascript? I have multiple textboxes that are dynamically generated; the number of boxes can differ each time. How do I match the number of variables created in javascript (box1, box2, etc) with the number of rows called from the table on the back-end?  An example: if there are only 2 rows as a result of $query, there should only be 2 javascript variables (box1 and box2).  At the same time, how do I dynamically generate the right url that corresponds to the right number?
$query = "SELECT * FROM `sessionid` WHERE `sessionid` = '$session'  ";
$result = mysql_query($query) or die(mysql_error());
echo '

';
$subtotal = 0;
$i=1;
while($row = mysql_fetch_assoc($result)) {
  echo '

' . $row['title'] . '
	' . $row['options'] . '
<input type="text" id="box' . $i . '"value="' . $row['qt'] . '" class="span1"> <input type="button" class="btn" value = "Refresh" onclick="ajaxFunction()" />
 $' . $row['price'] . '
Your result will display here

';
  $i++;
  $prodtotal= $row['qt'] * $row['price'];
  $subtotal= round($subtotal+ $prodtotal, 2);
  $_SESSION['subtotal']=$subtotal;
}

echo '</form>

';

//javascript later on
var box1 = document.getElementById('box1').value;
var box2 = document.getElementById('box2').value;
var box3 = document.getElementById('box3').value;
var box4 = document.getElementById('box4').value;
var queryString = "?box1=" + box1 + "&box2=" + box2 + "&box3=" + box3 + "&box4=" + box4;

A: You should output your JavaScript as part of the loop that goes through your result. Therefore you would change this:
        while($row = mysql_fetch_assoc($result)) {
                echo '

' . $row['title'] . '
	' . $row['options'] . '
<input type="text" id="box' . $i . '"value="' . $row['qt'] . '" class="span1"> <input type="button" class="btn" value = "Refresh" onclick="ajaxFunction()" />
 $' . $row['price'] . '
Your result will display here

';
                $i++;
                $prodtotal= $row['qt'] * $row['price'];
                $subtotal= round($subtotal+ $prodtotal, 2);
                $_SESSION['subtotal']=$subtotal;
                }

To something like:
$str = '';
while($row = mysql_fetch_assoc($result)) {
        echo '

' . $row['title'] . '
	' . $row['options'] . '
<input type="text" id="box' . $i . '"value="' . $row['qt'] . '" class="span1"> <input type="button" class="btn" value = "Refresh" onclick="ajaxFunction()" />
 $' . $row['price'] . '
Your result will display here

';

$str .= 'var box'.$i.' = document.getElementById("box'.$i.'").value;'.PHP_EOL;

        $i++;
        $prodtotal= $row['qt'] * $row['price'];
        $subtotal= round($subtotal+ $prodtotal, 2);
        $_SESSION['subtotal']=$subtotal;
    }

And where your JavaScript is...
echo $str;

A: My suggestions:
1 . PHP and javascript
PHP:
$cnt = 0;
while($row = mysql_fetch_assoc($result)) {
  cnt++;
.
.
.
}

JavaScript:
var qString = "";
for (var i=1;i<=<?php echo $cnt; ?>;i++) {
  qString += '&box'+i+'='+document.getElementById('box'+i).value;
}
qString = "?"+qString.substring(1);

2 . PHP only:
<input type="text" id="box[]" value="'....

and simply submit the form or use jQuery Ajax with serialize.

A: You could gather an array of box values in your JavaScript, e.g.
var boxValues = new Array();
var i = 1;
while (document.getElementById('box' + i) !== undefined) {
    var box = document.getElementById('box' + i);
    boxValues[i] = box.value;
    i++;
}
var queryString = '?';
for(i = 1; i < boxValues.length; i++) {
    queryString += 'box' + i + '=' + boxValues[i] + '&';
}
queryString = queryString.slice(0, -1); // eat the last '&'

This approach has the advantage of not needing to embed php in your JS (dubious comparisons aside, e.g. if you have another page element with id 'box6' and your table ends at 'box5', you will get funky results). Of course, if you don't need the references to the values other than to build the query string, you could just build the string while looping over the values and skip storing them in an array at all, e.g.
var i = 1;
var queryString = '?';
while (document.getElementById('box' + i) !== undefined) {
    var boxValue = document.getElementById('box' + i).value;
    queryString += 'box' + i + '=' + boxValue + '&';
    i++;
}
queryString = queryString.slice(0, -1); // eat the last '&'


text:
Q: Transaction Rollback while updating - Junit of DataJPA I am working with springboot 2.6.3 and junit5, and writing data jpa unit test cases , i am writing unit test case for update, the test result is success but I am getting transaction rollback, it is not committing to db.

2022-02-20 19:14:45.183  INFO 19942 --- [           main] o.s.t.c.transaction.TransactionContext   : Rolled back transaction for

Here is the more details of the logs

2022-02-20 19:14:19.324  INFO 19942 --- [           main] c.c.c.ConfigServicePropertySourceLocator : Fetching config from server at : http://localhost:8888
2022-02-20 19:14:19.688  INFO 19942 --- [           main] c.c.c.ConfigServicePropertySourceLocator : Connect Timeout Exception on Url - http://localhost:8888. Will be trying the next url if available
2022-02-20 19:14:19.689  WARN 19942 --- [           main] c.c.c.ConfigServicePropertySourceLocator : Could not locate PropertySource: I/O error on GET request for "http://localhost:8888/application/default": Connection refused; nested exception is java.net.ConnectException: Connection refused
2022-02-20 19:14:19.725  INFO 19942 --- [           main] c.u.r.SystemUserRepositoryTest           : No active profile set, falling back to default profiles: default
2022-02-20 19:14:22.366  INFO 19942 --- [           main] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data JPA repositories in DEFAULT mode.
2022-02-20 19:14:22.631  INFO 19942 --- [           main] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 241 ms. Found 3 JPA repository interfaces.
2022-02-20 19:14:23.634  INFO 19942 --- [           main] o.s.cloud.context.scope.GenericScope     : BeanFactory id=2d3b8fac-a232-3295-b483-ac7040d3c59c
2022-02-20 19:14:25.314  INFO 19942 --- [           main] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Starting...
2022-02-20 19:14:26.856  INFO 19942 --- [           main] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Start completed.
2022-02-20 19:14:27.118  INFO 19942 --- [           main] o.hibernate.jpa.internal.util.LogHelper  : HHH000204: Processing PersistenceUnitInfo [name: default]
2022-02-20 19:14:27.326  INFO 19942 --- [           main] org.hibernate.Version                    : HHH000412: Hibernate ORM core version 5.6.3.Final
2022-02-20 19:14:27.868  INFO 19942 --- [           main] o.hibernate.annotations.common.Version   : HCANN000001: Hibernate Commons Annotations {5.1.2.Final}
2022-02-20 19:14:28.538  INFO 19942 --- [           main] org.hibernate.dialect.Dialect            : HHH000400: Using dialect: org.hibernate.dialect.MySQL8Dialect
2022-02-20 19:14:31.940  INFO 19942 --- [           main] o.h.e.t.j.p.i.JtaPlatformInitiator       : HHH000490: Using JtaPlatform implementation: [org.hibernate.engine.transaction.jta.platform.internal.NoJtaPlatform]
2022-02-20 19:14:31.974  INFO 19942 --- [           main] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
2022-02-20 19:14:35.704  WARN 19942 --- [           main] JpaBaseConfiguration$JpaWebConfiguration : spring.jpa.open-in-view is enabled by default. Therefore, database queries may be performed during view rendering. Explicitly configure spring.jpa.open-in-view to disable this warning
2022-02-20 19:14:41.385  INFO 19942 --- [           main] c.u.c.UserManagementSecurityConfigurer   : The password of the restful service is $2a$10$ao9M1pLRtM06lPpRzU1SuOoVeESDiCOD/npBkFyesZN8i2P7t.F.y
2022-02-20 19:14:41.920  INFO 19942 --- [           main] o.s.s.web.DefaultSecurityFilterChain     : Will secure any request with [org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter@4ba32242, org.springframework.security.web.context.SecurityContextPersistenceFilter@10ecf244, org.springframework.security.web.header.HeaderWriterFilter@628d6320, org.springframework.security.web.authentication.logout.LogoutFilter@64ef9b9a, org.springframework.security.web.authentication.www.BasicAuthenticationFilter@5a0b925a, org.springframework.security.web.savedrequest.RequestCacheAwareFilter@a703934, org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter@369f85c6, org.springframework.security.web.authentication.AnonymousAuthenticationFilter@581f1f40, org.springframework.security.web.session.SessionManagementFilter@174e5929, org.springframework.security.web.access.ExceptionTranslationFilter@63ead376, org.springframework.security.web.access.intercept.AuthorizationFilter@6d21a69f]
2022-02-20 19:14:42.461  INFO 19942 --- [           main] c.u.r.SystemUserRepositoryTest           : Started SystemUserRepositoryTest in 26.565 seconds (JVM running for 29.504)
2022-02-20 19:14:42.610  INFO 19942 --- [           main] o.s.t.c.transaction.TransactionContext   : Began transaction (1) for test context [DefaultTestContext@3f390d63 testClass = SystemUserRepositoryTest, testInstance = com.usermgmtservice.repositories.SystemUserRepositoryTest@1cc5d8a9, testMethod = updateSystemUserTest@SystemUserRepositoryTest, testException = [null], mergedContextConfiguration = [WebMergedContextConfiguration@74a6a609 testClass = SystemUserRepositoryTest, locations = '{}', classes = '{class com.usermgmtservice.UserMgmtApplication}', contextInitializerClasses = '[]', activeProfiles = '{}', propertySourceLocations = '{}', propertySourceProperties = '{org.springframework.boot.test.context.SpringBootTestContextBootstrapper=true}', contextCustomizers = set[org.springframework.boot.test.context.filter.ExcludeFilterContextCustomizer@4808bc9b, org.springframework.boot.test.json.DuplicateJsonObjectContextCustomizerFactory$DuplicateJsonObjectContextCustomizer@13df2a8c, org.springframework.boot.test.mock.mockito.MockitoContextCustomizer@0, org.springframework.boot.test.web.client.TestRestTemplateContextCustomizer@e25951c, org.springframework.boot.test.autoconfigure.actuate.metrics.MetricsExportContextCustomizerFactory$DisableMetricExportContextCustomizer@2dc9b0f5, org.springframework.boot.test.autoconfigure.properties.PropertyMappingContextCustomizer@0, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverContextCustomizerFactory$Customizer@7bf3a5d8, org.springframework.boot.test.context.SpringBootTestArgs@1, org.springframework.boot.test.context.SpringBootTestWebEnvironment@22635ba0], resourceBasePath = 'src/main/webapp', contextLoader = 'org.springframework.boot.test.context.SpringBootContextLoader', parent = [null]], attributes = map['org.springframework.test.context.web.ServletTestExecutionListener.activateListener' -> true, 'org.springframework.test.context.web.ServletTestExecutionListener.populatedRequestContextHolder' -> true, 'org.springframework.test.context.web.ServletTestExecutionListener.resetRequestContextHolder' -> true, 'org.springframework.test.context.event.ApplicationEventsTestExecutionListener.recordApplicationEvents' -> false]]; transaction manager [org.springframework.orm.jpa.JpaTransactionManager@32c114d9]; rollback [true]
Hibernate: select systemuser0_.system_user_id as system_u1_1_, systemuser0_.activated_dt as activate2_1_, systemuser0_.created_by as created_3_1_, systemuser0_.created_dt as created_4_1_, systemuser0_.email_address as email_ad5_1_, systemuser0_.email_verification_otp_code as email_ve6_1_, systemuser0_.email_verification_otp_code_generated_dt as email_ve7_1_, systemuser0_.email_verification_otp_code_verified_status as email_ve8_1_, systemuser0_.first_nm as first_nm9_1_, systemuser0_.last_modified_by as last_mo10_1_, systemuser0_.last_modified_dt as last_mo11_1_, systemuser0_.last_nm as last_nm12_1_, systemuser0_.mobile_nbr as mobile_13_1_, systemuser0_.mobile_nbr_otp_code as mobile_14_1_, systemuser0_.mobile_nbr_otp_code_generated_dt as mobile_15_1_, systemuser0_.mobile_nbr_otp_code_verified_status as mobile_16_1_, systemuser0_.password as passwor17_1_, systemuser0_.registered_dt as registe18_1_, systemuser0_.status as status19_1_, systemuser0_.user_role_id as user_ro20_1_ from system_user systemuser0_ where systemuser0_.email_address=?
Hibernate: select userrole0_.user_role_id as user_rol1_2_0_, userrole0_.created_by as created_2_2_0_, userrole0_.created_dt as created_3_2_0_, userrole0_.description as descript4_2_0_, userrole0_.last_modified_by as last_mod5_2_0_, userrole0_.last_modified_dt as last_mod6_2_0_, userrole0_.role_nm as role_nm7_2_0_, userrole0_.status as status8_2_0_ from user_role userrole0_ where userrole0_.user_role_id=?
Before -> the opsystemuser is not empty and its firstname is David , systemUserId = 7, status = R
Hibernate: update system_user set status=?, mobile_nbr_otp_code_verified_status=?, email_verification_otp_code_verified_status=?, last_modified_dt=?, activated_dt=? where system_user_id=?
Hibernate: select systemuser0_.system_user_id as system_u1_1_, systemuser0_.activated_dt as activate2_1_, systemuser0_.created_by as created_3_1_, systemuser0_.created_dt as created_4_1_, systemuser0_.email_address as email_ad5_1_, systemuser0_.email_verification_otp_code as email_ve6_1_, systemuser0_.email_verification_otp_code_generated_dt as email_ve7_1_, systemuser0_.email_verification_otp_code_verified_status as email_ve8_1_, systemuser0_.first_nm as first_nm9_1_, systemuser0_.last_modified_by as last_mo10_1_, systemuser0_.last_modified_dt as last_mo11_1_, systemuser0_.last_nm as last_nm12_1_, systemuser0_.mobile_nbr as mobile_13_1_, systemuser0_.mobile_nbr_otp_code as mobile_14_1_, systemuser0_.mobile_nbr_otp_code_generated_dt as mobile_15_1_, systemuser0_.mobile_nbr_otp_code_verified_status as mobile_16_1_, systemuser0_.password as passwor17_1_, systemuser0_.registered_dt as registe18_1_, systemuser0_.status as status19_1_, systemuser0_.user_role_id as user_ro20_1_ from system_user systemuser0_ where systemuser0_.email_address=?
After -> the opsystemuser is not empty and its firstname is David , systemUserId = 7, status = R
2022-02-20 19:14:45.183  INFO 19942 --- [           main] o.s.t.c.transaction.TransactionContext   : Rolled back transaction for test: [DefaultTestContext@3f390d63 testClass = SystemUserRepositoryTest, testInstance = com.usermgmtservice.repositories.SystemUserRepositoryTest@1cc5d8a9, testMethod = updateSystemUserTest@SystemUserRepositoryTest, testException = [null], mergedContextConfiguration = [WebMergedContextConfiguration@74a6a609 testClass = SystemUserRepositoryTest, locations = '{}', classes = '{class com.usermgmtservice.UserMgmtApplication}', contextInitializerClasses = '[]', activeProfiles = '{}', propertySourceLocations = '{}', propertySourceProperties = '{org.springframework.boot.test.context.SpringBootTestContextBootstrapper=true}', contextCustomizers = set[org.springframework.boot.test.context.filter.ExcludeFilterContextCustomizer@4808bc9b, org.springframework.boot.test.json.DuplicateJsonObjectContextCustomizerFactory$DuplicateJsonObjectContextCustomizer@13df2a8c, org.springframework.boot.test.mock.mockito.MockitoContextCustomizer@0, org.springframework.boot.test.web.client.TestRestTemplateContextCustomizer@e25951c, org.springframework.boot.test.autoconfigure.actuate.metrics.MetricsExportContextCustomizerFactory$DisableMetricExportContextCustomizer@2dc9b0f5, org.springframework.boot.test.autoconfigure.properties.PropertyMappingContextCustomizer@0, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverContextCustomizerFactory$Customizer@7bf3a5d8, org.springframework.boot.test.context.SpringBootTestArgs@1, org.springframework.boot.test.context.SpringBootTestWebEnvironment@22635ba0], resourceBasePath = 'src/main/webapp', contextLoader = 'org.springframework.boot.test.context.SpringBootContextLoader', parent = [null]], attributes = map['org.springframework.test.context.web.ServletTestExecutionListener.activateListener' -> true, 'org.springframework.test.context.web.ServletTestExecutionListener.populatedRequestContextHolder' -> true, 'org.springframework.test.context.web.ServletTestExecutionListener.resetRequestContextHolder' -> true, 'org.springframework.test.context.event.ApplicationEventsTestExecutionListener.recordApplicationEvents' -> false]]
2022-02-20 19:14:45.299  INFO 19942 --- [ionShutdownHook] j.LocalContainerEntityManagerFactoryBean : Closing JPA EntityManagerFactory for persistence unit 'default'
2022-02-20 19:14:45.308  INFO 19942 --- [ionShutdownHook] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Shutdown initiated...
2022-02-20 19:14:45.341  INFO 19942 --- [ionShutdownHook] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Shutdown completed.

Here is my repository code

public interface SystemUserRepository extends JpaRepository<SystemUser, Long> {

    @Modifying
    @Query("update SystemUser su set su.status=?2, su.mobileNoOtpCodeVerifiedStatus=?3, su.emailVerificationOtpCodeVerifiedStatus=?4, su.lastModifiedDate = ?5 ,su.activatedDate = ?6 where su.systemUserId = ?1")
    public int update(long systemUserId, String status, int otpVerificationCodeVerifiedStatus,
            int emailVerificationCodeVerifiedStatus, Date lastModifiedDate, Date activatedDate);

    public Optional<SystemUser> findByEmailAddress(String emailAddress);

}

test code

@Test
@Transactional
void updateSystemUserTest() {
        String emailAddress = "test@gmail.com";
        Date date = new Date();
        Optional<SystemUser> opSystemUser = this.systemUserRepository.findByEmailAddress(emailAddress);

        SystemUser systemUser = opSystemUser.get();
        System.out.println("Before -> the opsystemuser is not empty and its firstname is "+systemUser.getFirstName()+" , systemUserId = "+ systemUser.getSystemUserId()+", status = " + systemUser.getStatus());

        int updatedRecords = this.systemUserRepository.update(systemUser.getSystemUserId(), "A", 1, 1, date, date);

        opSystemUser = this.systemUserRepository.findByEmailAddress(emailAddress);
        systemUser = opSystemUser.get();
        System.out.println("After -> the opsystemuser is not empty and its firstname is "+systemUser.getFirstName()+" , systemUserId = "+ systemUser.getSystemUserId()+", status = " + systemUser.getStatus());
        assertEquals(1, updatedRecords);

    }

A: you also need to add @Rollback(false) with @Test, @Transactional


text:
Q: Adding colors to a few cells in a table view I've looked at dozens of answers to this problem on this very site but I still can't get it to work. I, like many before me, want to change the color in a few cells in a table view. I tried putting a conditional if (indexPath.row == ...) then change the color of a few cells to red, but this always results in other cells gradually becoming red changing the more I scroll. I tried moving this code from:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

To here:
- (void)tableView: (UITableView*)tableView willDisplayCell: (UITableViewCell*)cell forRowAtIndexPath: (NSIndexPath*)indexPath

But this still doesn't work. How can I change the colors of cells, say, 5. 13, and 40 to be red?

A: This may be a problem in your cell reuse, that is why you got colours changing when scrolling.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

//Cell creation code goes here, including cell re-usage

    if(indexPath.row % 2 == 0){
        cell.backgroundColor = [UIColor redColor];
    }
    //This else part is IMPORTANT
    else{
        cell.backgroundColor = [UIColor clearColor];
    }
}

You'll get a better understanding about Cell Reuse in UITableView

A: Please try to use this method..
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(indexPath.row == 5 | indexPath.row == 13 | indexPath.row == 40)
        cell.backgroundColor = [UIColor redColor];
    else
        cell.backgroundColor = [UIColor clearColor];
}

A: If you large number of value you can take in array and put in a condition like
if([array containsObject:indexPath.row])

Otherwise this is good to give color in cell in willDisplayCell
-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath{
    if(indexPath.row == 5 | indexPath.row == 13 | indexPath.row == 40)
        cell.backgroundColor = [UIColor redColor];
    else
        cell.backgroundColor = [UIColor clearColor];
}


text:
Q: Log4net configuring programmatically an adoAppender I need to add an ado appender to an existing log4net config.
I need to add it via code. However i'm stuck on adding common string parameters like message as I can't define the layout property correctly : In xml configuration, we use PatternLayout, but via code PatternLayout is not a IRowLayout so I have an error with the following code :
    public static void AddStringParameterToAppender(this log4net.Appender.AdoNetAppender appender, string paramName, int size, string conversionPattern)
    {
        log4net.Appender.AdoNetAppenderParameter param = new log4net.Appender.AdoNetAppenderParameter();
        param.ParameterName = paramName;
        param.DbType = System.Data.DbType.String;
        param.Size = size;
        param.Layout = new log4net.Layout.PatternLayout(conversionPattern);
        appender.AddParameter(param);
    }

Does someone know how to add a string parameter in code which is similar to the following xml sample :
<parameter>
    <parameterName value="@message" />
    <dbType value="String" />
    <size value="4000" />
    <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%message" />
    </layout>
</parameter>

A: I've finally found how to transform the PatternLayout in an IRawLayout.
To do this, you have to use log4net.Layout.Layout2RawLayoutAdapter:
public static void AddStringParameterToAppender(this log4net.Appender.AdoNetAppender appender, string paramName, int size, string conversionPattern)
    {
        log4net.Appender.AdoNetAppenderParameter param = new log4net.Appender.AdoNetAppenderParameter();
        param.ParameterName = paramName;
        param.DbType = System.Data.DbType.String;
        param.Size = size;
        param.Layout = new log4net.Layout.Layout2RawLayoutAdapter(new log4net.Layout.PatternLayout(conversionPattern));
        appender.AddParameter(param);
    }


text:
Q: ASP.NET SessionID Management Hi I wanted to know how the server manages session between client and server. Does the server store a sessionID per web-application and client or only per client?

A: Session have following properties  Read this article
Session is Stored  per User basis.

from MSDN Docs Session in asp.net

Sessions are identified by a unique identifier that can be read by
  using the SessionID property. When session state is enabled for an
  ASP.NET application, each request for a page in the application is
  examined for a SessionID value sent from the browser. If no SessionID
  value is supplied, ASP.NET starts a new session and the SessionID
  value for that session is sent to the browser with the response. By
  default, SessionID values are stored in a cookie. However, you can
  also configure the application to store SessionID values in the URL
  for a "cookieless" session. A session is considered active as long as
  requests continue to be made with the same SessionID value. If the
  time between requests for a particular session exceeds the specified
  time-out value in minutes, the session is considered expired. Requests
  made with an expired SessionID value result in a new session.


text:
Q: Net::SCP / Net::SCP::Expect - how to deal with password vs key authentication I have a script that works on different clients, and need to SCP files to different hosts. Depending on the combination of client & server, I may need to use password authentication or public key authentication. I cannot really know in advance which one to use.
There are 2 CPAN libraries for SCP that I use:

*

*Net::SCP: works with public key authentication only

*Net::SCP::Expect: works with password authentication only

The problem is that neither library works for both authentications, and I don't know which one to use in advance. Do you know of any way to work with both authentication schemes?

A: Try one and fail over to the other:
#! /usr/bin/perl

use warnings;
use strict;

use Net::SCP qw/ scp /;
use Net::SCP::Expect;

my @hosts = qw/ host1 host2 host3 /;
my $user  = "YOUR-USERNAME-HERE";
my $pass  = "PASSWORD-GOES-HERE";
my $file  = "file-to-copy";

foreach my $host (@hosts) {
  my $dest = "$host:$file";

  my $scp = Net::SCP->new($host, $user);
  unless ($scp->scp($file => $dest)) {
    my $scpe = Net::SCP::Expect->new;
    $scpe->login($user, $pass);

    local $@;
    eval { $scpe->scp($file => $dest) };
    next unless $@;

    warn "$0: scp $file $dest failed:\n" .
         "Public key auth:\n" .
         "    $scp->{errstr}\n" .
         "Password auth:\n" .
         "    $@\n";
  }
}

A: try Net::OpenSSH


text:
Q: When is it established that Wolverine's Adamantium cannot be affected by heat? Thaddeus stated on this answer that Wolverine's Adamantium can't be affected by heat. To quote:

The reason hot Adamantium did not destroy his body was that it could not be applied "hot" because heat cannot affect Adamantium at all.

But where in the Marvel canon does it say that Logan's Adamantium cannot be affected by heat?
Likewise, where does it say that his Adamantium heals like his bone? As far as I know, Wolverine's beta Adamantium is weaker than true Adamantium.

A: Adamantium is indestructible; meaning it is completely resistant to any form of heat, light, radiation, force or electromagnetic manipulation. While beings such as Magneto have been able to push, pull or potentially manipulate the substance, it is considered by Marvel canon to be the most indestructible material on Marvel Earth-616.
A canon representation of the heat resistance of Wolverine's skeleton can be shown here from New X-Men #148 where his skeleton survives the heat of the sun!:

*

*Adamantium's resistance to electromagnetic forces including forces such as magic and telekinesis, has always existed in the normal canon of the Marvel Universe.

*This level of indestructibility is highlighted and illustrated by the best known example of Captain America's shield which is composed of Primary Adamantium, consider to be the strongest material in the Marvel Universe (that can be found on Earth...)**

Captain America's adamantium shield resists the powerful kinetic blasts of the mutant Cyclops.
See StackExchange Article: How does Captain America's shield work?

Captain America deflecting the cosmic radiation of the powerful mutant, Havoc.
The Wikipedia entry on Adamantium adds:

In the Marvel Universe, adamantium is a group of man-made metal alloys of varying durability, but all are nearly indestructible. Adamantium was inadvertently invented by the American metallurgist Dr. Myron MacLain in an attempt to recreate his prior discovery, a unique alloy of steel and vibranium (which required an unknown catalyst for its manufacture) that was used to create Captain America's shield.

This was established in Avengers (vol. 1) #66-68 (July – September 1969).

Before molding, the components of the alloy are kept in separate batches, typically in blocks of resin. Adamantium is prepared by melting the blocks together, mixing the components while the resin evaporates. The alloy must then be cast within eight minutes. Adamantium's extremely stable molecular structure prevents it from being further molded even if the temperature is high enough to keep it in its liquified form. In its solid form, it is colorless, shiny, and resembles high-grade steel or titanium.

Established in Avengers (vol. 1) #201-202 (November – December 1980)

It is almost impossible to destroy or fracture in this state and when crafted to a razor edge, it can penetrate most lesser materials with minimal application of strength.

Established in X-Men (vol. 1) #139 (November 1980)
Wolverine's skeleton is linked to a substance called beta adamantium. Wolverine's skeleton has not been completely replaced with adamantium. His bones have been laced and suffused with adamantium allowing them to become nearly unbreakable without adding significant weight to his body.
Adamantium's structure (defying the laws of physics as we understand them) once its form is set, it simply resists any form of physical transformation without an expenditure of cosmic forces, matter reorganization, or powerful magic. This means beings such as Magneto, Odin/Thor, the Silver Surfer, or the Phoenix are beings capable of manipulating or destroying adamantium beta.
See: Why did hot Adamantium not destroy Wolverine's body while replacing his skeleton?


text:
Q: Parsing issue with Microsoft Security Graph API #MISP #Azure Sentinel We have integrated Azure Sentinel with MISP using Security Graph API.
We are seeing IP field being parsed improperly on MS Azure Sentinel. It could be the issue with Security Graph API. Referring to the screenshot, Value field should be "IP addr" and type should be "ipv4-addr" . Because of this parsing issue, none of our IP feeds are triggering any alerts on sentinel.
Whereas URL field is parsed properly.
Screenshot from Sentinel - Improper IP field parsing
Did anyone else face the same issue ? How do we rectify this issue ?


text:
Q: Using information_schema find the right one text line how using information_schema find same text from all columns ?
Have this :
SELECT    *
FROM      information_schema.columns
WHERE     table_name like '%cb%';

Need to find all tables name start CB and some column contains the text "OutstandingAmount"


text:
Q: xcode loading view I would like to show a progress view while my app is downloading files when starts. Loading view should be active until download ends, then, main tab controller will be shown. Which is the best method to reach it? Thanks

A: I think, loading the "main tab controller" first and then adding a view on top which shows the Progress should do the work.
Maybe MBProgressHUD (GitHub) could be interesting for you.
It's nice if the user will see little more then only progress. So make the View in Front translucent.


text:
Q: Permission to local repository denied to github, 403 error returned I'm trying to push a local repository on github using
git push -u origin main

but after entering the PAT in the password prompt this error comes up
remote: Permission to jatinvijay03/Map_Surat.git denied to jatinvijay03.
fatal: unable to access 'https://github.com/jatinvijay03/Map_Surat.git/': The requested URL returned error: 403


text:
Q: RequestMapping head to know if email exist or not I use spring boot
I would like to check if an email address alread exist in the system.
I created this
@RequestMapping(method = { RequestMethod.HEAD }, value={"/email"})
public ResponseEntity<Boolean> checkEmailexist(@RequestParam String value){
    return ResponseEntity.ok(userService.checkIfEmailExist(value));
}

If i check the result of userService.checkIfEmailExist, depending of the value, I get true or false...
Result from the call it's alway undefined
 $.ajax({
     url: '/email?value=' + usernameValue.value,
     type: 'HEAD',
     success: function (result) {
     console.log(result);
     }
 });

A: Its not an answer but rather a set of steps to check that will (hopefully) help you to find a solution:

*

*Make sure your annotations are correct - whether the @RestController annotation is used properly, what is the result, etc.

*As a generalization of "1" try to understand whether the issue is on server at all
For that run CURL query/use postman - whatever on a deployed server and see the result.

*If the issue is on the client side try to understand the status code of the request. I'm not a jquery pro (I understand this is a jquery syntax), but read this question and especially the answer with 'done' method - probably its a better way to work anyway, or at least put a jquery tag on the question so that the relevant people could read it and respond.


text:
Q: WPF: how to bind a templated custom control? I have a custom control(Seven Segment) made up of line and I have a collection(ObservableCollection) of it. Now, this is what I want to do:

*

*add a custom property to that custom control (number)

*bind that property to a textbox

*change the appearance of the custom control based on the value of property

*I want the color of each segment (black or white only) internally

Is it possible to do it in using pure WPF without code-behind?
Please ask for clarification if my question is not clear enough.


text:
Q: bit field declaration in a c++ struct I was reading over the ISO standard of c++ and I came over this bit-field declarations. The following code is not well clear to me
struct {
 char a;
 int b:5,
 c:11,
 :0,
 d:8;
 struct {int ee:8;}
 e;
 }

Here it is specified that the fields a, d and e.ee have different memory locations and they can be modified independently using multiple threads. The bitfields b and c uses same memory locations so they cant be modified concurrently. I dont understand the significance of using two bit fields for c i.e, c:11,:0,. can anybody clear my vision about this? thank you

A: You asked;

I dont understand the significance of using two bit fields for c i.e, c:11,:0,. can anybody clear my vision about this?

c is not defined using two bit-fields. The second one is an unnamed bit-field. Unnamed bit-fields with width of zero have special significance. This is what the standard says about unnamed bit-field.

A declaration for a bit-field that omits the identifier declares an unnamed bit-field. Unnamed bit-fields are not members and cannot be initialized. [ Note: An unnamed bit-field is useful for padding to conform to externally-imposed layouts. — end note ] As a special case, an unnamed bit-field with a width of zero specifies alignment of the next bit-field at an allocation unit boundary. Only when declaring an unnamed bit-field may the value of the constant-expression be equal to zero.

A: the :0 listed after c forces d to be aligned on the next word boundary.
It depends on how large your word size is. Supposing your word size is 32 bits, a, b, and c will be crammed into the first 24 bits of your first 32 bits, then the :0 will force the next item, d, to be aligned on the next word. And because the next item is not a bit field, but rather a struct made up of a bit field, it will automatically align itself on the next word boundary.
So, a, b, and c will all be on the same word, then d will be on its own word, then finally your struct, e.


text:
Q: Using my websites link in a href is preventing me from receiving my message I am trying to send a message using php mail fucntion. This is a part of the message that is causing the issue.
a href="http://www.MYWEBSITE.com">Visit

Mail is returning with a 1 but I am not seeing the message in my inbox. If I change it to
a href="http://www.google.com">Visit

I receive the message in my inbox.
Any Ideas?

A: This will give you a list of what's spammy in your MIME header and html content, or if your sender isn't trusted. It mainly checks against SpamAssassin, which has most of the rules of other email filters.
http://isnotspam.com/


text:
Q: .net - Glass effect in C# 2.0 applications How can I give a Vista or Mac OS X style glass effects on windows forms applications in .net 2.0?

A: This is done using interop with the Vista DWM (Desktop Window Manager) API.
For example, import these functions:
[DllImport("dwmapi.dll")]
static extern void DwmExtendFrameIntoClientArea(IntPtr hWnd, ref Margins pMargins);

[StructLayout(LayoutKind.Sequential)]
struct Margins
{
    public int cxLeftWidth;
    public int cxRightWidth;
    public int cyTopHeight;
    public int cyBottomHeight;
}

Then you can use this to "pull down" glass from the top of the window down into the client area:
GlassMargins.Top = 40;
GlassMargins.Left = 0;
GlassMargins.Right = 0;
GlassMargins.Bottom = 0;

DwmExtendFrameIntoClientArea(this.Handle, ref GlassMargins);

From here, you can go on and do other things, like draw text or images onto the glass, or put controls on it, such as a Office 2007 style application button.

A: The glass window borders in Vista Aero are composited using the DWM.  This is an OS-level feature.  If you run your app on Vista, you should get the glass border for free.
If you want to extend the glass effect into the client area, use DwmExtendFrameIntoClientArea, which is how Internet Explorer does it in its toolbar.  I suspect you'll have to write the interop to call this native function yourself (or check http://pinvoke.net).

A: DevExpress components

*

*for .NET 2.0

http://devexpress.com/Products/NET/DXperience/editionWinForms.xml

Creating a Glass Button using GDI+
http://www.codeproject.com/KB/buttons/glassbutton.aspx


text:
Q: C - Copying a char to another I am a beginner in C language. I want to copy a char array to another, but I cannot. I got these errors:
Line 10 - [Warning] passing argument 1 of 'insert' makes pointer from integer without a cast
Line 4 - [Note] expected 'char *' but argument is of type 'char'

Can you help me with finding the errors in this code?
#include <stdio.h>
#include <string.h>

void insert(char d[100]);

int main( ) {

    char m[100];
    scanf("%s", &m);
    insert(m[100]);
    return 0;
}

void insert (char d[100]) {
    char s[200];
    strcpy(s, d);
}

A: You should pass m to insert() not m[100]. In that context,  m[100] represents a single element of the m array and not the array itself. That's why the "integer to pointer without a cast" warning, because char is an integer after all.

A: The function signature of main() should be one of:
int main(void) {}

or
int main(int argc, char *argv[]) {}

or equivalently,
int main(int argc, char **argv) {}

There is no need to use the address operator & with an array argument in scanf(), since arrays decay to pointers to their first elements in most expressions, including function calls.
Note that you should specify a maximum field width when using the %s conversion specifier with scanf() to avoid buffer overflows:
scanf("%99s", m);

It is adquate to declare the insert() function as:
void insert(char d[]);

When you call the insert() function, only use the name of the array that you want to pass as an argument; this will decay to a pointer to the first element of the array. It is worth pointing out that the original code had undefined behavior with:
insert(m[100]);

This attempts to access the element at index 100 of the array m[], which is out of bounds.
The code now looks like this:
#include <stdio.h>
#include <string.h>

void insert(char d[]);

int main(void)
{
    char m[100];
    scanf("%99s", m);
    insert(m);

    return 0;
}

void insert (char d[])
{
    char s[200];
    strcpy(s, d);
}

Now, I don't know what you intend to do with the copied string s, but it no longer exists after insert() returns control to main().


text:
Q: Laravel/PHP: Unidentified index that does exist I have an object with a property:
protected $recipients = array();

In one of my methods I set the contents of the $recipients property with an associative array of data using this method:
public function setRecipientData($recipientData){
    foreach($recipientData as $key => $value){
        $this->recipients[$key] = $value;
    }
}

When I dump the contents of $this->recipients, the array ends up looking like this:
array (size=2)
  0 =>
    array (size=6)
      'email'       => string 'info@mycompany.com' (length=29)
      'userEmail'   => string 'xxx@yyy.com' (length=11)
      'first_name'  => string 'Test' (length=4)
      'last_name'   => string 'User' (length=4)
      'jobTitle'    => string 'Customer User' (length=13)
      'phoneNumber' => string '123.456.7890' (length=12)

I also have a property that will extract only the email addresses from the property like this:
private function getRecipientEmails(){
    $emails = array();
    foreach($this->recipients as $recipient){
        $emailPair = array('email' => $recipient['userEmail']);
        $emails[] =  $emailPair;
    }
    return $emails;
}

The problem that I'm running into is that when I run the method getRecipientsEmails() I get the error:
Undefined index: userEmail

I don't understand why it's not seeing the index 'userEmail'. If I dump the nested array it shows a value:
private function getRecipientEmails(){
    $emails = array();
    foreach($this->recipients as $recipient){
        dd($emailPair = array('email' => $recipient['userEmail']));
        $emails[] =  $emailPair;
    }
    return $emails;
}

Result:
array (size=1)
  'email' => string 'xxx@yyy.com' (length=20)

I've tried dumping the autoload with composer but it makes no difference.
Can anyone help point me in the right direction??
EDIT: Sorry, I realized that I wrote the wrong method into my original post. I've added the original getRecipientEmails() method and the dump that shows the data.


text:
Q: Add code to XSLT before transformation I'm using C# to transform an XML document and it is working fine:
using System;
using System.IO;
using System.Xml;
using System.Xml.Xsl;
using System.Xml.XPath;

public class XmlTransformUtil
{

public static void Main(string[] args)
{

    if (args.Length == 2)
    {

        Transform(args[0], args[1]);
    }
    else
    {

        PrintUsage();
    }
}

public static void Transform(string sXmlPath, string sXslPath)
{
    try
    {
        //load the Xml doc
        XPathDocument myXPathDoc = new XPathDocument(sXmlPath);

        XslTransform myXslTrans = new XslTransform();

        //load the Xsl
        myXslTrans.Load(sXslPath);

        //create the output stream
        XmlTextWriter myWriter = new XmlTextWriter
            ("result.html", null);

        //do the actual transform of Xml
        myXslTrans.Transform(myXPathDoc, null, myWriter);

        myWriter.Close();
    }

    catch (Exception e)
    {
        Console.WriteLine("Exception: {0}", e.ToString());
    }
}

public static void PrintUsage()
{
    Console.WriteLine
    ("Usage: XmlTransformUtil.exe <xml path> <xsl path>");
}

}

The above code works perfectly, however what I want to do is, before the XSLT is transformed, I want it to add additional Lines of code to specific parts of the XSLT.
XSLT Code:
<?xml version="1.0"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

<xsl:template match="/">
    <html lang="en-GB">
        <body style="font-family:'Praxis Com Light'; color:#632423; width:100%; font-size:14px !important;">

//MAIN BODY OF CODE

        </body>
    </html>
</xsl:template>
</xsl:stylesheet>

How i want the XSLT Code changed in C# Before the transformation:
<?xml version="1.0"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:include href="HEAD.xslt"/>
<xsl:include href="FOOT.xslt"/>

<xsl:template match="/">
    <html lang="en-GB">
        <body style="font-family:'Praxis Com Light'; color:#632423; width:100%; font-size:14px !important;">

        <xsl:call-template name="Header"/>

//MAIN BODY OF CODE

            <xsl:call-template name="Footer"/>

            </body>
        </html>
    </xsl:template>
</xsl:stylesheet>

How can this be accomplished?

A: XNamespace ns = "http://www.w3.org/1999/XSL/Transform";

XElement xslt = XElement.Load(sXslPath);

xslt.AddFirst(new XElement(ns + "include", new XAttribute("href", "FOOT.xslt")));
xslt.AddFirst(new XElement(ns + "include", new XAttribute("href", "HEAD.xslt")));

XElement body = xslt.Descendants("body").Single();

body.AddFirst(new XElement(ns + "call-template", new XAttribute("name", "Header")));
body.Add(new XElement(ns + "call-template", new XAttribute("name", "Footer")));


text:
Q: password authentication failed for user "postgres" (already edit 'pg_hba.conf' but didn't work) < Update for solution >
For future reference, there might be multiple versions of postgres in my computer since I install so many times while I was trying. So I didn't edit the exact 'pg_hba.conf' file. That cause the problem.
Eventually, I completely uninstall and reinstall the postgres by following this article:
https://blog.testdouble.com/posts/2021-01-28-how-to-completely-uninstall-homebrew-postgres/
It help me fixed the problem.

< Question >
I installed postgresql by brew on my mac,
but I keep having trouble to start using it and getting this message cause I don't know what's my password.
psql: error: connection to server on socket "/tmp/.s.PGSQL.5432" failed: FATAL:  password authentication failed for user "postgres"
I had already edited my pg_hba.conf  file, modified it to
local   all             all                                     trust
host    all             all            127.0.0.1/32             trust
host    all             all            ::1/128                  trust
local   replication     all                                     trust
host    replication     all            127.0.0.1/32             trust
host    replication     all            ::1/128                  trust

p.s. I also tried set the 'method' to 'ident',add the 'address' with '127.0.0.1/32', and 'user' to 'postgres'. All these combination didn't work.
After that, I restart the server, but i still need password to connect to the server.
$postgres -V
postgres (PostgreSQL) 14.0
$brew services restart postgres
Stopping `postgresql`... (might take a while)
==> Successfully stopped `postgresql` (label: homebrew.mxcl.postgresql)
==> Successfully started `postgresql` (label: homebrew.mxcl.postgresql)
$psql -U postgres
Password for user postgres:
psql: error: connection to server on socket "/tmp/.s.PGSQL.5432" failed: FATAL:  password authentication failed for user "postgres"

And here are other things that I had tried in the past few days:

*

*re-install postgresql by brew several times.

*psql -U postgres

*$ sudo -u postgres psql -c "ALTER USER postgres PASSWORD 'postgres';"
Please help me with this problem, I've stuck here for several days...


text:
Q: How can I return boxed value? I basically have a function that creates some object which need to be allocated on the heap. What I want to do is return from that function a structure containing a reference to that heap-allocated value.
struct Cont<'a> {
    pub v: &'a i32
}

impl<'a> Cont<'a> {
    fn new(v: &'a i32) -> Cont {
        Cont {
            v: v
        }
    }
}

fn f<'a>() -> Cont<'a> {
    let v = Box::new(6);

    Cont::new(&v)
}

fn main() {
    let c = f();

    println!("{}", c.v);
}

I'm getting error: 'v' does not live long enough.
You can find the example here.

A: You cannot return a structure that only contains a borrowed pointer to your object, because your Box would be destroyed at the end of the function.
You need to transfer ownership of the Box out of the function so that the heap-allocated object remains alive. The simplest way to do this is to move the Box into your struct:
struct Cont {
    pub v: Box<i32>
}

impl Cont {
    fn new(v: Box<i32>) -> Cont {
        Cont {
            v: v
        }
    }
}

fn f() -> Cont {
    let v = Box::new(6);
    Cont::new(v)
}

fn main() {
    let c = f();

    println!("{}", c.v);
}

If you want a struct that is able to store either a borrowed pointer or an owning Box (or other kinds of smart pointers), we can make it generic over the Borrow trait.
use std::borrow::Borrow;

struct Cont<T> where T: Borrow<i32> {
    pub v: T
}

impl<T> Cont<T> where T: Borrow<i32> {
    fn new(v: T) -> Cont<T> {
        Cont {
            v: v
        }
    }
}

fn owned() -> Cont<Box<i32>> {
    let v = Box::new(6);
    Cont::new(v)
}

fn borrowed(v: &i32) -> Cont<&i32> {
    Cont::new(v)
}

fn main() {
    let c = owned();
    println!("{}", c.v);

    let x = 123;
    let c = borrowed(&x);
    println!("{}", c.v);
}


text:
Q: Create a sliding menu i'm trying to create a Sliding Menu for my android app. Well, at this moment i'm not well suceed.
I'm trying to do something like this:

If  I press button A, in option view will appear A's options, if I press B, same thing happens, C...
Can you help me?
Thanks a lot.

A:
see this: How to Create QuickAction Dialog in Android : http://www.londatiga.net/it/how-to-create-quickaction-dialog-in-android/

A: Simple sliding menu:
<HorizontalScrollView
    android:id="@+id/horizontalScrollView1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" >

    <LinearLayout
        android:id="@+id/linearLayout3"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:orientation="horizontal" >

        <Button
            android:id="@+id/button1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="25"
            android:adjustViewBounds="true"
            android:text="A" />

        <Button
            android:id="@+id/button2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="25"
            android:adjustViewBounds="true"
            android:text="B" />

        <Button
            android:id="@+id/button3"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="25"
            android:adjustViewBounds="true"
            android:text="C" />

        <Button
            android:id="@+id/button4"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="25"
            android:adjustViewBounds="true"
            android:text="D" />

    </LinearLayout>
</HorizontalScrollView>

Now set onclick listeners of these buttons in your java code.
If you want to show popups, see How to create a popup window in android?


text:
Q: Discrete Laplacian is symmetric Let $\Lambda \subset \mathbb{Z}^{d}$ be a finite lattice. The discrete Laplacian is defined as the linear operator $-\Delta: \mathbb{C}^{\Lambda}\to \mathbb{C}^{\Lambda}$ satisfying:
$$(-\Delta \phi)(x) := \sum_{k=1}^{d}[2\phi(x)-\phi(x+e_{k})-\phi(x-e_{k})] $$
where $\{e_{1},...,e_{d}\}$ is the canonical basis of $\mathbb{R}^{d}$. I'd like to prove that this is a symmetric operator, that is, it satisfies:
$$\langle \phi, -\Delta \psi\rangle = \langle -\Delta \phi, \psi\rangle$$
where $\langle \phi,\psi\rangle := \sum_{x\in \Lambda}\overline{\phi(x)}\psi(x)$ is the usual inner product on $\mathbb{C}^{\Lambda}$. Here is my proof:
$$\langle \phi, -\Delta \psi \rangle = \sum_{x\in \Lambda}\overline{\phi(x)}\sum_{k=1}^{d}[2\psi(x)-\psi(x+e_{k})-\psi(x-e_{k})] = \sum_{x\in \Lambda}\sum_{k=1}^{d}2\overline{\phi(x)}\psi(x) -\sum_{x\in \Lambda}\sum_{k=1}^{d}\overline{\phi(x)}\psi(x+e_{k})-\sum_{x\in \Lambda}\sum_{k=1}^{d}\overline{\phi(x)}\psi(x-e_{k}) $$
Now, changing variables $x' = x\pm e_{k}$, we can write:
\begin{eqnarray}
\sum_{x\in \Lambda}\sum_{k=1}^{d}\overline{\psi(x)}\psi(x\pm e_{k}) = \sum_{x'\in \Lambda}\sum_{k=1}^{d}\overline{\phi(x\mp e_{k})}\psi(x) \tag{1}\label{1}
\end{eqnarray}
and putting it on our previous relation, we get:
$$\langle \phi, -\Delta \psi\rangle = \sum_{x\in \Lambda}\sum_{k=1}^{d}[2\overline{\phi(x)}-\overline{\phi(x+e_{k})}-\overline{\phi(x-e_{k})}]\psi(x) = \langle -\Delta \phi, \psi\rangle$$
Is my proof correct? I'm not 100% sure about identity (\ref{1}). Any comments would be helpful!